changeset 7689:5be9c5bfcfe9 jdk8-b100

Merge
author lana
date Mon, 22 Jul 2013 17:37:15 -0700
parents 9b6070690e50 (current diff) f2558ef87d5a (diff)
children 690161232823
files src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java src/share/classes/java/util/stream/StreamBuilder.java src/share/classes/javax/security/auth/callback/package.html src/share/classes/javax/security/auth/kerberos/package.html src/share/classes/javax/security/auth/login/package.html src/share/classes/javax/security/auth/package.html src/share/classes/javax/security/auth/spi/package.html src/share/classes/javax/security/auth/x500/package.html src/share/classes/javax/security/cert/package.html src/share/classes/javax/security/sasl/package.html test/java/util/Collections/EmptySortedSet.java
diffstat 595 files changed, 44659 insertions(+), 34342 deletions(-) [+]
line wrap: on
line diff
--- a/make/sun/security/pkcs11/mapfile-vers	Thu Jul 18 03:38:49 2013 -0700
+++ b/make/sun/security/pkcs11/mapfile-vers	Mon Jul 22 17:37:15 2013 -0700
@@ -102,7 +102,7 @@
 		Java_sun_security_pkcs11_Secmod_nssGetLibraryHandle;
 		Java_sun_security_pkcs11_Secmod_nssLoadLibrary;
 		Java_sun_security_pkcs11_Secmod_nssVersionCheck;
-		Java_sun_security_pkcs11_Secmod_nssInit;
+		Java_sun_security_pkcs11_Secmod_nssInitialize;
 		Java_sun_security_pkcs11_Secmod_nssGetModuleList;
 
 	local:
--- a/makefiles/mapfiles/libj2pkcs11/mapfile-vers	Thu Jul 18 03:38:49 2013 -0700
+++ b/makefiles/mapfiles/libj2pkcs11/mapfile-vers	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -102,7 +102,7 @@
 		Java_sun_security_pkcs11_Secmod_nssGetLibraryHandle;
 		Java_sun_security_pkcs11_Secmod_nssLoadLibrary;
 		Java_sun_security_pkcs11_Secmod_nssVersionCheck;
-		Java_sun_security_pkcs11_Secmod_nssInit;
+		Java_sun_security_pkcs11_Secmod_nssInitialize;
 		Java_sun_security_pkcs11_Secmod_nssGetModuleList;
 
 	local:
--- a/src/macosx/classes/com/apple/eawt/FullScreenHandler.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/macosx/classes/com/apple/eawt/FullScreenHandler.java	Mon Jul 22 17:37:15 2013 -0700
@@ -32,6 +32,7 @@
 import javax.swing.RootPaneContainer;
 
 import com.apple.eawt.AppEvent.FullScreenEvent;
+import sun.awt.SunToolkit;
 
 import java.lang.annotation.Native;
 
@@ -75,7 +76,7 @@
     static void handleFullScreenEventFromNative(final Window window, final int type) {
         if (!(window instanceof RootPaneContainer)) return; // handles null
 
-        EventQueue.invokeLater(new Runnable() {
+        SunToolkit.executeOnEventHandlerThread(window, new Runnable() {
             public void run() {
                 final FullScreenHandler handler = getHandlerFor((RootPaneContainer)window);
                 if (handler != null) handler.notifyListener(new FullScreenEvent(window), type);
--- a/src/macosx/classes/com/apple/eawt/_AppEventHandler.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/macosx/classes/com/apple/eawt/_AppEventHandler.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,6 +31,8 @@
 import java.net.*;
 import java.util.*;
 import java.util.List;
+import sun.awt.AppContext;
+import sun.awt.SunToolkit;
 
 import com.apple.eawt.AppEvent.*;
 
@@ -269,11 +271,9 @@
     }
 
     class _AppReOpenedDispatcher extends _AppEventMultiplexor<AppReOpenedListener> {
-        void performOnListeners(final List<AppReOpenedListener> listeners, final _NativeEvent event) {
+        void performOnListener(AppReOpenedListener listener, final _NativeEvent event) {
             final AppReOpenedEvent e = new AppReOpenedEvent();
-            for (final AppReOpenedListener listener : listeners) {
-                listener.appReOpened(e);
-            }
+            listener.appReOpened(e);
         }
     }
 
@@ -415,50 +415,67 @@
     }
 
     abstract class _AppEventMultiplexor<L> {
-        final List<L> _listeners = new ArrayList<L>(0);
+        private final Map<L, AppContext> listenerToAppContext =
+                new IdentityHashMap<L, AppContext>();
         boolean nativeListenerRegistered;
 
         // called from AppKit Thread-0
         void dispatch(final _NativeEvent event, final Object... args) {
-            // grab a local ref to the listeners
-            final List<L> localListeners;
+            // grab a local ref to the listeners and its contexts as an array of the map's entries
+            final ArrayList<Map.Entry<L, AppContext>> localEntries;
             synchronized (this) {
-                if (_listeners.size() == 0) return;
-                localListeners = new ArrayList<L>(_listeners);
+                if (listenerToAppContext.size() == 0) {
+                    return;
+                }
+                localEntries = new ArrayList<Map.Entry<L, AppContext>>(listenerToAppContext.size());
+                localEntries.addAll(listenerToAppContext.entrySet());
             }
 
-            EventQueue.invokeLater(new Runnable() {
-                public void run() {
-                    performOnListeners(localListeners, event);
-                }
-            });
+            for (final Map.Entry<L, AppContext> e : localEntries) {
+                final L listener = e.getKey();
+                final AppContext listenerContext = e.getValue();
+                SunToolkit.invokeLaterOnAppContext(listenerContext, new Runnable() {
+                    public void run() {
+                        performOnListener(listener, event);
+                    }
+                });
+            }
         }
 
         synchronized void addListener(final L listener) {
+            setListenerContext(listener, AppContext.getAppContext());
+
             if (!nativeListenerRegistered) {
                 registerNativeListener();
                 nativeListenerRegistered = true;
             }
-            _listeners.add(listener);
         }
 
         synchronized void removeListener(final L listener) {
-            _listeners.remove(listener);
+            listenerToAppContext.remove(listener);
         }
 
-        abstract void performOnListeners(final List<L> listeners, final _NativeEvent event);
+        abstract void performOnListener(L listener, final _NativeEvent event);
         void registerNativeListener() { }
+
+        private void setListenerContext(L listener, AppContext listenerContext) {
+            if (listenerContext == null) {
+                throw new RuntimeException(
+                        "Attempting to add a listener from a thread group without AppContext");
+            }
+            listenerToAppContext.put(listener, AppContext.getAppContext());
+        }
     }
 
     abstract class _BooleanAppEventMultiplexor<L, E> extends _AppEventMultiplexor<L> {
         @Override
-        void performOnListeners(final List<L> listeners, final _NativeEvent event) {
+        void performOnListener(L listener, final _NativeEvent event) {
             final boolean isTrue = Boolean.TRUE.equals(event.get(0));
             final E e = createEvent(isTrue);
             if (isTrue) {
-                for (final L listener : listeners) performTrueEventOn(listener, e);
+                performTrueEventOn(listener, e);
             } else {
-                for (final L listener : listeners) performFalseEventOn(listener, e);
+                performFalseEventOn(listener, e);
             }
         }
 
@@ -479,30 +496,34 @@
      */
     abstract class _AppEventDispatcher<H> {
         H _handler;
+        AppContext handlerContext;
 
         // called from AppKit Thread-0
         void dispatch(final _NativeEvent event) {
-            EventQueue.invokeLater(new Runnable() {
-                public void run() {
-                    // grab a local ref to the handler
-                    final H localHandler;
-                    synchronized (_AppEventDispatcher.this) {
-                        localHandler = _handler;
-                    }
+            // grab a local ref to the handler
+            final H localHandler;
+            final AppContext localHandlerContext;
+            synchronized (_AppEventDispatcher.this) {
+                localHandler = _handler;
+                localHandlerContext = handlerContext;
+            }
 
-                    // invoke the handler outside of the synchronized block
-                    if (localHandler == null) {
-                        performDefaultAction(event);
-                    } else {
+            if (localHandler == null) {
+                performDefaultAction(event);
+            } else {
+                SunToolkit.invokeLaterOnAppContext(localHandlerContext, new Runnable() {
+                    public void run() {
                         performUsing(localHandler, event);
                     }
-                }
-            });
+                });
+            }
         }
 
         synchronized void setHandler(final H handler) {
             this._handler = handler;
 
+            setHandlerContext(AppContext.getAppContext());
+
             // if a new handler is installed, block addition of legacy ApplicationListeners
             if (handler == legacyHandler) return;
             legacyHandler.blockLegacyAPI();
@@ -510,6 +531,15 @@
 
         void performDefaultAction(final _NativeEvent event) { } // by default, do nothing
         abstract void performUsing(final H handler, final _NativeEvent event);
+
+        protected void setHandlerContext(AppContext ctx) {
+            if (ctx == null) {
+                throw new RuntimeException(
+                        "Attempting to set a handler from a thread group without AppContext");
+            }
+
+            handlerContext = ctx;
+        }
     }
 
     abstract class _QueuingAppEventDispatcher<H> extends _AppEventDispatcher<H> {
@@ -531,6 +561,8 @@
         synchronized void setHandler(final H handler) {
             this._handler = handler;
 
+            setHandlerContext(AppContext.getAppContext());
+
             // dispatch any events in the queue
             if (queuedEvents != null) {
                 // grab a local ref to the queue, so the real one can be nulled out
--- a/src/macosx/classes/com/apple/eawt/event/GestureHandler.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/macosx/classes/com/apple/eawt/event/GestureHandler.java	Mon Jul 22 17:37:15 2013 -0700
@@ -25,6 +25,8 @@
 
 package com.apple.eawt.event;
 
+import sun.awt.SunToolkit;
+
 import java.awt.*;
 import java.util.*;
 import java.util.List;
@@ -70,7 +72,7 @@
     static void handleGestureFromNative(final Window window, final int type, final double x, final double y, final double a, final double b) {
         if (window == null) return; // should never happen...
 
-        EventQueue.invokeLater(new Runnable() {
+        SunToolkit.executeOnEventHandlerThread(window, new Runnable() {
             public void run() {
                 final Component component = SwingUtilities.getDeepestComponentAt(window, (int)x, (int)y);
 
--- a/src/macosx/classes/com/apple/laf/ScreenMenu.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/macosx/classes/com/apple/laf/ScreenMenu.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,6 +32,7 @@
 
 import javax.swing.*;
 
+import sun.awt.SunToolkit;
 import sun.lwawt.LWToolkit;
 import sun.lwawt.macosx.*;
 
@@ -144,7 +145,7 @@
                     updateItems();
                     fItemBounds = new Rectangle[invoker.getMenuComponentCount()];
                 }
-            }, null);
+            }, invoker);
         } catch (final Exception e) {
             System.err.println(e);
             e.printStackTrace();
@@ -172,7 +173,7 @@
 
             fItemBounds = null;
     }
-            }, null);
+            }, invoker);
         } catch (final Exception e) {
             e.printStackTrace();
         }
@@ -200,7 +201,7 @@
         if (kind == 0) return;
         if (fItemBounds == null) return;
 
-        SwingUtilities.invokeLater(new Runnable() {
+        SunToolkit.executeOnEventHandlerThread(fInvoker, new Runnable() {
             @Override
             public void run() {
                 Component target = null;
--- a/src/macosx/classes/sun/lwawt/macosx/CCheckboxMenuItem.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/macosx/classes/sun/lwawt/macosx/CCheckboxMenuItem.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -53,7 +53,7 @@
 
     public void handleAction(final boolean state) {
         final CheckboxMenuItem target = (CheckboxMenuItem)getTarget();
-        EventQueue.invokeLater(new Runnable() {
+        SunToolkit.executeOnEventHandlerThread(target, new Runnable() {
             public void run() {
                 target.setState(state);
             }
--- a/src/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java	Mon Jul 22 17:37:15 2013 -0700
@@ -107,10 +107,6 @@
             loc = rootComponent.getLocation();
         }
 
-        //It sure will be LWComponentPeer instance as rootComponent is a Window
-        PlatformWindow platformWindow = ((LWComponentPeer)rootComponent.getPeer()).getPlatformWindow();
-        long nativeViewPtr = CPlatformWindow.getNativeViewPtr(platformWindow);
-
         // If there isn't any drag image make one of default appearance:
         if (fDragImage == null)
             this.setDefaultDragImage(component);
@@ -137,6 +133,11 @@
         }
 
         try {
+            //It sure will be LWComponentPeer instance as rootComponent is a Window
+            PlatformWindow platformWindow = ((LWComponentPeer)rootComponent.getPeer()).getPlatformWindow();
+            long nativeViewPtr = CPlatformWindow.getNativeViewPtr(platformWindow);
+            if (nativeViewPtr == 0L) throw new InvalidDnDOperationException("Unsupported platform window implementation");
+
             // Create native dragging source:
             final long nativeDragSource = createNativeDragSource(component, nativeViewPtr, transferable, triggerEvent,
                 (int) (dragOrigin.getX()), (int) (dragOrigin.getY()), extModifiers,
--- a/src/macosx/classes/sun/lwawt/macosx/CDropTarget.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/macosx/classes/sun/lwawt/macosx/CDropTarget.java	Mon Jul 22 17:37:15 2013 -0700
@@ -52,6 +52,8 @@
         fPeer = peer;
 
         long nativePeer = CPlatformWindow.getNativeViewPtr(((LWComponentPeer) peer).getPlatformWindow());
+        if (nativePeer == 0L) return; // Unsupported for a window without a native view (plugin)
+
         // Create native dragging destination:
         fNativeDropTarget = this.createNativeDropTarget(dropTarget, component, peer, nativePeer);
         if (fNativeDropTarget == 0) {
--- a/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Mon Jul 22 17:37:15 2013 -0700
@@ -479,12 +479,14 @@
             deliverZoom(true);
 
             this.normalBounds = peer.getBounds();
-            long screen = CWrapper.NSWindow.screen(getNSWindowPtr());
-            Rectangle toBounds = CWrapper.NSScreen.visibleFrame(screen).getBounds();
-            // Flip the y coordinate
-            Rectangle frame = CWrapper.NSScreen.frame(screen).getBounds();
-            toBounds.y = frame.height - toBounds.y - toBounds.height;
-            setBounds(toBounds.x, toBounds.y, toBounds.width, toBounds.height);
+
+            GraphicsConfiguration config = getPeer().getGraphicsConfiguration();
+            Insets i = ((CGraphicsDevice)config.getDevice()).getScreenInsets();
+            Rectangle toBounds = config.getBounds();
+            setBounds(toBounds.x + i.left,
+                      toBounds.y + i.top,
+                      toBounds.width - i.left - i.right,
+                      toBounds.height - i.top - i.bottom);
         }
     }
 
@@ -751,13 +753,7 @@
         // the move/size notification from the underlying system comes
         // but it contains a bounds smaller than the whole screen
         // and therefore we need to create the synthetic notifications
-        Rectangle screenBounds;
-        final long screenPtr = CWrapper.NSWindow.screen(getNSWindowPtr());
-        try {
-            screenBounds = CWrapper.NSScreen.frame(screenPtr).getBounds();
-        } finally {
-            CWrapper.NSObject.release(screenPtr);
-        }
+        Rectangle screenBounds = getPeer().getGraphicsConfiguration().getBounds();
         peer.notifyReshape(screenBounds.x, screenBounds.y, screenBounds.width,
                            screenBounds.height);
     }
@@ -900,8 +896,6 @@
             nativePeer = ((CPlatformWindow) platformWindow).getContentView().getAWTView();
         } else if (platformWindow instanceof CViewPlatformEmbeddedFrame){
             nativePeer = ((CViewPlatformEmbeddedFrame) platformWindow).getNSViewPtr();
-        } else {
-            throw new IllegalArgumentException("Unsupported platformWindow implementation");
         }
         return nativePeer;
     }
@@ -932,25 +926,19 @@
 
         final Rectangle oldB = nativeBounds;
         nativeBounds = new Rectangle(x, y, width, height);
-        final GraphicsConfiguration oldGC = peer.getGraphicsConfiguration();
-
-        final GraphicsConfiguration newGC = peer.getGraphicsConfiguration();
-        // System-dependent appearance optimization.
         if (peer != null) {
             peer.notifyReshape(x, y, width, height);
-        }
-
-        if ((byUser && !oldB.getSize().equals(nativeBounds.getSize()))
-            || isFullScreenAnimationOn || !Objects.equals(newGC, oldGC)) {
-            flushBuffers();
+            // System-dependent appearance optimization.
+            if ((byUser && !oldB.getSize().equals(nativeBounds.getSize()))
+                    || isFullScreenAnimationOn) {
+                flushBuffers();
+            }
         }
     }
 
     private void deliverWindowClosingEvent() {
-        if (peer != null) {
-            if (peer.getBlocker() == null)  {
-                peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING));
-            }
+        if (peer != null && peer.getBlocker() == null) {
+            peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING));
         }
     }
 
--- a/src/macosx/classes/sun/lwawt/macosx/CViewEmbeddedFrame.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/macosx/classes/sun/lwawt/macosx/CViewEmbeddedFrame.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -96,7 +96,7 @@
                     validate();
                     setVisible(true);
                 }
-            }, null);
+            }, this);
         } catch (InterruptedException | InvocationTargetException ex) {}
     }
 }
--- a/src/macosx/classes/sun/lwawt/macosx/CWrapper.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/macosx/classes/sun/lwawt/macosx/CWrapper.java	Mon Jul 22 17:37:15 2013 -0700
@@ -71,8 +71,6 @@
         public static native void zoom(long window);
 
         public static native void makeFirstResponder(long window, long responder);
-
-        public static native long screen(long window);
     }
 
     public static final class NSView {
@@ -95,12 +93,6 @@
         public static native void release(long object);
     }
 
-    public static final class NSScreen {
-        public static native Rectangle2D frame(long screen);
-        public static native Rectangle2D visibleFrame(long screen);
-        public static native long screenByDisplayId(int displayID);
-    }
-
     public static final class NSColor {
         public static native long clearColor();
     }
--- a/src/macosx/native/sun/awt/CMenuItem.m	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/macosx/native/sun/awt/CMenuItem.m	Mon Jul 22 17:37:15 2013 -0700
@@ -82,8 +82,13 @@
         // keys, so we need to do the same translation here that we do
         // for the regular key down events
         if ([eventKey length] == 1) {
-            unichar ch =  NsCharToJavaChar([eventKey characterAtIndex:0], 0);
-            eventKey = [NSString stringWithCharacters: &ch length: 1];
+            unichar origChar = [eventKey characterAtIndex:0];
+            unichar newChar =  NsCharToJavaChar(origChar, 0);
+            if (newChar == java_awt_event_KeyEvent_CHAR_UNDEFINED) {
+                newChar = origChar;
+            }
+
+            eventKey = [NSString stringWithCharacters: &newChar length: 1];
         }
 
         if ([menuKey isEqualToString:eventKey]) {
--- a/src/macosx/native/sun/awt/CWrapper.m	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/macosx/native/sun/awt/CWrapper.m	Mon Jul 22 17:37:15 2013 -0700
@@ -397,31 +397,6 @@
 }
 
 /*
- * Class:     sun_lwawt_macosx_CWrapper$NSWindow
- * Method:    screen
- * Signature: (J)J
- */
-JNIEXPORT jlong JNICALL
-Java_sun_lwawt_macosx_CWrapper_00024NSWindow_screen
-(JNIEnv *env, jclass cls, jlong windowPtr)
-{
-    __block jlong screenPtr = 0L;
-
-JNF_COCOA_ENTER(env);
-
-    AWTWindow *window = (AWTWindow *)jlong_to_ptr(windowPtr);
-    [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
-        const NSScreen *screen = [window screen];
-        CFRetain(screen); // GC
-        screenPtr = ptr_to_jlong(screen);
-    }];
-
-JNF_COCOA_EXIT(env);
-
-    return screenPtr;
-}
-
-/*
  * Method:    miniaturize
  * Signature: (J)V
  */
@@ -690,92 +665,6 @@
 JNF_COCOA_EXIT(env);
 }
 
-
-/*
- * Class:     sun_lwawt_macosx_CWrapper$NSScreen
- * Method:    frame
- * Signature: (J)Ljava/awt/Rectangle;
- */
-JNIEXPORT jobject JNICALL
-Java_sun_lwawt_macosx_CWrapper_00024NSScreen_frame
-(JNIEnv *env, jclass cls, jlong screenPtr)
-{
-    jobject jRect = NULL;
-
-JNF_COCOA_ENTER(env);
-
-    __block NSRect rect = NSZeroRect;
-
-    NSScreen *screen = (NSScreen *)jlong_to_ptr(screenPtr);
-    [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
-        rect = [screen frame];
-    }];
-
-    jRect = NSToJavaRect(env, rect);
-
-JNF_COCOA_EXIT(env);
-
-    return jRect;
-}
-
-/*
- * Class:     sun_lwawt_macosx_CWrapper_NSScreen
- * Method:    visibleFrame
- * Signature: (J)Ljava/awt/geom/Rectangle2D;
- */
-JNIEXPORT jobject JNICALL
-Java_sun_lwawt_macosx_CWrapper_00024NSScreen_visibleFrame
-(JNIEnv *env, jclass cls, jlong screenPtr)
-{
-    jobject jRect = NULL;
-
-JNF_COCOA_ENTER(env);
-
-    __block NSRect rect = NSZeroRect;
-
-    NSScreen *screen = (NSScreen *)jlong_to_ptr(screenPtr);
-    [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
-        rect = [screen visibleFrame];
-    }];
-
-    jRect = NSToJavaRect(env, rect);
-
-JNF_COCOA_EXIT(env);
-
-    return jRect;
-}
-
-/*
- * Class:     sun_lwawt_macosx_CWrapper_NSScreen
- * Method:    screenByDisplayId
- * Signature: (J)J
- */
-JNIEXPORT jlong JNICALL
-Java_sun_lwawt_macosx_CWrapper_00024NSScreen_screenByDisplayId
-(JNIEnv *env, jclass cls, jint displayID)
-{
-    __block jlong screenPtr = 0L;
-
-JNF_COCOA_ENTER(env); 
-
-    [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
-        NSArray *screens = [NSScreen screens];
-        for (NSScreen *screen in screens) {
-            NSDictionary *screenInfo = [screen deviceDescription];
-            NSNumber *screenID = [screenInfo objectForKey:@"NSScreenNumber"];
-            if ([screenID intValue] == displayID){
-                CFRetain(screen); // GC
-                screenPtr = ptr_to_jlong(screen);
-                break;
-            }
-        }
-    }];
-
-JNF_COCOA_EXIT(env);
-
-    return screenPtr;
-}
-
 /*
  * Class:     sun_lwawt_macosx_CWrapper$NSColor
  * Method:    clearColor
--- a/src/share/classes/com/sun/accessibility/internal/resources/accessibility.properties	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/accessibility/internal/resources/accessibility.properties	Mon Jul 22 17:37:15 2013 -0700
@@ -102,7 +102,7 @@
 #
 # accessible actions
 #
-toggle expand=toggle expand
+toggleexpand=toggle expand
 
 # new relations, roles and states for J2SE 1.5.0
 
--- a/src/share/classes/com/sun/accessibility/internal/resources/accessibility_de.properties	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/accessibility/internal/resources/accessibility_de.properties	Mon Jul 22 17:37:15 2013 -0700
@@ -102,7 +102,7 @@
 #
 # accessible actions
 #
-toggle expand=ein-/ausblenden
+toggleexpand=ein-/ausblenden
 
 # new relations, roles and states for J2SE 1.5.0
 
--- a/src/share/classes/com/sun/accessibility/internal/resources/accessibility_es.properties	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/accessibility/internal/resources/accessibility_es.properties	Mon Jul 22 17:37:15 2013 -0700
@@ -102,7 +102,7 @@
 #
 # accessible actions
 #
-toggle expand=activar/desactivar ampliaci\u00F3n
+toggleexpand=activar/desactivar ampliaci\u00F3n
 
 # new relations, roles and states for J2SE 1.5.0
 
--- a/src/share/classes/com/sun/accessibility/internal/resources/accessibility_fr.properties	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/accessibility/internal/resources/accessibility_fr.properties	Mon Jul 22 17:37:15 2013 -0700
@@ -102,7 +102,7 @@
 #
 # accessible actions
 #
-toggle expand=basculer le d\u00E9veloppement
+toggleexpand=basculer le d\u00E9veloppement
 
 # new relations, roles and states for J2SE 1.5.0
 
--- a/src/share/classes/com/sun/accessibility/internal/resources/accessibility_it.properties	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/accessibility/internal/resources/accessibility_it.properties	Mon Jul 22 17:37:15 2013 -0700
@@ -102,7 +102,7 @@
 #
 # accessible actions
 #
-toggle expand=abilita/disabilita espansione
+toggleexpand=abilita/disabilita espansione
 
 # new relations, roles and states for J2SE 1.5.0
 
--- a/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ja.properties	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ja.properties	Mon Jul 22 17:37:15 2013 -0700
@@ -102,7 +102,7 @@
 #
 # accessible actions
 #
-toggle expand=\u5C55\u958B\u306E\u30C8\u30B0\u30EB
+toggleexpand=\u5C55\u958B\u306E\u30C8\u30B0\u30EB
 
 # new relations, roles and states for J2SE 1.5.0
 
--- a/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ko.properties	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ko.properties	Mon Jul 22 17:37:15 2013 -0700
@@ -102,7 +102,7 @@
 #
 # accessible actions
 #
-toggle expand=\uD1A0\uAE00 \uD655\uC7A5
+toggleexpand=\uD1A0\uAE00 \uD655\uC7A5
 
 # new relations, roles and states for J2SE 1.5.0
 
--- a/src/share/classes/com/sun/accessibility/internal/resources/accessibility_pt_BR.properties	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/accessibility/internal/resources/accessibility_pt_BR.properties	Mon Jul 22 17:37:15 2013 -0700
@@ -102,7 +102,7 @@
 #
 # accessible actions
 #
-toggle expand=alternar expans\u00E3o
+toggleexpand=alternar expans\u00E3o
 
 # new relations, roles and states for J2SE 1.5.0
 
--- a/src/share/classes/com/sun/accessibility/internal/resources/accessibility_sv.properties	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/accessibility/internal/resources/accessibility_sv.properties	Mon Jul 22 17:37:15 2013 -0700
@@ -102,7 +102,7 @@
 #
 # accessible actions
 #
-toggle expand=v\u00E4xla ut\u00F6ka
+toggleexpand=v\u00E4xla ut\u00F6ka
 
 # new relations, roles and states for J2SE 1.5.0
 
--- a/src/share/classes/com/sun/accessibility/internal/resources/accessibility_zh_CN.properties	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/accessibility/internal/resources/accessibility_zh_CN.properties	Mon Jul 22 17:37:15 2013 -0700
@@ -102,7 +102,7 @@
 #
 # accessible actions
 #
-toggle expand=\u5207\u6362\u5C55\u5F00
+toggleexpand=\u5207\u6362\u5C55\u5F00
 
 # new relations, roles and states for J2SE 1.5.0
 
--- a/src/share/classes/com/sun/accessibility/internal/resources/accessibility_zh_TW.properties	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/accessibility/internal/resources/accessibility_zh_TW.properties	Mon Jul 22 17:37:15 2013 -0700
@@ -102,7 +102,7 @@
 #
 # accessible actions
 #
-toggle expand=\u5207\u63DB\u64F4\u5C55
+toggleexpand=\u5207\u63DB\u64F4\u5C55
 
 # new relations, roles and states for J2SE 1.5.0
 
--- a/src/share/classes/com/sun/crypto/provider/DESKeyFactory.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/crypto/provider/DESKeyFactory.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,6 +31,7 @@
 import java.security.InvalidKeyException;
 import java.security.spec.KeySpec;
 import java.security.spec.InvalidKeySpecException;
+import javax.crypto.spec.SecretKeySpec;
 
 /**
  * This class implements the DES key factory of the Sun provider.
@@ -60,20 +61,22 @@
      */
     protected SecretKey engineGenerateSecret(KeySpec keySpec)
         throws InvalidKeySpecException {
-        DESKey desKey = null;
 
         try {
-            if (!(keySpec instanceof DESKeySpec)) {
-                throw new InvalidKeySpecException
-                    ("Inappropriate key specification");
+            if (keySpec instanceof DESKeySpec) {
+                return new DESKey(((DESKeySpec)keySpec).getKey());
+            }
+
+            if (keySpec instanceof SecretKeySpec) {
+                return new DESKey(((SecretKeySpec)keySpec).getEncoded());
             }
-            else {
-                DESKeySpec desKeySpec = (DESKeySpec)keySpec;
-                desKey = new DESKey(desKeySpec.getKey());
-            }
+
+            throw new InvalidKeySpecException(
+                    "Inappropriate key specification");
+
         } catch (InvalidKeyException e) {
+            throw new InvalidKeySpecException(e.getMessage());
         }
-        return desKey;
     }
 
     /**
--- a/src/share/classes/com/sun/crypto/provider/DESedeKeyFactory.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/crypto/provider/DESedeKeyFactory.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,6 +31,7 @@
 import java.security.InvalidKeyException;
 import java.security.spec.KeySpec;
 import java.security.spec.InvalidKeySpecException;
+import javax.crypto.spec.SecretKeySpec;
 
 /**
  * This class implements the DES-EDE key factory of the Sun provider.
@@ -60,20 +61,20 @@
      */
     protected SecretKey engineGenerateSecret(KeySpec keySpec)
         throws InvalidKeySpecException {
-        DESedeKey desEdeKey = null;
 
         try {
             if (keySpec instanceof DESedeKeySpec) {
-                DESedeKeySpec desEdeKeySpec = (DESedeKeySpec)keySpec;
-                desEdeKey = new DESedeKey(desEdeKeySpec.getKey());
+                return new DESedeKey(((DESedeKeySpec)keySpec).getKey());
+            }
+            if (keySpec instanceof SecretKeySpec) {
+                return new DESedeKey(((SecretKeySpec)keySpec).getEncoded());
 
-            } else {
-                throw new InvalidKeySpecException
-                    ("Inappropriate key specification");
             }
+            throw new InvalidKeySpecException
+                ("Inappropriate key specification");
         } catch (InvalidKeyException e) {
+            throw new InvalidKeySpecException(e.getMessage());
         }
-        return desEdeKey;
     }
 
     /**
--- a/src/share/classes/com/sun/crypto/provider/DHKeyFactory.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/crypto/provider/DHKeyFactory.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -83,7 +83,7 @@
             }
         } catch (InvalidKeyException e) {
             throw new InvalidKeySpecException
-                ("Inappropriate key specification");
+                ("Inappropriate key specification", e);
         }
     }
 
@@ -118,7 +118,7 @@
             }
         } catch (InvalidKeyException e) {
             throw new InvalidKeySpecException
-                ("Inappropriate key specification");
+                ("Inappropriate key specification", e);
         }
     }
 
@@ -227,7 +227,7 @@
             }
 
         } catch (InvalidKeySpecException e) {
-            throw new InvalidKeyException("Cannot translate key");
+            throw new InvalidKeyException("Cannot translate key", e);
         }
     }
 }
--- a/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java	Mon Jul 22 17:37:15 2013 -0700
@@ -167,15 +167,16 @@
         BigInteger pMinus2 = p.subtract(BigInteger.valueOf(2));
 
         //
-        // Handbook of Applied Cryptography:  Menezes, et.al.
-        // Repeat if the following does not hold:
-        //     1 <= x <= p-2
+        // PKCS#3 section 7.1 "Private-value generation"
+        // Repeat if either of the followings does not hold:
+        //     0 < x < p-1
+        //     2^(lSize-1) <= x < 2^(lSize)
         //
         do {
             // generate random x up to 2^lSize bits long
             x = new BigInteger(lSize, random);
         } while ((x.compareTo(BigInteger.ONE) < 0) ||
-            ((x.compareTo(pMinus2) > 0)));
+            ((x.compareTo(pMinus2) > 0)) || (x.bitLength() != lSize));
 
         // calculate public value y
         BigInteger y = g.modPow(x, p);
--- a/src/share/classes/com/sun/crypto/provider/DHPrivateKey.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/crypto/provider/DHPrivateKey.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,7 @@
 package com.sun.crypto.provider;
 
 import java.io.*;
+import java.util.Objects;
 import java.math.BigInteger;
 import java.security.KeyRep;
 import java.security.PrivateKey;
@@ -67,7 +68,7 @@
     // the base generator
     private BigInteger g;
 
-    // the private-value length
+    // the private-value length (optional)
     private int l;
 
     private int DH_data[] = { 1, 2, 840, 113549, 1, 3, 1 };
@@ -179,20 +180,9 @@
             this.key = val.data.getOctetString();
             parseKeyBits();
 
-            // ignore OPTIONAL attributes
-
             this.encodedKey = encodedKey.clone();
-
-        } catch (NumberFormatException e) {
-            InvalidKeyException ike = new InvalidKeyException(
-                "Private-value length too big");
-            ike.initCause(e);
-            throw ike;
-        } catch (IOException e) {
-            InvalidKeyException ike = new InvalidKeyException(
-                "Error parsing key encoding: " + e.getMessage());
-            ike.initCause(e);
-            throw ike;
+        } catch (IOException | NumberFormatException e) {
+            throw new InvalidKeyException("Error parsing key encoding", e);
         }
     }
 
@@ -234,8 +224,9 @@
                 DerOutputStream params = new DerOutputStream();
                 params.putInteger(this.p);
                 params.putInteger(this.g);
-                if (this.l != 0)
+                if (this.l != 0) {
                     params.putInteger(this.l);
+                }
                 // wrap parameters into SEQUENCE
                 DerValue paramSequence = new DerValue(DerValue.tag_Sequence,
                                                       params.toByteArray());
@@ -273,10 +264,11 @@
      * @return the key parameters
      */
     public DHParameterSpec getParams() {
-        if (this.l != 0)
+        if (this.l != 0) {
             return new DHParameterSpec(this.p, this.g, this.l);
-        else
+        } else {
             return new DHParameterSpec(this.p, this.g);
+        }
     }
 
     public String toString() {
@@ -312,26 +304,21 @@
      * Objects that are equal will also have the same hashcode.
      */
     public int hashCode() {
-        int retval = 0;
-        byte[] enc = getEncoded();
-
-        for (int i = 1; i < enc.length; i++) {
-            retval += enc[i] * i;
-        }
-        return(retval);
+        return Objects.hash(x, p, g);
     }
 
     public boolean equals(Object obj) {
-        if (this == obj)
-            return true;
+        if (this == obj) return true;
 
-        if (!(obj instanceof PrivateKey))
+        if (!(obj instanceof javax.crypto.interfaces.DHPrivateKey)) {
             return false;
-
-        byte[] thisEncoded = this.getEncoded();
-        byte[] thatEncoded = ((PrivateKey)obj).getEncoded();
-
-        return java.util.Arrays.equals(thisEncoded, thatEncoded);
+        }
+        javax.crypto.interfaces.DHPrivateKey other =
+                (javax.crypto.interfaces.DHPrivateKey) obj;
+        DHParameterSpec otherParams = other.getParams();
+        return ((this.x.compareTo(other.getX()) == 0) &&
+                (this.p.compareTo(otherParams.getP()) == 0) &&
+                (this.g.compareTo(otherParams.getG()) == 0));
     }
 
     /**
--- a/src/share/classes/com/sun/crypto/provider/DHPublicKey.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/crypto/provider/DHPublicKey.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,7 @@
 package com.sun.crypto.provider;
 
 import java.io.*;
+import java.util.Objects;
 import java.math.BigInteger;
 import java.security.KeyRep;
 import java.security.InvalidKeyException;
@@ -64,7 +65,7 @@
     // the base generator
     private BigInteger g;
 
-    // the private-value length
+    // the private-value length (optional)
     private int l;
 
     private int DH_data[] = { 1, 2, 840, 113549, 1, 3, 1 };
@@ -173,13 +174,8 @@
             }
 
             this.encodedKey = encodedKey.clone();
-
-        } catch (NumberFormatException e) {
-            throw new InvalidKeyException("Private-value length too big");
-
-        } catch (IOException e) {
-            throw new InvalidKeyException(
-                "Error parsing key encoding: " + e.toString());
+        } catch (IOException | NumberFormatException e) {
+            throw new InvalidKeyException("Error parsing key encoding", e);
         }
     }
 
@@ -212,8 +208,9 @@
                 DerOutputStream params = new DerOutputStream();
                 params.putInteger(this.p);
                 params.putInteger(this.g);
-                if (this.l != 0)
+                if (this.l != 0) {
                     params.putInteger(this.l);
+                }
                 // wrap parameters into SEQUENCE
                 DerValue paramSequence = new DerValue(DerValue.tag_Sequence,
                                                       params.toByteArray());
@@ -253,10 +250,11 @@
      * @return the key parameters
      */
     public DHParameterSpec getParams() {
-        if (this.l != 0)
+        if (this.l != 0) {
             return new DHParameterSpec(this.p, this.g, this.l);
-        else
+        } else {
             return new DHParameterSpec(this.p, this.g);
+        }
     }
 
     public String toString() {
@@ -290,26 +288,22 @@
      * Objects that are equal will also have the same hashcode.
      */
     public int hashCode() {
-        int retval = 0;
-        byte[] enc = getEncoded();
-
-        for (int i = 1; i < enc.length; i++) {
-            retval += enc[i] * i;
-        }
-        return(retval);
+        return Objects.hash(y, p, g);
     }
 
     public boolean equals(Object obj) {
-        if (this == obj)
-            return true;
+        if (this == obj) return true;
 
-        if (!(obj instanceof PublicKey))
+        if (!(obj instanceof javax.crypto.interfaces.DHPublicKey)) {
             return false;
+        }
 
-        byte[] thisEncoded = this.getEncoded();
-        byte[] thatEncoded = ((PublicKey)obj).getEncoded();
-
-        return java.util.Arrays.equals(thisEncoded, thatEncoded);
+        javax.crypto.interfaces.DHPublicKey other =
+            (javax.crypto.interfaces.DHPublicKey) obj;
+        DHParameterSpec otherParams = other.getParams();
+        return ((this.y.compareTo(other.getY()) == 0) &&
+                (this.p.compareTo(otherParams.getP()) == 0) &&
+                (this.g.compareTo(otherParams.getG()) == 0));
     }
 
     /**
--- a/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java	Mon Jul 22 17:37:15 2013 -0700
@@ -134,7 +134,7 @@
             } else {
                 try {
                     (new NativeUnpack(this)).run(in0, out);
-                } catch (UnsatisfiedLinkError ule) {
+                } catch (UnsatisfiedLinkError | NoClassDefFoundError ex) {
                     // failover to java implementation
                     (new DoUnpack()).run(in0, out);
                 }
--- a/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java	Mon Jul 22 17:37:15 2013 -0700
@@ -52,6 +52,7 @@
 import com.sun.jmx.remote.util.EnvHelp;
 import java.lang.reflect.Array;
 import java.lang.reflect.InvocationTargetException;
+import java.security.AccessController;
 import javax.management.AttributeNotFoundException;
 import javax.management.openmbean.CompositeData;
 import sun.reflect.misc.MethodUtil;
@@ -64,7 +65,11 @@
  * @since 1.5
  */
 public class Introspector {
-
+    final public static boolean ALLOW_NONPUBLIC_MBEAN;
+    static {
+        String val = AccessController.doPrivileged(new GetPropertyAction("jdk.jmx.mbeans.allowNonPublic"));
+        ALLOW_NONPUBLIC_MBEAN = Boolean.parseBoolean(val);
+    }
 
      /*
      * ------------------------------------------
@@ -223,11 +228,27 @@
         return testCompliance(baseClass, null);
     }
 
+    /**
+     * Tests the given interface class for being a compliant MXBean interface.
+     * A compliant MXBean interface is any publicly accessible interface
+     * following the {@link MXBean} conventions.
+     * @param interfaceClass An interface class to test for the MXBean compliance
+     * @throws NotCompliantMBeanException Thrown when the tested interface
+     * is not public or contradicts the {@link MXBean} conventions.
+     */
     public static void testComplianceMXBeanInterface(Class<?> interfaceClass)
             throws NotCompliantMBeanException {
         MXBeanIntrospector.getInstance().getAnalyzer(interfaceClass);
     }
 
+    /**
+     * Tests the given interface class for being a compliant MBean interface.
+     * A compliant MBean interface is any publicly accessible interface
+     * following the {@code MBean} conventions.
+     * @param interfaceClass An interface class to test for the MBean compliance
+     * @throws NotCompliantMBeanException Thrown when the tested interface
+     * is not public or contradicts the {@code MBean} conventions.
+     */
     public static void testComplianceMBeanInterface(Class<?> interfaceClass)
             throws NotCompliantMBeanException{
         StandardMBeanIntrospector.getInstance().getAnalyzer(interfaceClass);
@@ -299,18 +320,18 @@
      * not a JMX compliant Standard MBean.
      */
     public static <T> Class<? super T> getStandardMBeanInterface(Class<T> baseClass)
-    throws NotCompliantMBeanException {
-        Class<? super T> current = baseClass;
-        Class<? super T> mbeanInterface = null;
-        while (current != null) {
-            mbeanInterface =
-                findMBeanInterface(current, current.getName());
-            if (mbeanInterface != null) break;
-            current = current.getSuperclass();
-        }
-        if (mbeanInterface != null) {
-            return mbeanInterface;
-        } else {
+        throws NotCompliantMBeanException {
+            Class<? super T> current = baseClass;
+            Class<? super T> mbeanInterface = null;
+            while (current != null) {
+                mbeanInterface =
+                    findMBeanInterface(current, current.getName());
+                if (mbeanInterface != null) break;
+                current = current.getSuperclass();
+            }
+                if (mbeanInterface != null) {
+                    return mbeanInterface;
+            } else {
             final String msg =
                 "Class " + baseClass.getName() +
                 " is not a JMX compliant Standard MBean";
@@ -507,8 +528,11 @@
         }
         Class<?>[] interfaces = c.getInterfaces();
         for (int i = 0;i < interfaces.length; i++) {
-            if (interfaces[i].getName().equals(clMBeanName))
+            if (interfaces[i].getName().equals(clMBeanName) &&
+                (Modifier.isPublic(interfaces[i].getModifiers()) ||
+                 ALLOW_NONPUBLIC_MBEAN)) {
                 return Util.cast(interfaces[i]);
+            }
         }
 
         return null;
--- a/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java	Mon Jul 22 17:37:15 2013 -0700
@@ -28,6 +28,8 @@
 import static com.sun.jmx.mbeanserver.Util.*;
 
 import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.security.AccessController;
 import java.util.Arrays;
 import java.util.Comparator;
 import java.util.List;
@@ -50,7 +52,6 @@
  * @since 1.6
  */
 class MBeanAnalyzer<M> {
-
     static interface MBeanVisitor<M> {
         public void visitAttribute(String attributeName,
                 M getter,
@@ -107,6 +108,10 @@
         if (!mbeanType.isInterface()) {
             throw new NotCompliantMBeanException("Not an interface: " +
                     mbeanType.getName());
+        } else if (!Modifier.isPublic(mbeanType.getModifiers()) &&
+                   !Introspector.ALLOW_NONPUBLIC_MBEAN) {
+            throw new NotCompliantMBeanException("Interface is not public: " +
+                mbeanType.getName());
         }
 
         try {
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,82 +2,78 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.algorithms;
 
-
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-
 /**
  * The Algorithm class which stores the Algorithm URI as a string.
- *
  */
 public abstract class Algorithm extends SignatureElementProxy {
 
-   /**
-    *
-    * @param doc
-    * @param algorithmURI is the URI of the algorithm as String
-    */
-   public Algorithm(Document doc, String algorithmURI) {
+    /**
+     *
+     * @param doc
+     * @param algorithmURI is the URI of the algorithm as String
+     */
+    public Algorithm(Document doc, String algorithmURI) {
+        super(doc);
+
+        this.setAlgorithmURI(algorithmURI);
+    }
 
-      super(doc);
-
-      this.setAlgorithmURI(algorithmURI);
-   }
+    /**
+     * Constructor Algorithm
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public Algorithm(Element element, String BaseURI) throws XMLSecurityException {
+        super(element, BaseURI);
+    }
 
-   /**
-    * Constructor Algorithm
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public Algorithm(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
-   }
+    /**
+     * Method getAlgorithmURI
+     *
+     * @return The URI of the algorithm
+     */
+    public String getAlgorithmURI() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
+    }
 
-   /**
-    * Method getAlgorithmURI
-    *
-    * @return The URI of the alogrithm
-    */
-   public String getAlgorithmURI() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
-   }
-
-   /**
-    * Sets the algorithm's URI as used in the signature.
-    *
-    * @param algorithmURI is the URI of the algorithm as String
-    */
-   protected void setAlgorithmURI(String algorithmURI) {
-
-      if ( (algorithmURI != null)) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM,
-                                                algorithmURI);
-      }
-   }
+    /**
+     * Sets the algorithm's URI as used in the signature.
+     *
+     * @param algorithmURI is the URI of the algorithm as String
+     */
+    protected void setAlgorithmURI(String algorithmURI) {
+        if (algorithmURI != null) {
+            this.constructionElement.setAttributeNS(
+                null, Constants._ATT_ALGORITHM, algorithmURI
+            );
+        }
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java	Mon Jul 22 17:37:15 2013 -0700
@@ -115,6 +115,18 @@
             new Algorithm("", "SHA1withECDSA", "Signature")
         );
         algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256,
+            new Algorithm("", "SHA256withECDSA", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384,
+            new Algorithm("", "SHA384withECDSA", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512,
+            new Algorithm("", "SHA512withECDSA", "Signature")
+        );
+        algorithmsMap.put(
             XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5,
             new Algorithm("", "HmacMD5", "Mac")
         );
@@ -155,6 +167,18 @@
             new Algorithm("AES", "AES/CBC/ISO10126Padding", "BlockEncryption", 256)
         );
         algorithmsMap.put(
+            XMLCipher.AES_128_GCM,
+            new Algorithm("AES", "AES/GCM/NoPadding", "BlockEncryption", 128)
+        );
+        algorithmsMap.put(
+            XMLCipher.AES_192_GCM,
+            new Algorithm("AES", "AES/GCM/NoPadding", "BlockEncryption", 192)
+        );
+        algorithmsMap.put(
+            XMLCipher.AES_256_GCM,
+            new Algorithm("AES", "AES/GCM/NoPadding", "BlockEncryption", 256)
+        );
+        algorithmsMap.put(
             XMLCipher.RSA_v1dot5,
             new Algorithm("RSA", "RSA/ECB/PKCS1Padding", "KeyTransport")
         );
@@ -163,6 +187,10 @@
             new Algorithm("RSA", "RSA/ECB/OAEPPadding", "KeyTransport")
         );
         algorithmsMap.put(
+            XMLCipher.RSA_OAEP_11,
+            new Algorithm("RSA", "RSA/ECB/OAEPPadding", "KeyTransport")
+        );
+        algorithmsMap.put(
             XMLCipher.DIFFIE_HELLMAN,
             new Algorithm("", "", "KeyAgreement")
         );
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,265 +2,254 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.algorithms;
 
 import java.security.MessageDigest;
 import java.security.NoSuchProviderException;
-import java.util.HashMap;
-import java.util.Map;
 
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants;
 import org.w3c.dom.Document;
 
-
 /**
  * Digest Message wrapper & selector class.
  *
  * <pre>
  * MessageDigestAlgorithm.getInstance()
  * </pre>
- *
  */
 public class MessageDigestAlgorithm extends Algorithm {
 
     /** Message Digest - NOT RECOMMENDED MD5*/
-   public static final String ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5 = Constants.MoreAlgorithmsSpecNS + "md5";
-   /** Digest - Required SHA1*/
-   public static final String ALGO_ID_DIGEST_SHA1 = Constants.SignatureSpecNS + "sha1";
-   /** Message Digest - RECOMMENDED SHA256*/
-   public static final String ALGO_ID_DIGEST_SHA256 = EncryptionConstants.EncryptionSpecNS + "sha256";
-   /** Message Digest - OPTIONAL SHA384*/
-   public static final String ALGO_ID_DIGEST_SHA384 = Constants.MoreAlgorithmsSpecNS + "sha384";
-   /** Message Digest - OPTIONAL SHA512*/
-   public static final String ALGO_ID_DIGEST_SHA512 = EncryptionConstants.EncryptionSpecNS + "sha512";
-   /** Message Digest - OPTIONAL RIPEMD-160*/
-   public static final String ALGO_ID_DIGEST_RIPEMD160 = EncryptionConstants.EncryptionSpecNS + "ripemd160";
+    public static final String ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5 =
+        Constants.MoreAlgorithmsSpecNS + "md5";
+    /** Digest - Required SHA1*/
+    public static final String ALGO_ID_DIGEST_SHA1 = Constants.SignatureSpecNS + "sha1";
+    /** Message Digest - RECOMMENDED SHA256*/
+    public static final String ALGO_ID_DIGEST_SHA256 =
+        EncryptionConstants.EncryptionSpecNS + "sha256";
+    /** Message Digest - OPTIONAL SHA384*/
+    public static final String ALGO_ID_DIGEST_SHA384 =
+        Constants.MoreAlgorithmsSpecNS + "sha384";
+    /** Message Digest - OPTIONAL SHA512*/
+    public static final String ALGO_ID_DIGEST_SHA512 =
+        EncryptionConstants.EncryptionSpecNS + "sha512";
+    /** Message Digest - OPTIONAL RIPEMD-160*/
+    public static final String ALGO_ID_DIGEST_RIPEMD160 =
+        EncryptionConstants.EncryptionSpecNS + "ripemd160";
 
-   /** Field algorithm stores the actual {@link java.security.MessageDigest} */
-   java.security.MessageDigest algorithm = null;
-
-   /**
-    * Constructor for the brave who pass their own message digest algorithms and the corresponding URI.
-    * @param doc
-    * @param messageDigest
-    * @param algorithmURI
-    */
-   private MessageDigestAlgorithm(Document doc, MessageDigest messageDigest,
-                                  String algorithmURI) {
+    /** Field algorithm stores the actual {@link java.security.MessageDigest} */
+    private final MessageDigest algorithm;
 
-      super(doc, algorithmURI);
-
-      this.algorithm = messageDigest;
-   }
+    /**
+     * Constructor for the brave who pass their own message digest algorithms and the
+     * corresponding URI.
+     * @param doc
+     * @param algorithmURI
+     */
+    private MessageDigestAlgorithm(Document doc, String algorithmURI)
+        throws XMLSignatureException {
+        super(doc, algorithmURI);
 
-   static ThreadLocal<Map<String, MessageDigest>> instances=new
-       ThreadLocal<Map<String, MessageDigest>>() {
-           protected Map<String, MessageDigest> initialValue() {
-               return new HashMap<String, MessageDigest>();
-           };
-   };
+        algorithm = getDigestInstance(algorithmURI);
+    }
 
-   /**
-    * Factory method for constructing a message digest algorithm by name.
-    *
-    * @param doc
-    * @param algorithmURI
-    * @return The MessageDigestAlgorithm element to attach in document and to digest
-    * @throws XMLSignatureException
-    */
-   public static MessageDigestAlgorithm getInstance(
-           Document doc, String algorithmURI) throws XMLSignatureException {
-          MessageDigest md = getDigestInstance(algorithmURI);
-      return new MessageDigestAlgorithm(doc, md, algorithmURI);
-   }
+    /**
+     * Factory method for constructing a message digest algorithm by name.
+     *
+     * @param doc
+     * @param algorithmURI
+     * @return The MessageDigestAlgorithm element to attach in document and to digest
+     * @throws XMLSignatureException
+     */
+    public static MessageDigestAlgorithm getInstance(
+        Document doc, String algorithmURI
+    ) throws XMLSignatureException {
+        return new MessageDigestAlgorithm(doc, algorithmURI);
+    }
+
+    private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException {
+        String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI);
 
-private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException {
-        MessageDigest result= instances.get().get(algorithmURI);
-        if (result!=null)
-                return result;
-    String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI);
-
-          if (algorithmID == null) {
-                  Object[] exArgs = { algorithmURI };
-                  throw new XMLSignatureException("algorithms.NoSuchMap", exArgs);
-          }
+        if (algorithmID == null) {
+            Object[] exArgs = { algorithmURI };
+            throw new XMLSignatureException("algorithms.NoSuchMap", exArgs);
+        }
 
-      MessageDigest md;
-      String provider=JCEMapper.getProviderId();
-      try {
-         if (provider==null) {
+        MessageDigest md;
+        String provider = JCEMapper.getProviderId();
+        try {
+            if (provider == null) {
                 md = MessageDigest.getInstance(algorithmID);
-         } else {
-                md = MessageDigest.getInstance(algorithmID,provider);
-         }
-      } catch (java.security.NoSuchAlgorithmException ex) {
-         Object[] exArgs = { algorithmID,
-                             ex.getLocalizedMessage() };
+            } else {
+                md = MessageDigest.getInstance(algorithmID, provider);
+            }
+        } catch (java.security.NoSuchAlgorithmException ex) {
+            Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
+
+            throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
+        } catch (NoSuchProviderException ex) {
+            Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
+
+            throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
+        }
+
+        return md;
+    }
 
-         throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
-      } catch (NoSuchProviderException ex) {
-        Object[] exArgs = { algorithmID,
-                                                ex.getLocalizedMessage() };
-
-        throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
-        }
-        instances.get().put(algorithmURI, md);
-        return md;
-}
+    /**
+     * Returns the actual {@link java.security.MessageDigest} algorithm object
+     *
+     * @return the actual {@link java.security.MessageDigest} algorithm object
+     */
+    public java.security.MessageDigest getAlgorithm() {
+        return algorithm;
+    }
 
-   /**
-    * Returns the actual {@link java.security.MessageDigest} algorithm object
-    *
-    * @return the actual {@link java.security.MessageDigest} algorithm object
-    */
-   public java.security.MessageDigest getAlgorithm() {
-      return this.algorithm;
-   }
+    /**
+     * Proxy method for {@link java.security.MessageDigest#isEqual}
+     * which is executed on the internal {@link java.security.MessageDigest} object.
+     *
+     * @param digesta
+     * @param digestb
+     * @return the result of the {@link java.security.MessageDigest#isEqual} method
+     */
+    public static boolean isEqual(byte[] digesta, byte[] digestb) {
+        return java.security.MessageDigest.isEqual(digesta, digestb);
+    }
 
-   /**
-    * Proxy method for {@link java.security.MessageDigest#isEqual}
-    * which is executed on the internal {@link java.security.MessageDigest} object.
-    *
-    * @param digesta
-    * @param digestb
-    * @return the result of the {@link java.security.MessageDigest#isEqual} method
-    */
-   public static boolean isEqual(byte[] digesta, byte[] digestb) {
-      return java.security.MessageDigest.isEqual(digesta, digestb);
-   }
+    /**
+     * Proxy method for {@link java.security.MessageDigest#digest()}
+     * which is executed on the internal {@link java.security.MessageDigest} object.
+     *
+     * @return the result of the {@link java.security.MessageDigest#digest()} method
+     */
+    public byte[] digest() {
+        return algorithm.digest();
+    }
 
-   /**
-    * Proxy method for {@link java.security.MessageDigest#digest()}
-    * which is executed on the internal {@link java.security.MessageDigest} object.
-    *
-    * @return the result of the {@link java.security.MessageDigest#digest()} method
-    */
-   public byte[] digest() {
-      return this.algorithm.digest();
-   }
-
-   /**
-    * Proxy method for {@link java.security.MessageDigest#digest(byte[])}
-    * which is executed on the internal {@link java.security.MessageDigest} object.
-    *
-    * @param input
-    * @return the result of the {@link java.security.MessageDigest#digest(byte[])} method
-    */
-   public byte[] digest(byte input[]) {
-      return this.algorithm.digest(input);
-   }
+    /**
+     * Proxy method for {@link java.security.MessageDigest#digest(byte[])}
+     * which is executed on the internal {@link java.security.MessageDigest} object.
+     *
+     * @param input
+     * @return the result of the {@link java.security.MessageDigest#digest(byte[])} method
+     */
+    public byte[] digest(byte input[]) {
+        return algorithm.digest(input);
+    }
 
-   /**
-    * Proxy method for {@link java.security.MessageDigest#digest(byte[], int, int)}
-    * which is executed on the internal {@link java.security.MessageDigest} object.
-    *
-    * @param buf
-    * @param offset
-    * @param len
-    * @return the result of the {@link java.security.MessageDigest#digest(byte[], int, int)} method
-    * @throws java.security.DigestException
-    */
-   public int digest(byte buf[], int offset, int len)
-           throws java.security.DigestException {
-      return this.algorithm.digest(buf, offset, len);
-   }
+    /**
+     * Proxy method for {@link java.security.MessageDigest#digest(byte[], int, int)}
+     * which is executed on the internal {@link java.security.MessageDigest} object.
+     *
+     * @param buf
+     * @param offset
+     * @param len
+     * @return the result of the {@link java.security.MessageDigest#digest(byte[], int, int)} method
+     * @throws java.security.DigestException
+     */
+    public int digest(byte buf[], int offset, int len) throws java.security.DigestException {
+        return algorithm.digest(buf, offset, len);
+    }
 
-   /**
-    * Proxy method for {@link java.security.MessageDigest#getAlgorithm}
-    * which is executed on the internal {@link java.security.MessageDigest} object.
-    *
-    * @return the result of the {@link java.security.MessageDigest#getAlgorithm} method
-    */
-   public String getJCEAlgorithmString() {
-      return this.algorithm.getAlgorithm();
-   }
+    /**
+     * Proxy method for {@link java.security.MessageDigest#getAlgorithm}
+     * which is executed on the internal {@link java.security.MessageDigest} object.
+     *
+     * @return the result of the {@link java.security.MessageDigest#getAlgorithm} method
+     */
+    public String getJCEAlgorithmString() {
+        return algorithm.getAlgorithm();
+    }
 
-   /**
-    * Proxy method for {@link java.security.MessageDigest#getProvider}
-    * which is executed on the internal {@link java.security.MessageDigest} object.
-    *
-    * @return the result of the {@link java.security.MessageDigest#getProvider} method
-    */
-   public java.security.Provider getJCEProvider() {
-      return this.algorithm.getProvider();
-   }
+    /**
+     * Proxy method for {@link java.security.MessageDigest#getProvider}
+     * which is executed on the internal {@link java.security.MessageDigest} object.
+     *
+     * @return the result of the {@link java.security.MessageDigest#getProvider} method
+     */
+    public java.security.Provider getJCEProvider() {
+        return algorithm.getProvider();
+    }
 
-   /**
-    * Proxy method for {@link java.security.MessageDigest#getDigestLength}
-    * which is executed on the internal {@link java.security.MessageDigest} object.
-    *
-    * @return the result of the {@link java.security.MessageDigest#getDigestLength} method
-    */
-   public int getDigestLength() {
-      return this.algorithm.getDigestLength();
-   }
+    /**
+     * Proxy method for {@link java.security.MessageDigest#getDigestLength}
+     * which is executed on the internal {@link java.security.MessageDigest} object.
+     *
+     * @return the result of the {@link java.security.MessageDigest#getDigestLength} method
+     */
+    public int getDigestLength() {
+        return algorithm.getDigestLength();
+    }
 
-   /**
-    * Proxy method for {@link java.security.MessageDigest#reset}
-    * which is executed on the internal {@link java.security.MessageDigest} object.
-    *
-    */
-   public void reset() {
-      this.algorithm.reset();
-   }
+    /**
+     * Proxy method for {@link java.security.MessageDigest#reset}
+     * which is executed on the internal {@link java.security.MessageDigest} object.
+     *
+     */
+    public void reset() {
+        algorithm.reset();
+    }
 
-   /**
-    * Proxy method for {@link java.security.MessageDigest#update(byte[])}
-    * which is executed on the internal {@link java.security.MessageDigest} object.
-    *
-    * @param input
-    */
-   public void update(byte[] input) {
-      this.algorithm.update(input);
-   }
+    /**
+     * Proxy method for {@link java.security.MessageDigest#update(byte[])}
+     * which is executed on the internal {@link java.security.MessageDigest} object.
+     *
+     * @param input
+     */
+    public void update(byte[] input) {
+        algorithm.update(input);
+    }
 
-   /**
-    * Proxy method for {@link java.security.MessageDigest#update(byte)}
-    * which is executed on the internal {@link java.security.MessageDigest} object.
-    *
-    * @param input
-    */
-   public void update(byte input) {
-      this.algorithm.update(input);
-   }
+    /**
+     * Proxy method for {@link java.security.MessageDigest#update(byte)}
+     * which is executed on the internal {@link java.security.MessageDigest} object.
+     *
+     * @param input
+     */
+    public void update(byte input) {
+        algorithm.update(input);
+    }
 
-   /**
-    * Proxy method for {@link java.security.MessageDigest#update(byte[], int, int)}
-    * which is executed on the internal {@link java.security.MessageDigest} object.
-    *
-    * @param buf
-    * @param offset
-    * @param len
-    */
-   public void update(byte buf[], int offset, int len) {
-      this.algorithm.update(buf, offset, len);
-   }
+    /**
+     * Proxy method for {@link java.security.MessageDigest#update(byte[], int, int)}
+     * which is executed on the internal {@link java.security.MessageDigest} object.
+     *
+     * @param buf
+     * @param offset
+     * @param len
+     */
+    public void update(byte buf[], int offset, int len) {
+        algorithm.update(buf, offset, len);
+    }
 
-   /** @inheritDoc */
-   public String getBaseNamespace() {
-      return Constants.SignatureSpecNS;
-   }
+    /** @inheritDoc */
+    public String getBaseNamespace() {
+        return Constants.SignatureSpecNS;
+    }
 
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_DIGESTMETHOD;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_DIGESTMETHOD;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java	Mon Jul 22 17:37:15 2013 -0700
@@ -74,7 +74,7 @@
         this.algorithmURI = algorithmURI;
 
         signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
-        signatureAlgorithm.engineGetContextFromElement(this._constructionElement);
+        signatureAlgorithm.engineGetContextFromElement(this.constructionElement);
     }
 
     /**
@@ -92,10 +92,10 @@
         this.algorithmURI = algorithmURI;
 
         signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
-        signatureAlgorithm.engineGetContextFromElement(this._constructionElement);
+        signatureAlgorithm.engineGetContextFromElement(this.constructionElement);
 
         signatureAlgorithm.engineSetHMACOutputLength(hmacOutputLength);
-        ((IntegrityHmac)signatureAlgorithm).engineAddContextToElement(_constructionElement);
+        ((IntegrityHmac)signatureAlgorithm).engineAddContextToElement(constructionElement);
     }
 
     /**
@@ -136,7 +136,7 @@
         }
 
         signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
-        signatureAlgorithm.engineGetContextFromElement(this._constructionElement);
+        signatureAlgorithm.engineGetContextFromElement(this.constructionElement);
     }
 
     /**
@@ -310,7 +310,7 @@
      * @return the URI representation of Transformation algorithm
      */
     public final String getURI() {
-        return _constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
+        return constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
     }
 
     /**
@@ -380,9 +380,7 @@
      * This method registers the default algorithms.
      */
     public static void registerDefaultAlgorithms() {
-        algorithmHash.put(
-            XMLSignature.ALGO_ID_SIGNATURE_DSA, SignatureDSA.class
-        );
+        algorithmHash.put(SignatureDSA.URI, SignatureDSA.class);
         algorithmHash.put(
             XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, SignatureBaseRSA.SignatureRSASHA1.class
         );
@@ -410,6 +408,15 @@
             XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1, SignatureECDSA.SignatureECDSASHA1.class
         );
         algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256, SignatureECDSA.SignatureECDSASHA256.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384, SignatureECDSA.SignatureECDSASHA384.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512, SignatureECDSA.SignatureECDSASHA512.class
+        );
+        algorithmHash.put(
             XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5, IntegrityHmac.IntegrityHmacMD5.class
         );
         algorithmHash.put(
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.algorithms;
 
@@ -27,157 +29,149 @@
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
 import org.w3c.dom.Element;
 
-
-/**
- *
- * @author $Author: mullan $
- */
 public abstract class SignatureAlgorithmSpi {
 
-   /**
-    * Returns the URI representation of <code>Transformation algorithm</code>
-    *
-    * @return the URI representation of <code>Transformation algorithm</code>
-    */
-   protected abstract String engineGetURI();
+    /**
+     * Returns the URI representation of <code>Transformation algorithm</code>
+     *
+     * @return the URI representation of <code>Transformation algorithm</code>
+     */
+    protected abstract String engineGetURI();
 
-   /**
-    * Proxy method for {@link java.security.Signature#getAlgorithm}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @return the result of the {@link java.security.Signature#getAlgorithm} method
-    */
-   protected abstract String engineGetJCEAlgorithmString();
+    /**
+     * Proxy method for {@link java.security.Signature#getAlgorithm}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @return the result of the {@link java.security.Signature#getAlgorithm} method
+     */
+    protected abstract String engineGetJCEAlgorithmString();
 
-   /**
-    * Method engineGetJCEProviderName
-    *
-    * @return the JCE ProviderName
-    */
-   protected abstract String engineGetJCEProviderName();
+    /**
+     * Method engineGetJCEProviderName
+     *
+     * @return the JCE ProviderName
+     */
+    protected abstract String engineGetJCEProviderName();
 
-   /**
-    * Proxy method for {@link java.security.Signature#update(byte[])}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param input
-    * @throws XMLSignatureException
-    */
-   protected abstract void engineUpdate(byte[] input)
-      throws XMLSignatureException;
+    /**
+     * Proxy method for {@link java.security.Signature#update(byte[])}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param input
+     * @throws XMLSignatureException
+     */
+    protected abstract void engineUpdate(byte[] input) throws XMLSignatureException;
+
+    /**
+     * Proxy method for {@link java.security.Signature#update(byte[])}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param input
+     * @throws XMLSignatureException
+     */
+    protected abstract void engineUpdate(byte input) throws XMLSignatureException;
 
-   /**
-    * Proxy method for {@link java.security.Signature#update(byte[])}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param input
-    * @throws XMLSignatureException
-    */
-   protected abstract void engineUpdate(byte input)
-      throws XMLSignatureException;
+    /**
+     * Proxy method for {@link java.security.Signature#update(byte[], int, int)}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param buf
+     * @param offset
+     * @param len
+     * @throws XMLSignatureException
+     */
+    protected abstract void engineUpdate(byte buf[], int offset, int len)
+        throws XMLSignatureException;
 
-   /**
-    * Proxy method for {@link java.security.Signature#update(byte[], int, int)}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param buf
-    * @param offset
-    * @param len
-    * @throws XMLSignatureException
-    */
-   protected abstract void engineUpdate(byte buf[], int offset, int len)
-      throws XMLSignatureException;
+    /**
+     * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param signingKey
+     * @throws XMLSignatureException if this method is called on a MAC
+     */
+    protected abstract void engineInitSign(Key signingKey) throws XMLSignatureException;
 
-   /**
-    * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param signingKey
-    * @throws XMLSignatureException if this method is called on a MAC
-    */
-   protected abstract void engineInitSign(Key signingKey)
-      throws XMLSignatureException;
+    /**
+     * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey,
+     * java.security.SecureRandom)}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param signingKey
+     * @param secureRandom
+     * @throws XMLSignatureException if this method is called on a MAC
+     */
+    protected abstract void engineInitSign(Key signingKey, SecureRandom secureRandom)
+        throws XMLSignatureException;
 
-   /**
-    * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey, java.security.SecureRandom)}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param signingKey
-    * @param secureRandom
-    * @throws XMLSignatureException if this method is called on a MAC
-    */
-   protected abstract void engineInitSign(
-      Key signingKey, SecureRandom secureRandom) throws XMLSignatureException;
-
-   /**
-    * Proxy method for {@link javax.crypto.Mac}
-    * which is executed on the internal {@link javax.crypto.Mac#init(Key)} object.
-    *
-    * @param signingKey
-    * @param algorithmParameterSpec
-    * @throws XMLSignatureException if this method is called on a Signature
-    */
-   protected abstract void engineInitSign(
-      Key signingKey, AlgorithmParameterSpec algorithmParameterSpec)
-         throws XMLSignatureException;
+    /**
+     * Proxy method for {@link javax.crypto.Mac}
+     * which is executed on the internal {@link javax.crypto.Mac#init(Key)} object.
+     *
+     * @param signingKey
+     * @param algorithmParameterSpec
+     * @throws XMLSignatureException if this method is called on a Signature
+     */
+    protected abstract void engineInitSign(
+        Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
+    ) throws XMLSignatureException;
 
-   /**
-    * Proxy method for {@link java.security.Signature#sign()}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @return the result of the {@link java.security.Signature#sign()} method
-    * @throws XMLSignatureException
-    */
-   protected abstract byte[] engineSign() throws XMLSignatureException;
+    /**
+     * Proxy method for {@link java.security.Signature#sign()}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @return the result of the {@link java.security.Signature#sign()} method
+     * @throws XMLSignatureException
+     */
+    protected abstract byte[] engineSign() throws XMLSignatureException;
 
-   /**
-    * Method engineInitVerify
-    *
-    * @param verificationKey
-    * @throws XMLSignatureException
-    */
-   protected abstract void engineInitVerify(Key verificationKey)
-      throws XMLSignatureException;
+    /**
+     * Method engineInitVerify
+     *
+     * @param verificationKey
+     * @throws XMLSignatureException
+     */
+    protected abstract void engineInitVerify(Key verificationKey) throws XMLSignatureException;
 
-   /**
-    * Proxy method for {@link java.security.Signature#verify(byte[])}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param signature
-    * @return true if the signature is correct
-    * @throws XMLSignatureException
-    */
-   protected abstract boolean engineVerify(byte[] signature)
-      throws XMLSignatureException;
+    /**
+     * Proxy method for {@link java.security.Signature#verify(byte[])}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param signature
+     * @return true if the signature is correct
+     * @throws XMLSignatureException
+     */
+    protected abstract boolean engineVerify(byte[] signature) throws XMLSignatureException;
 
-   /**
-    * Proxy method for {@link java.security.Signature#setParameter(java.security.spec.AlgorithmParameterSpec)}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param params
-    * @throws XMLSignatureException
-    */
-   protected abstract void engineSetParameter(AlgorithmParameterSpec params)
-      throws XMLSignatureException;
+    /**
+     * Proxy method for {@link java.security.Signature#setParameter(
+     * java.security.spec.AlgorithmParameterSpec)}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param params
+     * @throws XMLSignatureException
+     */
+    protected abstract void engineSetParameter(AlgorithmParameterSpec params)
+        throws XMLSignatureException;
 
 
-   /**
-    * Method engineGetContextFromElement
-    *
-    * @param element
-    */
-   protected void engineGetContextFromElement(Element element) {
-   }
+    /**
+     * Method engineGetContextFromElement
+     *
+     * @param element
+     */
+    protected void engineGetContextFromElement(Element element) {
+    }
 
-   /**
-    * Method engineSetHMACOutputLength
-    *
-    * @param HMACOutputLength
-    * @throws XMLSignatureException
-    */
-   protected abstract void engineSetHMACOutputLength(int HMACOutputLength)
-      throws XMLSignatureException;
+    /**
+     * Method engineSetHMACOutputLength
+     *
+     * @param HMACOutputLength
+     * @throws XMLSignatureException
+     */
+    protected abstract void engineSetHMACOutputLength(int HMACOutputLength)
+        throws XMLSignatureException;
 
     public void reset() {
-        }
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.algorithms.implementations;
 
-
-
 import java.security.InvalidAlgorithmParameterException;
 import java.security.InvalidKeyException;
 import java.security.Key;
@@ -42,570 +42,498 @@
 import org.w3c.dom.Element;
 import org.w3c.dom.Text;
 
-
-/**
- *
- * @author $Author: mullan $
- */
 public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(IntegrityHmacSHA1.class.getName());
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(IntegrityHmac.class.getName());
+
+    /** Field macAlgorithm */
+    private Mac macAlgorithm = null;
 
-   /**
-    * Method engineGetURI
-    *
-    *@inheritDoc
-    */
-   public abstract String engineGetURI();
+    /** Field HMACOutputLength */
+    private int HMACOutputLength = 0;
+    private boolean HMACOutputLengthSet = false;
 
-   /**
-    * Returns the output length of the hash/digest.
-    */
-   abstract int getDigestLength();
-
-   /** Field _macAlgorithm */
-   private Mac _macAlgorithm = null;
-   private boolean _HMACOutputLengthSet = false;
+    /**
+     * Method engineGetURI
+     *
+     *@inheritDoc
+     */
+    public abstract String engineGetURI();
 
-   /** Field _HMACOutputLength */
-   int _HMACOutputLength = 0;
-
-   /**
-    * Method IntegrityHmacSHA1das
-    *
-    * @throws XMLSignatureException
-    */
-   public IntegrityHmac() throws XMLSignatureException {
+    /**
+     * Returns the output length of the hash/digest.
+     */
+    abstract int getDigestLength();
 
-      String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
-      if (log.isLoggable(java.util.logging.Level.FINE))
-        log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID);
+    /**
+     * Method IntegrityHmac
+     *
+     * @throws XMLSignatureException
+     */
+    public IntegrityHmac() throws XMLSignatureException {
+        String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID);
+        }
 
-      try {
-         this._macAlgorithm = Mac.getInstance(algorithmID);
-      } catch (java.security.NoSuchAlgorithmException ex) {
-         Object[] exArgs = { algorithmID,
-                             ex.getLocalizedMessage() };
+        try {
+            this.macAlgorithm = Mac.getInstance(algorithmID);
+        } catch (java.security.NoSuchAlgorithmException ex) {
+            Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
 
-         throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
-      }
-   }
+            throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
+        }
+    }
 
-   /**
-    * Proxy method for {@link java.security.Signature#setParameter(java.security.spec.AlgorithmParameterSpec)}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param params
-    * @throws XMLSignatureException
-    */
-   protected void engineSetParameter(AlgorithmParameterSpec params)
-           throws XMLSignatureException {
-      throw new XMLSignatureException("empty");
-   }
+    /**
+     * Proxy method for {@link java.security.Signature#setParameter(
+     * java.security.spec.AlgorithmParameterSpec)}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param params
+     * @throws XMLSignatureException
+     */
+    protected void engineSetParameter(AlgorithmParameterSpec params) throws XMLSignatureException {
+        throw new XMLSignatureException("empty");
+    }
 
-   public void reset() {
-       _HMACOutputLength=0;
-       _HMACOutputLengthSet = false;
-       _macAlgorithm.reset();
-   }
-
-   /**
-    * Proxy method for {@link java.security.Signature#verify(byte[])}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param signature
-    * @return true if the signature is correct
-    * @throws XMLSignatureException
-    */
-   protected boolean engineVerify(byte[] signature)
-           throws XMLSignatureException {
+    public void reset() {
+        HMACOutputLength = 0;
+        HMACOutputLengthSet = false;
+        this.macAlgorithm.reset();
+    }
 
-      try {
-         if (this._HMACOutputLengthSet && this._HMACOutputLength < getDigestLength()) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE,
-                    "HMACOutputLength must not be less than " + getDigestLength());
+    /**
+     * Proxy method for {@link java.security.Signature#verify(byte[])}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param signature
+     * @return true if the signature is correct
+     * @throws XMLSignatureException
+     */
+    protected boolean engineVerify(byte[] signature) throws XMLSignatureException {
+        try {
+            if (this.HMACOutputLengthSet && this.HMACOutputLength < getDigestLength()) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "HMACOutputLength must not be less than " + getDigestLength());
+                }
+                Object[] exArgs = { String.valueOf(getDigestLength()) };
+                throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs);
+            } else {
+                byte[] completeResult = this.macAlgorithm.doFinal();
+                return MessageDigestAlgorithm.isEqual(completeResult, signature);
             }
-            throw new XMLSignatureException("errorMessages.XMLSignatureException");
-         } else {
-            byte[] completeResult = this._macAlgorithm.doFinal();
-            return MessageDigestAlgorithm.isEqual(completeResult, signature);
-         }
-      } catch (IllegalStateException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+        } catch (IllegalStateException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /**
-    * Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param secretKey
-    * @throws XMLSignatureException
-    */
-   protected void engineInitVerify(Key secretKey) throws XMLSignatureException {
+    /**
+     * Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param secretKey
+     * @throws XMLSignatureException
+     */
+    protected void engineInitVerify(Key secretKey) throws XMLSignatureException {
+        if (!(secretKey instanceof SecretKey)) {
+            String supplied = secretKey.getClass().getName();
+            String needed = SecretKey.class.getName();
+            Object exArgs[] = { supplied, needed };
 
-      if (!(secretKey instanceof SecretKey)) {
-         String supplied = secretKey.getClass().getName();
-         String needed = SecretKey.class.getName();
-         Object exArgs[] = { supplied, needed };
+            throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
+        }
 
-         throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
-                                         exArgs);
-      }
-
-      try {
-         this._macAlgorithm.init(secretKey);
-      } catch (InvalidKeyException ex) {
+        try {
+            this.macAlgorithm.init(secretKey);
+        } catch (InvalidKeyException ex) {
             // reinstantiate Mac object to work around bug in JDK
             // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
-            Mac mac = this._macAlgorithm;
+            Mac mac = this.macAlgorithm;
             try {
-                this._macAlgorithm = Mac.getInstance
-                    (_macAlgorithm.getAlgorithm());
+                this.macAlgorithm = Mac.getInstance(macAlgorithm.getAlgorithm());
             } catch (Exception e) {
                 // this shouldn't occur, but if it does, restore previous Mac
                 if (log.isLoggable(java.util.logging.Level.FINE)) {
                     log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Mac:" + e);
                 }
-                this._macAlgorithm = mac;
+                this.macAlgorithm = mac;
             }
             throw new XMLSignatureException("empty", ex);
-      }
-   }
+        }
+    }
 
-   /**
-    * Proxy method for {@link java.security.Signature#sign()}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @return the result of the {@link java.security.Signature#sign()} method
-    * @throws XMLSignatureException
-    */
-   protected byte[] engineSign() throws XMLSignatureException {
-
-      try {
-         if (this._HMACOutputLengthSet && this._HMACOutputLength < getDigestLength()) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE,
-                    "HMACOutputLength must not be less than " + getDigestLength());
+    /**
+     * Proxy method for {@link java.security.Signature#sign()}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @return the result of the {@link java.security.Signature#sign()} method
+     * @throws XMLSignatureException
+     */
+    protected byte[] engineSign() throws XMLSignatureException {
+        try {
+            if (this.HMACOutputLengthSet && this.HMACOutputLength < getDigestLength()) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "HMACOutputLength must not be less than " + getDigestLength());
+                }
+                Object[] exArgs = { String.valueOf(getDigestLength()) };
+                throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs);
+            } else {
+                return this.macAlgorithm.doFinal();
             }
-            throw new XMLSignatureException("errorMessages.XMLSignatureException");
-         } else {
-            return this._macAlgorithm.doFinal();
-         }
-      } catch (IllegalStateException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+        } catch (IllegalStateException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /**
-    * Method reduceBitLength
-    *
-    * @param completeResult
-    * @return the reduced bits.
-    * @param length
-    *
-    */
-   private static byte[] reduceBitLength(byte completeResult[], int length) {
+    /**
+     * Method engineInitSign
+     *
+     * @param secretKey
+     * @throws XMLSignatureException
+     */
+    protected void engineInitSign(Key secretKey) throws XMLSignatureException {
+        if (!(secretKey instanceof SecretKey)) {
+            String supplied = secretKey.getClass().getName();
+            String needed = SecretKey.class.getName();
+            Object exArgs[] = { supplied, needed };
 
-      int bytes = length / 8;
-      int abits = length % 8;
-      byte[] strippedResult = new byte[bytes + ((abits == 0)
-                                                ? 0
-                                                : 1)];
-
-      System.arraycopy(completeResult, 0, strippedResult, 0, bytes);
-
-      if (abits > 0) {
-         byte[] MASK = { (byte) 0x00, (byte) 0x80, (byte) 0xC0, (byte) 0xE0,
-                         (byte) 0xF0, (byte) 0xF8, (byte) 0xFC, (byte) 0xFE };
-
-         strippedResult[bytes] = (byte) (completeResult[bytes] & MASK[abits]);
-      }
+            throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
+        }
 
-      return strippedResult;
-   }
-
-   /**
-    * Method engineInitSign
-    *
-    * @param secretKey
-    * @throws XMLSignatureException
-    */
-   protected void engineInitSign(Key secretKey) throws XMLSignatureException {
+        try {
+            this.macAlgorithm.init(secretKey);
+        } catch (InvalidKeyException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-      if (!(secretKey instanceof SecretKey)) {
-         String supplied = secretKey.getClass().getName();
-         String needed = SecretKey.class.getName();
-         Object exArgs[] = { supplied, needed };
-
-         throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
-                                         exArgs);
-      }
-
-      try {
-         this._macAlgorithm.init(secretKey);
-      } catch (InvalidKeyException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /**
+     * Method engineInitSign
+     *
+     * @param secretKey
+     * @param algorithmParameterSpec
+     * @throws XMLSignatureException
+     */
+    protected void engineInitSign(
+        Key secretKey, AlgorithmParameterSpec algorithmParameterSpec
+    ) throws XMLSignatureException {
+        if (!(secretKey instanceof SecretKey)) {
+            String supplied = secretKey.getClass().getName();
+            String needed = SecretKey.class.getName();
+            Object exArgs[] = { supplied, needed };
 
-   /**
-    * Method engineInitSign
-    *
-    * @param secretKey
-    * @param algorithmParameterSpec
-    * @throws XMLSignatureException
-    */
-   protected void engineInitSign(
-           Key secretKey, AlgorithmParameterSpec algorithmParameterSpec)
-              throws XMLSignatureException {
+            throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
+        }
+
+        try {
+            this.macAlgorithm.init(secretKey, algorithmParameterSpec);
+        } catch (InvalidKeyException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (InvalidAlgorithmParameterException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-      if (!(secretKey instanceof SecretKey)) {
-         String supplied = secretKey.getClass().getName();
-         String needed = SecretKey.class.getName();
-         Object exArgs[] = { supplied, needed };
-
-         throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
-                                         exArgs);
-      }
-
-      try {
-         this._macAlgorithm.init(secretKey, algorithmParameterSpec);
-      } catch (InvalidKeyException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (InvalidAlgorithmParameterException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /**
+     * Method engineInitSign
+     *
+     * @param secretKey
+     * @param secureRandom
+     * @throws XMLSignatureException
+     */
+    protected void engineInitSign(Key secretKey, SecureRandom secureRandom)
+        throws XMLSignatureException {
+        throw new XMLSignatureException("algorithms.CannotUseSecureRandomOnMAC");
+    }
 
-   /**
-    * Method engineInitSign
-    *
-    * @param secretKey
-    * @param secureRandom
-    * @throws XMLSignatureException
-    */
-   protected void engineInitSign(Key secretKey, SecureRandom secureRandom)
-           throws XMLSignatureException {
-      throw new XMLSignatureException("algorithms.CannotUseSecureRandomOnMAC");
-   }
-
-   /**
-    * Proxy method for {@link java.security.Signature#update(byte[])}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param input
-    * @throws XMLSignatureException
-    */
-   protected void engineUpdate(byte[] input) throws XMLSignatureException {
+    /**
+     * Proxy method for {@link java.security.Signature#update(byte[])}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param input
+     * @throws XMLSignatureException
+     */
+    protected void engineUpdate(byte[] input) throws XMLSignatureException {
+        try {
+            this.macAlgorithm.update(input);
+        } catch (IllegalStateException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-      try {
-         this._macAlgorithm.update(input);
-      } catch (IllegalStateException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /**
+     * Proxy method for {@link java.security.Signature#update(byte)}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param input
+     * @throws XMLSignatureException
+     */
+    protected void engineUpdate(byte input) throws XMLSignatureException {
+        try {
+            this.macAlgorithm.update(input);
+        } catch (IllegalStateException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /**
-    * Proxy method for {@link java.security.Signature#update(byte)}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param input
-    * @throws XMLSignatureException
-    */
-   protected void engineUpdate(byte input) throws XMLSignatureException {
-
-      try {
-         this._macAlgorithm.update(input);
-      } catch (IllegalStateException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /**
+     * Proxy method for {@link java.security.Signature#update(byte[], int, int)}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param buf
+     * @param offset
+     * @param len
+     * @throws XMLSignatureException
+     */
+    protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException {
+        try {
+            this.macAlgorithm.update(buf, offset, len);
+        } catch (IllegalStateException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /**
-    * Proxy method for {@link java.security.Signature#update(byte[], int, int)}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param buf
-    * @param offset
-    * @param len
-    * @throws XMLSignatureException
-    */
-   protected void engineUpdate(byte buf[], int offset, int len)
-           throws XMLSignatureException {
+    /**
+     * Method engineGetJCEAlgorithmString
+     * @inheritDoc
+     *
+     */
+    protected String engineGetJCEAlgorithmString() {
+        return this.macAlgorithm.getAlgorithm();
+    }
 
-      try {
-         this._macAlgorithm.update(buf, offset, len);
-      } catch (IllegalStateException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
-
-   /**
-    * Method engineGetJCEAlgorithmString
-    * @inheritDoc
-    *
-    */
-   protected String engineGetJCEAlgorithmString() {
-
-      log.log(java.util.logging.Level.FINE, "engineGetJCEAlgorithmString()");
-
-      return this._macAlgorithm.getAlgorithm();
-   }
+    /**
+     * Method engineGetJCEAlgorithmString
+     *
+     * @inheritDoc
+     */
+    protected String engineGetJCEProviderName() {
+        return this.macAlgorithm.getProvider().getName();
+    }
 
-   /**
-    * Method engineGetJCEAlgorithmString
-    *
-    * @inheritDoc
-    */
-   protected String engineGetJCEProviderName() {
-      return this._macAlgorithm.getProvider().getName();
-   }
+    /**
+     * Method engineSetHMACOutputLength
+     *
+     * @param HMACOutputLength
+     */
+    protected void engineSetHMACOutputLength(int HMACOutputLength) {
+        this.HMACOutputLength = HMACOutputLength;
+        this.HMACOutputLengthSet = true;
+    }
 
-   /**
-    * Method engineSetHMACOutputLength
-    *
-    * @param HMACOutputLength
-    */
-   protected void engineSetHMACOutputLength(int HMACOutputLength) {
-      this._HMACOutputLength = HMACOutputLength;
-      this._HMACOutputLengthSet = true;
-   }
+    /**
+     * Method engineGetContextFromElement
+     *
+     * @param element
+     */
+    protected void engineGetContextFromElement(Element element) {
+        super.engineGetContextFromElement(element);
 
-   /**
-    * Method engineGetContextFromElement
-    *
-    * @param element
-    */
-   protected void engineGetContextFromElement(Element element) {
+        if (element == null) {
+            throw new IllegalArgumentException("element null");
+        }
 
-      super.engineGetContextFromElement(element);
+        Text hmaclength =
+            XMLUtils.selectDsNodeText(element.getFirstChild(), Constants._TAG_HMACOUTPUTLENGTH, 0);
 
-      if (element == null) {
-         throw new IllegalArgumentException("element null");
-      }
-
-      Text hmaclength =XMLUtils.selectDsNodeText(element.getFirstChild(),
-         Constants._TAG_HMACOUTPUTLENGTH,0);
+        if (hmaclength != null) {
+            this.HMACOutputLength = Integer.parseInt(hmaclength.getData());
+            this.HMACOutputLengthSet = true;
+        }
+    }
 
-      if (hmaclength != null) {
-         this._HMACOutputLength = Integer.parseInt(hmaclength.getData());
-         this._HMACOutputLengthSet = true;
-      }
-
-   }
+    /**
+     * Method engineAddContextToElement
+     *
+     * @param element
+     */
+    public void engineAddContextToElement(Element element) {
+        if (element == null) {
+            throw new IllegalArgumentException("null element");
+        }
 
-   /**
-    * Method engineAddContextToElement
-    *
-    * @param element
-    */
-   public void engineAddContextToElement(Element element) {
-
-      if (element == null) {
-         throw new IllegalArgumentException("null element");
-      }
+        if (this.HMACOutputLengthSet) {
+            Document doc = element.getOwnerDocument();
+            Element HMElem =
+                XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_HMACOUTPUTLENGTH);
+            Text HMText =
+                doc.createTextNode(Integer.valueOf(this.HMACOutputLength).toString());
 
-      if (this._HMACOutputLengthSet) {
-         Document doc = element.getOwnerDocument();
-         Element HMElem = XMLUtils.createElementInSignatureSpace(doc,
-                             Constants._TAG_HMACOUTPUTLENGTH);
-         Text HMText =
-            doc.createTextNode(new Integer(this._HMACOutputLength).toString());
+            HMElem.appendChild(HMText);
+            XMLUtils.addReturnToElement(element);
+            element.appendChild(HMElem);
+            XMLUtils.addReturnToElement(element);
+        }
+    }
 
-         HMElem.appendChild(HMText);
-         XMLUtils.addReturnToElement(element);
-         element.appendChild(HMElem);
-         XMLUtils.addReturnToElement(element);
-      }
-   }
+    /**
+     * Class IntegrityHmacSHA1
+     */
+    public static class IntegrityHmacSHA1 extends IntegrityHmac {
 
-   /**
-    * Class IntegrityHmacSHA1
-    *
-    * @author $Author: mullan $
-    * @version $Revision: 1.5 $
-    */
-   public static class IntegrityHmacSHA1 extends IntegrityHmac {
+        /**
+         * Constructor IntegrityHmacSHA1
+         *
+         * @throws XMLSignatureException
+         */
+        public IntegrityHmacSHA1() throws XMLSignatureException {
+            super();
+        }
 
-      /**
-       * Constructor IntegrityHmacSHA1
-       *
-       * @throws XMLSignatureException
-       */
-      public IntegrityHmacSHA1() throws XMLSignatureException {
-         super();
-      }
+        /**
+         * Method engineGetURI
+         * @inheritDoc
+         *
+         */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_MAC_HMAC_SHA1;
+        }
 
-      /**
-       * Method engineGetURI
-       * @inheritDoc
-       *
-       */
-      public String engineGetURI() {
-         return XMLSignature.ALGO_ID_MAC_HMAC_SHA1;
-      }
+        int getDigestLength() {
+            return 160;
+        }
+    }
 
-      int getDigestLength() {
-          return 160;
-      }
-   }
+    /**
+     * Class IntegrityHmacSHA256
+     */
+    public static class IntegrityHmacSHA256 extends IntegrityHmac {
 
-   /**
-    * Class IntegrityHmacSHA256
-    *
-    * @author $Author: mullan $
-    * @version $Revision: 1.5 $
-    */
-   public static class IntegrityHmacSHA256 extends IntegrityHmac {
+        /**
+         * Constructor IntegrityHmacSHA256
+         *
+         * @throws XMLSignatureException
+         */
+        public IntegrityHmacSHA256() throws XMLSignatureException {
+            super();
+        }
 
-      /**
-       * Constructor IntegrityHmacSHA256
-       *
-       * @throws XMLSignatureException
-       */
-      public IntegrityHmacSHA256() throws XMLSignatureException {
-         super();
-      }
+        /**
+         * Method engineGetURI
+         *
+         * @inheritDoc
+         */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_MAC_HMAC_SHA256;
+        }
+
+        int getDigestLength() {
+            return 256;
+        }
+    }
 
-      /**
-       * Method engineGetURI
-       *
-       * @inheritDoc
-       */
-      public String engineGetURI() {
-         return XMLSignature.ALGO_ID_MAC_HMAC_SHA256;
-      }
+    /**
+     * Class IntegrityHmacSHA384
+     */
+    public static class IntegrityHmacSHA384 extends IntegrityHmac {
 
-      int getDigestLength() {
-          return 256;
-      }
-   }
-
-   /**
-    * Class IntegrityHmacSHA384
-    *
-    * @author $Author: mullan $
-    * @version $Revision: 1.5 $
-    */
-   public static class IntegrityHmacSHA384 extends IntegrityHmac {
+        /**
+         * Constructor IntegrityHmacSHA384
+         *
+         * @throws XMLSignatureException
+         */
+        public IntegrityHmacSHA384() throws XMLSignatureException {
+            super();
+        }
 
-      /**
-       * Constructor IntegrityHmacSHA384
-       *
-       * @throws XMLSignatureException
-       */
-      public IntegrityHmacSHA384() throws XMLSignatureException {
-         super();
-      }
+        /**
+         * Method engineGetURI
+         * @inheritDoc
+         *
+         */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_MAC_HMAC_SHA384;
+        }
 
-      /**
-       * Method engineGetURI
-       * @inheritDoc
-       *
-       */
-      public String engineGetURI() {
-         return XMLSignature.ALGO_ID_MAC_HMAC_SHA384;
-      }
+        int getDigestLength() {
+            return 384;
+        }
+    }
 
-      int getDigestLength() {
-          return 384;
-      }
-   }
+    /**
+     * Class IntegrityHmacSHA512
+     */
+    public static class IntegrityHmacSHA512 extends IntegrityHmac {
 
-   /**
-    * Class IntegrityHmacSHA512
-    *
-    * @author $Author: mullan $
-    * @version $Revision: 1.5 $
-    */
-   public static class IntegrityHmacSHA512 extends IntegrityHmac {
+        /**
+         * Constructor IntegrityHmacSHA512
+         *
+         * @throws XMLSignatureException
+         */
+        public IntegrityHmacSHA512() throws XMLSignatureException {
+            super();
+        }
 
-      /**
-       * Constructor IntegrityHmacSHA512
-       *
-       * @throws XMLSignatureException
-       */
-      public IntegrityHmacSHA512() throws XMLSignatureException {
-         super();
-      }
+        /**
+         * Method engineGetURI
+         * @inheritDoc
+         *
+         */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_MAC_HMAC_SHA512;
+        }
 
-      /**
-       * Method engineGetURI
-       * @inheritDoc
-       *
-       */
-      public String engineGetURI() {
-         return XMLSignature.ALGO_ID_MAC_HMAC_SHA512;
-      }
+        int getDigestLength() {
+            return 512;
+        }
+    }
 
-      int getDigestLength() {
-          return 512;
-      }
-   }
+    /**
+     * Class IntegrityHmacRIPEMD160
+     */
+    public static class IntegrityHmacRIPEMD160 extends IntegrityHmac {
 
-   /**
-    * Class IntegrityHmacRIPEMD160
-    *
-    * @author $Author: mullan $
-    * @version $Revision: 1.5 $
-    */
-   public static class IntegrityHmacRIPEMD160 extends IntegrityHmac {
+        /**
+         * Constructor IntegrityHmacRIPEMD160
+         *
+         * @throws XMLSignatureException
+         */
+        public IntegrityHmacRIPEMD160() throws XMLSignatureException {
+            super();
+        }
 
-      /**
-       * Constructor IntegrityHmacRIPEMD160
-       *
-       * @throws XMLSignatureException
-       */
-      public IntegrityHmacRIPEMD160() throws XMLSignatureException {
-         super();
-      }
+        /**
+         * Method engineGetURI
+         *
+         * @inheritDoc
+         */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160;
+        }
 
-      /**
-       * Method engineGetURI
-       *
-       * @inheritDoc
-       */
-      public String engineGetURI() {
-         return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160;
-      }
-
-      int getDigestLength() {
-          return 160;
-      }
-   }
+        int getDigestLength() {
+            return 160;
+        }
+    }
 
-   /**
-    * Class IntegrityHmacMD5
-    *
-    * @author $Author: mullan $
-    * @version $Revision: 1.5 $
-    */
-   public static class IntegrityHmacMD5 extends IntegrityHmac {
+    /**
+     * Class IntegrityHmacMD5
+     */
+    public static class IntegrityHmacMD5 extends IntegrityHmac {
+
+        /**
+         * Constructor IntegrityHmacMD5
+         *
+         * @throws XMLSignatureException
+         */
+        public IntegrityHmacMD5() throws XMLSignatureException {
+            super();
+        }
 
-      /**
-       * Constructor IntegrityHmacMD5
-       *
-       * @throws XMLSignatureException
-       */
-      public IntegrityHmacMD5() throws XMLSignatureException {
-         super();
-      }
+        /**
+         * Method engineGetURI
+         *
+         * @inheritDoc
+         */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5;
+        }
 
-      /**
-       * Method engineGetURI
-       *
-       * @inheritDoc
-       */
-      public String engineGetURI() {
-         return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5;
-      }
-
-      int getDigestLength() {
-          return 128;
-      }
-   }
+        int getDigestLength() {
+            return 128;
+        }
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2007 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.algorithms.implementations;
 
@@ -36,22 +38,17 @@
 import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
 
-/**
- *
- * @author $Author: mullan $
- */
 public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
 
-    /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger
-        (SignatureBaseRSA.class.getName());
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(SignatureBaseRSA.class.getName());
 
     /** @inheritDoc */
     public abstract String engineGetURI();
 
     /** Field algorithm */
-    private java.security.Signature _signatureAlgorithm = null;
+    private java.security.Signature signatureAlgorithm = null;
 
     /**
      * Constructor SignatureRSA
@@ -59,17 +56,17 @@
      * @throws XMLSignatureException
      */
     public SignatureBaseRSA() throws XMLSignatureException {
-
         String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
 
-        if (log.isLoggable(java.util.logging.Level.FINE))
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
             log.log(java.util.logging.Level.FINE, "Created SignatureRSA using " + algorithmID);
-        String provider=JCEMapper.getProviderId();
+        }
+        String provider = JCEMapper.getProviderId();
         try {
-            if (provider==null) {
-                this._signatureAlgorithm = Signature.getInstance(algorithmID);
+            if (provider == null) {
+                this.signatureAlgorithm = Signature.getInstance(algorithmID);
             } else {
-                this._signatureAlgorithm = Signature.getInstance(algorithmID,provider);
+                this.signatureAlgorithm = Signature.getInstance(algorithmID,provider);
             }
         } catch (java.security.NoSuchAlgorithmException ex) {
             Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
@@ -85,20 +82,17 @@
     /** @inheritDoc */
     protected void engineSetParameter(AlgorithmParameterSpec params)
         throws XMLSignatureException {
-
         try {
-            this._signatureAlgorithm.setParameter(params);
+            this.signatureAlgorithm.setParameter(params);
         } catch (InvalidAlgorithmParameterException ex) {
             throw new XMLSignatureException("empty", ex);
         }
     }
 
     /** @inheritDoc */
-    protected boolean engineVerify(byte[] signature)
-        throws XMLSignatureException {
-
+    protected boolean engineVerify(byte[] signature) throws XMLSignatureException {
         try {
-            return this._signatureAlgorithm.verify(signature);
+            return this.signatureAlgorithm.verify(signature);
         } catch (SignatureException ex) {
             throw new XMLSignatureException("empty", ex);
         }
@@ -106,32 +100,29 @@
 
     /** @inheritDoc */
     protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
-
         if (!(publicKey instanceof PublicKey)) {
             String supplied = publicKey.getClass().getName();
             String needed = PublicKey.class.getName();
             Object exArgs[] = { supplied, needed };
 
-            throw new XMLSignatureException
-                ("algorithms.WrongKeyForThisOperation", exArgs);
+            throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
         }
 
         try {
-            this._signatureAlgorithm.initVerify((PublicKey) publicKey);
+            this.signatureAlgorithm.initVerify((PublicKey) publicKey);
         } catch (InvalidKeyException ex) {
             // reinstantiate Signature object to work around bug in JDK
             // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
-            Signature sig = this._signatureAlgorithm;
+            Signature sig = this.signatureAlgorithm;
             try {
-                this._signatureAlgorithm = Signature.getInstance
-                    (_signatureAlgorithm.getAlgorithm());
+                this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
             } catch (Exception e) {
                 // this shouldn't occur, but if it does, restore previous
                 // Signature
                 if (log.isLoggable(java.util.logging.Level.FINE)) {
                     log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
                 }
-                this._signatureAlgorithm = sig;
+                this.signatureAlgorithm = sig;
             }
             throw new XMLSignatureException("empty", ex);
         }
@@ -140,7 +131,7 @@
     /** @inheritDoc */
     protected byte[] engineSign() throws XMLSignatureException {
         try {
-            return this._signatureAlgorithm.sign();
+            return this.signatureAlgorithm.sign();
         } catch (SignatureException ex) {
             throw new XMLSignatureException("empty", ex);
         }
@@ -149,19 +140,16 @@
     /** @inheritDoc */
     protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
         throws XMLSignatureException {
-
         if (!(privateKey instanceof PrivateKey)) {
             String supplied = privateKey.getClass().getName();
             String needed = PrivateKey.class.getName();
             Object exArgs[] = { supplied, needed };
 
-            throw new XMLSignatureException
-                ("algorithms.WrongKeyForThisOperation", exArgs);
+            throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
         }
 
         try {
-            this._signatureAlgorithm.initSign
-                ((PrivateKey) privateKey, secureRandom);
+            this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
         } catch (InvalidKeyException ex) {
             throw new XMLSignatureException("empty", ex);
         }
@@ -169,18 +157,16 @@
 
     /** @inheritDoc */
     protected void engineInitSign(Key privateKey) throws XMLSignatureException {
-
         if (!(privateKey instanceof PrivateKey)) {
             String supplied = privateKey.getClass().getName();
             String needed = PrivateKey.class.getName();
             Object exArgs[] = { supplied, needed };
 
-            throw new XMLSignatureException
-                ("algorithms.WrongKeyForThisOperation", exArgs);
+            throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
         }
 
         try {
-            this._signatureAlgorithm.initSign((PrivateKey) privateKey);
+            this.signatureAlgorithm.initSign((PrivateKey) privateKey);
         } catch (InvalidKeyException ex) {
             throw new XMLSignatureException("empty", ex);
         }
@@ -189,7 +175,7 @@
     /** @inheritDoc */
     protected void engineUpdate(byte[] input) throws XMLSignatureException {
         try {
-            this._signatureAlgorithm.update(input);
+            this.signatureAlgorithm.update(input);
         } catch (SignatureException ex) {
             throw new XMLSignatureException("empty", ex);
         }
@@ -198,17 +184,16 @@
     /** @inheritDoc */
     protected void engineUpdate(byte input) throws XMLSignatureException {
         try {
-            this._signatureAlgorithm.update(input);
+            this.signatureAlgorithm.update(input);
         } catch (SignatureException ex) {
             throw new XMLSignatureException("empty", ex);
         }
     }
 
     /** @inheritDoc */
-    protected void engineUpdate(byte buf[], int offset, int len)
-        throws XMLSignatureException {
+    protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException {
         try {
-            this._signatureAlgorithm.update(buf, offset, len);
+            this.signatureAlgorithm.update(buf, offset, len);
         } catch (SignatureException ex) {
             throw new XMLSignatureException("empty", ex);
         }
@@ -216,34 +201,29 @@
 
     /** @inheritDoc */
     protected String engineGetJCEAlgorithmString() {
-        return this._signatureAlgorithm.getAlgorithm();
+        return this.signatureAlgorithm.getAlgorithm();
     }
 
     /** @inheritDoc */
     protected String engineGetJCEProviderName() {
-        return this._signatureAlgorithm.getProvider().getName();
+        return this.signatureAlgorithm.getProvider().getName();
     }
 
     /** @inheritDoc */
     protected void engineSetHMACOutputLength(int HMACOutputLength)
         throws XMLSignatureException {
-        throw new XMLSignatureException
-            ("algorithms.HMACOutputLengthOnlyForHMAC");
+        throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
     }
 
     /** @inheritDoc */
     protected void engineInitSign(
-        Key signingKey, AlgorithmParameterSpec algorithmParameterSpec)
-        throws XMLSignatureException {
-        throw new XMLSignatureException(
-            "algorithms.CannotUseAlgorithmParameterSpecOnRSA");
+        Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
+    ) throws XMLSignatureException {
+        throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnRSA");
     }
 
     /**
      * Class SignatureRSASHA1
-     *
-     * @author $Author: mullan $
-     * @version $Revision: 1.5 $
      */
     public static class SignatureRSASHA1 extends SignatureBaseRSA {
 
@@ -264,9 +244,6 @@
 
     /**
      * Class SignatureRSASHA256
-     *
-     * @author $Author: mullan $
-     * @version $Revision: 1.5 $
      */
     public static class SignatureRSASHA256 extends SignatureBaseRSA {
 
@@ -287,9 +264,6 @@
 
     /**
      * Class SignatureRSASHA384
-     *
-     * @author $Author: mullan $
-     * @version $Revision: 1.5 $
      */
     public static class SignatureRSASHA384 extends SignatureBaseRSA {
 
@@ -310,9 +284,6 @@
 
     /**
      * Class SignatureRSASHA512
-     *
-     * @author $Author: mullan $
-     * @version $Revision: 1.5 $
      */
     public static class SignatureRSASHA512 extends SignatureBaseRSA {
 
@@ -333,9 +304,6 @@
 
     /**
      * Class SignatureRSARIPEMD160
-     *
-     * @author $Author: mullan $
-     * @version $Revision: 1.5 $
      */
     public static class SignatureRSARIPEMD160 extends SignatureBaseRSA {
 
@@ -356,9 +324,6 @@
 
     /**
      * Class SignatureRSAMD5
-     *
-     * @author $Author: mullan $
-     * @version $Revision: 1.5 $
      */
     public static class SignatureRSAMD5 extends SignatureBaseRSA {
 
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.algorithms.implementations;
 
@@ -37,21 +39,17 @@
 import com.sun.org.apache.xml.internal.security.utils.Base64;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 
-/**
- *
- * @author $Author: mullan $
- */
 public class SignatureDSA extends SignatureAlgorithmSpi {
 
-    /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(SignatureDSA.class.getName());
 
-    /** Field _URI */
-    public static final String _URI = Constants.SignatureSpecNS + "dsa-sha1";
+    /** Field URI */
+    public static final String URI = Constants.SignatureSpecNS + "dsa-sha1";
 
     /** Field algorithm */
-    private java.security.Signature _signatureAlgorithm = null;
+    private java.security.Signature signatureAlgorithm = null;
 
     /**
      * Method engineGetURI
@@ -59,7 +57,7 @@
      * @inheritDoc
      */
     protected String engineGetURI() {
-        return SignatureDSA._URI;
+        return SignatureDSA.URI;
     }
 
     /**
@@ -68,17 +66,17 @@
      * @throws XMLSignatureException
      */
     public SignatureDSA() throws XMLSignatureException {
-
-        String algorithmID = JCEMapper.translateURItoJCEID(SignatureDSA._URI);
-        if (log.isLoggable(java.util.logging.Level.FINE))
+        String algorithmID = JCEMapper.translateURItoJCEID(SignatureDSA.URI);
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
             log.log(java.util.logging.Level.FINE, "Created SignatureDSA using " + algorithmID);
+        }
 
         String provider = JCEMapper.getProviderId();
         try {
             if (provider == null) {
-                this._signatureAlgorithm = Signature.getInstance(algorithmID);
+                this.signatureAlgorithm = Signature.getInstance(algorithmID);
             } else {
-                this._signatureAlgorithm =
+                this.signatureAlgorithm =
                     Signature.getInstance(algorithmID, provider);
             }
         } catch (java.security.NoSuchAlgorithmException ex) {
@@ -95,9 +93,8 @@
      */
     protected void engineSetParameter(AlgorithmParameterSpec params)
         throws XMLSignatureException {
-
         try {
-            this._signatureAlgorithm.setParameter(params);
+            this.signatureAlgorithm.setParameter(params);
         } catch (InvalidAlgorithmParameterException ex) {
             throw new XMLSignatureException("empty", ex);
         }
@@ -107,15 +104,15 @@
      * @inheritDoc
      */
     protected boolean engineVerify(byte[] signature)
-           throws XMLSignatureException {
-
+        throws XMLSignatureException {
         try {
-            if (log.isLoggable(java.util.logging.Level.FINE))
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
                 log.log(java.util.logging.Level.FINE, "Called DSA.verify() on " + Base64.encode(signature));
+            }
 
             byte[] jcebytes = SignatureDSA.convertXMLDSIGtoASN1(signature);
 
-            return this._signatureAlgorithm.verify(jcebytes);
+            return this.signatureAlgorithm.verify(jcebytes);
         } catch (SignatureException ex) {
             throw new XMLSignatureException("empty", ex);
         } catch (IOException ex) {
@@ -127,32 +124,29 @@
      * @inheritDoc
      */
     protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
-
         if (!(publicKey instanceof PublicKey)) {
             String supplied = publicKey.getClass().getName();
             String needed = PublicKey.class.getName();
             Object exArgs[] = { supplied, needed };
 
-            throw new XMLSignatureException
-                ("algorithms.WrongKeyForThisOperation", exArgs);
+            throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
         }
 
         try {
-            this._signatureAlgorithm.initVerify((PublicKey) publicKey);
+            this.signatureAlgorithm.initVerify((PublicKey) publicKey);
         } catch (InvalidKeyException ex) {
             // reinstantiate Signature object to work around bug in JDK
             // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
-            Signature sig = this._signatureAlgorithm;
+            Signature sig = this.signatureAlgorithm;
             try {
-                this._signatureAlgorithm = Signature.getInstance
-                    (_signatureAlgorithm.getAlgorithm());
+                this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
             } catch (Exception e) {
                 // this shouldn't occur, but if it does, restore previous
                 // Signature
                 if (log.isLoggable(java.util.logging.Level.FINE)) {
                     log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
                 }
-                this._signatureAlgorithm = sig;
+                this.signatureAlgorithm = sig;
             }
             throw new XMLSignatureException("empty", ex);
         }
@@ -162,9 +156,8 @@
      * @inheritDoc
      */
     protected byte[] engineSign() throws XMLSignatureException {
-
         try {
-            byte jcebytes[] = this._signatureAlgorithm.sign();
+            byte jcebytes[] = this.signatureAlgorithm.sign();
 
             return SignatureDSA.convertASN1toXMLDSIG(jcebytes);
         } catch (IOException ex) {
@@ -178,20 +171,17 @@
      * @inheritDoc
      */
     protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
-           throws XMLSignatureException {
-
+        throws XMLSignatureException {
         if (!(privateKey instanceof PrivateKey)) {
             String supplied = privateKey.getClass().getName();
             String needed = PrivateKey.class.getName();
             Object exArgs[] = { supplied, needed };
 
-            throw new XMLSignatureException
-                ("algorithms.WrongKeyForThisOperation", exArgs);
+            throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
         }
 
         try {
-            this._signatureAlgorithm.initSign((PrivateKey) privateKey,
-                                           secureRandom);
+            this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
         } catch (InvalidKeyException ex) {
             throw new XMLSignatureException("empty", ex);
         }
@@ -201,18 +191,16 @@
      * @inheritDoc
      */
     protected void engineInitSign(Key privateKey) throws XMLSignatureException {
-
         if (!(privateKey instanceof PrivateKey)) {
             String supplied = privateKey.getClass().getName();
             String needed = PrivateKey.class.getName();
             Object exArgs[] = { supplied, needed };
 
-            throw new XMLSignatureException
-                ("algorithms.WrongKeyForThisOperation", exArgs);
+            throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
         }
 
         try {
-            this._signatureAlgorithm.initSign((PrivateKey) privateKey);
+            this.signatureAlgorithm.initSign((PrivateKey) privateKey);
         } catch (InvalidKeyException ex) {
             throw new XMLSignatureException("empty", ex);
         }
@@ -223,7 +211,7 @@
      */
     protected void engineUpdate(byte[] input) throws XMLSignatureException {
         try {
-            this._signatureAlgorithm.update(input);
+            this.signatureAlgorithm.update(input);
         } catch (SignatureException ex) {
             throw new XMLSignatureException("empty", ex);
         }
@@ -234,7 +222,7 @@
      */
     protected void engineUpdate(byte input) throws XMLSignatureException {
         try {
-            this._signatureAlgorithm.update(input);
+            this.signatureAlgorithm.update(input);
         } catch (SignatureException ex) {
             throw new XMLSignatureException("empty", ex);
         }
@@ -243,10 +231,9 @@
     /**
      * @inheritDoc
      */
-    protected void engineUpdate(byte buf[], int offset, int len)
-        throws XMLSignatureException {
+    protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException {
         try {
-            this._signatureAlgorithm.update(buf, offset, len);
+            this.signatureAlgorithm.update(buf, offset, len);
         } catch (SignatureException ex) {
             throw new XMLSignatureException("empty", ex);
         }
@@ -258,7 +245,7 @@
      * @inheritDoc
      */
     protected String engineGetJCEAlgorithmString() {
-        return this._signatureAlgorithm.getAlgorithm();
+        return this.signatureAlgorithm.getAlgorithm();
     }
 
     /**
@@ -267,7 +254,7 @@
      * @inheritDoc
      */
     protected String engineGetJCEProviderName() {
-        return this._signatureAlgorithm.getProvider().getName();
+        return this.signatureAlgorithm.getProvider().getName();
     }
 
     /**
@@ -282,8 +269,7 @@
      * @throws IOException
      * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
      */
-    private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[])
-           throws IOException {
+    private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException {
 
         byte rLength = asn1Bytes[3];
         int i;
@@ -294,19 +280,18 @@
         int j;
 
         for (j = sLength;
-              (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--);
+            (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--);
 
         if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2)
-              || (asn1Bytes[2] != 2) || (i > 20)
-              || (asn1Bytes[4 + rLength] != 2) || (j > 20)) {
+            || (asn1Bytes[2] != 2) || (i > 20)
+            || (asn1Bytes[4 + rLength] != 2) || (j > 20)) {
             throw new IOException("Invalid ASN.1 format of DSA signature");
         }
         byte xmldsigBytes[] = new byte[40];
 
-        System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 20 - i,
-                          i);
+        System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 20 - i, i);
         System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes,
-                          40 - j, j);
+                         40 - j, j);
 
         return xmldsigBytes;
     }
@@ -323,8 +308,7 @@
      * @throws IOException
      * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
      */
-    private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[])
-           throws IOException {
+    private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException {
 
         if (xmldsigBytes.length != 40) {
             throw new IOException("Invalid XMLDSIG format of DSA signature");
@@ -337,7 +321,7 @@
         int j = i;
 
         if (xmldsigBytes[20 - i] < 0) {
-         j += 1;
+            j += 1;
         }
 
         int k;
@@ -373,10 +357,8 @@
      * @param HMACOutputLength
      * @throws XMLSignatureException
      */
-    protected void engineSetHMACOutputLength(int HMACOutputLength)
-            throws XMLSignatureException {
-        throw new XMLSignatureException(
-            "algorithms.HMACOutputLengthOnlyForHMAC");
+    protected void engineSetHMACOutputLength(int HMACOutputLength) throws XMLSignatureException {
+        throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
     }
 
     /**
@@ -387,9 +369,8 @@
      * @throws XMLSignatureException
      */
     protected void engineInitSign(
-        Key signingKey, AlgorithmParameterSpec algorithmParameterSpec)
-            throws XMLSignatureException {
-        throw new XMLSignatureException(
-            "algorithms.CannotUseAlgorithmParameterSpecOnDSA");
+        Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
+    ) throws XMLSignatureException {
+        throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnDSA");
     }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.algorithms.implementations;
 
-
-
 import java.io.IOException;
 import java.security.InvalidAlgorithmParameterException;
 import java.security.InvalidKeyException;
@@ -40,345 +40,417 @@
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
 import com.sun.org.apache.xml.internal.security.utils.Base64;
 
-
 /**
  *
- * @author $Author: mullan $
+ * @author $Author: raul $
+ * @author Alex Dupre
  */
 public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(SignatureECDSA.class.getName());
 
     /** @inheritDoc */
-   public abstract String engineGetURI();
+    public abstract String engineGetURI();
 
-   /** Field algorithm */
-   private java.security.Signature _signatureAlgorithm = null;
+    /** Field algorithm */
+    private java.security.Signature signatureAlgorithm = null;
 
-   /**
-    * Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value.
-    *
-    * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value
-    * pairs; the XML Signature requires the core BigInteger values.
-    *
-    * @param asn1Bytes
-    * @return the decode bytes
-    *
-    * @throws IOException
-    * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
-    * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
-    */
-   private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[])
-           throws IOException {
+    /**
+     * Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value.
+     *
+     * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value
+     * pairs; the XML Signature requires the core BigInteger values.
+     *
+     * @param asn1Bytes
+     * @return the decode bytes
+     *
+     * @throws IOException
+     * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
+     * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
+     */
+    public static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException {
 
-      byte rLength = asn1Bytes[3];
-      int i;
-
-      for (i = rLength; (i > 0) && (asn1Bytes[(4 + rLength) - i] == 0); i--);
-
-      byte sLength = asn1Bytes[5 + rLength];
-      int j;
-
-      for (j = sLength;
-              (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--);
+        if (asn1Bytes.length < 8 || asn1Bytes[0] != 48) {
+            throw new IOException("Invalid ASN.1 format of ECDSA signature");
+        }
+        int offset;
+        if (asn1Bytes[1] > 0) {
+            offset = 2;
+        } else if (asn1Bytes[1] == (byte) 0x81) {
+            offset = 3;
+        } else {
+            throw new IOException("Invalid ASN.1 format of ECDSA signature");
+        }
 
-      if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2)
-              || (asn1Bytes[2] != 2) || (i > 24)
-              || (asn1Bytes[4 + rLength] != 2) || (j > 24)) {
-         throw new IOException("Invalid ASN.1 format of ECDSA signature");
-      }
-      byte xmldsigBytes[] = new byte[48];
+        byte rLength = asn1Bytes[offset + 1];
+        int i;
+
+        for (i = rLength; (i > 0) && (asn1Bytes[(offset + 2 + rLength) - i] == 0); i--);
 
-      System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 24 - i,
-                          i);
-      System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes,
-                          48 - j, j);
+        byte sLength = asn1Bytes[offset + 2 + rLength + 1];
+        int j;
+
+        for (j = sLength;
+            (j > 0) && (asn1Bytes[(offset + 2 + rLength + 2 + sLength) - j] == 0); j--);
+
+        int rawLen = Math.max(i, j);
 
-       return xmldsigBytes;
-   }
+        if ((asn1Bytes[offset - 1] & 0xff) != asn1Bytes.length - offset
+            || (asn1Bytes[offset - 1] & 0xff) != 2 + rLength + 2 + sLength
+            || asn1Bytes[offset] != 2
+            || asn1Bytes[offset + 2 + rLength] != 2) {
+            throw new IOException("Invalid ASN.1 format of ECDSA signature");
+        }
+        byte xmldsigBytes[] = new byte[2*rawLen];
 
-   /**
-    * Converts a XML Signature ECDSA Value to an ASN.1 DSA value.
-    *
-    * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value
-    * pairs; the XML Signature requires the core BigInteger values.
-    *
-    * @param xmldsigBytes
-    * @return the encoded ASN.1 bytes
-    *
-    * @throws IOException
-    * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
-    * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
-    */
-   private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[])
-           throws IOException {
+        System.arraycopy(asn1Bytes, (offset + 2 + rLength) - i, xmldsigBytes, rawLen - i, i);
+        System.arraycopy(asn1Bytes, (offset + 2 + rLength + 2 + sLength) - j, xmldsigBytes,
+                         2*rawLen - j, j);
+
+        return xmldsigBytes;
+    }
 
-      if (xmldsigBytes.length != 48) {
-         throw new IOException("Invalid XMLDSIG format of ECDSA signature");
-      }
+    /**
+     * Converts a XML Signature ECDSA Value to an ASN.1 DSA value.
+     *
+     * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value
+     * pairs; the XML Signature requires the core BigInteger values.
+     *
+     * @param xmldsigBytes
+     * @return the encoded ASN.1 bytes
+     *
+     * @throws IOException
+     * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
+     * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
+     */
+    public static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException {
 
-      int i;
-
-      for (i = 24; (i > 0) && (xmldsigBytes[24 - i] == 0); i--);
-
-      int j = i;
+        int rawLen = xmldsigBytes.length/2;
 
-      if (xmldsigBytes[24 - i] < 0) {
-         j += 1;
-      }
+        int i;
+
+        for (i = rawLen; (i > 0) && (xmldsigBytes[rawLen - i] == 0); i--);
 
-      int k;
+        int j = i;
 
-      for (k = 24; (k > 0) && (xmldsigBytes[48 - k] == 0); k--);
+        if (xmldsigBytes[rawLen - i] < 0) {
+            j += 1;
+        }
 
-      int l = k;
+        int k;
+
+        for (k = rawLen; (k > 0) && (xmldsigBytes[2*rawLen - k] == 0); k--);
 
-      if (xmldsigBytes[48 - k] < 0) {
-         l += 1;
-      }
+        int l = k;
 
-      byte asn1Bytes[] = new byte[6 + j + l];
+        if (xmldsigBytes[2*rawLen - k] < 0) {
+            l += 1;
+        }
 
-      asn1Bytes[0] = 48;
-      asn1Bytes[1] = (byte) (4 + j + l);
-      asn1Bytes[2] = 2;
-      asn1Bytes[3] = (byte) j;
-
-      System.arraycopy(xmldsigBytes, 24 - i, asn1Bytes, (4 + j) - i, i);
-
-      asn1Bytes[4 + j] = 2;
-      asn1Bytes[5 + j] = (byte) l;
+        int len = 2 + j + 2 + l;
+        if (len > 255) {
+            throw new IOException("Invalid XMLDSIG format of ECDSA signature");
+        }
+        int offset;
+        byte asn1Bytes[];
+        if (len < 128) {
+            asn1Bytes = new byte[2 + 2 + j + 2 + l];
+            offset = 1;
+        } else {
+            asn1Bytes = new byte[3 + 2 + j + 2 + l];
+            asn1Bytes[1] = (byte) 0x81;
+            offset = 2;
+        }
+        asn1Bytes[0] = 48;
+        asn1Bytes[offset++] = (byte) len;
+        asn1Bytes[offset++] = 2;
+        asn1Bytes[offset++] = (byte) j;
 
-      System.arraycopy(xmldsigBytes, 48 - k, asn1Bytes, (6 + j + l) - k, k);
-
-      return asn1Bytes;
-   }
-
-   /**
-    * Constructor SignatureRSA
-    *
-    * @throws XMLSignatureException
-    */
-   public SignatureECDSA() throws XMLSignatureException {
+        System.arraycopy(xmldsigBytes, rawLen - i, asn1Bytes, (offset + j) - i, i);
 
-      String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
+        offset += j;
+
+        asn1Bytes[offset++] = 2;
+        asn1Bytes[offset++] = (byte) l;
+
+        System.arraycopy(xmldsigBytes, 2*rawLen - k, asn1Bytes, (offset + l) - k, k);
+
+        return asn1Bytes;
+    }
 
-      if (log.isLoggable(java.util.logging.Level.FINE))
-        log.log(java.util.logging.Level.FINE, "Created SignatureECDSA using " + algorithmID);
-      String provider=JCEMapper.getProviderId();
-      try {
-         if (provider==null) {
-                this._signatureAlgorithm = Signature.getInstance(algorithmID);
-         } else {
-                this._signatureAlgorithm = Signature.getInstance(algorithmID,provider);
-         }
-      } catch (java.security.NoSuchAlgorithmException ex) {
-         Object[] exArgs = { algorithmID,
-                             ex.getLocalizedMessage() };
+    /**
+     * Constructor SignatureRSA
+     *
+     * @throws XMLSignatureException
+     */
+    public SignatureECDSA() throws XMLSignatureException {
 
-         throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
-      } catch (NoSuchProviderException ex) {
-         Object[] exArgs = { algorithmID,
-                                                 ex.getLocalizedMessage() };
+        String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
 
-         throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Created SignatureECDSA using " + algorithmID);
         }
-   }
+        String provider = JCEMapper.getProviderId();
+        try {
+            if (provider == null) {
+                this.signatureAlgorithm = Signature.getInstance(algorithmID);
+            } else {
+                this.signatureAlgorithm = Signature.getInstance(algorithmID,provider);
+            }
+        } catch (java.security.NoSuchAlgorithmException ex) {
+            Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
 
-   /** @inheritDoc */
-   protected void engineSetParameter(AlgorithmParameterSpec params)
-           throws XMLSignatureException {
+            throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
+        } catch (NoSuchProviderException ex) {
+            Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
 
-      try {
-         this._signatureAlgorithm.setParameter(params);
-      } catch (InvalidAlgorithmParameterException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+            throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
+        }
+    }
 
-   /** @inheritDoc */
-   protected boolean engineVerify(byte[] signature)
-           throws XMLSignatureException {
-
-      try {
-         byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature);
-
-         if (log.isLoggable(java.util.logging.Level.FINE))
-            log.log(java.util.logging.Level.FINE, "Called ECDSA.verify() on " + Base64.encode(signature));
+    /** @inheritDoc */
+    protected void engineSetParameter(AlgorithmParameterSpec params)
+        throws XMLSignatureException {
+        try {
+            this.signatureAlgorithm.setParameter(params);
+        } catch (InvalidAlgorithmParameterException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-         return this._signatureAlgorithm.verify(jcebytes);
-      } catch (SignatureException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (IOException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /** @inheritDoc */
+    protected boolean engineVerify(byte[] signature) throws XMLSignatureException {
+        try {
+            byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature);
 
-   /** @inheritDoc */
-   protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "Called ECDSA.verify() on " + Base64.encode(signature));
+            }
 
-      if (!(publicKey instanceof PublicKey)) {
-         String supplied = publicKey.getClass().getName();
-         String needed = PublicKey.class.getName();
-         Object exArgs[] = { supplied, needed };
+            return this.signatureAlgorithm.verify(jcebytes);
+        } catch (SignatureException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (IOException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
+
+    /** @inheritDoc */
+    protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
 
-         throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
-                                         exArgs);
-      }
+        if (!(publicKey instanceof PublicKey)) {
+            String supplied = publicKey.getClass().getName();
+            String needed = PublicKey.class.getName();
+            Object exArgs[] = { supplied, needed };
 
-      try {
-         this._signatureAlgorithm.initVerify((PublicKey) publicKey);
-      } catch (InvalidKeyException ex) {
+            throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
+        }
+
+        try {
+            this.signatureAlgorithm.initVerify((PublicKey) publicKey);
+        } catch (InvalidKeyException ex) {
             // reinstantiate Signature object to work around bug in JDK
             // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
-            Signature sig = this._signatureAlgorithm;
+            Signature sig = this.signatureAlgorithm;
             try {
-                this._signatureAlgorithm = Signature.getInstance
-                    (_signatureAlgorithm.getAlgorithm());
+                this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
             } catch (Exception e) {
                 // this shouldn't occur, but if it does, restore previous
                 // Signature
                 if (log.isLoggable(java.util.logging.Level.FINE)) {
                     log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
                 }
-                this._signatureAlgorithm = sig;
+                this.signatureAlgorithm = sig;
             }
             throw new XMLSignatureException("empty", ex);
-      }
-   }
+        }
+    }
+
+    /** @inheritDoc */
+    protected byte[] engineSign() throws XMLSignatureException {
+        try {
+            byte jcebytes[] = this.signatureAlgorithm.sign();
 
-   /** @inheritDoc */
-   protected byte[] engineSign() throws XMLSignatureException {
-
-      try {
-         byte jcebytes[] = this._signatureAlgorithm.sign();
+            return SignatureECDSA.convertASN1toXMLDSIG(jcebytes);
+        } catch (SignatureException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (IOException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-         return SignatureECDSA.convertASN1toXMLDSIG(jcebytes);
-      } catch (SignatureException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (IOException ex) {
-          throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /** @inheritDoc */
+    protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
+        throws XMLSignatureException {
+        if (!(privateKey instanceof PrivateKey)) {
+            String supplied = privateKey.getClass().getName();
+            String needed = PrivateKey.class.getName();
+            Object exArgs[] = { supplied, needed };
+
+            throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
+        }
 
-   /** @inheritDoc */
-   protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
-           throws XMLSignatureException {
+        try {
+            this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
+        } catch (InvalidKeyException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-      if (!(privateKey instanceof PrivateKey)) {
-         String supplied = privateKey.getClass().getName();
-         String needed = PrivateKey.class.getName();
-         Object exArgs[] = { supplied, needed };
+    /** @inheritDoc */
+    protected void engineInitSign(Key privateKey) throws XMLSignatureException {
+        if (!(privateKey instanceof PrivateKey)) {
+            String supplied = privateKey.getClass().getName();
+            String needed = PrivateKey.class.getName();
+            Object exArgs[] = { supplied, needed };
 
-         throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
-                                         exArgs);
-      }
+            throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
+        }
 
-      try {
-         this._signatureAlgorithm.initSign((PrivateKey) privateKey,
-                                           secureRandom);
-      } catch (InvalidKeyException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+        try {
+            this.signatureAlgorithm.initSign((PrivateKey) privateKey);
+        } catch (InvalidKeyException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /** @inheritDoc */
-   protected void engineInitSign(Key privateKey) throws XMLSignatureException {
+    /** @inheritDoc */
+    protected void engineUpdate(byte[] input) throws XMLSignatureException {
+        try {
+            this.signatureAlgorithm.update(input);
+        } catch (SignatureException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-      if (!(privateKey instanceof PrivateKey)) {
-         String supplied = privateKey.getClass().getName();
-         String needed = PrivateKey.class.getName();
-         Object exArgs[] = { supplied, needed };
+    /** @inheritDoc */
+    protected void engineUpdate(byte input) throws XMLSignatureException {
+        try {
+            this.signatureAlgorithm.update(input);
+        } catch (SignatureException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-         throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
-                                         exArgs);
-      }
+    /** @inheritDoc */
+    protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException {
+        try {
+            this.signatureAlgorithm.update(buf, offset, len);
+        } catch (SignatureException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-      try {
-         this._signatureAlgorithm.initSign((PrivateKey) privateKey);
-      } catch (InvalidKeyException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /** @inheritDoc */
+    protected String engineGetJCEAlgorithmString() {
+        return this.signatureAlgorithm.getAlgorithm();
+    }
 
-   /** @inheritDoc */
-   protected void engineUpdate(byte[] input) throws XMLSignatureException {
+    /** @inheritDoc */
+    protected String engineGetJCEProviderName() {
+        return this.signatureAlgorithm.getProvider().getName();
+    }
 
-      try {
-         this._signatureAlgorithm.update(input);
-      } catch (SignatureException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /** @inheritDoc */
+    protected void engineSetHMACOutputLength(int HMACOutputLength)
+        throws XMLSignatureException {
+        throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
+    }
 
-   /** @inheritDoc */
-   protected void engineUpdate(byte input) throws XMLSignatureException {
+    /** @inheritDoc */
+    protected void engineInitSign(
+        Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
+    ) throws XMLSignatureException {
+        throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnRSA");
+    }
 
-      try {
-         this._signatureAlgorithm.update(input);
-      } catch (SignatureException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
-
-   /** @inheritDoc */
-   protected void engineUpdate(byte buf[], int offset, int len)
-           throws XMLSignatureException {
+    /**
+     * Class SignatureRSASHA1
+     *
+     * @author $Author: marcx $
+     */
+    public static class SignatureECDSASHA1 extends SignatureECDSA {
+        /**
+         * Constructor SignatureRSASHA1
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureECDSASHA1() throws XMLSignatureException {
+            super();
+        }
 
-      try {
-         this._signatureAlgorithm.update(buf, offset, len);
-      } catch (SignatureException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+        /** @inheritDoc */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1;
+        }
+    }
 
-   /** @inheritDoc */
-   protected String engineGetJCEAlgorithmString() {
-      return this._signatureAlgorithm.getAlgorithm();
-   }
+    /**
+     * Class SignatureRSASHA256
+     *
+     * @author Alex Dupre
+     */
+    public static class SignatureECDSASHA256 extends SignatureECDSA {
 
-   /** @inheritDoc */
-   protected String engineGetJCEProviderName() {
-      return this._signatureAlgorithm.getProvider().getName();
-   }
+        /**
+         * Constructor SignatureRSASHA256
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureECDSASHA256() throws XMLSignatureException {
+            super();
+        }
 
-   /** @inheritDoc */
-   protected void engineSetHMACOutputLength(int HMACOutputLength)
-           throws XMLSignatureException {
-      throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
-   }
+        /** @inheritDoc */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256;
+        }
+    }
 
-   /** @inheritDoc */
-   protected void engineInitSign(
-           Key signingKey, AlgorithmParameterSpec algorithmParameterSpec)
-              throws XMLSignatureException {
-      throw new XMLSignatureException(
-         "algorithms.CannotUseAlgorithmParameterSpecOnRSA");
-   }
+    /**
+     * Class SignatureRSASHA384
+     *
+     * @author Alex Dupre
+     */
+    public static class SignatureECDSASHA384 extends SignatureECDSA {
+
+        /**
+         * Constructor SignatureRSASHA384
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureECDSASHA384() throws XMLSignatureException {
+            super();
+        }
 
-   /**
-    * Class SignatureRSASHA1
-    *
-    * @author $Author: mullan $
-    * @version $Revision: 1.2 $
-    */
-   public static class SignatureECDSASHA1 extends SignatureECDSA {
+        /** @inheritDoc */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384;
+        }
+    }
+
+    /**
+     * Class SignatureRSASHA512
+     *
+     * @author Alex Dupre
+     */
+    public static class SignatureECDSASHA512 extends SignatureECDSA {
 
-      /**
-       * Constructor SignatureRSASHA1
-       *
-       * @throws XMLSignatureException
-       */
-      public SignatureECDSASHA1() throws XMLSignatureException {
-         super();
-      }
+        /**
+         * Constructor SignatureRSASHA512
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureECDSASHA512() throws XMLSignatureException {
+            super();
+        }
 
-      /** @inheritDoc */
-      public String engineGetURI() {
-         return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1;
-      }
-   }
+        /** @inheritDoc */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512;
+        }
+    }
 
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,29 +2,28 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.c14n;
 
-
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 
-
 /**
  * Class CanonicalizationException
  *
@@ -32,57 +31,58 @@
  */
 public class CanonicalizationException extends XMLSecurityException {
 
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
 
-   /**
-    * Constructor CanonicalizationException
-    *
-    */
-   public CanonicalizationException() {
-      super();
-   }
+    /**
+     * Constructor CanonicalizationException
+     *
+     */
+    public CanonicalizationException() {
+        super();
+    }
 
-   /**
-    * Constructor CanonicalizationException
-    *
-    * @param _msgID
-    */
-   public CanonicalizationException(String _msgID) {
-      super(_msgID);
-   }
+    /**
+     * Constructor CanonicalizationException
+     *
+     * @param msgID
+     */
+    public CanonicalizationException(String msgID) {
+        super(msgID);
+    }
 
-   /**
-    * Constructor CanonicalizationException
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public CanonicalizationException(String _msgID, Object exArgs[]) {
-      super(_msgID, exArgs);
-   }
+    /**
+     * Constructor CanonicalizationException
+     *
+     * @param msgID
+     * @param exArgs
+     */
+    public CanonicalizationException(String msgID, Object exArgs[]) {
+        super(msgID, exArgs);
+    }
 
-   /**
-    * Constructor CanonicalizationException
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public CanonicalizationException(String _msgID, Exception _originalException) {
-      super(_msgID, _originalException);
-   }
+    /**
+     * Constructor CanonicalizationException
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public CanonicalizationException(String msgID, Exception originalException) {
+        super(msgID, originalException);
+    }
 
-   /**
-    * Constructor CanonicalizationException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public CanonicalizationException(String _msgID, Object exArgs[],
-                                    Exception _originalException) {
-      super(_msgID, exArgs, _originalException);
-   }
+    /**
+     * Constructor CanonicalizationException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public CanonicalizationException(
+        String msgID, Object exArgs[], Exception originalException
+    ) {
+        super(msgID, exArgs, originalException);
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java	Mon Jul 22 17:37:15 2013 -0700
@@ -39,6 +39,7 @@
 import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315ExclWithComments;
 import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315OmitComments;
 import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315WithComments;
+import com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerPhysical;
 import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
@@ -91,6 +92,11 @@
      */
     public static final String ALGO_ID_C14N11_WITH_COMMENTS =
         ALGO_ID_C14N11_OMIT_COMMENTS + "#WithComments";
+    /**
+     * Non-standard algorithm to serialize the physical representation for XML Encryption
+     */
+    public static final String ALGO_ID_C14N_PHYSICAL =
+        "http://santuario.apache.org/c14n/physical";
 
     private static Map<String, Class<? extends CanonicalizerSpi>> canonicalizerHash =
         new ConcurrentHashMap<String, Class<? extends CanonicalizerSpi>>();
@@ -202,6 +208,10 @@
             Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS,
             Canonicalizer11_WithComments.class
         );
+        canonicalizerHash.put(
+            Canonicalizer.ALGO_ID_C14N_PHYSICAL,
+            CanonicalizerPhysical.class
+        );
     }
 
     /**
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.c14n;
 
-
-
 import java.io.ByteArrayInputStream;
 import java.io.OutputStream;
 import java.util.Set;
@@ -29,7 +29,6 @@
 import javax.xml.XMLConstants;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.xpath.XPath;
 
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Document;
@@ -37,166 +36,134 @@
 import org.w3c.dom.NodeList;
 import org.xml.sax.InputSource;
 
-
 /**
- * Base class which all Caninicalization algorithms extend.
+ * Base class which all Canonicalization algorithms extend.
  *
- * $todo$ cange JavaDoc
  * @author Christian Geuer-Pollmann
  */
 public abstract class CanonicalizerSpi {
 
-   /**
-    * Method canonicalize
-    *
-    *
-    * @param inputBytes
-    * @return the c14n bytes.
-    *
-    *
-    * @throws CanonicalizationException
-    * @throws java.io.IOException
-    * @throws javax.xml.parsers.ParserConfigurationException
-    * @throws org.xml.sax.SAXException
-    *
-    */
-   public byte[] engineCanonicalize(byte[] inputBytes)
-           throws javax.xml.parsers.ParserConfigurationException,
-                  java.io.IOException, org.xml.sax.SAXException,
-                  CanonicalizationException {
+    /** Reset the writer after a c14n */
+    protected boolean reset = false;
 
-      java.io.ByteArrayInputStream bais = new ByteArrayInputStream(inputBytes);
-      InputSource in = new InputSource(bais);
-      DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
-      dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
+    /**
+     * Method canonicalize
+     *
+     * @param inputBytes
+     * @return the c14n bytes.
+     *
+     * @throws CanonicalizationException
+     * @throws java.io.IOException
+     * @throws javax.xml.parsers.ParserConfigurationException
+     * @throws org.xml.sax.SAXException
+     */
+    public byte[] engineCanonicalize(byte[] inputBytes)
+        throws javax.xml.parsers.ParserConfigurationException, java.io.IOException,
+        org.xml.sax.SAXException, CanonicalizationException {
 
-      // needs to validate for ID attribute nomalization
-      dfactory.setNamespaceAware(true);
+        java.io.InputStream bais = new ByteArrayInputStream(inputBytes);
+        InputSource in = new InputSource(bais);
+        DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
+        dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
 
-      DocumentBuilder db = dfactory.newDocumentBuilder();
+        // needs to validate for ID attribute normalization
+        dfactory.setNamespaceAware(true);
+
+        DocumentBuilder db = dfactory.newDocumentBuilder();
 
-      /*
-       * for some of the test vectors from the specification,
-       * there has to be a validatin parser for ID attributes, default
-       * attribute values, NMTOKENS, etc.
-       * Unfortunaltely, the test vectors do use different DTDs or
-       * even no DTD. So Xerces 1.3.1 fires many warnings about using
-       * ErrorHandlers.
-       *
-       * Text from the spec:
-       *
-       * The input octet stream MUST contain a well-formed XML document,
-       * but the input need not be validated. However, the attribute
-       * value normalization and entity reference resolution MUST be
-       * performed in accordance with the behaviors of a validating
-       * XML processor. As well, nodes for default attributes (declared
-       * in the ATTLIST with an AttValue but not specified) are created
-       * in each element. Thus, the declarations in the document type
-       * declaration are used to help create the canonical form, even
-       * though the document type declaration is not retained in the
-       * canonical form.
-       *
-       */
+        Document document = db.parse(in);
+        return this.engineCanonicalizeSubTree(document);
+    }
 
-      // ErrorHandler eh = new C14NErrorHandler();
-      // db.setErrorHandler(eh);
-      Document document = db.parse(in);
-      byte result[] = this.engineCanonicalizeSubTree(document);
-      return result;
-   }
+    /**
+     * Method engineCanonicalizeXPathNodeSet
+     *
+     * @param xpathNodeSet
+     * @return the c14n bytes
+     * @throws CanonicalizationException
+     */
+    public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet)
+        throws CanonicalizationException {
+        return this.engineCanonicalizeXPathNodeSet(
+            XMLUtils.convertNodelistToSet(xpathNodeSet)
+        );
+    }
 
-   /**
-    * Method engineCanonicalizeXPathNodeSet
-    *
-    * @param xpathNodeSet
-    * @return the c14n bytes
-    * @throws CanonicalizationException
-    */
-   public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet)
-           throws CanonicalizationException {
-
-      return this
-         .engineCanonicalizeXPathNodeSet(XMLUtils
-            .convertNodelistToSet(xpathNodeSet));
-   }
+    /**
+     * Method engineCanonicalizeXPathNodeSet
+     *
+     * @param xpathNodeSet
+     * @param inclusiveNamespaces
+     * @return the c14n bytes
+     * @throws CanonicalizationException
+     */
+    public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet, String inclusiveNamespaces)
+        throws CanonicalizationException {
+        return this.engineCanonicalizeXPathNodeSet(
+            XMLUtils.convertNodelistToSet(xpathNodeSet), inclusiveNamespaces
+        );
+    }
 
-   /**
-    * Method engineCanonicalizeXPathNodeSet
-    *
-    * @param xpathNodeSet
-    * @param inclusiveNamespaces
-    * @return the c14n bytes
-    * @throws CanonicalizationException
-    */
-   public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet, String inclusiveNamespaces)
-           throws CanonicalizationException {
-
-      return this
-         .engineCanonicalizeXPathNodeSet(XMLUtils
-            .convertNodelistToSet(xpathNodeSet), inclusiveNamespaces);
-   }
+    /**
+     * Returns the URI of this engine.
+     * @return the URI
+     */
+    public abstract String engineGetURI();
 
-   //J-
-   /** Returns the URI of this engine.
-    * @return the URI
-    */
-   public abstract String engineGetURI();
+    /**
+     * Returns true if comments are included
+     * @return true if comments are included
+     */
+    public abstract boolean engineGetIncludeComments();
 
-   /** Returns the URI if include comments
-    * @return true if include.
-    */
-   public abstract boolean engineGetIncludeComments();
-
-   /**
-    * C14n a nodeset
-    *
-    * @param xpathNodeSet
-    * @return the c14n bytes
-    * @throws CanonicalizationException
-    */
-   public abstract byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet)
-      throws CanonicalizationException;
+    /**
+     * C14n a nodeset
+     *
+     * @param xpathNodeSet
+     * @return the c14n bytes
+     * @throws CanonicalizationException
+     */
+    public abstract byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet)
+        throws CanonicalizationException;
 
-   /**
-    * C14n a nodeset
-    *
-    * @param xpathNodeSet
-    * @param inclusiveNamespaces
-    * @return the c14n bytes
-    * @throws CanonicalizationException
-    */
-   public abstract byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet, String inclusiveNamespaces)
-      throws CanonicalizationException;
-
-   /**
-    * C14n a node tree.
-    *
-    * @param rootNode
-    * @return the c14n bytes
-    * @throws CanonicalizationException
-    */
-   public abstract byte[] engineCanonicalizeSubTree(Node rootNode)
-      throws CanonicalizationException;
+    /**
+     * C14n a nodeset
+     *
+     * @param xpathNodeSet
+     * @param inclusiveNamespaces
+     * @return the c14n bytes
+     * @throws CanonicalizationException
+     */
+    public abstract byte[] engineCanonicalizeXPathNodeSet(
+        Set<Node> xpathNodeSet, String inclusiveNamespaces
+    ) throws CanonicalizationException;
 
-   /**
-    * C14n a node tree.
-    *
-    * @param rootNode
-    * @param inclusiveNamespaces
-    * @return the c14n bytes
-    * @throws CanonicalizationException
-    */
-   public abstract byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces)
-      throws CanonicalizationException;
+    /**
+     * C14n a node tree.
+     *
+     * @param rootNode
+     * @return the c14n bytes
+     * @throws CanonicalizationException
+     */
+    public abstract byte[] engineCanonicalizeSubTree(Node rootNode)
+        throws CanonicalizationException;
 
-   /**
-    * Sets the writter where the cannocalization ends. ByteArrayOutputStream if
-    * none is setted.
-    * @param os
-    */
-   public abstract void setWriter(OutputStream os);
+    /**
+     * C14n a node tree.
+     *
+     * @param rootNode
+     * @param inclusiveNamespaces
+     * @return the c14n bytes
+     * @throws CanonicalizationException
+     */
+    public abstract byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces)
+        throws CanonicalizationException;
 
-   /** Reset the writter after a c14n */
-   protected boolean reset=false;
-   //J+
+    /**
+     * Sets the writer where the canonicalization ends. ByteArrayOutputStream if
+     * none is set.
+     * @param os
+     */
+    public abstract void setWriter(OutputStream os);
+
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,87 +2,82 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.c14n;
 
-
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 
-
-/**
- *
- * @author Christian Geuer-Pollmann
- */
 public class InvalidCanonicalizerException extends XMLSecurityException {
 
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
 
-   /**
-    * Constructor InvalidCanonicalizerException
-    *
-    */
-   public InvalidCanonicalizerException() {
-      super();
-   }
+    /**
+     * Constructor InvalidCanonicalizerException
+     *
+     */
+    public InvalidCanonicalizerException() {
+        super();
+    }
 
-   /**
-    * Constructor InvalidCanonicalizerException
-    *
-    * @param _msgID
-    */
-   public InvalidCanonicalizerException(String _msgID) {
-      super(_msgID);
-   }
+    /**
+     * Constructor InvalidCanonicalizerException
+     *
+     * @param msgID
+     */
+    public InvalidCanonicalizerException(String msgID) {
+        super(msgID);
+    }
 
-   /**
-    * Constructor InvalidCanonicalizerException
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public InvalidCanonicalizerException(String _msgID, Object exArgs[]) {
-      super(_msgID, exArgs);
-   }
+    /**
+     * Constructor InvalidCanonicalizerException
+     *
+     * @param msgID
+     * @param exArgs
+     */
+    public InvalidCanonicalizerException(String msgID, Object exArgs[]) {
+        super(msgID, exArgs);
+    }
 
-   /**
-    * Constructor InvalidCanonicalizerException
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public InvalidCanonicalizerException(String _msgID,
-                                        Exception _originalException) {
-      super(_msgID, _originalException);
-   }
+    /**
+     * Constructor InvalidCanonicalizerException
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public InvalidCanonicalizerException(String msgID, Exception originalException) {
+        super(msgID, originalException);
+    }
 
-   /**
-    * Constructor InvalidCanonicalizerException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public InvalidCanonicalizerException(String _msgID, Object exArgs[],
-                                        Exception _originalException) {
-      super(_msgID, exArgs, _originalException);
-   }
+    /**
+     * Constructor InvalidCanonicalizerException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public InvalidCanonicalizerException(
+        String msgID, Object exArgs[], Exception originalException
+    ) {
+        super(msgID, exArgs, originalException);
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.c14n.helper;
 
@@ -43,10 +45,10 @@
  */
 public class AttrCompare implements Comparator<Attr>, Serializable {
 
-    private final static long serialVersionUID = -7113259629930576230L;
-    private final static int ATTR0_BEFORE_ATTR1 = -1;
-    private final static int ATTR1_BEFORE_ATTR0 = 1;
-    private final static String XMLNS=Constants.NamespaceSpecNS;
+    private static final long serialVersionUID = -7113259629930576230L;
+    private static final int ATTR0_BEFORE_ATTR1 = -1;
+    private static final int ATTR1_BEFORE_ATTR0 = 1;
+    private static final String XMLNS = Constants.NamespaceSpecNS;
 
     /**
      * Compares two attributes based on the C14n specification.
@@ -69,12 +71,11 @@
      *
      */
     public int compare(Attr attr0, Attr attr1) {
-
         String namespaceURI0 = attr0.getNamespaceURI();
         String namespaceURI1 = attr1.getNamespaceURI();
 
-        boolean isNamespaceAttr0 = XMLNS==namespaceURI0;
-        boolean isNamespaceAttr1 = XMLNS==namespaceURI1;
+        boolean isNamespaceAttr0 = XMLNS.equals(namespaceURI0);
+        boolean isNamespaceAttr1 = XMLNS.equals(namespaceURI1);
 
         if (isNamespaceAttr0) {
             if (isNamespaceAttr1) {
@@ -82,11 +83,11 @@
                 String localname0 = attr0.getLocalName();
                 String localname1 = attr1.getLocalName();
 
-                if (localname0.equals("xmlns")) {
+                if ("xmlns".equals(localname0)) {
                     localname0 = "";
                 }
 
-                if (localname1.equals("xmlns")) {
+                if ("xmlns".equals(localname1)) {
                     localname1 = "";
                 }
 
@@ -94,9 +95,7 @@
             }
             // attr0 is a namespace, attr1 is not
             return ATTR0_BEFORE_ATTR1;
-        }
-
-        if (isNamespaceAttr1) {
+        } else if (isNamespaceAttr1) {
             // attr1 is a namespace, attr0 is not
             return ATTR1_BEFORE_ATTR0;
         }
@@ -109,9 +108,7 @@
                 return name0.compareTo(name1);
             }
             return ATTR0_BEFORE_ATTR1;
-        }
-
-        if (namespaceURI1 == null) {
+        } else if (namespaceURI1 == null) {
             return ATTR1_BEFORE_ATTR0;
         }
 
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,33 +2,32 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.c14n.helper;
 
-
-
 import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.NamedNodeMap;
 
-
 /**
  * Temporary swapped static functions from the normalizer Section
  *
@@ -36,129 +35,121 @@
  */
 public class C14nHelper {
 
-   /**
-    * Constructor C14nHelper
-    *
-    */
-   private C14nHelper() {
-
-      // don't allow instantiation
-   }
+    /**
+     * Constructor C14nHelper
+     *
+     */
+    private C14nHelper() {
+        // don't allow instantiation
+    }
 
-   /**
-    * Method namespaceIsRelative
-    *
-    * @param namespace
-    * @return true if the given namespace is relative.
-    */
-   public static boolean namespaceIsRelative(Attr namespace) {
-      return !namespaceIsAbsolute(namespace);
-   }
+    /**
+     * Method namespaceIsRelative
+     *
+     * @param namespace
+     * @return true if the given namespace is relative.
+     */
+    public static boolean namespaceIsRelative(Attr namespace) {
+        return !namespaceIsAbsolute(namespace);
+    }
 
-   /**
-    * Method namespaceIsRelative
-    *
-    * @param namespaceValue
-    * @return true if the given namespace is relative.
-    */
-   public static boolean namespaceIsRelative(String namespaceValue) {
-      return !namespaceIsAbsolute(namespaceValue);
-   }
+    /**
+     * Method namespaceIsRelative
+     *
+     * @param namespaceValue
+     * @return true if the given namespace is relative.
+     */
+    public static boolean namespaceIsRelative(String namespaceValue) {
+        return !namespaceIsAbsolute(namespaceValue);
+    }
 
-   /**
-    * Method namespaceIsAbsolute
-    *
-    * @param namespace
-    * @return true if the given namespace is absolute.
-    */
-   public static boolean namespaceIsAbsolute(Attr namespace) {
-      return namespaceIsAbsolute(namespace.getValue());
-   }
-
-   /**
-    * Method namespaceIsAbsolute
-    *
-    * @param namespaceValue
-    * @return true if the given namespace is absolute.
-    */
-   public static boolean namespaceIsAbsolute(String namespaceValue) {
+    /**
+     * Method namespaceIsAbsolute
+     *
+     * @param namespace
+     * @return true if the given namespace is absolute.
+     */
+    public static boolean namespaceIsAbsolute(Attr namespace) {
+        return namespaceIsAbsolute(namespace.getValue());
+    }
 
-      // assume empty namespaces are absolute
-      if (namespaceValue.length() == 0) {
-         return true;
-      }
-      return namespaceValue.indexOf(':')>0;
-   }
+    /**
+     * Method namespaceIsAbsolute
+     *
+     * @param namespaceValue
+     * @return true if the given namespace is absolute.
+     */
+    public static boolean namespaceIsAbsolute(String namespaceValue) {
+        // assume empty namespaces are absolute
+        if (namespaceValue.length() == 0) {
+            return true;
+        }
+        return namespaceValue.indexOf(':') > 0;
+    }
 
-   /**
-    * This method throws an exception if the Attribute value contains
-    * a relative URI.
-    *
-    * @param attr
-    * @throws CanonicalizationException
-    */
-   public static void assertNotRelativeNS(Attr attr)
-           throws CanonicalizationException {
+    /**
+     * This method throws an exception if the Attribute value contains
+     * a relative URI.
+     *
+     * @param attr
+     * @throws CanonicalizationException
+     */
+    public static void assertNotRelativeNS(Attr attr) throws CanonicalizationException {
+        if (attr == null) {
+            return;
+        }
 
-      if (attr == null) {
-         return;
-      }
+        String nodeAttrName = attr.getNodeName();
+        boolean definesDefaultNS = nodeAttrName.equals("xmlns");
+        boolean definesNonDefaultNS = nodeAttrName.startsWith("xmlns:");
 
-      String nodeAttrName = attr.getNodeName();
-      boolean definesDefaultNS = nodeAttrName.equals("xmlns");
-      boolean definesNonDefaultNS = nodeAttrName.startsWith("xmlns:");
-
-      if (definesDefaultNS || definesNonDefaultNS) {
-         if (namespaceIsRelative(attr)) {
+        if ((definesDefaultNS || definesNonDefaultNS) && namespaceIsRelative(attr)) {
             String parentName = attr.getOwnerElement().getTagName();
             String attrValue = attr.getValue();
             Object exArgs[] = { parentName, nodeAttrName, attrValue };
 
             throw new CanonicalizationException(
-               "c14n.Canonicalizer.RelativeNamespace", exArgs);
-         }
-      }
-   }
+                "c14n.Canonicalizer.RelativeNamespace", exArgs
+            );
+        }
+    }
 
-   /**
-    * This method throws a CanonicalizationException if the supplied Document
-    * is not able to be traversed using a TreeWalker.
-    *
-    * @param document
-    * @throws CanonicalizationException
-    */
-   public static void checkTraversability(Document document)
-           throws CanonicalizationException {
-
-      if (!document.isSupported("Traversal", "2.0")) {
-         Object exArgs[] = {
-            document.getImplementation().getClass().getName() };
-
-         throw new CanonicalizationException(
-            "c14n.Canonicalizer.TraversalNotSupported", exArgs);
-      }
-   }
+    /**
+     * This method throws a CanonicalizationException if the supplied Document
+     * is not able to be traversed using a TreeWalker.
+     *
+     * @param document
+     * @throws CanonicalizationException
+     */
+    public static void checkTraversability(Document document)
+        throws CanonicalizationException {
+        if (!document.isSupported("Traversal", "2.0")) {
+            Object exArgs[] = {document.getImplementation().getClass().getName() };
 
-   /**
-    * This method throws a CanonicalizationException if the supplied Element
-    * contains any relative namespaces.
-    *
-    * @param ctxNode
-    * @throws CanonicalizationException
-    * @see C14nHelper#assertNotRelativeNS(Attr)
-    */
-   public static void checkForRelativeNamespace(Element ctxNode)
-           throws CanonicalizationException {
+            throw new CanonicalizationException(
+                "c14n.Canonicalizer.TraversalNotSupported", exArgs
+            );
+        }
+    }
 
-      if (ctxNode != null) {
-         NamedNodeMap attributes = ctxNode.getAttributes();
+    /**
+     * This method throws a CanonicalizationException if the supplied Element
+     * contains any relative namespaces.
+     *
+     * @param ctxNode
+     * @throws CanonicalizationException
+     * @see C14nHelper#assertNotRelativeNS(Attr)
+     */
+    public static void checkForRelativeNamespace(Element ctxNode)
+        throws CanonicalizationException {
+        if (ctxNode != null) {
+            NamedNodeMap attributes = ctxNode.getAttributes();
 
-         for (int i = 0; i < attributes.getLength(); i++) {
-            C14nHelper.assertNotRelativeNS((Attr) attributes.item(i));
-         }
-      } else {
-         throw new CanonicalizationException(
-            "Called checkForRelativeNamespace() on null");
-      }
-   }
+            for (int i = 0; i < attributes.getLength(); i++) {
+                C14nHelper.assertNotRelativeNS((Attr) attributes.item(i));
+            }
+        } else {
+            throw new CanonicalizationException("Called checkForRelativeNamespace() on null");
+        }
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2008 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.c14n.implementations;
 
@@ -25,7 +27,6 @@
 import java.net.URISyntaxException;
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Comparator;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
@@ -34,7 +35,6 @@
 import java.util.SortedSet;
 import java.util.TreeSet;
 import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.xpath.XPath;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -42,8 +42,6 @@
 import org.w3c.dom.Node;
 import org.xml.sax.SAXException;
 
-import java.util.logging.Logger;
-import java.util.logging.Logger;
 import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
 import com.sun.org.apache.xml.internal.security.c14n.helper.C14nHelper;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
@@ -57,40 +55,46 @@
  *
  * @author Sean Mullan
  * @author Raul Benito
- * @version $Revision: 1.2 $
  */
 public abstract class Canonicalizer11 extends CanonicalizerBase {
-    boolean firstCall = true;
-    final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
-    static final String XMLNS_URI = Constants.NamespaceSpecNS;
-    static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS;
 
-    static Logger log = Logger.getLogger(Canonicalizer11.class.getName());
+    private static final String XMLNS_URI = Constants.NamespaceSpecNS;
+    private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS;
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(Canonicalizer11.class.getName());
+    private final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
 
-    static class XmlAttrStack {
-        int currentLevel = 0;
-        int lastlevel = 0;
-        XmlsStackElement cur;
+    private boolean firstCall = true;
+
+    private static class XmlAttrStack {
         static class XmlsStackElement {
             int level;
             boolean rendered = false;
             List<Attr> nodes = new ArrayList<Attr>();
         };
+
+        int currentLevel = 0;
+        int lastlevel = 0;
+        XmlsStackElement cur;
         List<XmlsStackElement> levels = new ArrayList<XmlsStackElement>();
+
         void push(int level) {
             currentLevel = level;
-            if (currentLevel == -1)
+            if (currentLevel == -1) {
                 return;
+            }
             cur = null;
             while (lastlevel >= currentLevel) {
                 levels.remove(levels.size() - 1);
-                if (levels.size() == 0) {
+                int newSize = levels.size();
+                if (newSize == 0) {
                     lastlevel = 0;
                     return;
                 }
-                lastlevel=(levels.get(levels.size()-1)).level;
+                lastlevel = (levels.get(newSize - 1)).level;
             }
         }
+
         void addXmlnsAttr(Attr n) {
             if (cur == null) {
                 cur = new XmlsStackElement();
@@ -100,22 +104,24 @@
             }
             cur.nodes.add(n);
         }
+
         void getXmlnsAttr(Collection<Attr> col) {
+            int size = levels.size() - 1;
             if (cur == null) {
                 cur = new XmlsStackElement();
                 cur.level = currentLevel;
                 lastlevel = currentLevel;
                 levels.add(cur);
             }
-            int size = levels.size() - 2;
             boolean parentRendered = false;
             XmlsStackElement e = null;
             if (size == -1) {
                 parentRendered = true;
             } else {
                 e = levels.get(size);
-                if (e.rendered && e.level+1 == currentLevel)
+                if (e.rendered && e.level + 1 == currentLevel) {
                     parentRendered = true;
+                }
             }
             if (parentRendered) {
                 col.addAll(cur.nodes);
@@ -126,7 +132,7 @@
             Map<String, Attr> loa = new HashMap<String, Attr>();
             List<Attr> baseAttrs = new ArrayList<Attr>();
             boolean successiveOmitted = true;
-            for (;size>=0;size--) {
+            for (; size >= 0; size--) {
                 e = levels.get(size);
                 if (e.rendered) {
                     successiveOmitted = false;
@@ -134,16 +140,15 @@
                 Iterator<Attr> it = e.nodes.iterator();
                 while (it.hasNext() && successiveOmitted) {
                     Attr n = it.next();
-                    if (n.getLocalName().equals("base")) {
-                        if (!e.rendered) {
-                            baseAttrs.add(n);
-                        }
-                    } else if (!loa.containsKey(n.getName()))
+                    if (n.getLocalName().equals("base") && !e.rendered) {
+                        baseAttrs.add(n);
+                    } else if (!loa.containsKey(n.getName())) {
                         loa.put(n.getName(), n);
+                    }
                 }
             }
             if (!baseAttrs.isEmpty()) {
-                Iterator<Attr> it = cur.nodes.iterator();
+                Iterator<Attr> it = col.iterator();
                 String base = null;
                 Attr baseAttr = null;
                 while (it.hasNext()) {
@@ -164,7 +169,9 @@
                         try {
                             base = joinURI(n.getValue(), base);
                         } catch (URISyntaxException ue) {
-                            ue.printStackTrace();
+                            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                                log.log(java.util.logging.Level.FINE, ue.getMessage(), ue);
+                            }
                         }
                     }
                 }
@@ -178,7 +185,8 @@
             col.addAll(loa.values());
         }
     };
-    XmlAttrStack xmlattrStack = new XmlAttrStack();
+
+    private XmlAttrStack xmlattrStack = new XmlAttrStack();
 
     /**
      * Constructor Canonicalizer11
@@ -190,194 +198,6 @@
     }
 
     /**
-     * Returns the Attr[]s to be outputted for the given element.
-     * <br>
-     * The code of this method is a copy of {@link #handleAttributes(Element,
-     * NameSpaceSymbTable)},
-     * whereas it takes into account that subtree-c14n is -- well --
-     * subtree-based.
-     * So if the element in question isRoot of c14n, it's parent is not in the
-     * node set, as well as all other ancestors.
-     *
-     * @param E
-     * @param ns
-     * @return the Attr[]s to be outputted
-     * @throws CanonicalizationException
-     */
-    Iterator<Attr> handleAttributesSubtree(Element E, NameSpaceSymbTable ns)
-        throws CanonicalizationException {
-        if (!E.hasAttributes() && !firstCall) {
-            return null;
-        }
-        // result will contain the attrs which have to be outputted
-        final SortedSet<Attr> result = this.result;
-        result.clear();
-        NamedNodeMap attrs = E.getAttributes();
-        int attrsLength = attrs.getLength();
-
-        for (int i = 0; i < attrsLength; i++) {
-            Attr N = (Attr) attrs.item(i);
-            String NUri = N.getNamespaceURI();
-
-            if (XMLNS_URI != NUri) {
-                // It's not a namespace attr node. Add to the result and
-                // continue.
-                result.add(N);
-                continue;
-            }
-
-            String NName = N.getLocalName();
-            String NValue = N.getValue();
-            if (XML.equals(NName)
-                && XML_LANG_URI.equals(NValue)) {
-                // The default mapping for xml must not be output.
-                continue;
-            }
-
-            Node n = ns.addMappingAndRender(NName, NValue, N);
-
-            if (n != null) {
-                // Render the ns definition
-                result.add((Attr)n);
-                if (C14nHelper.namespaceIsRelative(N)) {
-                    Object exArgs[] = {E.getTagName(), NName, N.getNodeValue()};
-                    throw new CanonicalizationException(
-                        "c14n.Canonicalizer.RelativeNamespace", exArgs);
-                }
-            }
-        }
-
-        if (firstCall) {
-            // It is the first node of the subtree
-            // Obtain all the namespaces defined in the parents, and added
-            // to the output.
-            ns.getUnrenderedNodes(result);
-            // output the attributes in the xml namespace.
-            xmlattrStack.getXmlnsAttr(getSortedSetAsCollection(result));
-            firstCall = false;
-        }
-
-        return result.iterator();
-    }
-
-
-
-    /**
-     * Returns the Attr[]s to be outputted for the given element.
-     * <br>
-     * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a
-     * DOM which has been prepared using
-     * {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650(
-     * org.w3c.dom.Document)}.
-     *
-     * @param E
-     * @param ns
-     * @return the Attr[]s to be outputted
-     * @throws CanonicalizationException
-     */
-    Iterator<Attr> handleAttributes(Element E, NameSpaceSymbTable ns)
-        throws CanonicalizationException {
-        // result will contain the attrs which have to be output
-        xmlattrStack.push(ns.getLevel());
-        boolean isRealVisible = isVisibleDO(E, ns.getLevel()) == 1;
-        NamedNodeMap attrs = null;
-        int attrsLength = 0;
-        if (E.hasAttributes()) {
-            attrs = E.getAttributes();
-            attrsLength = attrs.getLength();
-        }
-
-        SortedSet<Attr> result = this.result;
-        result.clear();
-
-        for (int i = 0; i < attrsLength; i++) {
-            Attr N = (Attr)attrs.item(i);
-            String NUri = N.getNamespaceURI();
-
-            if (XMLNS_URI != NUri) {
-                // A non namespace definition node.
-                if (XML_LANG_URI == NUri) {
-                    if (N.getLocalName().equals("id")) {
-                        if (isRealVisible) {
-                            // treat xml:id like any other attribute
-                            // (emit it, but don't inherit it)
-                            result.add(N);
-                        }
-                    } else {
-                        xmlattrStack.addXmlnsAttr(N);
-                    }
-                } else if (isRealVisible) {
-                    // The node is visible add the attribute to the list of
-                    // output attributes.
-                    result.add(N);
-                }
-                // keep working
-                continue;
-            }
-
-            String NName = N.getLocalName();
-            String NValue = N.getValue();
-            if ("xml".equals(NName)
-                && XML_LANG_URI.equals(NValue)) {
-                /* except omit namespace node with local name xml, which defines
-                 * the xml prefix, if its string value is
-                 * http://www.w3.org/XML/1998/namespace.
-                 */
-                continue;
-            }
-            // add the prefix binding to the ns symb table.
-            // ns.addInclusiveMapping(NName,NValue,N,isRealVisible);
-            if (isVisible(N))  {
-                if (!isRealVisible && ns.removeMappingIfRender(NName)) {
-                    continue;
-                }
-                // The xpath select this node output it if needed.
-                // Node n = ns.addMappingAndRenderXNodeSet
-                //      (NName, NValue, N, isRealVisible);
-                Node n = ns.addMappingAndRender(NName, NValue, N);
-                if (n != null) {
-                    result.add((Attr)n);
-                    if (C14nHelper.namespaceIsRelative(N)) {
-                        Object exArgs[] =
-                            { E.getTagName(), NName, N.getNodeValue() };
-                        throw new CanonicalizationException(
-                            "c14n.Canonicalizer.RelativeNamespace", exArgs);
-                    }
-                }
-            } else {
-                if (isRealVisible && NName != XMLNS) {
-                    ns.removeMapping(NName);
-                } else {
-                    ns.addMapping(NName, NValue, N);
-                }
-            }
-        }
-        if (isRealVisible) {
-            // The element is visible, handle the xmlns definition
-            Attr xmlns = E.getAttributeNodeNS(XMLNS_URI, XMLNS);
-            Node n = null;
-            if (xmlns == null) {
-                // No xmlns def just get the already defined.
-                n = ns.getMapping(XMLNS);
-            } else if (!isVisible(xmlns)) {
-                // There is a defn but the xmlns is not selected by the xpath.
-                // then xmlns=""
-                n = ns.addMappingAndRender(XMLNS, "", nullNode);
-            }
-            // output the xmlns def if needed.
-            if (n != null) {
-                result.add((Attr)n);
-            }
-            // Float all xml:* attributes of the unselected parent elements to
-            // this one. addXmlAttributes(E,result);
-            xmlattrStack.getXmlnsAttr(result);
-            ns.getUnrenderedNodes(result);
-        }
-
-        return result.iterator();
-    }
-
-    /**
      * Always throws a CanonicalizationException because this is inclusive c14n.
      *
      * @param xpathNodeSet
@@ -385,10 +205,10 @@
      * @return none it always fails
      * @throws CanonicalizationException always
      */
-    public byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet,
-        String inclusiveNamespaces) throws CanonicalizationException {
-        throw new CanonicalizationException(
-         "c14n.Canonicalizer.UnsupportedOperation");
+    public byte[] engineCanonicalizeXPathNodeSet(
+        Set<Node> xpathNodeSet, String inclusiveNamespaces
+    ) throws CanonicalizationException {
+        throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
     }
 
     /**
@@ -399,17 +219,189 @@
      * @return none it always fails
      * @throws CanonicalizationException
      */
-    public byte[] engineCanonicalizeSubTree(Node rootNode,
-        String inclusiveNamespaces) throws CanonicalizationException {
-        throw new CanonicalizationException(
-            "c14n.Canonicalizer.UnsupportedOperation");
+    public byte[] engineCanonicalizeSubTree(
+        Node rootNode, String inclusiveNamespaces
+    ) throws CanonicalizationException {
+        throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
+    }
+
+    /**
+     * Returns the Attr[]s to be output for the given element.
+     * <br>
+     * The code of this method is a copy of {@link #handleAttributes(Element,
+     * NameSpaceSymbTable)},
+     * whereas it takes into account that subtree-c14n is -- well --
+     * subtree-based.
+     * So if the element in question isRoot of c14n, it's parent is not in the
+     * node set, as well as all other ancestors.
+     *
+     * @param element
+     * @param ns
+     * @return the Attr[]s to be output
+     * @throws CanonicalizationException
+     */
+    @Override
+    protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
+        throws CanonicalizationException {
+        if (!element.hasAttributes() && !firstCall) {
+            return null;
+        }
+        // result will contain the attrs which have to be output
+        final SortedSet<Attr> result = this.result;
+        result.clear();
+
+        if (element.hasAttributes()) {
+            NamedNodeMap attrs = element.getAttributes();
+            int attrsLength = attrs.getLength();
+
+            for (int i = 0; i < attrsLength; i++) {
+                Attr attribute = (Attr) attrs.item(i);
+                String NUri = attribute.getNamespaceURI();
+                String NName = attribute.getLocalName();
+                String NValue = attribute.getValue();
+
+                if (!XMLNS_URI.equals(NUri)) {
+                    // It's not a namespace attr node. Add to the result and continue.
+                    result.add(attribute);
+                } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NValue))) {
+                    // The default mapping for xml must not be output.
+                    Node n = ns.addMappingAndRender(NName, NValue, attribute);
+
+                    if (n != null) {
+                        // Render the ns definition
+                        result.add((Attr)n);
+                        if (C14nHelper.namespaceIsRelative(attribute)) {
+                            Object exArgs[] = {element.getTagName(), NName, attribute.getNodeValue()};
+                            throw new CanonicalizationException(
+                                "c14n.Canonicalizer.RelativeNamespace", exArgs
+                            );
+                        }
+                    }
+                }
+            }
+        }
+
+        if (firstCall) {
+            // It is the first node of the subtree
+            // Obtain all the namespaces defined in the parents, and added to the output.
+            ns.getUnrenderedNodes(result);
+            // output the attributes in the xml namespace.
+            xmlattrStack.getXmlnsAttr(result);
+            firstCall = false;
+        }
+
+        return result.iterator();
     }
 
-    void circumventBugIfNeeded(XMLSignatureInput input)
+    /**
+     * Returns the Attr[]s to be output for the given element.
+     * <br>
+     * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a
+     * DOM which has been prepared using
+     * {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650(
+     * org.w3c.dom.Document)}.
+     *
+     * @param element
+     * @param ns
+     * @return the Attr[]s to be output
+     * @throws CanonicalizationException
+     */
+    @Override
+    protected Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
+        throws CanonicalizationException {
+        // result will contain the attrs which have to be output
+        xmlattrStack.push(ns.getLevel());
+        boolean isRealVisible = isVisibleDO(element, ns.getLevel()) == 1;
+        final SortedSet<Attr> result = this.result;
+        result.clear();
+
+        if (element.hasAttributes()) {
+            NamedNodeMap attrs = element.getAttributes();
+            int attrsLength = attrs.getLength();
+
+            for (int i = 0; i < attrsLength; i++) {
+                Attr attribute = (Attr) attrs.item(i);
+                String NUri = attribute.getNamespaceURI();
+                String NName = attribute.getLocalName();
+                String NValue = attribute.getValue();
+
+                if (!XMLNS_URI.equals(NUri)) {
+                    //A non namespace definition node.
+                    if (XML_LANG_URI.equals(NUri)) {
+                        if (NName.equals("id")) {
+                            if (isRealVisible) {
+                                // treat xml:id like any other attribute
+                                // (emit it, but don't inherit it)
+                                result.add(attribute);
+                            }
+                        } else {
+                            xmlattrStack.addXmlnsAttr(attribute);
+                        }
+                    } else if (isRealVisible) {
+                        //The node is visible add the attribute to the list of output attributes.
+                        result.add(attribute);
+                    }
+                } else if (!XML.equals(NName) || !XML_LANG_URI.equals(NValue)) {
+                    /* except omit namespace node with local name xml, which defines
+                     * the xml prefix, if its string value is
+                     * http://www.w3.org/XML/1998/namespace.
+                     */
+                    // add the prefix binding to the ns symb table.
+                    if (isVisible(attribute))  {
+                        if (isRealVisible || !ns.removeMappingIfRender(NName)) {
+                            // The xpath select this node output it if needed.
+                            Node n = ns.addMappingAndRender(NName, NValue, attribute);
+                            if (n != null) {
+                                result.add((Attr)n);
+                                if (C14nHelper.namespaceIsRelative(attribute)) {
+                                    Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() };
+                                    throw new CanonicalizationException(
+                                        "c14n.Canonicalizer.RelativeNamespace", exArgs
+                                    );
+                                }
+                            }
+                        }
+                    } else {
+                        if (isRealVisible && !XMLNS.equals(NName)) {
+                            ns.removeMapping(NName);
+                        } else {
+                            ns.addMapping(NName, NValue, attribute);
+                        }
+                    }
+                }
+            }
+        }
+
+        if (isRealVisible) {
+            //The element is visible, handle the xmlns definition
+            Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS);
+            Node n = null;
+            if (xmlns == null) {
+                //No xmlns def just get the already defined.
+                n = ns.getMapping(XMLNS);
+            } else if (!isVisible(xmlns)) {
+                //There is a definition but the xmlns is not selected by the xpath.
+                //then xmlns=""
+                n = ns.addMappingAndRender(XMLNS, "", nullNode);
+            }
+            //output the xmlns def if needed.
+            if (n != null) {
+                result.add((Attr)n);
+            }
+            //Float all xml:* attributes of the unselected parent elements to this one.
+            xmlattrStack.getXmlnsAttr(result);
+            ns.getUnrenderedNodes(result);
+        }
+
+        return result.iterator();
+    }
+
+    protected void circumventBugIfNeeded(XMLSignatureInput input)
         throws CanonicalizationException, ParserConfigurationException,
         IOException, SAXException {
-        if (!input.isNeedsToBeExpanded())
+        if (!input.isNeedsToBeExpanded()) {
             return;
+        }
         Document doc = null;
         if (input.getSubNode() != null) {
             doc = XMLUtils.getOwnerDocument(input.getSubNode());
@@ -419,40 +411,47 @@
         XMLUtils.circumventBug2650(doc);
     }
 
-    void handleParent(Element e, NameSpaceSymbTable ns) {
-        if (!e.hasAttributes()) {
+    protected void handleParent(Element e, NameSpaceSymbTable ns) {
+        if (!e.hasAttributes() && e.getNamespaceURI() == null) {
             return;
         }
         xmlattrStack.push(-1);
         NamedNodeMap attrs = e.getAttributes();
         int attrsLength = attrs.getLength();
         for (int i = 0; i < attrsLength; i++) {
-            Attr N = (Attr) attrs.item(i);
-            if (Constants.NamespaceSpecNS != N.getNamespaceURI()) {
-                // Not a namespace definition, ignore.
-                if (XML_LANG_URI == N.getNamespaceURI()) {
-                    xmlattrStack.addXmlnsAttr(N);
+            Attr attribute = (Attr) attrs.item(i);
+            String NName = attribute.getLocalName();
+            String NValue = attribute.getNodeValue();
+
+            if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())) {
+                if (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
+                    ns.addMapping(NName, NValue, attribute);
                 }
-                continue;
+            } else if (!"id".equals(NName) && XML_LANG_URI.equals(attribute.getNamespaceURI())) {
+                xmlattrStack.addXmlnsAttr(attribute);
             }
-
-            String NName = N.getLocalName();
-            String NValue = N.getNodeValue();
-            if (XML.equals(NName)
-                && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
-                continue;
+        }
+        if (e.getNamespaceURI() != null) {
+            String NName = e.getPrefix();
+            String NValue = e.getNamespaceURI();
+            String Name;
+            if (NName == null || NName.equals("")) {
+                NName = "xmlns";
+                Name = "xmlns";
+            } else {
+                Name = "xmlns:" + NName;
             }
-            ns.addMapping(NName,NValue,N);
+            Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name);
+            n.setValue(NValue);
+            ns.addMapping(NName, NValue, n);
         }
     }
 
-    private static String joinURI(String baseURI, String relativeURI)
-        throws URISyntaxException {
+    private static String joinURI(String baseURI, String relativeURI) throws URISyntaxException {
         String bscheme = null;
         String bauthority = null;
         String bpath = "";
         String bquery = null;
-        String bfragment = null; // Is this correct?
 
         // pre-parse the baseURI
         if (baseURI != null) {
@@ -464,7 +463,6 @@
             bauthority = base.getAuthority();
             bpath = base.getPath();
             bquery = base.getQuery();
-            bfragment = base.getFragment();
         }
 
         URI r = new URI(relativeURI);
@@ -472,9 +470,8 @@
         String rauthority = r.getAuthority();
         String rpath = r.getPath();
         String rquery = r.getQuery();
-        String rfragment = null;
 
-        String tscheme, tauthority, tpath, tquery, tfragment;
+        String tscheme, tauthority, tpath, tquery;
         if (rscheme != null && rscheme.equals(bscheme)) {
             rscheme = null;
         }
@@ -518,13 +515,13 @@
             }
             tscheme = bscheme;
         }
-        tfragment = rfragment;
-        return new URI(tscheme, tauthority, tpath, tquery, tfragment).toString();
+        return new URI(tscheme, tauthority, tpath, tquery, null).toString();
     }
 
     private static String removeDotSegments(String path) {
-
-        log.log(java.util.logging.Level.FINE, "STEP   OUTPUT BUFFER\t\tINPUT BUFFER");
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "STEP   OUTPUT BUFFER\t\tINPUT BUFFER");
+        }
 
         // 1. The input buffer is initialized with the now-appended path
         // components then replace occurrences of "//" in the input buffer
@@ -535,7 +532,7 @@
         }
 
         // Initialize the output buffer with the empty string.
-        StringBuffer output = new StringBuffer();
+        StringBuilder output = new StringBuilder();
 
         // If the input buffer starts with a root slash "/" then move this
         // character to the output buffer.
@@ -563,9 +560,9 @@
                     output.append("../");
                 }
                 printStep("2A", output.toString(), input);
-            // 2B. if the input buffer begins with a prefix of "/./" or "/.",
-            // where "." is a complete path segment, then replace that prefix
-            // with "/" in the input buffer; otherwise,
+                // 2B. if the input buffer begins with a prefix of "/./" or "/.",
+                // where "." is a complete path segment, then replace that prefix
+                // with "/" in the input buffer; otherwise,
             } else if (input.startsWith("/./")) {
                 input = input.substring(2);
                 printStep("2B", output.toString(), input);
@@ -573,16 +570,16 @@
                 // FIXME: what is complete path segment?
                 input = input.replaceFirst("/.", "/");
                 printStep("2B", output.toString(), input);
-            // 2C. if the input buffer begins with a prefix of "/../" or "/..",
-            // where ".." is a complete path segment, then replace that prefix
-            // with "/" in the input buffer and if also the output buffer is
-            // empty, last segment in the output buffer equals "../" or "..",
-            // where ".." is a complete path segment, then append ".." or "/.."
-            // for the latter case respectively to the output buffer else
-            // remove the last segment and its preceding "/" (if any) from the
-            // output buffer and if hereby the first character in the output
-            // buffer was removed and it was not the root slash then delete a
-            // leading slash from the input buffer; otherwise,
+                // 2C. if the input buffer begins with a prefix of "/../" or "/..",
+                // where ".." is a complete path segment, then replace that prefix
+                // with "/" in the input buffer and if also the output buffer is
+                // empty, last segment in the output buffer equals "../" or "..",
+                // where ".." is a complete path segment, then append ".." or "/.."
+                // for the latter case respectively to the output buffer else
+                // remove the last segment and its preceding "/" (if any) from the
+                // output buffer and if hereby the first character in the output
+                // buffer was removed and it was not the root slash then delete a
+                // leading slash from the input buffer; otherwise,
             } else if (input.startsWith("/../")) {
                 input = input.substring(3);
                 if (output.length() == 0) {
@@ -594,7 +591,7 @@
                 } else {
                     int index = output.lastIndexOf("/");
                     if (index == -1) {
-                        output = new StringBuffer();
+                        output = new StringBuilder();
                         if (input.charAt(0) == '/') {
                             input = input.substring(1);
                         }
@@ -615,7 +612,7 @@
                 } else {
                     int index = output.lastIndexOf("/");
                     if (index == -1) {
-                        output = new StringBuffer();
+                        output = new StringBuilder();
                         if (input.charAt(0) == '/') {
                             input = input.substring(1);
                         }
@@ -624,23 +621,24 @@
                     }
                 }
                 printStep("2C", output.toString(), input);
-            // 2D. if the input buffer consists only of ".", then remove
-            // that from the input buffer else if the input buffer consists
-            // only of ".." and if the output buffer does not contain only
-            // the root slash "/", then move the ".." to the output buffer
-            // else delte it.; otherwise,
+                // 2D. if the input buffer consists only of ".", then remove
+                // that from the input buffer else if the input buffer consists
+                // only of ".." and if the output buffer does not contain only
+                // the root slash "/", then move the ".." to the output buffer
+                // else delte it.; otherwise,
             } else if (input.equals(".")) {
                 input = "";
                 printStep("2D", output.toString(), input);
             } else if (input.equals("..")) {
-                if (!output.toString().equals("/"))
+                if (!output.toString().equals("/")) {
                     output.append("..");
+                }
                 input = "";
                 printStep("2D", output.toString(), input);
-            // 2E. move the first path segment (if any) in the input buffer
-            // to the end of the output buffer, including the initial "/"
-            // character (if any) and any subsequent characters up to, but not
-            // including, the next "/" character or the end of the input buffer.
+                // 2E. move the first path segment (if any) in the input buffer
+                // to the end of the output buffer, including the initial "/"
+                // character (if any) and any subsequent characters up to, but not
+                // including, the next "/" character or the end of the input buffer.
             } else {
                 int end = -1;
                 int begin = input.indexOf('/');
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2008 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.c14n.implementations;
 
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2008 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.c14n.implementations;
 
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.c14n.implementations;
 
-
-
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Collection;
@@ -47,344 +47,348 @@
 import org.w3c.dom.Node;
 import org.xml.sax.SAXException;
 
-
 /**
  * Implements <A HREF="http://www.w3.org/TR/2001/REC-xml-c14n-20010315">Canonical
  * XML Version 1.0</A>, a W3C Recommendation from 15 March 2001.
  *
  * @author Christian Geuer-Pollmann <geuerp@apache.org>
- * @version $Revision: 1.5 $
  */
 public abstract class Canonicalizer20010315 extends CanonicalizerBase {
-        boolean firstCall=true;
-        final SortedSet<Attr> result= new TreeSet<Attr>(COMPARE);
-    static final String XMLNS_URI=Constants.NamespaceSpecNS;
-    static final String XML_LANG_URI=Constants.XML_LANG_SPACE_SpecNS;
-    static class XmlAttrStack {
-        int currentLevel=0;
-        int lastlevel=0;
+    private static final String XMLNS_URI = Constants.NamespaceSpecNS;
+    private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS;
+
+    private boolean firstCall = true;
+    private final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
+
+    private static class XmlAttrStack {
+        static class XmlsStackElement {
+            int level;
+            boolean rendered = false;
+            List<Attr> nodes = new ArrayList<Attr>();
+        };
+
+        int currentLevel = 0;
+        int lastlevel = 0;
         XmlsStackElement cur;
-        static class XmlsStackElement {
-                int level;
-                boolean rendered=false;
-                List<Attr> nodes=new ArrayList<Attr>();
-        };
-        List<XmlsStackElement> levels=new ArrayList<XmlsStackElement>();
+        List<XmlsStackElement> levels = new ArrayList<XmlsStackElement>();
+
         void push(int level) {
-                currentLevel=level;
-                if (currentLevel==-1)
-                        return;
-                cur=null;
-                while (lastlevel>=currentLevel) {
-                        levels.remove(levels.size()-1);
-                        if (levels.size()==0) {
-                                lastlevel=0;
-                                return;
-                        }
-                        lastlevel=(levels.get(levels.size()-1)).level;
+            currentLevel = level;
+            if (currentLevel == -1) {
+                return;
+            }
+            cur = null;
+            while (lastlevel >= currentLevel) {
+                levels.remove(levels.size() - 1);
+                int newSize = levels.size();
+                if (newSize == 0) {
+                    lastlevel = 0;
+                    return;
                 }
+                lastlevel = (levels.get(newSize - 1)).level;
+            }
         }
+
         void addXmlnsAttr(Attr n) {
-                if (cur==null) {
-                        cur=new XmlsStackElement();
-                        cur.level=currentLevel;
-                        levels.add(cur);
-                        lastlevel=currentLevel;
-                }
-                cur.nodes.add(n);
+            if (cur == null) {
+                cur = new XmlsStackElement();
+                cur.level = currentLevel;
+                levels.add(cur);
+                lastlevel = currentLevel;
+            }
+            cur.nodes.add(n);
         }
+
         void getXmlnsAttr(Collection<Attr> col) {
-                int size=levels.size()-1;
-                if (cur==null) {
-                        cur=new XmlsStackElement();
-                        cur.level=currentLevel;
-                        lastlevel=currentLevel;
-                        levels.add(cur);
-                }
-                boolean parentRendered=false;
-                XmlsStackElement e=null;
-                if (size==-1) {
-                        parentRendered=true;
-                } else {
-                        e=levels.get(size);
-                        if (e.rendered && e.level+1==currentLevel)
-                                parentRendered=true;
-
+            int size = levels.size() - 1;
+            if (cur == null) {
+                cur = new XmlsStackElement();
+                cur.level = currentLevel;
+                lastlevel = currentLevel;
+                levels.add(cur);
+            }
+            boolean parentRendered = false;
+            XmlsStackElement e = null;
+            if (size == -1) {
+                parentRendered = true;
+            } else {
+                e = levels.get(size);
+                if (e.rendered && e.level + 1 == currentLevel) {
+                    parentRendered = true;
                 }
-                if (parentRendered) {
-                                col.addAll(cur.nodes);
-                                cur.rendered=true;
-                                return;
-                        }
+            }
+            if (parentRendered) {
+                col.addAll(cur.nodes);
+                cur.rendered = true;
+                return;
+            }
 
-                        Map<String,Attr> loa = new HashMap<String,Attr>();
-                for (;size>=0;size--) {
-                        e=levels.get(size);
-                        Iterator<Attr> it=e.nodes.iterator();
-                        while (it.hasNext()) {
-                                Attr n=it.next();
-                                if (!loa.containsKey(n.getName()))
-                                        loa.put(n.getName(),n);
-                        }
-                        //if (e.rendered)
-                                //break;
+            Map<String, Attr> loa = new HashMap<String, Attr>();
+            for (; size >= 0; size--) {
+                e = levels.get(size);
+                Iterator<Attr> it = e.nodes.iterator();
+                while (it.hasNext()) {
+                    Attr n = it.next();
+                    if (!loa.containsKey(n.getName())) {
+                        loa.put(n.getName(), n);
+                    }
+                }
+            }
 
-                };
-                //cur.nodes.clear();
-                //cur.nodes.addAll(loa.values());
-                        cur.rendered=true;
-                col.addAll(loa.values());
+            cur.rendered = true;
+            col.addAll(loa.values());
         }
 
     }
-    XmlAttrStack xmlattrStack=new XmlAttrStack();
+
+    private XmlAttrStack xmlattrStack = new XmlAttrStack();
+
     /**
-    * Constructor Canonicalizer20010315
-    *
-    * @param includeComments
-    */
-   public Canonicalizer20010315(boolean includeComments) {
-      super(includeComments);
-   }
+     * Constructor Canonicalizer20010315
+     *
+     * @param includeComments
+     */
+    public Canonicalizer20010315(boolean includeComments) {
+        super(includeComments);
+    }
 
-   /**
-    * Returns the Attr[]s to be outputted for the given element.
-    * <br>
-    * The code of this method is a copy of {@link #handleAttributes(Element,
-    * NameSpaceSymbTable)},
-    * whereas it takes into account that subtree-c14n is -- well -- subtree-based.
-    * So if the element in question isRoot of c14n, it's parent is not in the
-    * node set, as well as all other ancestors.
-    *
-    * @param E
-    * @param ns
-    * @return the Attr[]s to be outputted
-    * @throws CanonicalizationException
-    */
-   Iterator<Attr> handleAttributesSubtree(Element E,  NameSpaceSymbTable ns )
-           throws CanonicalizationException {
-          if (!E.hasAttributes() && !firstCall) {
-         return null;
-      }
-      // result will contain the attrs which have to be outputted
-      final SortedSet<Attr> result = this.result;
-      result.clear();
-      NamedNodeMap attrs = E.getAttributes();
-      int attrsLength = attrs.getLength();
+    /**
+     * Always throws a CanonicalizationException because this is inclusive c14n.
+     *
+     * @param xpathNodeSet
+     * @param inclusiveNamespaces
+     * @return none it always fails
+     * @throws CanonicalizationException always
+     */
+    public byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet, String inclusiveNamespaces)
+        throws CanonicalizationException {
+
+        /** $todo$ well, should we throw UnsupportedOperationException ? */
+        throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
+    }
 
-      for (int i = 0; i < attrsLength; i++) {
-         Attr N = (Attr) attrs.item(i);
-         String NUri =N.getNamespaceURI();
+    /**
+     * Always throws a CanonicalizationException because this is inclusive c14n.
+     *
+     * @param rootNode
+     * @param inclusiveNamespaces
+     * @return none it always fails
+     * @throws CanonicalizationException
+     */
+    public byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces)
+        throws CanonicalizationException {
 
-         if (XMLNS_URI!=NUri) {
-                //It's not a namespace attr node. Add to the result and continue.
-            result.add(N);
-            continue;
-         }
+        /** $todo$ well, should we throw UnsupportedOperationException ? */
+        throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
+    }
 
-         String NName=N.getLocalName();
-         String NValue=N.getValue();
-         if (XML.equals(NName)
-                 && XML_LANG_URI.equals(NValue)) {
-                //The default mapping for xml must not be output.
-                continue;
-         }
-
-         Node n=ns.addMappingAndRender(NName,NValue,N);
+    /**
+     * Returns the Attr[]s to be output for the given element.
+     * <br>
+     * The code of this method is a copy of {@link #handleAttributes(Element,
+     * NameSpaceSymbTable)},
+     * whereas it takes into account that subtree-c14n is -- well -- subtree-based.
+     * So if the element in question isRoot of c14n, it's parent is not in the
+     * node set, as well as all other ancestors.
+     *
+     * @param element
+     * @param ns
+     * @return the Attr[]s to be output
+     * @throws CanonicalizationException
+     */
+    @Override
+    protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
+        throws CanonicalizationException {
+        if (!element.hasAttributes() && !firstCall) {
+            return null;
+        }
+        // result will contain the attrs which have to be output
+        final SortedSet<Attr> result = this.result;
+        result.clear();
 
-          if (n!=null) {
-                 //Render the ns definition
-             result.add((Attr)n);
-             if (C14nHelper.namespaceIsRelative(N)) {
-                Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() };
-                throw new CanonicalizationException(
-                   "c14n.Canonicalizer.RelativeNamespace", exArgs);
-             }
-          }
-      }
+        if (element.hasAttributes()) {
+            NamedNodeMap attrs = element.getAttributes();
+            int attrsLength = attrs.getLength();
 
-      if (firstCall) {
-        //It is the first node of the subtree
-        //Obtain all the namespaces defined in the parents, and added to the output.
-        ns.getUnrenderedNodes(getSortedSetAsCollection(result));
-        //output the attributes in the xml namespace.
-        xmlattrStack.getXmlnsAttr(result);
-                firstCall=false;
-      }
+            for (int i = 0; i < attrsLength; i++) {
+                Attr attribute = (Attr) attrs.item(i);
+                String NUri = attribute.getNamespaceURI();
+                String NName = attribute.getLocalName();
+                String NValue = attribute.getValue();
 
-      return result.iterator();
-   }
+                if (!XMLNS_URI.equals(NUri)) {
+                    //It's not a namespace attr node. Add to the result and continue.
+                    result.add(attribute);
+                } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NValue))) {
+                    //The default mapping for xml must not be output.
+                    Node n = ns.addMappingAndRender(NName, NValue, attribute);
 
-   /**
-    * Returns the Attr[]s to be outputted for the given element.
-    * <br>
-    * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has
-    * been prepared using {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650(
-    * org.w3c.dom.Document)}.
-    *
-    * @param E
-    * @param ns
-    * @return the Attr[]s to be outputted
-    * @throws CanonicalizationException
-    */
-   Iterator<Attr> handleAttributes(Element E,  NameSpaceSymbTable ns ) throws CanonicalizationException {
-    // result will contain the attrs which have to be outputted
-        xmlattrStack.push(ns.getLevel());
-    boolean isRealVisible=isVisibleDO(E,ns.getLevel())==1;
-    NamedNodeMap attrs = null;
-    int attrsLength = 0;
-    if (E.hasAttributes()) {
-        attrs=E.getAttributes();
-       attrsLength= attrs.getLength();
+                    if (n != null) {
+                        //Render the ns definition
+                        result.add((Attr)n);
+                        if (C14nHelper.namespaceIsRelative(attribute)) {
+                            Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() };
+                            throw new CanonicalizationException(
+                                "c14n.Canonicalizer.RelativeNamespace", exArgs
+                            );
+                        }
+                    }
+                }
+            }
+        }
+
+        if (firstCall) {
+            //It is the first node of the subtree
+            //Obtain all the namespaces defined in the parents, and added to the output.
+            ns.getUnrenderedNodes(result);
+            //output the attributes in the xml namespace.
+            xmlattrStack.getXmlnsAttr(result);
+            firstCall = false;
+        }
+
+        return result.iterator();
     }
 
-
-    SortedSet<Attr> result = this.result;
-    result.clear();
-
-    for (int i = 0; i < attrsLength; i++) {
-       Attr N = (Attr) attrs.item(i);
-       String NUri =N.getNamespaceURI();
+    /**
+     * Returns the Attr[]s to be output for the given element.
+     * <br>
+     * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has
+     * been prepared using {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650(
+     * org.w3c.dom.Document)}.
+     *
+     * @param element
+     * @param ns
+     * @return the Attr[]s to be output
+     * @throws CanonicalizationException
+     */
+    @Override
+    protected Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
+        throws CanonicalizationException {
+        // result will contain the attrs which have to be output
+        xmlattrStack.push(ns.getLevel());
+        boolean isRealVisible = isVisibleDO(element, ns.getLevel()) == 1;
+        final SortedSet<Attr> result = this.result;
+        result.clear();
 
-       if (XMLNS_URI!=NUri) {
-          //A non namespace definition node.
-           if (XML_LANG_URI==NUri) {
-                          xmlattrStack.addXmlnsAttr(N);
-           } else if (isRealVisible){
-                //The node is visible add the attribute to the list of output attributes.
-                result.add(N);
-          }
-          //keep working
-          continue;
-       }
+        if (element.hasAttributes()) {
+            NamedNodeMap attrs = element.getAttributes();
+            int attrsLength = attrs.getLength();
+
+            for (int i = 0; i < attrsLength; i++) {
+                Attr attribute = (Attr) attrs.item(i);
+                String NUri = attribute.getNamespaceURI();
+                String NName = attribute.getLocalName();
+                String NValue = attribute.getValue();
 
-       String NName=N.getLocalName();
-       String NValue=N.getValue();
-       if ("xml".equals(NName)
-               && XML_LANG_URI.equals(NValue)) {
-          /* except omit namespace node with local name xml, which defines
-           * the xml prefix, if its string value is http://www.w3.org/XML/1998/namespace.
-           */
-          continue;
-       }
-       //add the prefix binding to the ns symb table.
-       //ns.addInclusiveMapping(NName,NValue,N,isRealVisible);
-            if  (isVisible(N))  {
-                if (!isRealVisible && ns.removeMappingIfRender(NName)) {
-                        continue;
+                if (!XMLNS_URI.equals(NUri)) {
+                    //A non namespace definition node.
+                    if (XML_LANG_URI.equals(NUri)) {
+                        xmlattrStack.addXmlnsAttr(attribute);
+                    } else if (isRealVisible) {
+                        //The node is visible add the attribute to the list of output attributes.
+                        result.add(attribute);
+                    }
+                } else if (!XML.equals(NName) || !XML_LANG_URI.equals(NValue)) {
+                    /* except omit namespace node with local name xml, which defines
+                     * the xml prefix, if its string value is http://www.w3.org/XML/1998/namespace.
+                     */
+                    //add the prefix binding to the ns symb table.
+                    if (isVisible(attribute))  {
+                        if (isRealVisible || !ns.removeMappingIfRender(NName)) {
+                            //The xpath select this node output it if needed.
+                            Node n = ns.addMappingAndRender(NName, NValue, attribute);
+                            if (n != null) {
+                                result.add((Attr)n);
+                                if (C14nHelper.namespaceIsRelative(attribute)) {
+                                    Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() };
+                                    throw new CanonicalizationException(
+                                        "c14n.Canonicalizer.RelativeNamespace", exArgs
+                                    );
+                                }
+                            }
+                        }
+                    } else {
+                        if (isRealVisible && !XMLNS.equals(NName)) {
+                            ns.removeMapping(NName);
+                        } else {
+                            ns.addMapping(NName, NValue, attribute);
+                        }
+                    }
                 }
-                        //The xpath select this node output it if needed.
-                //Node n=ns.addMappingAndRenderXNodeSet(NName,NValue,N,isRealVisible);
-                Node n=ns.addMappingAndRender(NName,NValue,N);
-                        if (n!=null) {
-                                        result.add((Attr)n);
-                    if (C14nHelper.namespaceIsRelative(N)) {
-                       Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() };
-                       throw new CanonicalizationException(
-                          "c14n.Canonicalizer.RelativeNamespace", exArgs);
-                   }
-                         }
-        } else {
-                if (isRealVisible && NName!=XMLNS) {
-                        ns.removeMapping(NName);
-                } else {
-                        ns.addMapping(NName,NValue,N);
-                }
+            }
         }
-    }
-    if (isRealVisible) {
-        //The element is visible, handle the xmlns definition
-        Attr xmlns = E.getAttributeNodeNS(XMLNS_URI, XMLNS);
-        Node n=null;
-        if (xmlns == null) {
+        if (isRealVisible) {
+            //The element is visible, handle the xmlns definition
+            Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS);
+            Node n = null;
+            if (xmlns == null) {
                 //No xmlns def just get the already defined.
-                n=ns.getMapping(XMLNS);
-        } else if ( !isVisible(xmlns)) {
+                n = ns.getMapping(XMLNS);
+            } else if (!isVisible(xmlns)) {
                 //There is a definition but the xmlns is not selected by the xpath.
                 //then xmlns=""
-                n=ns.addMappingAndRender(XMLNS,"",nullNode);
-        }
-        //output the xmlns def if needed.
-        if (n!=null) {
-                        result.add((Attr)n);
+                n = ns.addMappingAndRender(XMLNS, "", nullNode);
+            }
+            //output the xmlns def if needed.
+            if (n != null) {
+                result.add((Attr)n);
+            }
+            //Float all xml:* attributes of the unselected parent elements to this one.
+            xmlattrStack.getXmlnsAttr(result);
+            ns.getUnrenderedNodes(result);
         }
-        //Float all xml:* attributes of the unselected parent elements to this one.
-        //addXmlAttributes(E,result);
-        xmlattrStack.getXmlnsAttr(result);
-        ns.getUnrenderedNodes(getSortedSetAsCollection(result));
+
+        return result.iterator();
+    }
 
+    protected void circumventBugIfNeeded(XMLSignatureInput input)
+        throws CanonicalizationException, ParserConfigurationException, IOException, SAXException {
+        if (!input.isNeedsToBeExpanded()) {
+            return;
+        }
+        Document doc = null;
+        if (input.getSubNode() != null) {
+            doc = XMLUtils.getOwnerDocument(input.getSubNode());
+        } else {
+            doc = XMLUtils.getOwnerDocument(input.getNodeSet());
+        }
+        XMLUtils.circumventBug2650(doc);
     }
 
-    return result.iterator();
-   }
-   /**
-    * Always throws a CanonicalizationException because this is inclusive c14n.
-    *
-    * @param xpathNodeSet
-    * @param inclusiveNamespaces
-    * @return none it always fails
-    * @throws CanonicalizationException always
-    */
-   public byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet, String inclusiveNamespaces)
-           throws CanonicalizationException {
-
-      /** $todo$ well, should we throw UnsupportedOperationException ? */
-      throw new CanonicalizationException(
-         "c14n.Canonicalizer.UnsupportedOperation");
-   }
-
-   /**
-    * Always throws a CanonicalizationException because this is inclusive c14n.
-    *
-    * @param rootNode
-    * @param inclusiveNamespaces
-    * @return none it always fails
-    * @throws CanonicalizationException
-    */
-   public byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces)
-           throws CanonicalizationException {
+    @Override
+    protected void handleParent(Element e, NameSpaceSymbTable ns) {
+        if (!e.hasAttributes() && e.getNamespaceURI() == null) {
+            return;
+        }
+        xmlattrStack.push(-1);
+        NamedNodeMap attrs = e.getAttributes();
+        int attrsLength = attrs.getLength();
+        for (int i = 0; i < attrsLength; i++) {
+            Attr attribute = (Attr) attrs.item(i);
+            String NName = attribute.getLocalName();
+            String NValue = attribute.getNodeValue();
 
-      /** $todo$ well, should we throw UnsupportedOperationException ? */
-      throw new CanonicalizationException(
-         "c14n.Canonicalizer.UnsupportedOperation");
-   }
-   void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException {
-           if (!input.isNeedsToBeExpanded())
-                   return;
-           Document doc = null;
-       if (input.getSubNode() != null) {
-           doc=XMLUtils.getOwnerDocument(input.getSubNode());
-       } else {
-           doc=XMLUtils.getOwnerDocument(input.getNodeSet());
-       }
-           XMLUtils.circumventBug2650(doc);
-
-   }
-
-   void handleParent(Element e, NameSpaceSymbTable ns) {
-           if (!e.hasAttributes()) {
-                        return;
-           }
-           xmlattrStack.push(-1);
-           NamedNodeMap attrs = e.getAttributes();
-           int attrsLength = attrs.getLength();
-           for (int i = 0; i < attrsLength; i++) {
-                   Attr N = (Attr) attrs.item(i);
-                   if (Constants.NamespaceSpecNS!=N.getNamespaceURI()) {
-                           //Not a namespace definition, ignore.
-                           if (XML_LANG_URI==N.getNamespaceURI()) {
-                                   xmlattrStack.addXmlnsAttr(N);
-                           }
-                           continue;
-                   }
-
-                   String NName=N.getLocalName();
-                   String NValue=N.getNodeValue();
-                   if (XML.equals(NName)
-                                   && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
-                                continue;
-                   }
-                   ns.addMapping(NName,NValue,N);
-           }
-   }
+            if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())) {
+                if (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
+                    ns.addMapping(NName, NValue, attribute);
+                }
+            } else if (XML_LANG_URI.equals(attribute.getNamespaceURI())) {
+                xmlattrStack.addXmlnsAttr(attribute);
+            }
+        }
+        if (e.getNamespaceURI() != null) {
+            String NName = e.getPrefix();
+            String NValue = e.getNamespaceURI();
+            String Name;
+            if (NName == null || NName.equals("")) {
+                NName = "xmlns";
+                Name = "xmlns";
+            } else {
+                Name = "xmlns:" + NName;
+            }
+            Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name);
+            n.setValue(NValue);
+            ns.addMapping(NName, NValue, n);
+        }
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
  * http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.c14n.implementations;
 
@@ -25,7 +27,6 @@
 import java.util.Set;
 import java.util.SortedSet;
 import java.util.TreeSet;
-
 import javax.xml.parsers.ParserConfigurationException;
 
 import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
@@ -40,6 +41,7 @@
 import org.w3c.dom.NamedNodeMap;
 import org.w3c.dom.Node;
 import org.xml.sax.SAXException;
+
 /**
  * Implements &quot; <A
  * HREF="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/">Exclusive XML
@@ -52,301 +54,279 @@
  * <i>THIS </i> implementation is a complete rewrite of the algorithm.
  *
  * @author Christian Geuer-Pollmann <geuerp@apache.org>
- * @version $Revision: 1.5 $
+ * @version $Revision: 1147448 $
  * @see <a href="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/ Exclusive#">
  *          XML Canonicalization, Version 1.0</a>
  */
 public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
+
+    private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS;
+    private static final String XMLNS_URI = Constants.NamespaceSpecNS;
+
     /**
       * This Set contains the names (Strings like "xmlns" or "xmlns:foo") of
       * the inclusive namespaces.
       */
-    TreeSet<String> _inclusiveNSSet = new TreeSet<String>();
-    static final String XMLNS_URI=Constants.NamespaceSpecNS;
-    final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
-        /**
-         * Constructor Canonicalizer20010315Excl
-         *
-         * @param includeComments
-         */
-        public Canonicalizer20010315Excl(boolean includeComments) {
-                super(includeComments);
-        }
+    private SortedSet<String> inclusiveNSSet;
+
+    private final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
+
+    /**
+     * Constructor Canonicalizer20010315Excl
+     *
+     * @param includeComments
+     */
+    public Canonicalizer20010315Excl(boolean includeComments) {
+        super(includeComments);
+    }
 
-        /**
-         * Method engineCanonicalizeSubTree
-         * @inheritDoc
-         * @param rootNode
-         *
-         * @throws CanonicalizationException
-         */
-        public byte[] engineCanonicalizeSubTree(Node rootNode)
-                        throws CanonicalizationException {
-                return this.engineCanonicalizeSubTree(rootNode, "",null);
-        }
-        /**
-         * Method engineCanonicalizeSubTree
-         *  @inheritDoc
-         * @param rootNode
-         * @param inclusiveNamespaces
-         *
-         * @throws CanonicalizationException
-         */
-        public byte[] engineCanonicalizeSubTree(Node rootNode,
-                        String inclusiveNamespaces) throws CanonicalizationException {
-                return this.engineCanonicalizeSubTree(rootNode, inclusiveNamespaces,null);
-        }
-        /**
-         * Method engineCanonicalizeSubTree
-         * @param rootNode
+    /**
+     * Method engineCanonicalizeSubTree
+     * @inheritDoc
+     * @param rootNode
+     *
+     * @throws CanonicalizationException
+     */
+    public byte[] engineCanonicalizeSubTree(Node rootNode)
+        throws CanonicalizationException {
+        return engineCanonicalizeSubTree(rootNode, "", null);
+    }
+
+    /**
+     * Method engineCanonicalizeSubTree
+     *  @inheritDoc
+     * @param rootNode
+     * @param inclusiveNamespaces
+     *
+     * @throws CanonicalizationException
+     */
+    public byte[] engineCanonicalizeSubTree(
+        Node rootNode, String inclusiveNamespaces
+    ) throws CanonicalizationException {
+        return engineCanonicalizeSubTree(rootNode, inclusiveNamespaces, null);
+    }
+
+    /**
+     * Method engineCanonicalizeSubTree
+     * @param rootNode
      * @param inclusiveNamespaces
      * @param excl A element to exclude from the c14n process.
-         * @return the rootNode c14n.
-         * @throws CanonicalizationException
-         */
-        public byte[] engineCanonicalizeSubTree(Node rootNode,
-                        String inclusiveNamespaces,Node excl) throws CanonicalizationException {
-                        this._inclusiveNSSet = getInclusiveNameSpace(inclusiveNamespaces);
-                        return super.engineCanonicalizeSubTree(rootNode,excl);
-        }
-        /**
-         *
-         * @param rootNode
-         * @param inclusiveNamespaces
-         * @return the rootNode c14n.
-         * @throws CanonicalizationException
-         */
-        @SuppressWarnings("unchecked")
-        public byte[] engineCanonicalize(XMLSignatureInput rootNode,
-                        String inclusiveNamespaces) throws CanonicalizationException {
-                        this._inclusiveNSSet = getInclusiveNameSpace(inclusiveNamespaces);
-                        return super.engineCanonicalize(rootNode);
-        }
+     * @return the rootNode c14n.
+     * @throws CanonicalizationException
+     */
+    public byte[] engineCanonicalizeSubTree(
+        Node rootNode, String inclusiveNamespaces, Node excl
+    ) throws CanonicalizationException{
+        inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces);
+        return super.engineCanonicalizeSubTree(rootNode, excl);
+    }
 
-        /**
-         * Method handleAttributesSubtree
-         * @inheritDoc
-         * @param E
-         * @throws CanonicalizationException
-         */
-        Iterator<Attr> handleAttributesSubtree(Element E,NameSpaceSymbTable ns)
-                        throws CanonicalizationException {
-                // System.out.println("During the traversal, I encountered " +
-                // XMLUtils.getXPath(E));
-                // result will contain the attrs which have to be outputted
-                SortedSet<Attr> result = this.result;
-            result.clear();
-                NamedNodeMap attrs=null;
-
-                int attrsLength = 0;
-        if (E.hasAttributes()) {
-            attrs = E.getAttributes();
-                attrsLength = attrs.getLength();
-        }
-                //The prefix visibly utilized(in the attribute or in the name) in the element
-                SortedSet<String> visiblyUtilized = getNSSetClone();
-
-                for (int i = 0; i < attrsLength; i++) {
-                        Attr N = (Attr) attrs.item(i);
+    /**
+     *
+     * @param rootNode
+     * @param inclusiveNamespaces
+     * @return the rootNode c14n.
+     * @throws CanonicalizationException
+     */
+    public byte[] engineCanonicalize(
+        XMLSignatureInput rootNode, String inclusiveNamespaces
+    ) throws CanonicalizationException {
+        inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces);
+        return super.engineCanonicalize(rootNode);
+    }
 
-                        if (XMLNS_URI!=N.getNamespaceURI()) {
-                                //Not a namespace definition.
-                                //The Element is output element, add his prefix(if used) to visibyUtilized
-                                String prefix = N.getPrefix();
-                                if ( (prefix != null) && (!prefix.equals(XML) && !prefix.equals(XMLNS)) ) {
-                                                visiblyUtilized.add(prefix);
-                                }
-                                //Add to the result.
-                                 result.add(N);
-                                continue;
-                        }
-                        String NName=N.getLocalName();
-                        String NNodeValue=N.getNodeValue();
+    /**
+     * Method engineCanonicalizeXPathNodeSet
+     * @inheritDoc
+     * @param xpathNodeSet
+     * @param inclusiveNamespaces
+     * @throws CanonicalizationException
+     */
+    public byte[] engineCanonicalizeXPathNodeSet(
+        Set<Node> xpathNodeSet, String inclusiveNamespaces
+    ) throws CanonicalizationException {
+        inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces);
+        return super.engineCanonicalizeXPathNodeSet(xpathNodeSet);
+    }
 
-                        if (ns.addMapping(NName, NNodeValue,N)) {
-                                //New definition check if it is relative.
-                if (C14nHelper.namespaceIsRelative(NNodeValue)) {
-                    Object exArgs[] = {E.getTagName(), NName,
-                            N.getNodeValue()};
-                    throw new CanonicalizationException(
-                            "c14n.Canonicalizer.RelativeNamespace", exArgs);
-                }
-            }
-                }
-                String prefix;
-                if (E.getNamespaceURI() != null) {
-                        prefix = E.getPrefix();
-                        if ((prefix == null) || (prefix.length() == 0)) {
-                                prefix=XMLNS;
-                        }
+    @Override
+    protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
+        throws CanonicalizationException {
+        // result will contain the attrs which have to be output
+        final SortedSet<Attr> result = this.result;
+        result.clear();
 
-                } else {
-                        prefix=XMLNS;
-                }
-                visiblyUtilized.add(prefix);
-
-                //This can be optimezed by I don't have time
-                Iterator<String> it=visiblyUtilized.iterator();
-                while (it.hasNext()) {
-                        String s=it.next();
-                        Attr key=ns.getMapping(s);
-                        if (key==null) {
-                                continue;
-                        }
-                        result.add(key);
-                }
-
-                return result.iterator();
+        // The prefix visibly utilized (in the attribute or in the name) in
+        // the element
+        SortedSet<String> visiblyUtilized = new TreeSet<String>();
+        if (inclusiveNSSet != null && !inclusiveNSSet.isEmpty()) {
+            visiblyUtilized.addAll(inclusiveNSSet);
         }
 
-        /**
-         * Method engineCanonicalizeXPathNodeSet
-         * @inheritDoc
-         * @param xpathNodeSet
-         * @param inclusiveNamespaces
-         * @throws CanonicalizationException
-         */
-        public byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet,
-                        String inclusiveNamespaces) throws CanonicalizationException {
+        if (element.hasAttributes()) {
+            NamedNodeMap attrs = element.getAttributes();
+            int attrsLength = attrs.getLength();
+            for (int i = 0; i < attrsLength; i++) {
+                Attr attribute = (Attr) attrs.item(i);
+                String NName = attribute.getLocalName();
+                String NNodeValue = attribute.getNodeValue();
 
-                        this._inclusiveNSSet = getInclusiveNameSpace(inclusiveNamespaces);
-                        return super.engineCanonicalizeXPathNodeSet(xpathNodeSet);
+                if (!XMLNS_URI.equals(attribute.getNamespaceURI())) {
+                    // Not a namespace definition.
+                    // The Element is output element, add the prefix (if used) to
+                    // visiblyUtilized
+                    String prefix = attribute.getPrefix();
+                    if (prefix != null && !(prefix.equals(XML) || prefix.equals(XMLNS))) {
+                        visiblyUtilized.add(prefix);
+                    }
+                    // Add to the result.
+                    result.add(attribute);
+                } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NNodeValue))
+                    && ns.addMapping(NName, NNodeValue, attribute)
+                    && C14nHelper.namespaceIsRelative(NNodeValue)) {
+                    // The default mapping for xml must not be output.
+                    // New definition check if it is relative.
+                    Object exArgs[] = {element.getTagName(), NName, attribute.getNodeValue()};
+                    throw new CanonicalizationException(
+                        "c14n.Canonicalizer.RelativeNamespace", exArgs
+                    );
+                }
+            }
+        }
+        String prefix = null;
+        if (element.getNamespaceURI() != null
+            && !(element.getPrefix() == null || element.getPrefix().length() == 0)) {
+            prefix = element.getPrefix();
+        } else {
+            prefix = XMLNS;
+        }
+        visiblyUtilized.add(prefix);
 
+        for (String s : visiblyUtilized) {
+            Attr key = ns.getMapping(s);
+            if (key != null) {
+                result.add(key);
+            }
         }
 
-    @SuppressWarnings("unchecked")
-    private TreeSet<String> getInclusiveNameSpace(String inclusiveNameSpaces) {
-        return (TreeSet<String>)InclusiveNamespaces.prefixStr2Set(inclusiveNameSpaces);
-    }
-
-
-    @SuppressWarnings("unchecked")
-    private SortedSet<String> getNSSetClone() {
-        return (SortedSet<String>) this._inclusiveNSSet.clone();
+        return result.iterator();
     }
 
-
-        /**
+    /**
      * @inheritDoc
-         * @param E
-         * @throws CanonicalizationException
-         */
-        final Iterator<Attr> handleAttributes(Element E, NameSpaceSymbTable ns)
-                        throws CanonicalizationException {
-                // result will contain the attrs which have to be outputted
-                SortedSet<Attr> result = this.result;
-            result.clear();
-                NamedNodeMap attrs = null;
-                int attrsLength = 0;
-        if (E.hasAttributes()) {
-            attrs = E.getAttributes();
-                attrsLength = attrs.getLength();
+     * @param element
+     * @throws CanonicalizationException
+     */
+    @Override
+    protected final Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
+        throws CanonicalizationException {
+        // result will contain the attrs which have to be output
+        final SortedSet<Attr> result = this.result;
+        result.clear();
+
+        // The prefix visibly utilized (in the attribute or in the name) in
+        // the element
+        Set<String> visiblyUtilized = null;
+        // It's the output selected.
+        boolean isOutputElement = isVisibleDO(element, ns.getLevel()) == 1;
+        if (isOutputElement) {
+            visiblyUtilized = new TreeSet<String>();
+            if (inclusiveNSSet != null && !inclusiveNSSet.isEmpty()) {
+                visiblyUtilized.addAll(inclusiveNSSet);
+            }
         }
-                //The prefix visibly utilized(in the attribute or in the name) in the element
-                Set<String> visiblyUtilized =null;
-                //It's the output selected.
-                boolean isOutputElement=isVisibleDO(E,ns.getLevel())==1;
-                if (isOutputElement) {
-                        visiblyUtilized =  getNSSetClone();
-                }
 
-                for (int i = 0; i < attrsLength; i++) {
-                        Attr N = (Attr) attrs.item(i);
+        if (element.hasAttributes()) {
+            NamedNodeMap attrs = element.getAttributes();
+            int attrsLength = attrs.getLength();
+            for (int i = 0; i < attrsLength; i++) {
+                Attr attribute = (Attr) attrs.item(i);
 
+                String NName = attribute.getLocalName();
+                String NNodeValue = attribute.getNodeValue();
 
-                        if (XMLNS_URI!=N.getNamespaceURI()) {
-                                if ( !isVisible(N) )  {
-                                        //The node is not in the nodeset(if there is a nodeset)
-                                        continue;
-                                }
-                                //Not a namespace definition.
-                                if (isOutputElement) {
-                                        //The Element is output element, add his prefix(if used) to visibyUtilized
-                                        String prefix = N.getPrefix();
-                                        if ((prefix != null) && (!prefix.equals(XML) && !prefix.equals(XMLNS)) ){
-                                                        visiblyUtilized.add(prefix);
-                                        }
-                                        //Add to the result.
-                                    result.add(N);
-                                }
-                                continue;
+                if (!XMLNS_URI.equals(attribute.getNamespaceURI())) {
+                    if (isVisible(attribute) && isOutputElement) {
+                        // The Element is output element, add the prefix (if used)
+                        // to visibyUtilized
+                        String prefix = attribute.getPrefix();
+                        if (prefix != null && !(prefix.equals(XML) || prefix.equals(XMLNS))) {
+                            visiblyUtilized.add(prefix);
                         }
-                        String NName=N.getLocalName();
-                        if (isOutputElement && !isVisible(N) && NName!=XMLNS) {
-                        ns.removeMappingIfNotRender(NName);
-                        continue;
-                }
-                        String NNodeValue=N.getNodeValue();
+                        // Add to the result.
+                        result.add(attribute);
+                    }
+                } else if (isOutputElement && !isVisible(attribute) && !XMLNS.equals(NName)) {
+                    ns.removeMappingIfNotRender(NName);
+                } else {
+                    if (!isOutputElement && isVisible(attribute)
+                        && inclusiveNSSet.contains(NName)
+                        && !ns.removeMappingIfRender(NName)) {
+                        Node n = ns.addMappingAndRender(NName, NNodeValue, attribute);
+                        if (n != null) {
+                            result.add((Attr)n);
+                            if (C14nHelper.namespaceIsRelative(attribute)) {
+                                Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() };
+                                throw new CanonicalizationException(
+                                    "c14n.Canonicalizer.RelativeNamespace", exArgs
+                                );
+                            }
+                        }
+                    }
 
-                        if (!isOutputElement && isVisible(N) && _inclusiveNSSet.contains(NName) && !ns.removeMappingIfRender(NName)) {
-                                Node n=ns.addMappingAndRender(NName,NNodeValue,N);
-                                if (n!=null) {
-                                                result.add((Attr)n);
-                            if (C14nHelper.namespaceIsRelative(N)) {
-                               Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() };
-                               throw new CanonicalizationException(
-                                  "c14n.Canonicalizer.RelativeNamespace", exArgs);
-                           }
-                                 }
-                        }
-
-
-
-                        if (ns.addMapping(NName, NNodeValue,N)) {
-                //New definiton check if it is relative
-                if (C14nHelper.namespaceIsRelative(NNodeValue)) {
-                    Object exArgs[] = {E.getTagName(), NName,
-                            N.getNodeValue()};
-                    throw new CanonicalizationException(
-                            "c14n.Canonicalizer.RelativeNamespace", exArgs);
+                    if (ns.addMapping(NName, NNodeValue, attribute)
+                        && C14nHelper.namespaceIsRelative(NNodeValue)) {
+                        // New definition check if it is relative
+                        Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() };
+                        throw new CanonicalizationException(
+                            "c14n.Canonicalizer.RelativeNamespace", exArgs
+                        );
+                    }
                 }
             }
-                }
+        }
 
-                if (isOutputElement) {
-           //The element is visible, handle the xmlns definition
-           Attr xmlns = E.getAttributeNodeNS(XMLNS_URI, XMLNS);
-           if ((xmlns!=null) &&  (!isVisible(xmlns))) {
-              //There is a definition but the xmlns is not selected by the xpath.
-              //then xmlns=""
-              ns.addMapping(XMLNS,"",nullNode);
+        if (isOutputElement) {
+            // The element is visible, handle the xmlns definition
+            Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS);
+            if (xmlns != null && !isVisible(xmlns)) {
+                // There is a definition but the xmlns is not selected by the
+                // xpath. then xmlns=""
+                ns.addMapping(XMLNS, "", nullNode);
             }
 
-                        if (E.getNamespaceURI() != null) {
-                                String prefix = E.getPrefix();
-                                if ((prefix == null) || (prefix.length() == 0)) {
-                                        visiblyUtilized.add(XMLNS);
-                                } else {
-                                        visiblyUtilized.add( prefix);
-                                }
-                        } else {
-                                visiblyUtilized.add(XMLNS);
-                        }
-                        //This can be optimezed by I don't have time
-                        //visiblyUtilized.addAll(this._inclusiveNSSet);
-                        Iterator<String> it=visiblyUtilized.iterator();
-                        while (it.hasNext()) {
-                                String s=it.next();
-                                Attr key=ns.getMapping(s);
-                                if (key==null) {
-                                        continue;
-                                }
-                                result.add(key);
-                        }
+            String prefix = null;
+            if (element.getNamespaceURI() != null
+                && !(element.getPrefix() == null || element.getPrefix().length() == 0)) {
+                prefix = element.getPrefix();
+            } else {
+                prefix = XMLNS;
+            }
+            visiblyUtilized.add(prefix);
+
+            for (String s : visiblyUtilized) {
+                Attr key = ns.getMapping(s);
+                if (key != null) {
+                    result.add(key);
                 }
-
-                return result.iterator();
+            }
         }
-        void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException {
-                if (!input.isNeedsToBeExpanded() || _inclusiveNSSet.isEmpty())
-                        return;
-                Document doc = null;
-               if (input.getSubNode() != null) {
-                   doc=XMLUtils.getOwnerDocument(input.getSubNode());
-               } else {
-                   doc=XMLUtils.getOwnerDocument(input.getNodeSet());
-               }
+
+        return result.iterator();
+    }
 
-                XMLUtils.circumventBug2650(doc);
-           }
+    protected void circumventBugIfNeeded(XMLSignatureInput input)
+        throws CanonicalizationException, ParserConfigurationException,
+               IOException, SAXException {
+        if (!input.isNeedsToBeExpanded() || inclusiveNSSet.isEmpty() || inclusiveNSSet.isEmpty()) {
+            return;
+        }
+        Document doc = null;
+        if (input.getSubNode() != null) {
+            doc = XMLUtils.getOwnerDocument(input.getSubNode());
+        } else {
+            doc = XMLUtils.getOwnerDocument(input.getNodeSet());
+        }
+        XMLUtils.circumventBug2650(doc);
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,48 +2,44 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
-
 package com.sun.org.apache.xml.internal.security.c14n.implementations;
 
 import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
 
-/**
- *
- *
- */
-public class Canonicalizer20010315ExclOmitComments
-        extends Canonicalizer20010315Excl {
+public class Canonicalizer20010315ExclOmitComments extends Canonicalizer20010315Excl {
+
+    /**
+     *
+     */
+    public Canonicalizer20010315ExclOmitComments() {
+        super(false);
+    }
 
-   /**
-    *
-    */
-        public Canonicalizer20010315ExclOmitComments() {
-      super(false);
-   }
+    /** @inheritDoc */
+    public final String engineGetURI() {
+        return Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS;
+    }
 
-   /** @inheritDoc */
-   public final String engineGetURI() {
-      return Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS;
-   }
-
-   /** @inheritDoc */
-   public final boolean engineGetIncludeComments() {
-      return false;
-   }
+    /** @inheritDoc */
+    public final boolean engineGetIncludeComments() {
+        return false;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,52 +2,48 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.c14n.implementations;
 
-
-
 import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
 
-
 /**
  * Class Canonicalizer20010315ExclWithComments
- *
- * @version $Revision: 1.5 $
  */
-public class Canonicalizer20010315ExclWithComments
-        extends Canonicalizer20010315Excl {
+public class Canonicalizer20010315ExclWithComments extends Canonicalizer20010315Excl {
+
+    /**
+     * Constructor Canonicalizer20010315ExclWithComments
+     *
+     */
+    public Canonicalizer20010315ExclWithComments() {
+        super(true);
+    }
 
-   /**
-    * Constructor Canonicalizer20010315ExclWithComments
-    *
-    */
-   public Canonicalizer20010315ExclWithComments() {
-      super(true);
-   }
+    /** @inheritDoc */
+    public final String engineGetURI() {
+        return Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS;
+    }
 
-   /** @inheritDoc */
-   public final String engineGetURI() {
-      return Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS;
-   }
-
-   /** @inheritDoc */
-   public final boolean engineGetIncludeComments() {
-      return true;
-   }
+    /** @inheritDoc */
+    public final boolean engineGetIncludeComments() {
+        return true;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,50 +2,48 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.c14n.implementations;
 
-
-
 import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
 
-
 /**
- *
  * @author Christian Geuer-Pollmann
  */
 public class Canonicalizer20010315OmitComments extends Canonicalizer20010315 {
 
-   /**
-    * Constructor Canonicalizer20010315WithXPathOmitComments
-    *
-    */
-   public Canonicalizer20010315OmitComments() {
-      super(false);
-   }
+    /**
+     * Constructor Canonicalizer20010315WithXPathOmitComments
+     *
+     */
+    public Canonicalizer20010315OmitComments() {
+        super(false);
+    }
 
-   /** @inheritDoc */
-   public final String engineGetURI() {
-      return Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS;
-   }
+    /** @inheritDoc */
+    public final String engineGetURI() {
+        return Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS;
+    }
 
-   /** @inheritDoc */
-   public final boolean engineGetIncludeComments() {
-      return false;
-   }
+    /** @inheritDoc */
+    public final boolean engineGetIncludeComments() {
+        return false;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,47 +2,47 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.c14n.implementations;
 
 import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
 
 /**
- *
  * @author Christian Geuer-Pollmann
  */
 public class Canonicalizer20010315WithComments extends Canonicalizer20010315 {
 
-   /**
-    * Constructor Canonicalizer20010315WithXPathWithComments
-    *
-    */
-   public Canonicalizer20010315WithComments() {
-      super(true);
-   }
+    /**
+     * Constructor Canonicalizer20010315WithXPathWithComments
+     */
+    public Canonicalizer20010315WithComments() {
+        super(true);
+    }
 
-   /** @inheritDoc */
-   public final String engineGetURI() {
-      return Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS;
-   }
+    /** @inheritDoc */
+    public final String engineGetURI() {
+        return Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS;
+    }
 
-   /** @inheritDoc */
-   public final boolean engineGetIncludeComments() {
-      return true;
-   }
+    /** @inheritDoc */
+    public final boolean engineGetIncludeComments() {
+        return true;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.c14n.implementations;
 
-
-
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.OutputStream;
@@ -33,12 +33,10 @@
 import java.util.ListIterator;
 import java.util.Map;
 import java.util.Set;
-import java.util.SortedSet;
-import java.util.Collection;
 
+import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.xpath.XPath;
 
 import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
 import com.sun.org.apache.xml.internal.security.c14n.CanonicalizerSpi;
@@ -56,794 +54,829 @@
 import org.w3c.dom.ProcessingInstruction;
 import org.xml.sax.SAXException;
 
-
 /**
  * Abstract base class for canonicalization algorithms.
  *
  * @author Christian Geuer-Pollmann <geuerp@apache.org>
- * @version $Revision: 1.5 $
  */
 public abstract class CanonicalizerBase extends CanonicalizerSpi {
-   //Constants to be outputed, In char array form, so
-   //less garbage is generate when outputed.
-   private static final byte[] _END_PI = {'?','>'};
-   private static final byte[] _BEGIN_PI = {'<','?'};
-   private static final byte[] _END_COMM = {'-','-','>'};
-   private static final byte[] _BEGIN_COMM = {'<','!','-','-'};
-   private static final byte[] __XA_ = {'&','#','x','A',';'};
-   private static final byte[] __X9_ = {'&','#','x','9',';'};
-   private static final byte[] _QUOT_ = {'&','q','u','o','t',';'};
-   private static final byte[] __XD_ = {'&','#','x','D',';'};
-   private static final byte[] _GT_ = {'&','g','t',';'};
-   private static final byte[] _LT_ = {'&','l','t',';'};
-   private static final byte[] _END_TAG = {'<','/'};
-   private static final byte[] _AMP_ = {'&','a','m','p',';'};
-   final static AttrCompare COMPARE=new AttrCompare();
-   final static String XML="xml";
-   final static String XMLNS="xmlns";
-   final static byte[] equalsStr= {'=','\"'};
-   static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1;
-   static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0;
-   static final int NODE_AFTER_DOCUMENT_ELEMENT = 1;
-   //The null xmlns definiton.
-   protected static final Attr nullNode;
-   static {
-    try {
-        nullNode=DocumentBuilderFactory.newInstance().
-            newDocumentBuilder().newDocument().createAttributeNS(Constants.NamespaceSpecNS,XMLNS);
-        nullNode.setValue("");
-    } catch (Exception e) {
-        throw new RuntimeException("Unable to create nullNode"/*,*/+e);
+    public static final String XML = "xml";
+    public static final String XMLNS = "xmlns";
+
+    protected static final AttrCompare COMPARE = new AttrCompare();
+    protected static final Attr nullNode;
+
+    private static final byte[] END_PI = {'?','>'};
+    private static final byte[] BEGIN_PI = {'<','?'};
+    private static final byte[] END_COMM = {'-','-','>'};
+    private static final byte[] BEGIN_COMM = {'<','!','-','-'};
+    private static final byte[] XA = {'&','#','x','A',';'};
+    private static final byte[] X9 = {'&','#','x','9',';'};
+    private static final byte[] QUOT = {'&','q','u','o','t',';'};
+    private static final byte[] XD = {'&','#','x','D',';'};
+    private static final byte[] GT = {'&','g','t',';'};
+    private static final byte[] LT = {'&','l','t',';'};
+    private static final byte[] END_TAG = {'<','/'};
+    private static final byte[] AMP = {'&','a','m','p',';'};
+    private static final byte[] equalsStr = {'=','\"'};
+
+    protected static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1;
+    protected static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0;
+    protected static final int NODE_AFTER_DOCUMENT_ELEMENT = 1;
+
+    static {
+        // The null xmlns definition.
+        try {
+            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
+            nullNode = documentBuilder.newDocument().createAttributeNS(Constants.NamespaceSpecNS, XMLNS);
+            nullNode.setValue("");
+        } catch (Exception e) {
+            throw new RuntimeException("Unable to create nullNode: " + e);
+        }
     }
-   }
 
-   List<NodeFilter> nodeFilter;
+    private List<NodeFilter> nodeFilter;
 
-   boolean _includeComments;
-   Set<Node> _xpathNodeSet = null;
-   /**
-    * The node to be skiped/excluded from the DOM tree
-    * in subtree canonicalizations.
-    */
-   Node _excludeNode =null;
-   OutputStream _writer = new UnsyncByteArrayOutputStream();//null;
+    private boolean includeComments;
+    private Set<Node> xpathNodeSet;
+    /**
+     * The node to be skipped/excluded from the DOM tree
+     * in subtree canonicalizations.
+     */
+    private Node excludeNode;
+    private OutputStream writer = new ByteArrayOutputStream();
 
-   /**
-    * Constructor CanonicalizerBase
-    *
-    * @param includeComments
-    */
-   public CanonicalizerBase(boolean includeComments) {
-      this._includeComments = includeComments;
-   }
+    /**
+     * Constructor CanonicalizerBase
+     *
+     * @param includeComments
+     */
+    public CanonicalizerBase(boolean includeComments) {
+        this.includeComments = includeComments;
+    }
+
+    /**
+     * Method engineCanonicalizeSubTree
+     * @inheritDoc
+     * @param rootNode
+     * @throws CanonicalizationException
+     */
+    public byte[] engineCanonicalizeSubTree(Node rootNode)
+        throws CanonicalizationException {
+        return engineCanonicalizeSubTree(rootNode, (Node)null);
+    }
 
-   /**
-    * Method engineCanonicalizeSubTree
-    * @inheritDoc
-    * @param rootNode
-    * @throws CanonicalizationException
-    */
-   public byte[] engineCanonicalizeSubTree(Node rootNode)
-           throws CanonicalizationException {
-                return engineCanonicalizeSubTree(rootNode,(Node)null);
-   }
-   /**
-    * Method engineCanonicalizeXPathNodeSet
-    * @inheritDoc
-    * @param xpathNodeSet
-    * @throws CanonicalizationException
-    */
-   public byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet)
-           throws CanonicalizationException {
-           this._xpathNodeSet = xpathNodeSet;
-           return engineCanonicalizeXPathNodeSetInternal(XMLUtils.getOwnerDocument(this._xpathNodeSet));
-   }
+    /**
+     * Method engineCanonicalizeXPathNodeSet
+     * @inheritDoc
+     * @param xpathNodeSet
+     * @throws CanonicalizationException
+     */
+    public byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet)
+        throws CanonicalizationException {
+        this.xpathNodeSet = xpathNodeSet;
+        return engineCanonicalizeXPathNodeSetInternal(XMLUtils.getOwnerDocument(this.xpathNodeSet));
+    }
 
-   /**
-    * Canonicalizes a Subtree node.
-    * @param input the root of the subtree to canicalize
-    * @return The canonicalize stream.
-    * @throws CanonicalizationException
-    */
-    public byte[] engineCanonicalize(XMLSignatureInput input)
-    throws CanonicalizationException {
+    /**
+     * Canonicalizes a Subtree node.
+     * @param input the root of the subtree to canicalize
+     * @return The canonicalize stream.
+     * @throws CanonicalizationException
+     */
+    public byte[] engineCanonicalize(XMLSignatureInput input) throws CanonicalizationException {
         try {
-                if (input.isExcludeComments())
-                        _includeComments = false;
-                        byte[] bytes;
-                        if (input.isOctetStream()) {
-                                return engineCanonicalize(input.getBytes());
-                        }
-                        if (input.isElement()) {
-                                bytes = engineCanonicalizeSubTree(input.getSubNode(), input
-                                                .getExcludeNode());
-                                return bytes;
-                        } else if (input.isNodeSet()) {
-                                nodeFilter=input.getNodeFilters();
+            if (input.isExcludeComments()) {
+                includeComments = false;
+            }
+            if (input.isOctetStream()) {
+                return engineCanonicalize(input.getBytes());
+            }
+            if (input.isElement()) {
+                return engineCanonicalizeSubTree(input.getSubNode(), input.getExcludeNode());
+            } else if (input.isNodeSet()) {
+                nodeFilter = input.getNodeFilters();
 
                 circumventBugIfNeeded(input);
 
-                                if (input.getSubNode() != null) {
-                                    bytes = engineCanonicalizeXPathNodeSetInternal(input.getSubNode());
-                                } else {
-                                    bytes = engineCanonicalizeXPathNodeSet(input.getNodeSet());
-                                }
-                                return bytes;
+                if (input.getSubNode() != null) {
+                    return engineCanonicalizeXPathNodeSetInternal(input.getSubNode());
+                } else {
+                    return engineCanonicalizeXPathNodeSet(input.getNodeSet());
+                }
+            }
+            return null;
+        } catch (CanonicalizationException ex) {
+            throw new CanonicalizationException("empty", ex);
+        } catch (ParserConfigurationException ex) {
+            throw new CanonicalizationException("empty", ex);
+        } catch (IOException ex) {
+            throw new CanonicalizationException("empty", ex);
+        } catch (SAXException ex) {
+            throw new CanonicalizationException("empty", ex);
+        }
+    }
 
-                        }
-                        return null;
-                } catch (CanonicalizationException ex) {
-                        throw new CanonicalizationException("empty", ex);
-                } catch (ParserConfigurationException ex) {
-                        throw new CanonicalizationException("empty", ex);
-                } catch (IOException ex) {
-                        throw new CanonicalizationException("empty", ex);
-                } catch (SAXException ex) {
-                        throw new CanonicalizationException("empty", ex);
-                }
-   }
-   /**
-    * @param _writer The _writer to set.
-    */
-    public void setWriter(OutputStream _writer) {
-        this._writer = _writer;
+    /**
+     * @param writer The writer to set.
+     */
+    public void setWriter(OutputStream writer) {
+        this.writer = writer;
     }
 
     /**
-         * Canonicalizes a Subtree node.
-         *
-         * @param rootNode
-         *            the root of the subtree to canicalize
-         * @param excludeNode
-         *            a node to be excluded from the canicalize operation
-         * @return The canonicalize stream.
-         * @throws CanonicalizationException
-         */
-    byte[] engineCanonicalizeSubTree(Node rootNode,Node excludeNode)
-    throws CanonicalizationException {
-        this._excludeNode = excludeNode;
+     * Canonicalizes a Subtree node.
+     *
+     * @param rootNode
+     *            the root of the subtree to canonicalize
+     * @param excludeNode
+     *            a node to be excluded from the canonicalize operation
+     * @return The canonicalize stream.
+     * @throws CanonicalizationException
+     */
+    protected byte[] engineCanonicalizeSubTree(Node rootNode, Node excludeNode)
+        throws CanonicalizationException {
+        this.excludeNode = excludeNode;
         try {
-         NameSpaceSymbTable ns=new NameSpaceSymbTable();
-         int nodeLevel=NODE_BEFORE_DOCUMENT_ELEMENT;
-         if (rootNode != null && rootNode.getNodeType() == Node.ELEMENT_NODE) {
+            NameSpaceSymbTable ns = new NameSpaceSymbTable();
+            int nodeLevel = NODE_BEFORE_DOCUMENT_ELEMENT;
+            if (rootNode != null && Node.ELEMENT_NODE == rootNode.getNodeType()) {
                 //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;
-         }
-         this.canonicalizeSubTree(rootNode,ns,rootNode,nodeLevel);
-         this._writer.close();
-         if (this._writer instanceof ByteArrayOutputStream) {
-            byte []result=((ByteArrayOutputStream)this._writer).toByteArray();
-            if (reset) {
-                ((ByteArrayOutputStream)this._writer).reset();
+                getParentNameSpaces((Element)rootNode, ns);
+                nodeLevel = NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
             }
+            this.canonicalizeSubTree(rootNode, ns, rootNode, nodeLevel);
+            this.writer.flush();
+            if (this.writer instanceof ByteArrayOutputStream) {
+                byte[] result = ((ByteArrayOutputStream)this.writer).toByteArray();
+                if (reset) {
+                    ((ByteArrayOutputStream)this.writer).reset();
+                } else {
+                    this.writer.close();
+                }
                 return result;
-         }  else if (this._writer instanceof UnsyncByteArrayOutputStream) {
-                 byte []result=((UnsyncByteArrayOutputStream)this._writer).toByteArray();
-             if (reset) {
-                 ((UnsyncByteArrayOutputStream)this._writer).reset();
-             }
-                 return result;
-         }
-         return null;
+            } else if (this.writer instanceof UnsyncByteArrayOutputStream) {
+                byte[] result = ((UnsyncByteArrayOutputStream)this.writer).toByteArray();
+                if (reset) {
+                    ((UnsyncByteArrayOutputStream)this.writer).reset();
+                } else {
+                    this.writer.close();
+                }
+                return result;
+            } else {
+                this.writer.close();
+            }
+            return null;
 
-      } catch (UnsupportedEncodingException ex) {
-         throw new CanonicalizationException("empty", ex);
-      } catch (IOException ex) {
-         throw new CanonicalizationException("empty", ex);
-      }
-   }
+        } catch (UnsupportedEncodingException ex) {
+            throw new CanonicalizationException("empty", ex);
+        } catch (IOException ex) {
+            throw new CanonicalizationException("empty", ex);
+        }
+    }
 
 
-   /**
-    * Method canonicalizeSubTree, this function is a recursive one.
-    *
-    * @param currentNode
-    * @param ns
-    * @param endnode
-    * @throws CanonicalizationException
-    * @throws IOException
-    */
-    final void canonicalizeSubTree(Node currentNode, NameSpaceSymbTable ns,Node endnode,
-                int documentLevel)
-    throws CanonicalizationException, IOException {
-        if (isVisibleInt(currentNode)==-1)
-                return;
-        Node sibling=null;
-        Node parentNode=null;
-        final OutputStream writer=this._writer;
-        final Node excludeNode=this._excludeNode;
-        final boolean includeComments=this._includeComments;
-        Map<String, byte[]> cache=new HashMap<String, byte[]>();
+    /**
+     * Method canonicalizeSubTree, this function is a recursive one.
+     *
+     * @param currentNode
+     * @param ns
+     * @param endnode
+     * @throws CanonicalizationException
+     * @throws IOException
+     */
+    protected final void canonicalizeSubTree(
+        Node currentNode, NameSpaceSymbTable ns, Node endnode, int documentLevel
+    ) throws CanonicalizationException, IOException {
+        if (isVisibleInt(currentNode) == -1) {
+            return;
+        }
+        Node sibling = null;
+        Node parentNode = null;
+        final OutputStream writer = this.writer;
+        final Node excludeNode = this.excludeNode;
+        final boolean includeComments = this.includeComments;
+        Map<String, byte[]> cache = new HashMap<String, byte[]>();
         do {
-                switch (currentNode.getNodeType()) {
-
-                case Node.DOCUMENT_TYPE_NODE :
-                default :
-                        break;
+            switch (currentNode.getNodeType()) {
 
-                case Node.ENTITY_NODE :
-                case Node.NOTATION_NODE :
-                case Node.ATTRIBUTE_NODE :
-                        // illegal node type during traversal
-                        throw new CanonicalizationException("empty");
+            case Node.ENTITY_NODE :
+            case Node.NOTATION_NODE :
+            case Node.ATTRIBUTE_NODE :
+                // illegal node type during traversal
+                throw new CanonicalizationException("empty");
 
             case Node.DOCUMENT_FRAGMENT_NODE :
-                case Node.DOCUMENT_NODE :
-                        ns.outputNodePush();
-                        sibling= currentNode.getFirstChild();
-                        break;
+            case Node.DOCUMENT_NODE :
+                ns.outputNodePush();
+                sibling = currentNode.getFirstChild();
+                break;
 
-                case Node.COMMENT_NODE :
-                        if (includeComments) {
-                                outputCommentToWriter((Comment) currentNode, writer, documentLevel);
-                        }
-                        break;
+            case Node.COMMENT_NODE :
+                if (includeComments) {
+                    outputCommentToWriter((Comment) currentNode, writer, documentLevel);
+                }
+                break;
 
-                case Node.PROCESSING_INSTRUCTION_NODE :
-                        outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel);
-                        break;
+            case Node.PROCESSING_INSTRUCTION_NODE :
+                outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel);
+                break;
 
-                case Node.TEXT_NODE :
-                case Node.CDATA_SECTION_NODE :
-                        outputTextToWriter(currentNode.getNodeValue(), writer);
-                        break;
+            case Node.TEXT_NODE :
+            case Node.CDATA_SECTION_NODE :
+                outputTextToWriter(currentNode.getNodeValue(), writer);
+                break;
 
-                case Node.ELEMENT_NODE :
-                        documentLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
-                        if (currentNode==excludeNode) {
-                                break;
-                        }
-                        Element currentElement = (Element) currentNode;
-                        //Add a level to the nssymbtable. So latter can be pop-back.
-                        ns.outputNodePush();
-                        writer.write('<');
-                        String name=currentElement.getTagName();
-                        UtfHelpper.writeByte(name,writer,cache);
+            case Node.ELEMENT_NODE :
+                documentLevel = NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
+                if (currentNode == excludeNode) {
+                    break;
+                }
+                Element currentElement = (Element)currentNode;
+                //Add a level to the nssymbtable. So latter can be pop-back.
+                ns.outputNodePush();
+                writer.write('<');
+                String name = currentElement.getTagName();
+                UtfHelpper.writeByte(name, writer, cache);
 
-                        Iterator<Attr> attrs = this.handleAttributesSubtree(currentElement,ns);
-                        if (attrs!=null) {
-                                //we output all Attrs which are available
-                                while (attrs.hasNext()) {
-                                        Attr attr = attrs.next();
-                                        outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer,cache);
-                                }
-                        }
-                        writer.write('>');
-                        sibling= currentNode.getFirstChild();
-                        if (sibling==null) {
-                                writer.write(_END_TAG);
-                                UtfHelpper.writeStringToUtf8(name,writer);
-                                writer.write('>');
-                                //We fineshed with this level, pop to the previous definitions.
-                                ns.outputNodePop();
-                                    if (parentNode != null) {
-                                        sibling= currentNode.getNextSibling();
-                                    }
-                        } else {
-                                parentNode=currentElement;
-                        }
-                        break;
+                Iterator<Attr> attrs = this.handleAttributesSubtree(currentElement, ns);
+                if (attrs != null) {
+                    //we output all Attrs which are available
+                    while (attrs.hasNext()) {
+                        Attr attr = attrs.next();
+                        outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache);
+                    }
+                }
+                writer.write('>');
+                sibling = currentNode.getFirstChild();
+                if (sibling == null) {
+                    writer.write(END_TAG);
+                    UtfHelpper.writeStringToUtf8(name, writer);
+                    writer.write('>');
+                    //We finished with this level, pop to the previous definitions.
+                    ns.outputNodePop();
+                    if (parentNode != null) {
+                        sibling = currentNode.getNextSibling();
+                    }
+                } else {
+                    parentNode = currentElement;
                 }
-                while (sibling==null  && parentNode!=null) {
-                        writer.write(_END_TAG);
-                        UtfHelpper.writeByte(((Element)parentNode).getTagName(),writer,cache);
-                        writer.write('>');
-                        //We fineshed with this level, pop to the previous definitions.
-                        ns.outputNodePop();
-                        if (parentNode==endnode)
-                                return;
-                        sibling=parentNode.getNextSibling();
-                        parentNode=parentNode.getParentNode();
-                        if (parentNode !=null && parentNode.getNodeType() != Node.ELEMENT_NODE) {
-                                documentLevel=NODE_AFTER_DOCUMENT_ELEMENT;
-                                parentNode=null;
-                        }
+                break;
+
+            case Node.DOCUMENT_TYPE_NODE :
+            default :
+                break;
+            }
+            while (sibling == null && parentNode != null) {
+                writer.write(END_TAG);
+                UtfHelpper.writeByte(((Element)parentNode).getTagName(), writer, cache);
+                writer.write('>');
+                //We finished with this level, pop to the previous definitions.
+                ns.outputNodePop();
+                if (parentNode == endnode) {
+                    return;
                 }
-                if (sibling==null)
-                        return;
-                currentNode=sibling;
-                sibling=currentNode.getNextSibling();
+                sibling = parentNode.getNextSibling();
+                parentNode = parentNode.getParentNode();
+                if (parentNode == null || Node.ELEMENT_NODE != parentNode.getNodeType()) {
+                    documentLevel = NODE_AFTER_DOCUMENT_ELEMENT;
+                    parentNode = null;
+                }
+            }
+            if (sibling == null) {
+                return;
+            }
+            currentNode = sibling;
+            sibling = currentNode.getNextSibling();
         } while(true);
     }
 
 
-
-   private  byte[] engineCanonicalizeXPathNodeSetInternal(Node doc)
-           throws CanonicalizationException {
-
-      try {
-         this.canonicalizeXPathNodeSet(doc,doc);
-         this._writer.close();
-         if (this._writer instanceof ByteArrayOutputStream) {
-            byte [] sol=((ByteArrayOutputStream)this._writer).toByteArray();
-            if (reset) {
-                ((ByteArrayOutputStream)this._writer).reset();
-            }
+    private byte[] engineCanonicalizeXPathNodeSetInternal(Node doc)
+        throws CanonicalizationException {
+        try {
+            this.canonicalizeXPathNodeSet(doc, doc);
+            this.writer.flush();
+            if (this.writer instanceof ByteArrayOutputStream) {
+                byte[] sol = ((ByteArrayOutputStream)this.writer).toByteArray();
+                if (reset) {
+                    ((ByteArrayOutputStream)this.writer).reset();
+                } else {
+                    this.writer.close();
+                }
                 return sol;
-         }  else if (this._writer instanceof UnsyncByteArrayOutputStream) {
-                 byte []result=((UnsyncByteArrayOutputStream)this._writer).toByteArray();
-             if (reset) {
-                 ((UnsyncByteArrayOutputStream)this._writer).reset();
-             }
-                 return result;
-         }
-         return null;
-      } catch (UnsupportedEncodingException ex) {
-         throw new CanonicalizationException("empty", ex);
-      } catch (IOException ex) {
-         throw new CanonicalizationException("empty", ex);
-      }
-   }
+            } else if (this.writer instanceof UnsyncByteArrayOutputStream) {
+                byte[] result = ((UnsyncByteArrayOutputStream)this.writer).toByteArray();
+                if (reset) {
+                    ((UnsyncByteArrayOutputStream)this.writer).reset();
+                } else {
+                    this.writer.close();
+                }
+                return result;
+            } else {
+                this.writer.close();
+            }
+            return null;
+        } catch (UnsupportedEncodingException ex) {
+            throw new CanonicalizationException("empty", ex);
+        } catch (IOException ex) {
+            throw new CanonicalizationException("empty", ex);
+        }
+    }
 
-   /**
-    * Canoicalizes all the nodes included in the currentNode and contained in the
-        * _xpathNodeSet field.
-    *
-    * @param currentNode
-        * @param endnode
-    * @throws CanonicalizationException
-    * @throws IOException
-    */
-   final void canonicalizeXPathNodeSet(Node currentNode,Node endnode )
-           throws CanonicalizationException, IOException {
-        if (isVisibleInt(currentNode)==-1)
-                return;
+    /**
+     * Canonicalizes all the nodes included in the currentNode and contained in the
+     * xpathNodeSet field.
+     *
+     * @param currentNode
+     * @param endnode
+     * @throws CanonicalizationException
+     * @throws IOException
+     */
+    protected final void canonicalizeXPathNodeSet(Node currentNode, Node endnode)
+        throws CanonicalizationException, IOException {
+        if (isVisibleInt(currentNode) == -1) {
+            return;
+        }
         boolean currentNodeIsVisible = false;
-        NameSpaceSymbTable ns=new  NameSpaceSymbTable();
-        if (currentNode != null && currentNode.getNodeType() == Node.ELEMENT_NODE)
-                getParentNameSpaces((Element)currentNode,ns);
-        Node sibling=null;
-        Node parentNode=null;
-        OutputStream writer=this._writer;
-        int documentLevel=NODE_BEFORE_DOCUMENT_ELEMENT;
-        Map<String, byte[]> cache=new HashMap<String,byte[]>();
+        NameSpaceSymbTable ns = new NameSpaceSymbTable();
+        if (currentNode != null && Node.ELEMENT_NODE == currentNode.getNodeType()) {
+            getParentNameSpaces((Element)currentNode, ns);
+        }
+        if (currentNode == null) {
+            return;
+        }
+        Node sibling = null;
+        Node parentNode = null;
+        OutputStream writer = this.writer;
+        int documentLevel = NODE_BEFORE_DOCUMENT_ELEMENT;
+        Map<String, byte[]> cache = new HashMap<String, byte[]>();
         do {
-                switch (currentNode.getNodeType()) {
+            switch (currentNode.getNodeType()) {
+
+            case Node.ENTITY_NODE :
+            case Node.NOTATION_NODE :
+            case Node.ATTRIBUTE_NODE :
+                // illegal node type during traversal
+                throw new CanonicalizationException("empty");
+
+            case Node.DOCUMENT_FRAGMENT_NODE :
+            case Node.DOCUMENT_NODE :
+                ns.outputNodePush();
+                sibling = currentNode.getFirstChild();
+                break;
 
-                case Node.DOCUMENT_TYPE_NODE :
-                default :
-                        break;
+            case Node.COMMENT_NODE :
+                if (this.includeComments && (isVisibleDO(currentNode, ns.getLevel()) == 1)) {
+                    outputCommentToWriter((Comment) currentNode, writer, documentLevel);
+                }
+                break;
+
+            case Node.PROCESSING_INSTRUCTION_NODE :
+                if (isVisible(currentNode)) {
+                    outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel);
+                }
+                break;
 
-                case Node.ENTITY_NODE :
-                case Node.NOTATION_NODE :
-                case Node.ATTRIBUTE_NODE :
-                        // illegal node type during traversal
-                        throw new CanonicalizationException("empty");
-
-        case Node.DOCUMENT_FRAGMENT_NODE :
-                case Node.DOCUMENT_NODE :
-                        ns.outputNodePush();
-                        //currentNode = currentNode.getFirstChild();
-                        sibling= currentNode.getFirstChild();
-                        break;
+            case Node.TEXT_NODE :
+            case Node.CDATA_SECTION_NODE :
+                if (isVisible(currentNode)) {
+                    outputTextToWriter(currentNode.getNodeValue(), writer);
+                    for (Node nextSibling = currentNode.getNextSibling();
+                        (nextSibling != null) && ((nextSibling.getNodeType() == Node.TEXT_NODE)
+                            || (nextSibling.getNodeType() == Node.CDATA_SECTION_NODE));
+                        nextSibling = nextSibling.getNextSibling()) {
+                        outputTextToWriter(nextSibling.getNodeValue(), writer);
+                        currentNode = nextSibling;
+                        sibling = currentNode.getNextSibling();
+                    }
+                }
+                break;
 
-                case Node.COMMENT_NODE :
-                        if (this._includeComments && (isVisibleDO(currentNode,ns.getLevel())==1)) {
-                                outputCommentToWriter((Comment) currentNode, writer, documentLevel);
-                        }
-                        break;
+            case Node.ELEMENT_NODE :
+                documentLevel = NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
+                Element currentElement = (Element) currentNode;
+                //Add a level to the nssymbtable. So latter can be pop-back.
+                String name = null;
+                int i = isVisibleDO(currentNode, ns.getLevel());
+                if (i == -1) {
+                    sibling = currentNode.getNextSibling();
+                    break;
+                }
+                currentNodeIsVisible = (i == 1);
+                if (currentNodeIsVisible) {
+                    ns.outputNodePush();
+                    writer.write('<');
+                    name = currentElement.getTagName();
+                    UtfHelpper.writeByte(name, writer, cache);
+                } else {
+                    ns.push();
+                }
 
-                case Node.PROCESSING_INSTRUCTION_NODE :
-                        if (isVisible(currentNode))
-                                outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel);
-                        break;
+                Iterator<Attr> attrs = handleAttributes(currentElement,ns);
+                if (attrs != null) {
+                    //we output all Attrs which are available
+                    while (attrs.hasNext()) {
+                        Attr attr = attrs.next();
+                        outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache);
+                    }
+                }
+                if (currentNodeIsVisible) {
+                    writer.write('>');
+                }
+                sibling = currentNode.getFirstChild();
 
-                case Node.TEXT_NODE :
-                case Node.CDATA_SECTION_NODE :
-                        if (isVisible(currentNode)) {
-                        outputTextToWriter(currentNode.getNodeValue(), writer);
-                        for (Node nextSibling = currentNode.getNextSibling();
-                    (nextSibling != null)
-                    && ((nextSibling.getNodeType() == Node.TEXT_NODE)
-                        || (nextSibling.getNodeType()
-                            == Node.CDATA_SECTION_NODE));
-                    nextSibling = nextSibling.getNextSibling()) {
-               outputTextToWriter(nextSibling.getNodeValue(), writer);
-               currentNode=nextSibling;
-               sibling=currentNode.getNextSibling();
+                if (sibling == null) {
+                    if (currentNodeIsVisible) {
+                        writer.write(END_TAG);
+                        UtfHelpper.writeByte(name, writer, cache);
+                        writer.write('>');
+                        //We finished with this level, pop to the previous definitions.
+                        ns.outputNodePop();
+                    } else {
+                        ns.pop();
+                    }
+                    if (parentNode != null) {
+                        sibling = currentNode.getNextSibling();
+                    }
+                } else {
+                    parentNode = currentElement;
+                }
+                break;
+
+            case Node.DOCUMENT_TYPE_NODE :
+            default :
+                break;
             }
-
-                        }
-                        break;
+            while (sibling == null && parentNode != null) {
+                if (isVisible(parentNode)) {
+                    writer.write(END_TAG);
+                    UtfHelpper.writeByte(((Element)parentNode).getTagName(), writer, cache);
+                    writer.write('>');
+                    //We finished with this level, pop to the previous definitions.
+                    ns.outputNodePop();
+                } else {
+                    ns.pop();
+                }
+                if (parentNode == endnode) {
+                    return;
+                }
+                sibling = parentNode.getNextSibling();
+                parentNode = parentNode.getParentNode();
+                if (parentNode == null || Node.ELEMENT_NODE != parentNode.getNodeType()) {
+                    parentNode = null;
+                    documentLevel = NODE_AFTER_DOCUMENT_ELEMENT;
+                }
+            }
+            if (sibling == null) {
+                return;
+            }
+            currentNode = sibling;
+            sibling = currentNode.getNextSibling();
+        } while(true);
+    }
 
-                case Node.ELEMENT_NODE :
-                        documentLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
-                        Element currentElement = (Element) currentNode;
-                        //Add a level to the nssymbtable. So latter can be pop-back.
-                        String name=null;
-                        int i=isVisibleDO(currentNode,ns.getLevel());
-                        if (i==-1) {
-                                sibling= currentNode.getNextSibling();
-                                break;
-                        }
-                        currentNodeIsVisible=(i==1);
-                        if (currentNodeIsVisible) {
-                                ns.outputNodePush();
-                                writer.write('<');
-                                name=currentElement.getTagName();
-                                UtfHelpper.writeByte(name,writer,cache);
-                        } else {
-                                ns.push();
-                        }
+    protected int isVisibleDO(Node currentNode, int level) {
+        if (nodeFilter != null) {
+            Iterator<NodeFilter> it = nodeFilter.iterator();
+            while (it.hasNext()) {
+                int i = (it.next()).isNodeIncludeDO(currentNode, level);
+                if (i != 1) {
+                    return i;
+                }
+            }
+        }
+        if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) {
+            return 0;
+        }
+        return 1;
+    }
 
-                        Iterator<Attr> attrs = handleAttributes(currentElement,ns);
-                        if (attrs!=null) {
-                                //we output all Attrs which are available
-                                while (attrs.hasNext()) {
-                                        Attr attr = attrs.next();
-                                        outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer,cache);
-                                }
-                        }
-                        if (currentNodeIsVisible) {
-                                writer.write('>');
-                        }
-                        sibling= currentNode.getFirstChild();
+    protected int isVisibleInt(Node currentNode) {
+        if (nodeFilter != null) {
+            Iterator<NodeFilter> it = nodeFilter.iterator();
+            while (it.hasNext()) {
+                int i = (it.next()).isNodeInclude(currentNode);
+                if (i != 1) {
+                    return i;
+                }
+            }
+        }
+        if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) {
+            return 0;
+        }
+        return 1;
+    }
 
-                        if (sibling==null) {
-                                if (currentNodeIsVisible) {
-                                        writer.write(_END_TAG);
-                                        UtfHelpper.writeByte(name,writer,cache);
-                                        writer.write('>');
-                                        //We fineshed with this level, pop to the previous definitions.
-                                        ns.outputNodePop();
-                                } else {
-                                        ns.pop();
-                                }
-                                if (parentNode != null) {
-                                        sibling= currentNode.getNextSibling();
-                                }
-                        } else {
-                                parentNode=currentElement;
-                        }
-                        break;
+    protected boolean isVisible(Node currentNode) {
+        if (nodeFilter != null) {
+            Iterator<NodeFilter> it = nodeFilter.iterator();
+            while (it.hasNext()) {
+                if (it.next().isNodeInclude(currentNode) != 1) {
+                    return false;
                 }
-                while (sibling==null  && parentNode!=null) {
-                        if (isVisible(parentNode)) {
-                                writer.write(_END_TAG);
-                                UtfHelpper.writeByte(((Element)parentNode).getTagName(),writer,cache);
-                                writer.write('>');
-                                //We fineshed with this level, pop to the previous definitions.
-                                ns.outputNodePop();
-                        } else {
-                                ns.pop();
-                        }
-                        if (parentNode==endnode)
-                                return;
-                        sibling=parentNode.getNextSibling();
-                        parentNode=parentNode.getParentNode();
-                        if (parentNode != null && parentNode.getNodeType() != Node.ELEMENT_NODE) {
-                                parentNode=null;
-                                documentLevel=NODE_AFTER_DOCUMENT_ELEMENT;
-                        }
+            }
+        }
+        if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) {
+            return false;
+        }
+        return true;
+    }
+
+    protected void handleParent(Element e, NameSpaceSymbTable ns) {
+        if (!e.hasAttributes() && e.getNamespaceURI() == null) {
+            return;
+        }
+        NamedNodeMap attrs = e.getAttributes();
+        int attrsLength = attrs.getLength();
+        for (int i = 0; i < attrsLength; i++) {
+            Attr attribute = (Attr) attrs.item(i);
+            String NName = attribute.getLocalName();
+            String NValue = attribute.getNodeValue();
+
+            if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())
+                && (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue))) {
+                ns.addMapping(NName, NValue, attribute);
+            }
+        }
+        if (e.getNamespaceURI() != null) {
+            String NName = e.getPrefix();
+            String NValue = e.getNamespaceURI();
+            String Name;
+            if (NName == null || NName.equals("")) {
+                NName = XMLNS;
+                Name = XMLNS;
+            } else {
+                Name = XMLNS + ":" + NName;
+            }
+            Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name);
+            n.setValue(NValue);
+            ns.addMapping(NName, NValue, n);
+        }
+    }
+
+    /**
+     * Adds to ns the definitions from the parent elements of el
+     * @param el
+     * @param ns
+     */
+    protected final void getParentNameSpaces(Element el, NameSpaceSymbTable ns)  {
+        Node n1 = el.getParentNode();
+        if (n1 == null || Node.ELEMENT_NODE != n1.getNodeType()) {
+            return;
+        }
+        //Obtain all the parents of the element
+        List<Element> parents = new ArrayList<Element>();
+        Node parent = n1;
+        while (parent != null && Node.ELEMENT_NODE == parent.getNodeType()) {
+            parents.add((Element)parent);
+            parent = parent.getParentNode();
+        }
+        //Visit them in reverse order.
+        ListIterator<Element> it = parents.listIterator(parents.size());
+        while (it.hasPrevious()) {
+            Element ele = it.previous();
+            handleParent(ele, ns);
+        }
+        parents.clear();
+        Attr nsprefix;
+        if (((nsprefix = ns.getMappingWithoutRendered(XMLNS)) != null)
+            && "".equals(nsprefix.getValue())) {
+            ns.addMappingAndRender(XMLNS, "", nullNode);
+        }
+    }
+
+    /**
+     * Obtain the attributes to output for this node in XPathNodeSet c14n.
+     *
+     * @param element
+     * @param ns
+     * @return the attributes nodes to output.
+     * @throws CanonicalizationException
+     */
+    abstract Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
+        throws CanonicalizationException;
+
+    /**
+     * Obtain the attributes to output for this node in a Subtree c14n.
+     *
+     * @param element
+     * @param ns
+     * @return the attributes nodes to output.
+     * @throws CanonicalizationException
+     */
+    abstract Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
+        throws CanonicalizationException;
+
+    abstract void circumventBugIfNeeded(XMLSignatureInput input)
+        throws CanonicalizationException, ParserConfigurationException, IOException, SAXException;
+
+    /**
+     * Outputs an Attribute to the internal Writer.
+     *
+     * The string value of the node is modified by replacing
+     * <UL>
+     * <LI>all ampersands (&) with <CODE>&amp;amp;</CODE></LI>
+     * <LI>all open angle brackets (<) with <CODE>&amp;lt;</CODE></LI>
+     * <LI>all quotation mark characters with <CODE>&amp;quot;</CODE></LI>
+     * <LI>and the whitespace characters <CODE>#x9</CODE>, #xA, and #xD, with character
+     * references. The character references are written in uppercase
+     * hexadecimal with no leading zeroes (for example, <CODE>#xD</CODE> is represented
+     * by the character reference <CODE>&amp;#xD;</CODE>)</LI>
+     * </UL>
+     *
+     * @param name
+     * @param value
+     * @param writer
+     * @throws IOException
+     */
+    protected static final void outputAttrToWriter(
+        final String name, final String value,
+        final OutputStream writer, final Map<String, byte[]> cache
+    ) throws IOException {
+        writer.write(' ');
+        UtfHelpper.writeByte(name, writer, cache);
+        writer.write(equalsStr);
+        byte[] toWrite;
+        final int length = value.length();
+        int i = 0;
+        while (i < length) {
+            char c = value.charAt(i++);
+
+            switch (c) {
+
+            case '&' :
+                toWrite = AMP;
+                break;
+
+            case '<' :
+                toWrite = LT;
+                break;
+
+            case '"' :
+                toWrite = QUOT;
+                break;
+
+            case 0x09 :    // '\t'
+                toWrite = X9;
+                break;
+
+            case 0x0A :    // '\n'
+                toWrite = XA;
+                break;
+
+            case 0x0D :    // '\r'
+                toWrite = XD;
+                break;
+
+            default :
+                if (c < 0x80) {
+                    writer.write(c);
+                } else {
+                    UtfHelpper.writeCharToUtf8(c, writer);
                 }
-                if (sibling==null)
-                        return;
-                currentNode=sibling;
-                sibling=currentNode.getNextSibling();
-        } while(true);
-   }
-   int isVisibleDO(Node currentNode,int level) {
-           if (nodeFilter!=null) {
-                        Iterator<NodeFilter> it=nodeFilter.iterator();
-                        while (it.hasNext()) {
-                                int i=(it.next()).isNodeIncludeDO(currentNode,level);
-                                if (i!=1)
-                                        return i;
-                        }
-                   }
-           if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode))
-                        return 0;
-           return 1;
-   }
-   int isVisibleInt(Node currentNode) {
-           if (nodeFilter!=null) {
-                Iterator<NodeFilter> it=nodeFilter.iterator();
-                while (it.hasNext()) {
-                        int i=(it.next()).isNodeInclude(currentNode);
-                        if (i!=1)
-                                return i;
-                }
-           }
-                if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode))
-                        return 0;
-                return 1;
-        }
-
-   boolean isVisible(Node currentNode) {
-           if (nodeFilter!=null) {
-                Iterator<NodeFilter> it=nodeFilter.iterator();
-                while (it.hasNext()) {
-                        if ((it.next()).isNodeInclude(currentNode)!=1)
-                                return false;
-                }
-           }
-                if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode))
-                        return false;
-                return true;
+                continue;
+            }
+            writer.write(toWrite);
         }
 
-        void handleParent(Element e,NameSpaceSymbTable ns) {
-           if (!e.hasAttributes()) {
-                                return;
-                }
-                NamedNodeMap attrs = e.getAttributes();
-                int attrsLength = attrs.getLength();
-                for (int i = 0; i < attrsLength; i++) {
-                        Attr N = (Attr) attrs.item(i);
-                        if (Constants.NamespaceSpecNS!=N.getNamespaceURI()) {
-                                //Not a namespace definition, ignore.
-                                continue;
-                        }
-
-                        String NName=N.getLocalName();
-                        String NValue=N.getNodeValue();
-                        if (XML.equals(NName)
-               && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
-                                        continue;
-                        }
-                        ns.addMapping(NName,NValue,N);
-                }
-   }
-
-        /**
-         * Adds to ns the definitons from the parent elements of el
-         * @param el
-         * @param ns
-         */
-        final void getParentNameSpaces(Element el,NameSpaceSymbTable ns)  {
-                List<Element> parents=new ArrayList<Element>(10);
-                Node n1=el.getParentNode();
-                if (n1 == null || n1.getNodeType() != Node.ELEMENT_NODE) {
-                        return;
-                }
-                //Obtain all the parents of the elemnt
-                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());
-                while (it.hasPrevious()) {
-                        Element ele=it.previous();
-                        handleParent(ele, ns);
-        }
-        Attr nsprefix;
-        if (((nsprefix=ns.getMappingWithoutRendered("xmlns"))!=null)
-                && "".equals(nsprefix.getValue())) {
-             ns.addMappingAndRender("xmlns","",nullNode);
-        }
-        }
-   /**
-    * Obtain the attributes to output for this node in XPathNodeSet c14n.
-    *
-    * @param E
-        * @param ns
-        * @return the attributes nodes to output.
-    * @throws CanonicalizationException
-    */
-   abstract Iterator<Attr> handleAttributes(Element E, NameSpaceSymbTable ns )
-   throws CanonicalizationException;
+        writer.write('\"');
+    }
 
-   /**
-    * Obtain the attributes to output for this node in a Subtree c14n.
-    *
-    * @param E
-        * @param ns
-        * @return the attributes nodes to output.
-    * @throws CanonicalizationException
-    */
-   abstract Iterator<Attr> handleAttributesSubtree(Element E, NameSpaceSymbTable ns)
-   throws CanonicalizationException;
-
-   abstract void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException;
+    /**
+     * Outputs a PI to the internal Writer.
+     *
+     * @param currentPI
+     * @param writer where to write the things
+     * @throws IOException
+     */
+    protected void outputPItoWriter(
+        ProcessingInstruction currentPI, OutputStream writer, int position
+    ) throws IOException {
+        if (position == NODE_AFTER_DOCUMENT_ELEMENT) {
+            writer.write('\n');
+        }
+        writer.write(BEGIN_PI);
 
-   /**
-            * Outputs an Attribute to the internal Writer.
-            *
-            * The string value of the node is modified by replacing
-            * <UL>
-            * <LI>all ampersands (&) with <CODE>&amp;amp;</CODE></LI>
-            * <LI>all open angle brackets (<) with <CODE>&amp;lt;</CODE></LI>
-            * <LI>all quotation mark characters with <CODE>&amp;quot;</CODE></LI>
-            * <LI>and the whitespace characters <CODE>#x9</CODE>, #xA, and #xD, with character
-            * references. The character references are written in uppercase
-            * hexadecimal with no leading zeroes (for example, <CODE>#xD</CODE> is represented
-            * by the character reference <CODE>&amp;#xD;</CODE>)</LI>
-            * </UL>
-            *
-            * @param name
-            * @param value
-            * @param writer
-            * @throws IOException
-            */
-           static final void outputAttrToWriter(final String name, final String value, final OutputStream writer,
-                                final Map<String, byte[]> cache) throws IOException {
-              writer.write(' ');
-              UtfHelpper.writeByte(name,writer,cache);
-              writer.write(equalsStr);
-              byte  []toWrite;
-              final int length = value.length();
-              int i=0;
-              while (i < length) {
-                 char c = value.charAt(i++);
-
-                 switch (c) {
-
-                 case '&' :
-                        toWrite=_AMP_;
-                    break;
-
-                 case '<' :
-                        toWrite=_LT_;
-                    break;
-
-                 case '"' :
-                        toWrite=_QUOT_;
-                    break;
-
-                 case 0x09 :    // '\t'
-                        toWrite=__X9_;
-                    break;
-
-                 case 0x0A :    // '\n'
-                        toWrite=__XA_;
-                    break;
-
-                 case 0x0D :    // '\r'
-                        toWrite=__XD_;
-                    break;
+        final String target = currentPI.getTarget();
+        int length = target.length();
 
-                 default :
-                        if (c < 0x80 ) {
-                                writer.write(c);
-                        } else {
-                                UtfHelpper.writeCharToUtf8(c,writer);
-                        };
-                    continue;
-                 }
-                 writer.write(toWrite);
-              }
-
-              writer.write('\"');
-           }
-
-        /**
-            * Outputs a PI to the internal Writer.
-            *
-            * @param currentPI
-            * @param writer where to write the things
-            * @throws IOException
-            */
-           static final void outputPItoWriter(ProcessingInstruction currentPI, OutputStream writer,int position) throws IOException {
-
-              if (position == NODE_AFTER_DOCUMENT_ELEMENT) {
-                writer.write('\n');
-              }
-              writer.write(_BEGIN_PI);
-
-              final String target = currentPI.getTarget();
-              int length = target.length();
+        for (int i = 0; i < length; i++) {
+            char c = target.charAt(i);
+            if (c == 0x0D) {
+                writer.write(XD);
+            } else {
+                if (c < 0x80) {
+                    writer.write(c);
+                } else {
+                    UtfHelpper.writeCharToUtf8(c, writer);
+                }
+            }
+        }
 
-              for (int i = 0; i < length; i++) {
-                 char c=target.charAt(i);
-                 if (c==0x0D) {
-                    writer.write(__XD_);
-                 } else {
-                         if (c < 0x80)  {
-                                writer.write(c);
-                        } else {
-                                UtfHelpper.writeCharToUtf8(c,writer);
-                        };
-                 }
-              }
-
-              final String data = currentPI.getData();
-
-              length = data.length();
+        final String data = currentPI.getData();
 
-              if (length > 0) {
-                 writer.write(' ');
-
-                 for (int i = 0; i < length; i++) {
-                        char c=data.charAt(i);
-                    if (c==0x0D) {
-                       writer.write(__XD_);
-                    } else {
-                        UtfHelpper.writeCharToUtf8(c,writer);
-                    }
-                 }
-              }
-
-              writer.write(_END_PI);
-              if (position == NODE_BEFORE_DOCUMENT_ELEMENT) {
-                writer.write('\n');
-             }
-           }
+        length = data.length();
 
-           /**
-            * Method outputCommentToWriter
-            *
-            * @param currentComment
-            * @param writer writer where to write the things
-            * @throws IOException
-            */
-           static final void outputCommentToWriter(Comment currentComment, OutputStream writer,int position) throws IOException {
-                  if (position == NODE_AFTER_DOCUMENT_ELEMENT) {
-                        writer.write('\n');
-                  }
-              writer.write(_BEGIN_COMM);
-
-              final String data = currentComment.getData();
-              final int length = data.length();
-
-              for (int i = 0; i < length; i++) {
-                 char c=data.charAt(i);
-                 if (c==0x0D) {
-                    writer.write(__XD_);
-                 } else {
-                         if (c < 0x80)  {
-                                writer.write(c);
-                        } else {
-                                UtfHelpper.writeCharToUtf8(c,writer);
-                        };
-                 }
-              }
-
-              writer.write(_END_COMM);
-              if (position == NODE_BEFORE_DOCUMENT_ELEMENT) {
-                        writer.write('\n');
-                 }
-           }
+        if (length > 0) {
+            writer.write(' ');
 
-           /**
-            * Outputs a Text of CDATA section to the internal Writer.
-            *
-            * @param text
-            * @param writer writer where to write the things
-            * @throws IOException
-            */
-           static final void outputTextToWriter(final String text, final OutputStream writer) throws IOException {
-              final int length = text.length();
-              byte []toWrite;
-              for (int i = 0; i < length; i++) {
-                 char c = text.charAt(i);
-
-                 switch (c) {
-
-                 case '&' :
-                        toWrite=_AMP_;
-                    break;
-
-                 case '<' :
-                        toWrite=_LT_;
-                    break;
+            for (int i = 0; i < length; i++) {
+                char c = data.charAt(i);
+                if (c == 0x0D) {
+                    writer.write(XD);
+                } else {
+                    UtfHelpper.writeCharToUtf8(c, writer);
+                }
+            }
+        }
 
-                 case '>' :
-                        toWrite=_GT_;
-                    break;
-
-                 case 0xD :
-                        toWrite=__XD_;
-                    break;
-
-                 default :
-                         if (c < 0x80) {
-                                 writer.write(c);
-                         } else {
-                                 UtfHelpper.writeCharToUtf8(c,writer);
-                         };
-                    continue;
-                 }
-                 writer.write(toWrite);
-              }
-           }
-
-    @SuppressWarnings("unchecked")
-    protected Collection<Attr> getSortedSetAsCollection(SortedSet<Attr> result) {
-        return (Collection<Attr>)(Collection)result;
+        writer.write(END_PI);
+        if (position == NODE_BEFORE_DOCUMENT_ELEMENT) {
+            writer.write('\n');
+        }
     }
 
+    /**
+     * Method outputCommentToWriter
+     *
+     * @param currentComment
+     * @param writer writer where to write the things
+     * @throws IOException
+     */
+    protected void outputCommentToWriter(
+        Comment currentComment, OutputStream writer, int position
+    ) throws IOException {
+        if (position == NODE_AFTER_DOCUMENT_ELEMENT) {
+            writer.write('\n');
+        }
+        writer.write(BEGIN_COMM);
+
+        final String data = currentComment.getData();
+        final int length = data.length();
+
+        for (int i = 0; i < length; i++) {
+            char c = data.charAt(i);
+            if (c == 0x0D) {
+                writer.write(XD);
+            } else {
+                if (c < 0x80) {
+                    writer.write(c);
+                } else {
+                    UtfHelpper.writeCharToUtf8(c, writer);
+                }
+            }
+        }
+
+        writer.write(END_COMM);
+        if (position == NODE_BEFORE_DOCUMENT_ELEMENT) {
+            writer.write('\n');
+        }
+    }
+
+    /**
+     * Outputs a Text of CDATA section to the internal Writer.
+     *
+     * @param text
+     * @param writer writer where to write the things
+     * @throws IOException
+     */
+    protected static final void outputTextToWriter(
+        final String text, final OutputStream writer
+    ) throws IOException {
+        final int length = text.length();
+        byte[] toWrite;
+        for (int i = 0; i < length; i++) {
+            char c = text.charAt(i);
+
+            switch (c) {
+
+            case '&' :
+                toWrite = AMP;
+                break;
+
+            case '<' :
+                toWrite = LT;
+                break;
+
+            case '>' :
+                toWrite = GT;
+                break;
+
+            case 0xD :
+                toWrite = XD;
+                break;
+
+            default :
+                if (c < 0x80) {
+                    writer.write(c);
+                } else {
+                    UtfHelpper.writeCharToUtf8(c, writer);
+                }
+                continue;
+            }
+            writer.write(toWrite);
+        }
+    }
 
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,184 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.c14n.implementations;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Iterator;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+import javax.xml.parsers.ParserConfigurationException;
+
+import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
+import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
+import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Comment;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.ProcessingInstruction;
+import org.xml.sax.SAXException;
+
+/**
+ * Serializes the physical representation of the subtree. All the attributes
+ * present in the subtree are emitted. The attributes are sorted within an element,
+ * with the namespace declarations appearing before the regular attributes.
+ * This algorithm is not a true canonicalization since equivalent subtrees
+ * may produce different output. It is therefore unsuitable for digital signatures.
+ * This same property makes it ideal for XML Encryption Syntax and Processing,
+ * because the decrypted XML content will share the same physical representation
+ * as the original XML content that was encrypted.
+ */
+public class CanonicalizerPhysical extends CanonicalizerBase {
+
+    private final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
+
+    /**
+     * Constructor Canonicalizer20010315
+     */
+    public CanonicalizerPhysical() {
+        super(true);
+    }
+
+    /**
+     * Always throws a CanonicalizationException.
+     *
+     * @param xpathNodeSet
+     * @param inclusiveNamespaces
+     * @return none it always fails
+     * @throws CanonicalizationException always
+     */
+    public byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet, String inclusiveNamespaces)
+        throws CanonicalizationException {
+
+        /** $todo$ well, should we throw UnsupportedOperationException ? */
+        throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
+    }
+
+    /**
+     * Always throws a CanonicalizationException.
+     *
+     * @param rootNode
+     * @param inclusiveNamespaces
+     * @return none it always fails
+     * @throws CanonicalizationException
+     */
+    public byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces)
+        throws CanonicalizationException {
+
+        /** $todo$ well, should we throw UnsupportedOperationException ? */
+        throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
+    }
+
+    /**
+     * Returns the Attr[]s to be output for the given element.
+     * <br>
+     * The code of this method is a copy of {@link #handleAttributes(Element,
+     * NameSpaceSymbTable)},
+     * whereas it takes into account that subtree-c14n is -- well -- subtree-based.
+     * So if the element in question isRoot of c14n, it's parent is not in the
+     * node set, as well as all other ancestors.
+     *
+     * @param element
+     * @param ns
+     * @return the Attr[]s to be output
+     * @throws CanonicalizationException
+     */
+    @Override
+    protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
+        throws CanonicalizationException {
+        if (!element.hasAttributes()) {
+            return null;
+        }
+
+        // result will contain all the attrs declared directly on that element
+        final SortedSet<Attr> result = this.result;
+        result.clear();
+
+        if (element.hasAttributes()) {
+            NamedNodeMap attrs = element.getAttributes();
+            int attrsLength = attrs.getLength();
+
+            for (int i = 0; i < attrsLength; i++) {
+                Attr attribute = (Attr) attrs.item(i);
+                result.add(attribute);
+            }
+        }
+
+        return result.iterator();
+    }
+
+    /**
+     * Returns the Attr[]s to be output for the given element.
+     *
+     * @param element
+     * @param ns
+     * @return the Attr[]s to be output
+     * @throws CanonicalizationException
+     */
+    @Override
+    protected Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
+        throws CanonicalizationException {
+
+        /** $todo$ well, should we throw UnsupportedOperationException ? */
+        throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
+    }
+
+    protected void circumventBugIfNeeded(XMLSignatureInput input)
+        throws CanonicalizationException, ParserConfigurationException, IOException, SAXException {
+        // nothing to do
+    }
+
+    @Override
+    protected void handleParent(Element e, NameSpaceSymbTable ns) {
+        // nothing to do
+    }
+
+    /** @inheritDoc */
+    public final String engineGetURI() {
+        return Canonicalizer.ALGO_ID_C14N_PHYSICAL;
+    }
+
+    /** @inheritDoc */
+    public final boolean engineGetIncludeComments() {
+        return true;
+    }
+
+    @Override
+    protected void outputPItoWriter(ProcessingInstruction currentPI,
+                                    OutputStream writer, int position) throws IOException {
+        // Processing Instructions before or after the document element are not treated specially
+        super.outputPItoWriter(currentPI, writer, NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT);
+    }
+
+    @Override
+    protected void outputCommentToWriter(Comment currentComment,
+                                         OutputStream writer, int position) throws IOException {
+        // Comments before or after the document element are not treated specially
+        super.outputCommentToWriter(currentComment, writer, NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT);
+    }
+
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.c14n.implementations;
 
@@ -29,191 +31,185 @@
 import org.w3c.dom.Attr;
 import org.w3c.dom.Node;
 
-
-
 /**
- * A stack based Symble Table.
+ * A stack based Symbol Table.
  *<br>For speed reasons all the symbols are introduced in the same map,
  * and at the same time in a list so it can be removed when the frame is pop back.
  * @author Raul Benito
- **/
+ */
 public class NameSpaceSymbTable {
 
-        /**The map betwen prefix-> entry table. */
-        SymbMap symb;
-        /**The level of nameSpaces (for Inclusive visibility).*/
-        int nameSpaces=0;
-        /**The stacks for removing the definitions when doing pop.*/
-        List<SymbMap> level;
-    boolean cloned=true;
-        static final String XMLNS="xmlns";
-        final static SymbMap initialMap=new SymbMap();
-        static {
-                NameSpaceSymbEntry ne=new NameSpaceSymbEntry("",null,true,XMLNS);
-                ne.lastrendered="";
-                initialMap.put(XMLNS,ne);
-        }
+    private static final String XMLNS = "xmlns";
+    private static final SymbMap initialMap = new SymbMap();
+
+    static {
+        NameSpaceSymbEntry ne = new NameSpaceSymbEntry("", null, true, XMLNS);
+        ne.lastrendered = "";
+        initialMap.put(XMLNS, ne);
+    }
+
+    /**The map betwen prefix-> entry table. */
+    private SymbMap symb;
+
+    /**The stacks for removing the definitions when doing pop.*/
+    private List<SymbMap> level;
+    private boolean cloned = true;
+
     /**
      * Default constractor
      **/
     public NameSpaceSymbTable() {
-        level = new ArrayList<SymbMap>(10);
+        level = new ArrayList<SymbMap>();
         //Insert the default binding for xmlns.
-        symb=(SymbMap) initialMap.clone();
+        symb = (SymbMap) initialMap.clone();
     }
 
     /**
-         * Get all the unrendered nodes in the name space.
-         * For Inclusive rendering
+     * Get all the unrendered nodes in the name space.
+     * For Inclusive rendering
      * @param result the list where to fill the unrendered xmlns definitions.
-         **/
-        public  void getUnrenderedNodes(Collection<Attr> result) {
-           //List result=new ArrayList();
-           Iterator<NameSpaceSymbEntry> it=symb.entrySet().iterator();
-           while (it.hasNext()) {
-                        NameSpaceSymbEntry n= it.next();
-                        //put them rendered?
-                        if ((!n.rendered) && (n.n!=null)) {
-                                n=(NameSpaceSymbEntry) n.clone();
+     **/
+    public void getUnrenderedNodes(Collection<Attr> result) {
+        Iterator<NameSpaceSymbEntry> it = symb.entrySet().iterator();
+        while (it.hasNext()) {
+            NameSpaceSymbEntry n = it.next();
+            //put them rendered?
+            if ((!n.rendered) && (n.n != null)) {
+                n = (NameSpaceSymbEntry) n.clone();
                 needsClone();
-                symb.put(n.prefix,n);
-                n.lastrendered=n.uri;
-                n.rendered=true;
-
-                                result.add(n.n);
+                symb.put(n.prefix, n);
+                n.lastrendered = n.uri;
+                n.rendered = true;
 
-                        }
-           }
+                result.add(n.n);
+            }
         }
+    }
 
-        /**
+    /**
      * Push a frame for visible namespace.
      * For Inclusive rendering.
      **/
-        public void outputNodePush() {
-                nameSpaces++;
-                push();
-        }
+    public void outputNodePush() {
+        push();
+    }
 
-        /**
+    /**
      * Pop a frame for visible namespace.
      **/
-        public void outputNodePop() {
-                nameSpaces--;
-                pop();
-        }
+    public void outputNodePop() {
+        pop();
+    }
 
-        /**
+    /**
      * Push a frame for a node.
      * Inclusive or Exclusive.
      **/
-        public void push() {
-                //Put the number of namespace definitions in the stack.
+    public void push() {
+        //Put the number of namespace definitions in the stack.
         level.add(null);
-        cloned=false;
-        }
+        cloned = false;
+    }
 
-        /**
+    /**
      * Pop a frame.
      * Inclusive or Exclusive.
      **/
-        public void pop() {
-        int size=level.size()-1;
-        Object ob= level.remove(size);
-        if (ob!=null) {
-                symb=(SymbMap)ob;
-            if (size==0) {
-               cloned=false;
-            } else
-                cloned=(level.get(size-1)!=symb);
+    public void pop() {
+        int size = level.size() - 1;
+        Object ob = level.remove(size);
+        if (ob != null) {
+            symb = (SymbMap)ob;
+            if (size == 0) {
+                cloned = false;
+            } else {
+                cloned = (level.get(size - 1) != symb);
+            }
         } else {
-                cloned=false;
+            cloned = false;
         }
-
-
-        }
+    }
 
-        final void needsClone() {
-                if (!cloned) {
-            level.set(level.size()-1,symb);
-                        symb=(SymbMap) symb.clone();
-            cloned=true;
+    final void needsClone() {
+        if (!cloned) {
+            level.set(level.size() - 1, symb);
+            symb = (SymbMap) symb.clone();
+            cloned = true;
         }
     }
 
 
-        /**
-         * Gets the attribute node that defines the binding for the prefix.
+    /**
+     * Gets the attribute node that defines the binding for the prefix.
      * @param prefix the prefix to obtain the attribute.
      * @return null if there is no need to render the prefix. Otherwise the node of
      * definition.
      **/
-        public Attr getMapping(String prefix) {
-                NameSpaceSymbEntry entry=symb.get(prefix);
-                if (entry==null) {
-                        //There is no definition for the prefix(a bug?).
-                        return null;
-                }
-                if (entry.rendered) {
-                        //No need to render an entry already rendered.
-                        return null;
-                }
-                // Mark this entry as render.
-        entry=(NameSpaceSymbEntry) entry.clone();
+    public Attr getMapping(String prefix) {
+        NameSpaceSymbEntry entry = symb.get(prefix);
+        if (entry == null) {
+            //There is no definition for the prefix(a bug?).
+            return null;
+        }
+        if (entry.rendered) {
+            //No need to render an entry already rendered.
+            return null;
+        }
+        // Mark this entry as render.
+        entry = (NameSpaceSymbEntry) entry.clone();
         needsClone();
-        symb.put(prefix,entry);
-                entry.rendered=true;
-                entry.level=nameSpaces;
-                entry.lastrendered=entry.uri;
-                // Return the node for outputing.
-                return entry.n;
-        }
+        symb.put(prefix, entry);
+        entry.rendered = true;
+        entry.lastrendered = entry.uri;
+        // Return the node for outputing.
+        return entry.n;
+    }
 
-        /**
+    /**
      * Gets a definition without mark it as render.
      * For render in exclusive c14n the namespaces in the include prefixes.
      * @param prefix The prefix whose definition is neaded.
      * @return the attr to render, null if there is no need to render
      **/
-        public Attr getMappingWithoutRendered(String prefix) {
-                NameSpaceSymbEntry entry= symb.get(prefix);
-                if (entry==null) {
-                        return null;
-                }
-                if (entry.rendered) {
-                        return null;
-                }
-                return entry.n;
+    public Attr getMappingWithoutRendered(String prefix) {
+        NameSpaceSymbEntry entry = symb.get(prefix);
+        if (entry == null) {
+            return null;
         }
+        if (entry.rendered) {
+            return null;
+        }
+        return entry.n;
+    }
 
-        /**
+    /**
      * Adds the mapping for a prefix.
      * @param prefix the prefix of definition
      * @param uri the Uri of the definition
      * @param n the attribute that have the definition
      * @return true if there is already defined.
      **/
-        public boolean addMapping(String prefix, String uri,Attr n) {
-                NameSpaceSymbEntry ob = symb.get(prefix);
-                if ((ob!=null) && uri.equals(ob.uri)) {
-                        //If we have it previously defined. Don't keep working.
-                        return false;
-                }
-                //Creates and entry in the table for this new definition.
-                NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,false,prefix);
+    public boolean addMapping(String prefix, String uri, Attr n) {
+        NameSpaceSymbEntry ob = symb.get(prefix);
+        if ((ob != null) && uri.equals(ob.uri)) {
+            //If we have it previously defined. Don't keep working.
+            return false;
+        }
+        //Creates and entry in the table for this new definition.
+        NameSpaceSymbEntry ne = new NameSpaceSymbEntry(uri, n, false, prefix);
         needsClone();
-                symb.put(prefix, ne);
-                if (ob != null) {
-                        //We have a previous definition store it for the pop.
-                        //Check if a previous definition(not the inmidiatly one) has been rendered.
-                        ne.lastrendered=ob.lastrendered;
-                        if ((ob.lastrendered!=null)&& (ob.lastrendered.equals(uri))) {
-                                //Yes it is. Mark as rendered.
-                                ne.rendered=true;
-                        }
-                }
+        symb.put(prefix, ne);
+        if (ob != null) {
+            //We have a previous definition store it for the pop.
+            //Check if a previous definition(not the inmidiatly one) has been rendered.
+            ne.lastrendered = ob.lastrendered;
+            if ((ob.lastrendered != null) && (ob.lastrendered.equals(uri))) {
+                //Yes it is. Mark as rendered.
+                ne.rendered = true;
+            }
+        }
         return true;
-        }
+    }
 
     /**
      * Adds a definition and mark it as render.
@@ -223,79 +219,91 @@
      * @param n the attribute that have the definition
      * @return the attr to render, null if there is no need to render
      **/
-    public Node addMappingAndRender(String prefix, String uri,Attr n) {
+    public Node addMappingAndRender(String prefix, String uri, Attr n) {
         NameSpaceSymbEntry ob = symb.get(prefix);
 
-        if ((ob!=null) && uri.equals(ob.uri)) {
+        if ((ob != null) && uri.equals(ob.uri)) {
             if (!ob.rendered) {
-                ob=(NameSpaceSymbEntry) ob.clone();
+                ob = (NameSpaceSymbEntry) ob.clone();
                 needsClone();
-                symb.put(prefix,ob);
-                ob.lastrendered=uri;
-                ob.rendered=true;
+                symb.put(prefix, ob);
+                ob.lastrendered = uri;
+                ob.rendered = true;
                 return ob.n;
             }
             return null;
         }
 
-        NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,true,prefix);
-        ne.lastrendered=uri;
+        NameSpaceSymbEntry ne = new NameSpaceSymbEntry(uri,n,true,prefix);
+        ne.lastrendered = uri;
         needsClone();
         symb.put(prefix, ne);
-        if (ob != null) {
-
-            if ((ob.lastrendered!=null)&& (ob.lastrendered.equals(uri))) {
-                ne.rendered=true;
-                return null;
-            }
+        if ((ob != null) && (ob.lastrendered != null) && (ob.lastrendered.equals(uri))) {
+            ne.rendered = true;
+            return null;
         }
         return ne.n;
     }
 
-        public int getLevel() {
-                // TODO Auto-generated method stub
-                return level.size();
-        }
+    public int getLevel() {
+        return level.size();
+    }
 
-        public void removeMapping(String prefix) {
-                NameSpaceSymbEntry ob = symb.get(prefix);
+    public void removeMapping(String prefix) {
+        NameSpaceSymbEntry ob = symb.get(prefix);
 
-        if (ob!=null) {
+        if (ob != null) {
             needsClone();
-            symb.put(prefix,null);
+            symb.put(prefix, null);
         }
-        }
+    }
 
-        public void removeMappingIfNotRender(String prefix) {
-                NameSpaceSymbEntry ob = symb.get(prefix);
+    public void removeMappingIfNotRender(String prefix) {
+        NameSpaceSymbEntry ob = symb.get(prefix);
 
-        if (ob!=null && !ob.rendered) {
+        if (ob != null && !ob.rendered) {
             needsClone();
-            symb.put(prefix,null);
-        }
+            symb.put(prefix, null);
         }
-
-        public boolean removeMappingIfRender(String prefix) {
-                NameSpaceSymbEntry ob = symb.get(prefix);
+    }
 
-        if (ob!=null && ob.rendered) {
+    public boolean removeMappingIfRender(String prefix) {
+        NameSpaceSymbEntry ob = symb.get(prefix);
+
+        if (ob != null && ob.rendered) {
             needsClone();
-            symb.put(prefix,null);
+            symb.put(prefix, null);
         }
         return false;
-        }
+    }
 }
 
 /**
  * The internal structure of NameSpaceSymbTable.
  **/
 class NameSpaceSymbEntry implements Cloneable {
-    NameSpaceSymbEntry(String name,Attr n,boolean rendered,String prefix) {
-        this.uri=name;
-        this.rendered=rendered;
-        this.n=n;
-        this.prefix=prefix;
+
+    String prefix;
+
+    /**The URI that the prefix defines */
+    String uri;
+
+    /**The last output in the URI for this prefix (This for speed reason).*/
+    String lastrendered = null;
+
+    /**This prefix-URI has been already render or not.*/
+    boolean rendered = false;
+
+    /**The attribute to include.*/
+    Attr n;
+
+    NameSpaceSymbEntry(String name, Attr n, boolean rendered, String prefix) {
+        this.uri = name;
+        this.rendered = rendered;
+        this.n = n;
+        this.prefix = prefix;
     }
+
     /** @inheritDoc */
     public Object clone() {
         try {
@@ -304,46 +312,35 @@
             return null;
         }
     }
-    /** The level where the definition was rendered(Only for inclusive) */
-    int level=0;
-    String prefix;
-    /**The URI that the prefix defines */
-    String uri;
-    /**The last output in the URI for this prefix (This for speed reason).*/
-    String lastrendered=null;
-    /**This prefix-URI has been already render or not.*/
-    boolean rendered=false;
-    /**The attribute to include.*/
-    Attr n;
 };
 
 class SymbMap implements Cloneable {
-    int free=23;
+    int free = 23;
     NameSpaceSymbEntry[] entries;
     String[] keys;
-        SymbMap() {
-                entries=new NameSpaceSymbEntry[free];
-                keys=new String[free];
-        }
+
+    SymbMap() {
+        entries = new NameSpaceSymbEntry[free];
+        keys = new String[free];
+    }
+
     void put(String key, NameSpaceSymbEntry value) {
         int index = index(key);
         Object oldKey = keys[index];
         keys[index] = key;
         entries[index] = value;
-        if (oldKey==null || !oldKey.equals(key)) {
-            if (--free == 0) {
-                free=entries.length;
-                int newCapacity = free<<2;
-                rehash(newCapacity);
-            }
+        if ((oldKey == null || !oldKey.equals(key)) && (--free == 0)) {
+            free = entries.length;
+            int newCapacity = free << 2;
+            rehash(newCapacity);
         }
     }
 
     List<NameSpaceSymbEntry> entrySet() {
-        List<NameSpaceSymbEntry> a=new ArrayList<NameSpaceSymbEntry>();
-        for (int i=0;i<entries.length;i++) {
-                if ((entries[i]!=null) && !("".equals(entries[i].uri))) {
-                        a.add(entries[i]);
+        List<NameSpaceSymbEntry> a = new ArrayList<NameSpaceSymbEntry>();
+        for (int i = 0;i < entries.length;i++) {
+            if ((entries[i] != null) && !("".equals(entries[i].uri))) {
+                a.add(entries[i]);
             }
         }
         return a;
@@ -353,16 +350,16 @@
         Object[] set = keys;
         int length = set.length;
         //abs of index
-        int index = (obj.hashCode() & 0x7fffffff) %  length;
+        int index = (obj.hashCode() & 0x7fffffff) % length;
         Object cur = set[index];
 
-        if (cur == null || (cur.equals( obj))) {
-                return index;
+        if (cur == null || (cur.equals(obj))) {
+            return index;
         }
-        length=length-1;
+        length--;
         do {
-                index=index==length? 0:++index;
-                cur = set[index];
+            index = index == length ? 0 : ++index;
+            cur = set[index];
         } while (cur != null && (!cur.equals(obj)));
         return index;
     }
@@ -381,7 +378,7 @@
         entries = new NameSpaceSymbEntry[newCapacity];
 
         for (int i = oldCapacity; i-- > 0;) {
-            if(oldKeys[i] != null) {
+            if (oldKeys[i] != null) {
                 String o = oldKeys[i];
                 int index = index(o);
                 keys[index] = o;
@@ -391,20 +388,19 @@
     }
 
     NameSpaceSymbEntry get(String key) {
-        return  entries[index(key)];
+        return entries[index(key)];
     }
 
     protected Object clone()  {
         try {
-                SymbMap copy=(SymbMap) super.clone();
-                copy.entries=new NameSpaceSymbEntry[entries.length];
-                System.arraycopy(entries,0,copy.entries,0,entries.length);
-                copy.keys=new String[keys.length];
-                System.arraycopy(keys,0,copy.keys,0,keys.length);
+            SymbMap copy = (SymbMap) super.clone();
+            copy.entries = new NameSpaceSymbEntry[entries.length];
+            System.arraycopy(entries, 0, copy.entries, 0, entries.length);
+            copy.keys = new String[keys.length];
+            System.arraycopy(keys, 0, copy.keys, 0, keys.length);
 
-                return copy;
+            return copy;
         } catch (CloneNotSupportedException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
         return null;
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,3 +1,25 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
 package com.sun.org.apache.xml.internal.security.c14n.implementations;
 
 import java.io.IOException;
@@ -6,150 +28,153 @@
 
 public class UtfHelpper {
 
-        final static void writeByte(final String str,final OutputStream out,Map<String,byte[]> cache) throws IOException {
-                   byte []result= cache.get(str);
-                   if (result==null) {
-                           result=getStringInUtf8(str);
-                           cache.put(str,result);
-                   }
+    static final void writeByte(
+        final String str,
+        final OutputStream out,
+        Map<String, byte[]> cache
+    ) throws IOException {
+        byte[] result = cache.get(str);
+        if (result == null) {
+            result = getStringInUtf8(str);
+            cache.put(str, result);
+        }
 
-                   out.write(result);
+        out.write(result);
+    }
 
-           }
+    static final void writeCharToUtf8(final char c, final OutputStream out) throws IOException {
+        if (c < 0x80) {
+            out.write(c);
+            return;
+        }
+        if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) {
+            //No Surrogates in sun java
+            out.write(0x3f);
+            return;
+        }
+        int bias;
+        int write;
+        char ch;
+        if (c > 0x07FF) {
+            ch = (char)(c>>>12);
+            write = 0xE0;
+            if (ch > 0) {
+                write |= (ch & 0x0F);
+            }
+            out.write(write);
+            write = 0x80;
+            bias = 0x3F;
+        } else {
+            write = 0xC0;
+            bias = 0x1F;
+        }
+        ch = (char)(c>>>6);
+        if (ch > 0) {
+            write |= (ch & bias);
+        }
+        out.write(write);
+        out.write(0x80 | ((c) & 0x3F));
 
-        final static void writeCharToUtf8(final char c,final OutputStream out) throws IOException{
-                if (c < 0x80) {
+    }
+
+    static final void writeStringToUtf8(
+        final String str,
+        final OutputStream out
+    ) throws IOException{
+        final int length = str.length();
+        int i = 0;
+        char c;
+        while (i < length) {
+            c = str.charAt(i++);
+            if (c < 0x80)  {
                 out.write(c);
-                return;
+                continue;
             }
-                if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){
+            if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) {
                 //No Surrogates in sun java
                 out.write(0x3f);
-                return;
-        }
+                continue;
+            }
+            char ch;
             int bias;
             int write;
-            char ch;
             if (c > 0x07FF) {
-                ch=(char)(c>>>12);
-                write=0xE0;
-                if (ch>0) {
-                    write |= ( ch & 0x0F);
+                ch = (char)(c>>>12);
+                write = 0xE0;
+                if (ch > 0) {
+                    write |= (ch & 0x0F);
                 }
                 out.write(write);
-                write=0x80;
-                bias=0x3F;
+                write = 0x80;
+                bias = 0x3F;
             } else {
-                write=0xC0;
-                bias=0x1F;
+                write = 0xC0;
+                bias = 0x1F;
             }
-            ch=(char)(c>>>6);
-            if (ch>0) {
-                 write|= (ch & bias);
+            ch = (char)(c>>>6);
+            if (ch > 0) {
+                write |= (ch & bias);
             }
             out.write(write);
             out.write(0x80 | ((c) & 0x3F));
 
-           }
+        }
 
-        final static void writeStringToUtf8(final String str,final OutputStream out) throws IOException{
-                final int length=str.length();
-                int i=0;
-            char c;
-                while (i<length) {
-                        c=str.charAt(i++);
-                if (c < 0x80)  {
-                    out.write(c);
-                    continue;
-                }
-                if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){
-                        //No Surrogates in sun java
-                        out.write(0x3f);
-                        continue;
-                }
-                char ch;
-                int bias;
-                int write;
-                if (c > 0x07FF) {
-                    ch=(char)(c>>>12);
-                    write=0xE0;
-                    if (ch>0) {
-                        write |= ( ch & 0x0F);
-                    }
-                    out.write(write);
-                    write=0x80;
-                    bias=0x3F;
-                } else {
-                        write=0xC0;
-                        bias=0x1F;
-                }
-                ch=(char)(c>>>6);
-                if (ch>0) {
-                     write|= (ch & bias);
-                }
-                out.write(write);
-                out.write(0x80 | ((c) & 0x3F));
-
-                }
+    }
 
-           }
-        public final static byte[] getStringInUtf8(final String str) {
-                   final int length=str.length();
-                   boolean expanded=false;
-                   byte []result=new byte[length];
-                        int i=0;
-                        int out=0;
-                    char c;
-                        while (i<length) {
-                                c=str.charAt(i++);
-                        if ( c < 0x80 ) {
-                            result[out++]=(byte)c;
-                            continue;
-                        }
-                        if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){
-                                   //No Surrogates in sun java
-                                   result[out++]=0x3f;
-
-                                continue;
-                        }
-                        if (!expanded) {
-                                byte newResult[]=new byte[3*length];
-                                        System.arraycopy(result, 0, newResult, 0, out);
-                                        result=newResult;
-                                        expanded=true;
-                        }
-                        char ch;
-                        int bias;
-                        byte write;
-                        if (c > 0x07FF) {
-                            ch=(char)(c>>>12);
-                            write=(byte)0xE0;
-                            if (ch>0) {
-                                write |= ( ch & 0x0F);
-                            }
-                            result[out++]=write;
-                            write=(byte)0x80;
-                            bias=0x3F;
-                        } else {
-                                write=(byte)0xC0;
-                                bias=0x1F;
-                        }
-                        ch=(char)(c>>>6);
-                        if (ch>0) {
-                             write|= (ch & bias);
-                        }
-                        result[out++]=write;
-                        result[out++]=(byte)(0x80 | ((c) & 0x3F));/**/
-
-                        }
-                        if (expanded) {
-                                byte newResult[]=new byte[out];
-                                System.arraycopy(result, 0, newResult, 0, out);
-                                result=newResult;
-                        }
-                        return result;
-           }
-
-
+    public static final byte[] getStringInUtf8(final String str) {
+        final int length = str.length();
+        boolean expanded = false;
+        byte[] result = new byte[length];
+        int i = 0;
+        int out = 0;
+        char c;
+        while (i < length) {
+            c = str.charAt(i++);
+            if (c < 0x80) {
+                result[out++] = (byte)c;
+                continue;
+            }
+            if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) {
+                //No Surrogates in sun java
+                result[out++] = 0x3f;
+                continue;
+            }
+            if (!expanded) {
+                byte newResult[] = new byte[3*length];
+                System.arraycopy(result, 0, newResult, 0, out);
+                result = newResult;
+                expanded = true;
+            }
+            char ch;
+            int bias;
+            byte write;
+            if (c > 0x07FF) {
+                ch = (char)(c>>>12);
+                write = (byte)0xE0;
+                if (ch > 0) {
+                    write |= (ch & 0x0F);
+                }
+                result[out++] = write;
+                write = (byte)0x80;
+                bias = 0x3F;
+            } else {
+                write = (byte)0xC0;
+                bias = 0x1F;
+            }
+            ch = (char)(c>>>6);
+            if (ch > 0) {
+                write |= (ch & bias);
+            }
+            result[out++] = write;
+            result[out++] = (byte)(0x80 | ((c) & 0x3F));
+        }
+        if (expanded) {
+            byte newResult[] = new byte[out];
+            System.arraycopy(result, 0, newResult, 0, out);
+            result = newResult;
+        }
+        return result;
+    }
 
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,249 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.encryption;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
+import java.util.HashMap;
+import java.util.Map;
+
+import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * Converts <code>String</code>s into <code>Node</code>s and visa versa.
+ *
+ * An abstract class for common Serializer functionality
+ */
+public abstract class AbstractSerializer implements Serializer {
+
+    protected Canonicalizer canon;
+
+    public void setCanonicalizer(Canonicalizer canon) {
+        this.canon = canon;
+    }
+
+    /**
+     * Returns a <code>String</code> representation of the specified
+     * <code>Element</code>.
+     * <p/>
+     * Refer also to comments about setup of format.
+     *
+     * @param element the <code>Element</code> to serialize.
+     * @return the <code>String</code> representation of the serilaized
+     *   <code>Element</code>.
+     * @throws Exception
+     */
+    public String serialize(Element element) throws Exception {
+        return canonSerialize(element);
+    }
+
+    /**
+     * Returns a <code>byte[]</code> representation of the specified
+     * <code>Element</code>.
+     *
+     * @param element the <code>Element</code> to serialize.
+     * @return the <code>byte[]</code> representation of the serilaized
+     *   <code>Element</code>.
+     * @throws Exception
+     */
+    public byte[] serializeToByteArray(Element element) throws Exception {
+        return canonSerializeToByteArray(element);
+    }
+
+    /**
+     * Returns a <code>String</code> representation of the specified
+     * <code>NodeList</code>.
+     * <p/>
+     * This is a special case because the NodeList may represent a
+     * <code>DocumentFragment</code>. A document fragment may be a
+     * non-valid XML document (refer to appropriate description of
+     * W3C) because it my start with a non-element node, e.g. a text
+     * node.
+     * <p/>
+     * The methods first converts the node list into a document fragment.
+     * Special care is taken to not destroy the current document, thus
+     * the method clones the nodes (deep cloning) before it appends
+     * them to the document fragment.
+     * <p/>
+     * Refer also to comments about setup of format.
+     *
+     * @param content the <code>NodeList</code> to serialize.
+     * @return the <code>String</code> representation of the serialized
+     *   <code>NodeList</code>.
+     * @throws Exception
+     */
+    public String serialize(NodeList content) throws Exception {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        canon.setWriter(baos);
+        canon.notReset();
+        for (int i = 0; i < content.getLength(); i++) {
+            canon.canonicalizeSubtree(content.item(i));
+        }
+        String ret = baos.toString("UTF-8");
+        baos.reset();
+        return ret;
+    }
+
+    /**
+     * Returns a <code>byte[]</code> representation of the specified
+     * <code>NodeList</code>.
+     *
+     * @param content the <code>NodeList</code> to serialize.
+     * @return the <code>byte[]</code> representation of the serialized
+     *   <code>NodeList</code>.
+     * @throws Exception
+     */
+    public byte[] serializeToByteArray(NodeList content) throws Exception {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        canon.setWriter(baos);
+        canon.notReset();
+        for (int i = 0; i < content.getLength(); i++) {
+            canon.canonicalizeSubtree(content.item(i));
+        }
+        return baos.toByteArray();
+    }
+
+    /**
+     * Use the Canonicalizer to serialize the node
+     * @param node
+     * @return the canonicalization of the node
+     * @throws Exception
+     */
+    public String canonSerialize(Node node) throws Exception {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        canon.setWriter(baos);
+        canon.notReset();
+        canon.canonicalizeSubtree(node);
+        String ret = baos.toString("UTF-8");
+        baos.reset();
+        return ret;
+    }
+
+    /**
+     * Use the Canonicalizer to serialize the node
+     * @param node
+     * @return the (byte[]) canonicalization of the node
+     * @throws Exception
+     */
+    public byte[] canonSerializeToByteArray(Node node) throws Exception {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        canon.setWriter(baos);
+        canon.notReset();
+        canon.canonicalizeSubtree(node);
+        return baos.toByteArray();
+    }
+
+    /**
+     * @param source
+     * @param ctx
+     * @return the Node resulting from the parse of the source
+     * @throws XMLEncryptionException
+     */
+    public abstract Node deserialize(String source, Node ctx) throws XMLEncryptionException;
+
+    /**
+     * @param source
+     * @param ctx
+     * @return the Node resulting from the parse of the source
+     * @throws XMLEncryptionException
+     */
+    public abstract Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException;
+
+    protected static byte[] createContext(byte[] source, Node ctx) throws XMLEncryptionException {
+        // Create the context to parse the document against
+        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+        try {
+            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream, "UTF-8");
+            outputStreamWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?><dummy");
+
+            // Run through each node up to the document node and find any xmlns: nodes
+            Map<String, String> storedNamespaces = new HashMap<String, String>();
+            Node wk = ctx;
+            while (wk != null) {
+                NamedNodeMap atts = wk.getAttributes();
+                if (atts != null) {
+                    for (int i = 0; i < atts.getLength(); ++i) {
+                        Node att = atts.item(i);
+                        String nodeName = att.getNodeName();
+                        if ((nodeName.equals("xmlns") || nodeName.startsWith("xmlns:"))
+                                && !storedNamespaces.containsKey(att.getNodeName())) {
+                            outputStreamWriter.write(" ");
+                            outputStreamWriter.write(nodeName);
+                            outputStreamWriter.write("=\"");
+                            outputStreamWriter.write(att.getNodeValue());
+                            outputStreamWriter.write("\"");
+                            storedNamespaces.put(nodeName, att.getNodeValue());
+                        }
+                    }
+                }
+                wk = wk.getParentNode();
+            }
+            outputStreamWriter.write(">");
+            outputStreamWriter.flush();
+            byteArrayOutputStream.write(source);
+
+            outputStreamWriter.write("</dummy>");
+            outputStreamWriter.close();
+
+            return byteArrayOutputStream.toByteArray();
+        } catch (UnsupportedEncodingException e) {
+            throw new XMLEncryptionException("empty", e);
+        } catch (IOException e) {
+            throw new XMLEncryptionException("empty", e);
+        }
+    }
+
+    protected static String createContext(String source, Node ctx) {
+        // Create the context to parse the document against
+        StringBuilder sb = new StringBuilder();
+        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><dummy");
+
+        // Run through each node up to the document node and find any xmlns: nodes
+        Map<String, String> storedNamespaces = new HashMap<String, String>();
+        Node wk = ctx;
+        while (wk != null) {
+            NamedNodeMap atts = wk.getAttributes();
+            if (atts != null) {
+                for (int i = 0; i < atts.getLength(); ++i) {
+                    Node att = atts.item(i);
+                    String nodeName = att.getNodeName();
+                    if ((nodeName.equals("xmlns") || nodeName.startsWith("xmlns:"))
+                        && !storedNamespaces.containsKey(att.getNodeName())) {
+                        sb.append(" " + nodeName + "=\"" + att.getNodeValue() + "\"");
+                        storedNamespaces.put(nodeName, att.getNodeValue());
+                    }
+                }
+            }
+            wk = wk.getParentNode();
+        }
+        sb.append(">" + source + "</dummy>");
+        return sb.toString();
+    }
+
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,30 +2,30 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  2003-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.encryption;
 
-
 import java.util.Iterator;
 import com.sun.org.apache.xml.internal.security.keys.KeyInfo;
 import org.w3c.dom.Element;
 
-
 /**
  * A Key Agreement algorithm provides for the derivation of a shared secret key
  * based on a shared secret computed from certain types of compatible public
@@ -79,9 +79,10 @@
  * @author Axl Mattheus
  */
 public interface AgreementMethod {
+
     /**
-     * Returns an <code>byte</code> array.
-     * @return
+     * Returns a <code>byte</code> array.
+     * @return a <code>byte</code> array.
      */
     byte[] getKANonce();
 
@@ -92,8 +93,8 @@
     void setKANonce(byte[] kanonce);
 
     /**
-     * Returns aditional information regarding the <code>AgreementMethod</code>.
-     * @return
+     * Returns additional information regarding the <code>AgreementMethod</code>.
+     * @return additional information regarding the <code>AgreementMethod</code>.
      */
     Iterator<Element> getAgreementMethodInformation();
 
@@ -134,7 +135,7 @@
     void setOriginatorKeyInfo(KeyInfo keyInfo);
 
     /**
-     * Retruns information relating to the recipient's shared secret.
+     * Returns information relating to the recipient's shared secret.
      *
      * @return information relating to the recipient's shared secret.
      */
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,25 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  2003-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.encryption;
 
-
 /**
  * <code>CipherData</code> provides encrypted data. It must either contain the
  * encrypted octet sequence as base64 encoded text of the
@@ -42,10 +43,12 @@
  * @author Axl Mattheus
  */
 public interface CipherData {
+
     /** VALUE_TYPE ASN */
-    public static final int VALUE_TYPE = 0x00000001;
+    int VALUE_TYPE = 0x00000001;
+
     /** REFERENCE_TYPE ASN */
-    public static final int REFERENCE_TYPE = 0x00000002;
+    int REFERENCE_TYPE = 0x00000002;
 
     /**
      * Returns the type of encrypted data contained in the
@@ -76,18 +79,17 @@
      * Returns a reference to an external location containing the encrypted
      * octet sequence (<code>byte</code> array).
      *
-     * @return the reference to an external location containing the enctrypted
-     *   octet sequence.
+     * @return the reference to an external location containing the encrypted
+     * octet sequence.
      */
     CipherReference getCipherReference();
 
     /**
      * Sets the <code>CipherData</code>'s reference.
      *
-     * @param reference an external location containing the enctrypted octet
-     *   sequence.
+     * @param reference an external location containing the encrypted octet sequence.
      * @throws XMLEncryptionException
      */
-    void setCipherReference(CipherReference reference) throws
-        XMLEncryptionException;
+    void setCipherReference(CipherReference reference) throws XMLEncryptionException;
 }
+
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,34 +2,34 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  2003-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.encryption;
 
 import org.w3c.dom.Attr;
 
-
 /**
  * <code>CipherReference</code> identifies a source which, when processed,
  * yields the encrypted octet sequence.
  * <p>
  * The actual value is obtained as follows. The <code>CipherReference URI</code>
  * contains an identifier that is dereferenced. Should the
- * <code>CipherReference</code> element contain an OPTIONAL sequence of
  * Transforms, the data resulting from dereferencing the <code>URI</code> is
  * transformed as specified so as to yield the intended cipher value. For
  * example, if the value is base64 encoded within an XML document; the
@@ -62,20 +62,21 @@
     /**
      * Returns an <code>URI</code> that contains an identifier that should be
      * dereferenced.
-     * @return
+     * @return an <code>URI</code> that contains an identifier that should be
+     * dereferenced.
      */
     String getURI();
 
-        /**
-         * Gets the URI as an Attribute node.  Used to meld the CipherREference
-         * with the XMLSignature ResourceResolvers
-     * @return
-         */
-        public Attr getURIAsAttr();
+    /**
+     * Gets the URI as an Attribute node.  Used to meld the CipherReference
+     * with the XMLSignature ResourceResolvers
+     * @return the URI as an Attribute node
+     */
+    Attr getURIAsAttr();
 
     /**
      * Returns the <code>Transforms</code> that specifies how to transform the
-     * <code>URI</code> to yield the appropiate cipher value.
+     * <code>URI</code> to yield the appropriate cipher value.
      *
      * @return the transform that specifies how to transform the reference to
      *   yield the intended cipher value.
@@ -84,10 +85,11 @@
 
     /**
      * Sets the <code>Transforms</code> that specifies how to transform the
-     * <code>URI</code> to yield the appropiate cipher value.
+     * <code>URI</code> to yield the appropriate cipher value.
      *
      * @param transforms the set of <code>Transforms</code> that specifies how
      *   to transform the reference to yield the intended cipher value.
      */
     void setTransforms(Transforms transforms);
 }
+
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,25 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  2003-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.encryption;
 
-
 /**
  * <code>CipherValue</code> is the wrapper for cipher text.
  *
@@ -28,20 +29,18 @@
  */
 public interface CipherValue {
     /**
-     * Resturns the Base 64 encoded, encrypted octets that is the
-     * <code>CihperValue</code>.
+     * Returns the Base 64 encoded, encrypted octets that is the
+     * <code>CipherValue</code>.
      *
      * @return cipher value.
      */
-        String getValue();
-        // byte[] getValue();
+    String getValue();
 
     /**
      * Sets the Base 64 encoded, encrypted octets that is the
-     * <code>CihperValue</code>.
+     * <code>CipherValue</code>.
      *
      * @param value the cipher value.
      */
-        void setValue(String value);
-        // void setValue(byte[] value);
+    void setValue(String value);
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,114 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.encryption;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.StringReader;
+
+import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentFragment;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+/**
+ * Converts <code>String</code>s into <code>Node</code>s and visa versa.
+ */
+public class DocumentSerializer extends AbstractSerializer {
+
+    protected DocumentBuilderFactory dbf;
+
+    /**
+     * @param source
+     * @param ctx
+     * @return the Node resulting from the parse of the source
+     * @throws XMLEncryptionException
+     */
+    public Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException {
+        byte[] fragment = createContext(source, ctx);
+        return deserialize(ctx, new InputSource(new ByteArrayInputStream(fragment)));
+    }
+
+    /**
+     * @param source
+     * @param ctx
+     * @return the Node resulting from the parse of the source
+     * @throws XMLEncryptionException
+     */
+    public Node deserialize(String source, Node ctx) throws XMLEncryptionException {
+        String fragment = createContext(source, ctx);
+        return deserialize(ctx, new InputSource(new StringReader(fragment)));
+    }
+
+    /**
+     * @param ctx
+     * @param inputSource
+     * @return the Node resulting from the parse of the source
+     * @throws XMLEncryptionException
+     */
+    private Node deserialize(Node ctx, InputSource inputSource) throws XMLEncryptionException {
+        try {
+            if (dbf == null) {
+                dbf = DocumentBuilderFactory.newInstance();
+                dbf.setNamespaceAware(true);
+                dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
+                dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE);
+                dbf.setValidating(false);
+            }
+            DocumentBuilder db = dbf.newDocumentBuilder();
+            Document d = db.parse(inputSource);
+
+            Document contextDocument = null;
+            if (Node.DOCUMENT_NODE == ctx.getNodeType()) {
+                contextDocument = (Document)ctx;
+            } else {
+                contextDocument = ctx.getOwnerDocument();
+            }
+
+            Element fragElt =
+                    (Element) contextDocument.importNode(d.getDocumentElement(), true);
+            DocumentFragment result = contextDocument.createDocumentFragment();
+            Node child = fragElt.getFirstChild();
+            while (child != null) {
+                fragElt.removeChild(child);
+                result.appendChild(child);
+                child = fragElt.getFirstChild();
+            }
+            return result;
+        } catch (SAXException se) {
+            throw new XMLEncryptionException("empty", se);
+        } catch (ParserConfigurationException pce) {
+            throw new XMLEncryptionException("empty", pce);
+        } catch (IOException ioe) {
+            throw new XMLEncryptionException("empty", ioe);
+        }
+    }
+
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,25 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  2003-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.encryption;
 
-
 /**
  * The <code>EncryptedData</code> element is the core element in the syntax. Not
  * only does its <code>CipherData</code> child contain the encrypted data, but
@@ -42,3 +43,4 @@
  */
 public interface EncryptedData extends EncryptedType {
 }
+
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  2003-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.encryption;
 
-
-
 /**
  * The <code>EncryptedKey</code> element is used to transport encryption keys
  * from the originator to a known recipient(s). It may be used as a stand-alone
@@ -51,9 +51,9 @@
  * @author Axl Mattheus
  */
 public interface EncryptedKey extends EncryptedType {
+
     /**
-     * Returns a hint as to which recipient this encrypted key value is intended
-     * for.
+     * Returns a hint as to which recipient this encrypted key value is intended for.
      *
      * @return the recipient of the <code>EncryptedKey</code>.
      */
@@ -110,3 +110,4 @@
      */
     void setCarriedName(String name);
 }
+
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,28 +2,28 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  2003-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.encryption;
 
-
 import com.sun.org.apache.xml.internal.security.keys.KeyInfo;
 
-
 /**
  * EncryptedType is the abstract type from which <code>EncryptedData</code> and
  * <code>EncryptedKey</code> are derived. While these two latter element types
@@ -50,6 +50,7 @@
  * @author Axl Mattheus
  */
 public interface EncryptedType {
+
     /**
      * Returns a <code>String</code> providing for the standard method of
      * assigning an id to the element within the document context.
@@ -61,7 +62,7 @@
     /**
      * Sets the id.
      *
-     * @param id.
+     * @param id
      */
     void setId(String id);
 
@@ -117,7 +118,7 @@
     void setMimeType(String type);
 
     /**
-     * Retusn an <code>URI</code> representing the encoding of the
+     * Return an <code>URI</code> representing the encoding of the
      * <code>EncryptedType</code>.
      *
      * @return the encoding of this <code>EncryptedType</code>.
@@ -128,7 +129,7 @@
      * Sets the <code>URI</code> representing the encoding of the
      * <code>EncryptedType</code>.
      *
-     * @param encoding.
+     * @param encoding
      */
     void setEncoding(String encoding);
 
@@ -189,7 +190,8 @@
      * Sets the <code>EncryptionProperties</code> that supplies additional
      * information about the generation of the <code>EncryptedType</code>.
      *
-     * @param properties.
+     * @param properties
      */
     void setEncryptionProperties(EncryptionProperties properties);
 }
+
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,29 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  2003-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.encryption;
 
-
 import java.util.Iterator;
 import org.w3c.dom.Element;
 
-
 /**
  * <code>EncryptionMethod</code> describes the encryption algorithm applied to
  * the cipher data. If the element is absent, the encryption algorithm must be
@@ -83,6 +83,30 @@
     void setOAEPparams(byte[] parameters);
 
     /**
+     * Set the Digest Algorithm to use
+     * @param digestAlgorithm the Digest Algorithm to use
+     */
+    void setDigestAlgorithm(String digestAlgorithm);
+
+    /**
+     * Get the Digest Algorithm to use
+     * @return the Digest Algorithm to use
+     */
+    String getDigestAlgorithm();
+
+    /**
+     * Set the MGF Algorithm to use
+     * @param mgfAlgorithm the MGF Algorithm to use
+     */
+    void setMGFAlgorithm(String mgfAlgorithm);
+
+    /**
+     * Get the MGF Algorithm to use
+     * @return the MGF Algorithm to use
+     */
+    String getMGFAlgorithm();
+
+    /**
      * Returns an iterator over all the additional elements contained in the
      * <code>EncryptionMethod</code>.
      *
@@ -106,3 +130,4 @@
      */
     void removeEncryptionMethodInformation(Element information);
 }
+
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,28 +2,28 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  2003-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.encryption;
 
-
 import java.util.Iterator;
 
-
 /**
  * <code>EncryptionProperties</code> can hold additional information concerning
  * the generation of the <code>EncryptedData</code> or
@@ -46,6 +46,7 @@
  * @author Axl Mattheus
  */
 public interface EncryptionProperties {
+
     /**
      * Returns the <code>EncryptionProperties</code>' id.
      *
@@ -72,14 +73,15 @@
     /**
      * Adds an <code>EncryptionProperty</code>.
      *
-     * @param property.
+     * @param property
      */
     void addEncryptionProperty(EncryptionProperty property);
 
     /**
      * Removes the specified <code>EncryptionProperty</code>.
      *
-     * @param property.
+     * @param property
      */
     void removeEncryptionProperty(EncryptionProperty property);
 }
+
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,25 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  2003-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.encryption;
 
-
 import java.util.Iterator;
 import org.w3c.dom.Element;
 
@@ -50,6 +51,7 @@
  * @author Axl Mattheus
  */
 public interface EncryptionProperty {
+
     /**
      * Returns the <code>EncryptedType</code> being described.
      *
@@ -61,7 +63,7 @@
     /**
      * Sets the target.
      *
-     * @param target.
+     * @param target
      */
     void setTarget(String target);
 
@@ -75,7 +77,7 @@
     /**
      * Sets the id.
      *
-     * @param id.
+     * @param id
      */
     void setId(String id);
 
@@ -98,7 +100,7 @@
     /**
      * Returns the properties of the <CODE>EncryptionProperty</CODE>.
      *
-     * @return an <code>Iterator</code> over all the addiitonal encryption
+     * @return an <code>Iterator</code> over all the additional encryption
      *   information contained in this class.
      */
     Iterator<Element> getEncryptionInformation();
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,29 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  2003-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.encryption;
 
-
 import java.util.Iterator;
 import org.w3c.dom.Element;
 
-
 /**
  * A wrapper for a pointer from a key value of an <code>EncryptedKey</code> to
  * items encrypted by that key value (<code>EncryptedData</code> or
@@ -45,6 +45,13 @@
  */
 public interface Reference {
     /**
+     * Returns the <code>Element</code> tag name for this <code>Reference</code>.
+     *
+     * @return the tag name of this <code>Reference</code>.
+     */
+    String getType();
+
+    /**
      * Returns a <code>URI</code> that points to an <code>Element</code> that
      * were encrypted using the key defined in the enclosing
      * <code>EncryptedKey</code> element.
@@ -79,14 +86,14 @@
     /**
      * Adds retrieval information.
      *
-     * @param info.
+     * @param info
      */
     void addElementRetrievalInformation(Element info);
 
     /**
      * Removes the specified retrieval information.
      *
-     * @param info.
+     * @param info
      */
     void removeElementRetrievalInformation(Element info);
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,28 +2,28 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  2003-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.encryption;
 
-
 import java.util.Iterator;
 
-
 /**
  * <code>ReferenceList</code> is an element that contains pointers from a key
  * value of an <code>EncryptedKey</code> to items encrypted by that key value
@@ -45,10 +45,12 @@
  * @see Reference
  */
 public interface ReferenceList {
-        /** DATA TAG */
-    public static final int DATA_REFERENCE = 0x00000001;
+
+    /** DATA TAG */
+    int DATA_REFERENCE = 0x00000001;
+
     /** KEY TAG */
-    public static final int KEY_REFERENCE  = 0x00000002;
+    int KEY_REFERENCE  = 0x00000002;
 
     /**
      * Adds a reference to this reference list.
@@ -57,21 +59,21 @@
      * @throws IllegalAccessException if the <code>Reference</code> is not an
      *   instance of <code>DataReference</code> or <code>KeyReference</code>.
      */
-    public void add(Reference reference);
+    void add(Reference reference);
 
     /**
      * Removes a reference from the <code>ReferenceList</code>.
      *
      * @param reference the reference to remove.
      */
-    public void remove(Reference reference);
+    void remove(Reference reference);
 
     /**
      * Returns the size of the <code>ReferenceList</code>.
      *
      * @return the size of the <code>ReferenceList</code>.
      */
-    public int size();
+    int size();
 
     /**
      * Indicates if the <code>ReferenceList</code> is empty.
@@ -79,29 +81,29 @@
      * @return <code><b>true</b></code> if the <code>ReferenceList</code> is
      *     empty, else <code><b>false</b></code>.
      */
-    public boolean isEmpty();
+    boolean isEmpty();
 
     /**
      * Returns an <code>Iterator</code> over all the <code>Reference</code>s
-     * contatined in this <code>ReferenceList</code>.
+     * contained in this <code>ReferenceList</code>.
      *
      * @return Iterator.
      */
-    public Iterator<Reference> getReferences();
+    Iterator<Reference> getReferences();
 
     /**
      * <code>DataReference</code> factory method. Returns a
      * <code>DataReference</code>.
      * @param uri
-     * @return
+     * @return a <code>DataReference</code>.
      */
-    public Reference newDataReference(String uri);
+    Reference newDataReference(String uri);
 
     /**
      * <code>KeyReference</code> factory method. Returns a
      * <code>KeyReference</code>.
      * @param uri
-     * @return
+     * @return a <code>KeyReference</code>.
      */
-    public Reference newKeyReference(String uri);
+    Reference newKeyReference(String uri);
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,77 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.encryption;
+
+import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * Converts <code>String</code>s into <code>Node</code>s and visa versa.
+ */
+public interface Serializer {
+
+    /**
+     * Set the Canonicalizer object to use.
+     */
+    void setCanonicalizer(Canonicalizer canon);
+
+    /**
+     * Returns a <code>byte[]</code> representation of the specified
+     * <code>Element</code>.
+     *
+     * @param element the <code>Element</code> to serialize.
+     * @return the <code>byte[]</code> representation of the serilaized
+     *   <code>Element</code>.
+     * @throws Exception
+     */
+    byte[] serializeToByteArray(Element element) throws Exception;
+
+    /**
+     * Returns a <code>byte[]</code> representation of the specified
+     * <code>NodeList</code>.
+     *
+     * @param content the <code>NodeList</code> to serialize.
+     * @return the <code>byte[]</code> representation of the serialized
+     *   <code>NodeList</code>.
+     * @throws Exception
+     */
+    byte[] serializeToByteArray(NodeList content) throws Exception;
+
+    /**
+     * Use the Canonicalizer to serialize the node
+     * @param node
+     * @return the (byte[]) canonicalization of the node
+     * @throws Exception
+     */
+    byte[] canonSerializeToByteArray(Node node) throws Exception;
+
+    /**
+     * @param source
+     * @param ctx
+     * @return the Node resulting from the parse of the source
+     * @throws XMLEncryptionException
+     */
+    Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException;
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  2003-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.encryption;
 
-
-
-
 /**
  * A container for <code>ds:Transform</code>s.
  * <p>
@@ -40,36 +39,12 @@
  */
 public interface Transforms {
     /**
-     * Returns an <code>Iterator</code> over all the transforms contained in
-     * this transform list.
-     *
-     * @return all transforms.
-     */
-    /* Iterator getTransforms(); */
-
-    /**
-     * Adds a <code>ds:Transform</code> to the list of transforms.
-     *
-     * @param transform.
+     * Temporary method to turn the XMLEncryption Transforms class
+     * into a DS class.  The main logic is currently implemented in the
+     * DS class, so we need to get to get the base class.
+     * <p>
+     * <b>Note</b> This will be removed in future versions
      */
-    /* void addTransform(Transform transform); */
-
-    /**
-     * Removes the specified transform.
-     *
-     * @param transform.
-     */
-        /*    void removeTransform(Transform transform); */
-
-        /**
-         * Temporary method to turn the XMLEncryption Transforms class
-         * into a DS class.  The main logic is currently implemented in the
-         * DS class, so we need to get to get the base class.
-         * <p>
-         * <b>Note</b> This will be removed in future versions
-     * @return
-         */
-
-        com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms();
+    com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms();
 
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,57 +2,62 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  2003-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.encryption;
 
-
 import java.io.ByteArrayOutputStream;
 import java.io.InputStream;
-import java.io.IOException;
-import java.io.StringReader;
 import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URISyntaxException;
 import java.security.InvalidAlgorithmParameterException;
 import java.security.InvalidKeyException;
 import java.security.Key;
 import java.security.NoSuchAlgorithmException;
 import java.security.NoSuchProviderException;
+import java.security.SecureRandom;
+import java.security.spec.MGF1ParameterSpec;
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Map;
 
 import javax.crypto.BadPaddingException;
 import javax.crypto.Cipher;
 import javax.crypto.IllegalBlockSizeException;
 import javax.crypto.NoSuchPaddingException;
 import javax.crypto.spec.IvParameterSpec;
-import javax.xml.XMLConstants;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
+import javax.crypto.spec.OAEPParameterSpec;
+import javax.crypto.spec.PSource;
 
 import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
 import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
 import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
 import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException;
+import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.keys.KeyInfo;
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.EncryptedKeyResolver;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
 import com.sun.org.apache.xml.internal.security.transforms.InvalidTransformException;
@@ -62,17 +67,11 @@
 import com.sun.org.apache.xml.internal.security.utils.ElementProxy;
 import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
-import com.sun.org.apache.xml.internal.utils.URI;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
-import org.w3c.dom.DocumentFragment;
 import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
 
 /**
  * <code>XMLCipher</code> encrypts and decrypts the contents of
@@ -85,133 +84,245 @@
  */
 public class XMLCipher {
 
-    private static java.util.logging.Logger logger =
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(XMLCipher.class.getName());
 
-        //J-
-        /** Triple DES EDE (192 bit key) in CBC mode */
+    /** Triple DES EDE (192 bit key) in CBC mode */
     public static final String TRIPLEDES =
         EncryptionConstants.ALGO_ID_BLOCKCIPHER_TRIPLEDES;
+
     /** AES 128 Cipher */
     public static final String AES_128 =
         EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128;
+
     /** AES 256 Cipher */
     public static final String AES_256 =
         EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256;
+
     /** AES 192 Cipher */
     public static final String AES_192 =
         EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES192;
+
+    /** AES 128 GCM Cipher */
+    public static final String AES_128_GCM =
+        EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128_GCM;
+
+    /** AES 192 GCM Cipher */
+    public static final String AES_192_GCM =
+        EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES192_GCM;
+
+    /** AES 256 GCM Cipher */
+    public static final String AES_256_GCM =
+        EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256_GCM;
+
     /** RSA 1.5 Cipher */
     public static final String RSA_v1dot5 =
         EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15;
+
     /** RSA OAEP Cipher */
     public static final String RSA_OAEP =
         EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP;
+
+    /** RSA OAEP Cipher */
+    public static final String RSA_OAEP_11 =
+        EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP_11;
+
     /** DIFFIE_HELLMAN Cipher */
     public static final String DIFFIE_HELLMAN =
         EncryptionConstants.ALGO_ID_KEYAGREEMENT_DH;
+
     /** Triple DES EDE (192 bit key) in CBC mode KEYWRAP*/
     public static final String TRIPLEDES_KeyWrap =
         EncryptionConstants.ALGO_ID_KEYWRAP_TRIPLEDES;
+
     /** AES 128 Cipher KeyWrap */
     public static final String AES_128_KeyWrap =
         EncryptionConstants.ALGO_ID_KEYWRAP_AES128;
+
     /** AES 256 Cipher KeyWrap */
     public static final String AES_256_KeyWrap =
         EncryptionConstants.ALGO_ID_KEYWRAP_AES256;
+
     /** AES 192 Cipher KeyWrap */
     public static final String AES_192_KeyWrap =
         EncryptionConstants.ALGO_ID_KEYWRAP_AES192;
+
     /** SHA1 Cipher */
     public static final String SHA1 =
         Constants.ALGO_ID_DIGEST_SHA1;
+
     /** SHA256 Cipher */
     public static final String SHA256 =
         MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256;
+
     /** SHA512 Cipher */
     public static final String SHA512 =
         MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA512;
+
     /** RIPEMD Cipher */
     public static final String RIPEMD_160 =
         MessageDigestAlgorithm.ALGO_ID_DIGEST_RIPEMD160;
+
     /** XML Signature NS */
     public static final String XML_DSIG =
         Constants.SignatureSpecNS;
+
     /** N14C_XML */
     public static final String N14C_XML =
         Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS;
+
     /** N14C_XML with comments*/
     public static final String N14C_XML_WITH_COMMENTS =
         Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS;
-    /** N14C_XML excluisve */
+
+    /** N14C_XML exclusive */
     public static final String EXCL_XML_N14C =
         Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS;
-    /** N14C_XML exclusive with commetns*/
+
+    /** N14C_XML exclusive with comments*/
     public static final String EXCL_XML_N14C_WITH_COMMENTS =
         Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS;
+
+    /** N14C_PHYSICAL preserve the physical representation*/
+    public static final String PHYSICAL_XML_N14C =
+        Canonicalizer.ALGO_ID_C14N_PHYSICAL;
+
     /** Base64 encoding */
     public static final String BASE64_ENCODING =
         com.sun.org.apache.xml.internal.security.transforms.Transforms.TRANSFORM_BASE64_DECODE;
-        //J+
 
     /** ENCRYPT Mode */
     public static final int ENCRYPT_MODE = Cipher.ENCRYPT_MODE;
+
     /** DECRYPT Mode */
     public static final int DECRYPT_MODE = Cipher.DECRYPT_MODE;
+
     /** UNWRAP Mode */
     public static final int UNWRAP_MODE  = Cipher.UNWRAP_MODE;
+
     /** WRAP Mode */
     public static final int WRAP_MODE    = Cipher.WRAP_MODE;
 
     private static final String ENC_ALGORITHMS = TRIPLEDES + "\n" +
-        AES_128 + "\n" + AES_256 + "\n" + AES_192 + "\n" + RSA_v1dot5 + "\n" +
-        RSA_OAEP + "\n" + TRIPLEDES_KeyWrap + "\n" + AES_128_KeyWrap + "\n" +
-        AES_256_KeyWrap + "\n" + AES_192_KeyWrap+ "\n";
-
-        /** Cipher created during initialisation that is used for encryption */
-    private Cipher _contextCipher;
-        /** Mode that the XMLCipher object is operating in */
-    private int _cipherMode = Integer.MIN_VALUE;
-        /** URI of algorithm that is being used for cryptographic operation */
-    private String _algorithm = null;
-        /** Cryptographic provider requested by caller */
-        private String _requestedJCEProvider = null;
-        /** Holds c14n to serialize, if initialized then _always_ use this c14n to serialize */
-        private Canonicalizer _canon;
-        /** Used for creation of DOM nodes in WRAP and ENCRYPT modes */
-    private Document _contextDocument;
-        /** Instance of factory used to create XML Encryption objects */
-    private Factory _factory;
-        /** Internal serializer class for going to/from UTF-8 */
-    private Serializer _serializer;
-
-        /** Local copy of user's key */
-        private Key _key;
-        /** Local copy of the kek (used to decrypt EncryptedKeys during a
+    AES_128 + "\n" + AES_256 + "\n" + AES_192 + "\n" + RSA_v1dot5 + "\n" +
+    RSA_OAEP + "\n" + RSA_OAEP_11 + "\n" + TRIPLEDES_KeyWrap + "\n" +
+    AES_128_KeyWrap + "\n" + AES_256_KeyWrap + "\n" + AES_192_KeyWrap + "\n" +
+    AES_128_GCM + "\n" + AES_192_GCM + "\n" + AES_256_GCM + "\n";
+
+    /** Cipher created during initialisation that is used for encryption */
+    private Cipher contextCipher;
+
+    /** Mode that the XMLCipher object is operating in */
+    private int cipherMode = Integer.MIN_VALUE;
+
+    /** URI of algorithm that is being used for cryptographic operation */
+    private String algorithm = null;
+
+    /** Cryptographic provider requested by caller */
+    private String requestedJCEProvider = null;
+
+    /** Holds c14n to serialize, if initialized then _always_ use this c14n to serialize */
+    private Canonicalizer canon;
+
+    /** Used for creation of DOM nodes in WRAP and ENCRYPT modes */
+    private Document contextDocument;
+
+    /** Instance of factory used to create XML Encryption objects */
+    private Factory factory;
+
+    /** Serializer class for going to/from UTF-8 */
+    private Serializer serializer;
+
+    /** Local copy of user's key */
+    private Key key;
+
+    /** Local copy of the kek (used to decrypt EncryptedKeys during a
      *  DECRYPT_MODE operation */
-        private Key _kek;
-
-        // The EncryptedKey being built (part of a WRAP operation) or read
-        // (part of an UNWRAP operation)
-
-        private EncryptedKey _ek;
-
-        // The EncryptedData being built (part of a WRAP operation) or read
-        // (part of an UNWRAP operation)
-
-        private EncryptedData _ed;
+    private Key kek;
+
+    // The EncryptedKey being built (part of a WRAP operation) or read
+    // (part of an UNWRAP operation)
+    private EncryptedKey ek;
+
+    // The EncryptedData being built (part of a WRAP operation) or read
+    // (part of an UNWRAP operation)
+    private EncryptedData ed;
+
+    private SecureRandom random;
+
+    private boolean secureValidation;
+
+    private String digestAlg;
+
+    /** List of internal KeyResolvers for DECRYPT and UNWRAP modes. */
+    private List<KeyResolverSpi> internalKeyResolvers;
+
+    /**
+     * Set the Serializer algorithm to use
+     */
+    public void setSerializer(Serializer serializer) {
+        this.serializer = serializer;
+        serializer.setCanonicalizer(this.canon);
+    }
+
+    /**
+     * Get the Serializer algorithm to use
+     */
+    public Serializer getSerializer() {
+        return serializer;
+    }
 
     /**
      * Creates a new <code>XMLCipher</code>.
      *
-     * @since 1.0.
+     * @param transformation    the name of the transformation, e.g.,
+     *                          <code>XMLCipher.TRIPLEDES</code>. If null the XMLCipher can only
+     *                          be used for decrypt or unwrap operations where the encryption method
+     *                          is defined in the <code>EncryptionMethod</code> element.
+     * @param provider          the JCE provider that supplies the transformation,
+     *                          if null use the default provider.
+     * @param canon             the name of the c14n algorithm, if
+     *                          <code>null</code> use standard serializer
+     * @param digestMethod      An optional digestMethod to use.
      */
-    private XMLCipher() {
-        logger.log(java.util.logging.Level.FINE, "Constructing XMLCipher...");
-
-        _factory = new Factory();
-        _serializer = new Serializer();
-
+    private XMLCipher(
+        String transformation,
+        String provider,
+        String canonAlg,
+        String digestMethod
+    ) throws XMLEncryptionException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Constructing XMLCipher...");
+        }
+
+        factory = new Factory();
+
+        algorithm = transformation;
+        requestedJCEProvider = provider;
+        digestAlg = digestMethod;
+
+        // Create a canonicalizer - used when serializing DOM to octets
+        // prior to encryption (and for the reverse)
+
+        try {
+            if (canonAlg == null) {
+                // The default is to preserve the physical representation.
+                this.canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_PHYSICAL);
+            } else {
+                this.canon = Canonicalizer.getInstance(canonAlg);
+            }
+        } catch (InvalidCanonicalizerException ice) {
+            throw new XMLEncryptionException("empty", ice);
+        }
+
+        if (serializer == null) {
+            serializer = new DocumentSerializer();
+        }
+        serializer.setCanonicalizer(this.canon);
+
+        if (transformation != null) {
+            contextCipher = constructCipher(transformation, digestMethod);
+        }
     }
 
     /**
@@ -222,20 +333,38 @@
      * @since 1.0.
      */
     private static boolean isValidEncryptionAlgorithm(String algorithm) {
-        boolean result = (
+        return (
             algorithm.equals(TRIPLEDES) ||
             algorithm.equals(AES_128) ||
             algorithm.equals(AES_256) ||
             algorithm.equals(AES_192) ||
+            algorithm.equals(AES_128_GCM) ||
+            algorithm.equals(AES_192_GCM) ||
+            algorithm.equals(AES_256_GCM) ||
             algorithm.equals(RSA_v1dot5) ||
             algorithm.equals(RSA_OAEP) ||
+            algorithm.equals(RSA_OAEP_11) ||
             algorithm.equals(TRIPLEDES_KeyWrap) ||
             algorithm.equals(AES_128_KeyWrap) ||
             algorithm.equals(AES_256_KeyWrap) ||
             algorithm.equals(AES_192_KeyWrap)
         );
-
-        return (result);
+    }
+
+    /**
+     * Validate the transformation argument of getInstance or getProviderInstance
+     *
+     * @param transformation the name of the transformation, e.g.,
+     *   <code>XMLCipher.TRIPLEDES</code> which is shorthand for
+     *   &quot;http://www.w3.org/2001/04/xmlenc#tripledes-cbc&quot;
+     */
+    private static void validateTransformation(String transformation) {
+        if (null == transformation) {
+            throw new NullPointerException("Transformation unexpectedly null...");
+        }
+        if (!isValidEncryptionAlgorithm(transformation)) {
+            log.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS);
+        }
     }
 
     /**
@@ -248,7 +377,7 @@
      * the default provider package, other provider packages are searched.
      * <p>
      * <b>NOTE<sub>1</sub>:</b> The transformation name does not follow the same
-     * pattern as that oulined in the Java Cryptography Extension Reference
+     * pattern as that outlined in the Java Cryptography Extension Reference
      * Guide but rather that specified by the XML Encryption Syntax and
      * Processing document. The rational behind this is to make it easier for a
      * novice at writing Java Encryption software to use the library.
@@ -257,7 +386,7 @@
      * same pattern regarding exceptional conditions as that used in
      * <code>javax.crypto.Cipher</code>. Instead, it only throws an
      * <code>XMLEncryptionException</code> which wraps an underlying exception.
-     * The stack trace from the exception should be self explanitory.
+     * The stack trace from the exception should be self explanatory.
      *
      * @param transformation the name of the transformation, e.g.,
      *   <code>XMLCipher.TRIPLEDES</code> which is shorthand for
@@ -266,293 +395,169 @@
      * @return the XMLCipher
      * @see javax.crypto.Cipher#getInstance(java.lang.String)
      */
-    public static XMLCipher getInstance(String transformation) throws
-            XMLEncryptionException {
-        // sanity checks
-        logger.log(java.util.logging.Level.FINE, "Getting XMLCipher...");
-        if (null == transformation)
-            logger.log(java.util.logging.Level.SEVERE, "Transformation unexpectedly null...");
-        if(!isValidEncryptionAlgorithm(transformation))
-            logger.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS);
-
-                XMLCipher instance = new XMLCipher();
-
-        instance._algorithm = transformation;
-                instance._key = null;
-                instance._kek = null;
-
-
-                /* Create a canonicaliser - used when serialising DOM to octets
-                 * prior to encryption (and for the reverse) */
-
-                try {
-                        instance._canon = Canonicalizer.getInstance
-                                (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
-
-                } catch (InvalidCanonicalizerException ice) {
-                        throw new XMLEncryptionException("empty", ice);
-                }
-
-                String jceAlgorithm = JCEMapper.translateURItoJCEID(transformation);
-
-                try {
-            instance._contextCipher = Cipher.getInstance(jceAlgorithm);
-            logger.log(java.util.logging.Level.FINE, "cihper.algoritm = " +
-                instance._contextCipher.getAlgorithm());
-        } catch (NoSuchAlgorithmException nsae) {
-            throw new XMLEncryptionException("empty", nsae);
-        } catch (NoSuchPaddingException nspe) {
-            throw new XMLEncryptionException("empty", nspe);
+    public static XMLCipher getInstance(String transformation) throws XMLEncryptionException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation");
         }
-
-        return (instance);
+        validateTransformation(transformation);
+        return new XMLCipher(transformation, null, null, null);
     }
 
-        /**
-         * Returns an <code>XMLCipher</code> that implements the specified
-         * transformation, operates on the specified context document and serializes
-         * the document with the specified canonicalization algorithm before it
-         * encrypts the document.
-         * <p>
-         *
-         * @param transformation        the name of the transformation, e.g.,
-         *                                              <code>XMLCipher.TRIPLEDES</code> which is
-         *                                                      shorthand for
-         *                              &quot;http://www.w3.org/2001/04/xmlenc#tripledes-cbc&quot;
-         * @param canon                         the name of the c14n algorithm, if
-         *                                                      <code>null</code> use standard serializer
-         * @return
-         * @throws XMLEncryptionException
-         */
-
-        public static XMLCipher getInstance(String transformation, String canon)
-                throws XMLEncryptionException {
-                XMLCipher instance = XMLCipher.getInstance(transformation);
-
-                if (canon != null) {
-                        try {
-                                instance._canon = Canonicalizer.getInstance(canon);
-                        } catch (InvalidCanonicalizerException ice) {
-                                throw new XMLEncryptionException("empty", ice);
-                        }
-                }
-
-                return instance;
+    /**
+     * Returns an <code>XMLCipher</code> that implements the specified
+     * transformation, operates on the specified context document and serializes
+     * the document with the specified canonicalization algorithm before it
+     * encrypts the document.
+     * <p>
+     *
+     * @param transformation    the name of the transformation
+     * @param canon             the name of the c14n algorithm, if <code>null</code> use
+     *                          standard serializer
+     * @return the XMLCipher
+     * @throws XMLEncryptionException
+     */
+    public static XMLCipher getInstance(String transformation, String canon)
+        throws XMLEncryptionException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation and c14n algorithm");
         }
-
-    public static XMLCipher getInstance(String transformation,Cipher cipher) throws XMLEncryptionException {
-        // sanity checks
-        logger.log(java.util.logging.Level.FINE, "Getting XMLCipher...");
-        if (null == transformation)
-            logger.log(java.util.logging.Level.SEVERE, "Transformation unexpectedly null...");
-        if(!isValidEncryptionAlgorithm(transformation))
-            logger.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS);
-
-        XMLCipher instance = new XMLCipher();
-
-        instance._algorithm = transformation;
-        instance._key = null;
-        instance._kek = null;
-
-
-        /* Create a canonicaliser - used when serialising DOM to octets
-         * prior to encryption (and for the reverse) */
-
-        try {
-            instance._canon = Canonicalizer.getInstance
-                    (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
-
-        } catch (InvalidCanonicalizerException ice) {
-            throw new XMLEncryptionException("empty", ice);
+        validateTransformation(transformation);
+        return new XMLCipher(transformation, null, canon, null);
+    }
+
+    /**
+     * Returns an <code>XMLCipher</code> that implements the specified
+     * transformation, operates on the specified context document and serializes
+     * the document with the specified canonicalization algorithm before it
+     * encrypts the document.
+     * <p>
+     *
+     * @param transformation    the name of the transformation
+     * @param canon             the name of the c14n algorithm, if <code>null</code> use
+     *                          standard serializer
+     * @param digestMethod      An optional digestMethod to use
+     * @return the XMLCipher
+     * @throws XMLEncryptionException
+     */
+    public static XMLCipher getInstance(String transformation, String canon, String digestMethod)
+        throws XMLEncryptionException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation and c14n algorithm");
         }
-
-        String jceAlgorithm = JCEMapper.translateURItoJCEID(transformation);
-
-        try {
-            instance._contextCipher = cipher;
-            //Cipher.getInstance(jceAlgorithm);
-            logger.log(java.util.logging.Level.FINE, "cihper.algoritm = " +
-                    instance._contextCipher.getAlgorithm());
-        }catch(Exception ex) {
-            throw new XMLEncryptionException("empty", ex);
-        }
-
-        return (instance);
+        validateTransformation(transformation);
+        return new XMLCipher(transformation, null, canon, digestMethod);
     }
 
     /**
      * Returns an <code>XMLCipher</code> that implements the specified
      * transformation and operates on the specified context document.
      *
-     * @param transformation the name of the transformation, e.g.,
-     *   <code>XMLCipher.TRIPLEDES</code> which is shorthand for
-     *   &quot;http://www.w3.org/2001/04/xmlenc#tripledes-cbc&quot;
-     * @param provider the JCE provider that supplies the transformation
+     * @param transformation    the name of the transformation
+     * @param provider          the JCE provider that supplies the transformation
      * @return the XMLCipher
      * @throws XMLEncryptionException
      */
-
     public static XMLCipher getProviderInstance(String transformation, String provider)
-            throws XMLEncryptionException {
-        // sanity checks
-        logger.log(java.util.logging.Level.FINE, "Getting XMLCipher...");
-        if (null == transformation)
-            logger.log(java.util.logging.Level.SEVERE, "Transformation unexpectedly null...");
-        if(null == provider)
-            logger.log(java.util.logging.Level.SEVERE, "Provider unexpectedly null..");
-        if("" == provider)
-            logger.log(java.util.logging.Level.SEVERE, "Provider's value unexpectedly not specified...");
-        if(!isValidEncryptionAlgorithm(transformation))
-            logger.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS);
-
-                XMLCipher instance = new XMLCipher();
-
-        instance._algorithm = transformation;
-                instance._requestedJCEProvider = provider;
-                instance._key = null;
-                instance._kek = null;
-
-                /* Create a canonicaliser - used when serialising DOM to octets
-                 * prior to encryption (and for the reverse) */
-
-                try {
-                        instance._canon = Canonicalizer.getInstance
-                                (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
-                } catch (InvalidCanonicalizerException ice) {
-                        throw new XMLEncryptionException("empty", ice);
-                }
-
-        try {
-                        String jceAlgorithm =
-                                JCEMapper.translateURItoJCEID(transformation);
-
-            instance._contextCipher = Cipher.getInstance(jceAlgorithm, provider);
-
-            logger.log(java.util.logging.Level.FINE, "cipher._algorithm = " +
-                instance._contextCipher.getAlgorithm());
-            logger.log(java.util.logging.Level.FINE, "provider.name = " + provider);
-        } catch (NoSuchAlgorithmException nsae) {
-            throw new XMLEncryptionException("empty", nsae);
-        } catch (NoSuchProviderException nspre) {
-            throw new XMLEncryptionException("empty", nspre);
-        } catch (NoSuchPaddingException nspe) {
-            throw new XMLEncryptionException("empty", nspe);
+        throws XMLEncryptionException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation and provider");
+        }
+        if (null == provider) {
+            throw new NullPointerException("Provider unexpectedly null..");
         }
-
-        return (instance);
+        validateTransformation(transformation);
+        return new XMLCipher(transformation, provider, null, null);
     }
 
-        /**
-         * Returns an <code>XMLCipher</code> that implements the specified
+    /**
+     * Returns an <code>XMLCipher</code> that implements the specified
+     * transformation, operates on the specified context document and serializes
+     * the document with the specified canonicalization algorithm before it
+     * encrypts the document.
+     * <p>
+     *
+     * @param transformation    the name of the transformation
+     * @param provider          the JCE provider that supplies the transformation
+     * @param canon             the name of the c14n algorithm, if <code>null</code> use standard
+     *                          serializer
+     * @return the XMLCipher
+     * @throws XMLEncryptionException
+     */
+    public static XMLCipher getProviderInstance(
+        String transformation, String provider, String canon
+    ) throws XMLEncryptionException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation, provider and c14n algorithm");
+        }
+        if (null == provider) {
+            throw new NullPointerException("Provider unexpectedly null..");
+        }
+        validateTransformation(transformation);
+        return new XMLCipher(transformation, provider, canon, null);
+    }
+
+    /**
+     * Returns an <code>XMLCipher</code> that implements the specified
      * transformation, operates on the specified context document and serializes
      * the document with the specified canonicalization algorithm before it
      * encrypts the document.
      * <p>
-         *
-         * @param transformation        the name of the transformation, e.g.,
-     *                                                  <code>XMLCipher.TRIPLEDES</code> which is
-     *                                                  shorthand for
-     *                                  &quot;http://www.w3.org/2001/04/xmlenc#tripledes-cbc&quot;
-         * @param provider              the JCE provider that supplies the transformation
-         * @param canon                         the name of the c14n algorithm, if
-         *                                                      <code>null</code> use standard serializer
-         * @return
-         * @throws XMLEncryptionException
-         */
-        public static XMLCipher getProviderInstance(
-                String transformation,
-                String provider,
-                String canon)
-                throws XMLEncryptionException {
-
-                XMLCipher instance = XMLCipher.getProviderInstance(transformation, provider);
-                if (canon != null) {
-                        try {
-                                instance._canon = Canonicalizer.getInstance(canon);
-                        } catch (InvalidCanonicalizerException ice) {
-                                throw new XMLEncryptionException("empty", ice);
-                        }
-                }
-                return instance;
-        }
-
-    /**
-     * Returns an <code>XMLCipher</code> that implements no specific
-         * transformation, and can therefore only be used for decrypt or
-         * unwrap operations where the encryption method is defined in the
-         * <code>EncryptionMethod</code> element.
-         *
-     * @return The XMLCipher
+     *
+     * @param transformation    the name of the transformation
+     * @param provider          the JCE provider that supplies the transformation
+     * @param canon             the name of the c14n algorithm, if <code>null</code> use standard
+     *                          serializer
+     * @param digestMethod      An optional digestMethod to use
+     * @return the XMLCipher
      * @throws XMLEncryptionException
      */
-
-    public static XMLCipher getInstance()
-            throws XMLEncryptionException {
-        // sanity checks
-        logger.log(java.util.logging.Level.FINE, "Getting XMLCipher for no transformation...");
-
-                XMLCipher instance = new XMLCipher();
-
-        instance._algorithm = null;
-                instance._requestedJCEProvider = null;
-                instance._key = null;
-                instance._kek = null;
-                instance._contextCipher = null;
-
-                /* Create a canonicaliser - used when serialising DOM to octets
-                 * prior to encryption (and for the reverse) */
-
-                try {
-                        instance._canon = Canonicalizer.getInstance
-                                (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
-                } catch (InvalidCanonicalizerException ice) {
-                        throw new XMLEncryptionException("empty", ice);
-                }
-
-        return (instance);
+    public static XMLCipher getProviderInstance(
+        String transformation, String provider, String canon, String digestMethod
+    ) throws XMLEncryptionException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation, provider and c14n algorithm");
+        }
+        if (null == provider) {
+            throw new NullPointerException("Provider unexpectedly null..");
+        }
+        validateTransformation(transformation);
+        return new XMLCipher(transformation, provider, canon, digestMethod);
     }
 
     /**
      * Returns an <code>XMLCipher</code> that implements no specific
-         * transformation, and can therefore only be used for decrypt or
-         * unwrap operations where the encryption method is defined in the
-         * <code>EncryptionMethod</code> element.
-         *
-         * Allows the caller to specify a provider that will be used for
-         * cryptographic operations.
+     * transformation, and can therefore only be used for decrypt or
+     * unwrap operations where the encryption method is defined in the
+     * <code>EncryptionMethod</code> element.
      *
-     * @param provider the JCE provider that supplies the cryptographic
-         * needs.
+     * @return The XMLCipher
+     * @throws XMLEncryptionException
+     */
+    public static XMLCipher getInstance() throws XMLEncryptionException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Getting XMLCipher with no arguments");
+        }
+        return new XMLCipher(null, null, null, null);
+    }
+
+    /**
+     * Returns an <code>XMLCipher</code> that implements no specific
+     * transformation, and can therefore only be used for decrypt or
+     * unwrap operations where the encryption method is defined in the
+     * <code>EncryptionMethod</code> element.
+     *
+     * Allows the caller to specify a provider that will be used for
+     * cryptographic operations.
+     *
+     * @param provider          the JCE provider that supplies the transformation
      * @return the XMLCipher
      * @throws XMLEncryptionException
      */
-
-    public static XMLCipher getProviderInstance(String provider)
-            throws XMLEncryptionException {
-        // sanity checks
-
-        logger.log(java.util.logging.Level.FINE, "Getting XMLCipher, provider but no transformation");
-        if(null == provider)
-            logger.log(java.util.logging.Level.SEVERE, "Provider unexpectedly null..");
-        if("" == provider)
-            logger.log(java.util.logging.Level.SEVERE, "Provider's value unexpectedly not specified...");
-
-                XMLCipher instance = new XMLCipher();
-
-        instance._algorithm = null;
-                instance._requestedJCEProvider = provider;
-                instance._key = null;
-                instance._kek = null;
-                instance._contextCipher = null;
-
-                try {
-                        instance._canon = Canonicalizer.getInstance
-                                (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
-                } catch (InvalidCanonicalizerException ice) {
-                        throw new XMLEncryptionException("empty", ice);
-                }
-
-        return (instance);
+    public static XMLCipher getProviderInstance(String provider) throws XMLEncryptionException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Getting XMLCipher with provider");
+        }
+        return new XMLCipher(null, provider, null, null);
     }
 
     /**
@@ -561,13 +566,13 @@
      * The cipher is initialized for one of the following four operations:
      * encryption, decryption, key wrapping or key unwrapping, depending on the
      * value of opmode.
-         *
-         * For WRAP and ENCRYPT modes, this also initialises the internal
-         * EncryptedKey or EncryptedData (with a CipherValue)
-         * structure that will be used during the ensuing operations.  This
-         * can be obtained (in order to modify KeyInfo elements etc. prior to
-         * finalising the encryption) by calling
-         * {@link #getEncryptedData} or {@link #getEncryptedKey}.
+     *
+     * For WRAP and ENCRYPT modes, this also initialises the internal
+     * EncryptedKey or EncryptedData (with a CipherValue)
+     * structure that will be used during the ensuing operations.  This
+     * can be obtained (in order to modify KeyInfo elements etc. prior to
+     * finalising the encryption) by calling
+     * {@link #getEncryptedData} or {@link #getEncryptedKey}.
      *
      * @param opmode the operation mode of this cipher (this is one of the
      *   following: ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE or UNWRAP_MODE)
@@ -577,164 +582,216 @@
      */
     public void init(int opmode, Key key) throws XMLEncryptionException {
         // sanity checks
-        logger.log(java.util.logging.Level.FINE, "Initializing XMLCipher...");
-
-                _ek = null;
-                _ed = null;
-
-                switch (opmode) {
-
-                case ENCRYPT_MODE :
-                        logger.log(java.util.logging.Level.FINE, "opmode = ENCRYPT_MODE");
-                        _ed = createEncryptedData(CipherData.VALUE_TYPE, "NO VALUE YET");
-                        break;
-                case DECRYPT_MODE :
-                        logger.log(java.util.logging.Level.FINE, "opmode = DECRYPT_MODE");
-                        break;
-                case WRAP_MODE :
-                        logger.log(java.util.logging.Level.FINE, "opmode = WRAP_MODE");
-                        _ek = createEncryptedKey(CipherData.VALUE_TYPE, "NO VALUE YET");
-                        break;
-                case UNWRAP_MODE :
-                        logger.log(java.util.logging.Level.FINE, "opmode = UNWRAP_MODE");
-                        break;
-                default :
-                        logger.log(java.util.logging.Level.SEVERE, "Mode unexpectedly invalid");
-                        throw new XMLEncryptionException("Invalid mode in init");
-                }
-
-        _cipherMode = opmode;
-                _key = key;
-
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Initializing XMLCipher...");
+        }
+
+        ek = null;
+        ed = null;
+
+        switch (opmode) {
+
+        case ENCRYPT_MODE :
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "opmode = ENCRYPT_MODE");
+            }
+            ed = createEncryptedData(CipherData.VALUE_TYPE, "NO VALUE YET");
+            break;
+        case DECRYPT_MODE :
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "opmode = DECRYPT_MODE");
+            }
+            break;
+        case WRAP_MODE :
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "opmode = WRAP_MODE");
+            }
+            ek = createEncryptedKey(CipherData.VALUE_TYPE, "NO VALUE YET");
+            break;
+        case UNWRAP_MODE :
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "opmode = UNWRAP_MODE");
+            }
+            break;
+        default :
+            log.log(java.util.logging.Level.SEVERE, "Mode unexpectedly invalid");
+            throw new XMLEncryptionException("Invalid mode in init");
+        }
+
+        cipherMode = opmode;
+        this.key = key;
+    }
+
+    /**
+     * Set whether secure validation is enabled or not. The default is false.
+     */
+    public void setSecureValidation(boolean secureValidation) {
+        this.secureValidation = secureValidation;
     }
 
-        /**
-         * Get the EncryptedData being build
-         *
-         * Returns the EncryptedData being built during an ENCRYPT operation.
-         * This can then be used by applications to add KeyInfo elements and
-         * set other parameters.
-         *
-         * @return The EncryptedData being built
-         */
-
-        public EncryptedData getEncryptedData() {
-
-                // Sanity checks
-                logger.log(java.util.logging.Level.FINE, "Returning EncryptedData");
-                return _ed;
-
+    /**
+     * This method is used to add a custom {@link KeyResolverSpi} to an XMLCipher.
+     * These KeyResolvers are used in KeyInfo objects in DECRYPT and
+     * UNWRAP modes.
+     *
+     * @param keyResolver
+     */
+    public void registerInternalKeyResolver(KeyResolverSpi keyResolver) {
+        if (internalKeyResolvers == null) {
+            internalKeyResolvers = new ArrayList<KeyResolverSpi>();
         }
-
-        /**
-         * Get the EncryptedData being build
-         *
-         * Returns the EncryptedData being built during an ENCRYPT operation.
-         * This can then be used by applications to add KeyInfo elements and
-         * set other parameters.
-         *
-         * @return The EncryptedData being built
-         */
-
-        public EncryptedKey getEncryptedKey() {
-
-                // Sanity checks
-                logger.log(java.util.logging.Level.FINE, "Returning EncryptedKey");
-                return _ek;
+        internalKeyResolvers.add(keyResolver);
+    }
+
+    /**
+     * Get the EncryptedData being built
+     * <p>
+     * Returns the EncryptedData being built during an ENCRYPT operation.
+     * This can then be used by applications to add KeyInfo elements and
+     * set other parameters.
+     *
+     * @return The EncryptedData being built
+     */
+    public EncryptedData getEncryptedData() {
+        // Sanity checks
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Returning EncryptedData");
+        }
+        return ed;
+    }
+
+    /**
+     * Get the EncryptedData being build
+     *
+     * Returns the EncryptedData being built during an ENCRYPT operation.
+     * This can then be used by applications to add KeyInfo elements and
+     * set other parameters.
+     *
+     * @return The EncryptedData being built
+     */
+    public EncryptedKey getEncryptedKey() {
+        // Sanity checks
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Returning EncryptedKey");
         }
-
-        /**
-         * Set a Key Encryption Key.
-         * <p>
-         * The Key Encryption Key (KEK) is used for encrypting/decrypting
-         * EncryptedKey elements.  By setting this separately, the XMLCipher
-         * class can know whether a key applies to the data part or wrapped key
-         * part of an encrypted object.
-         *
-         * @param kek The key to use for de/encrypting key data
-         */
-
-        public void setKEK(Key kek) {
-
-                _kek = kek;
-
-        }
-
-        /**
-         * Martial an EncryptedData
-         *
-         * Takes an EncryptedData object and returns a DOM Element that
-         * represents the appropriate <code>EncryptedData</code>
-         * <p>
-         * <b>Note:</b> This should only be used in cases where the context
-         * document has been passed in via a call to doFinal.
-         *
-         * @param encryptedData EncryptedData object to martial
-         * @return the DOM <code>Element</code> representing the passed in
-         * object
+        return ek;
+    }
+
+    /**
+     * Set a Key Encryption Key.
+     * <p>
+     * The Key Encryption Key (KEK) is used for encrypting/decrypting
+     * EncryptedKey elements.  By setting this separately, the XMLCipher
+     * class can know whether a key applies to the data part or wrapped key
+     * part of an encrypted object.
+     *
+     * @param kek The key to use for de/encrypting key data
+     */
+
+    public void setKEK(Key kek) {
+        this.kek = kek;
+    }
+
+    /**
+     * Martial an EncryptedData
+     *
+     * Takes an EncryptedData object and returns a DOM Element that
+     * represents the appropriate <code>EncryptedData</code>
+     * <p>
+     * <b>Note:</b> This should only be used in cases where the context
+     * document has been passed in via a call to doFinal.
+     *
+     * @param encryptedData EncryptedData object to martial
+     * @return the DOM <code>Element</code> representing the passed in
+     * object
+     */
+    public Element martial(EncryptedData encryptedData) {
+        return factory.toElement(encryptedData);
+    }
+
+    /**
+     * Martial an EncryptedData
+     *
+     * Takes an EncryptedData object and returns a DOM Element that
+     * represents the appropriate <code>EncryptedData</code>
+     *
+     * @param context The document that will own the returned nodes
+     * @param encryptedData EncryptedData object to martial
+     * @return the DOM <code>Element</code> representing the passed in
+     * object
      */
-
-        public Element martial(EncryptedData encryptedData) {
-
-                return (_factory.toElement (encryptedData));
-
-        }
-
-        /**
-         * Martial an EncryptedKey
-         *
-         * Takes an EncryptedKey object and returns a DOM Element that
-         * represents the appropriate <code>EncryptedKey</code>
-         *
-         * <p>
-         * <b>Note:</b> This should only be used in cases where the context
-         * document has been passed in via a call to doFinal.
-         *
-         * @param encryptedKey EncryptedKey object to martial
-         * @return the DOM <code>Element</code> representing the passed in
-         * object */
-
-        public Element martial(EncryptedKey encryptedKey) {
-
-                return (_factory.toElement (encryptedKey));
-
-        }
-
-        /**
-         * Martial an EncryptedData
-         *
-         * Takes an EncryptedData object and returns a DOM Element that
-         * represents the appropriate <code>EncryptedData</code>
-         *
-         * @param context The document that will own the returned nodes
-         * @param encryptedData EncryptedData object to martial
-         * @return the DOM <code>Element</code> representing the passed in
-         * object */
-
-        public Element martial(Document context, EncryptedData encryptedData) {
-
-                _contextDocument = context;
-                return (_factory.toElement (encryptedData));
-
-        }
-
-        /**
-         * Martial an EncryptedKey
-         *
-         * Takes an EncryptedKey object and returns a DOM Element that
-         * represents the appropriate <code>EncryptedKey</code>
-         *
-         * @param context The document that will own the created nodes
-         * @param encryptedKey EncryptedKey object to martial
-         * @return the DOM <code>Element</code> representing the passed in
-         * object */
-
-        public Element martial(Document context, EncryptedKey encryptedKey) {
-
-                _contextDocument = context;
-                return (_factory.toElement (encryptedKey));
-
-        }
+    public Element martial(Document context, EncryptedData encryptedData) {
+        contextDocument = context;
+        return factory.toElement(encryptedData);
+    }
+
+    /**
+     * Martial an EncryptedKey
+     *
+     * Takes an EncryptedKey object and returns a DOM Element that
+     * represents the appropriate <code>EncryptedKey</code>
+     *
+     * <p>
+     * <b>Note:</b> This should only be used in cases where the context
+     * document has been passed in via a call to doFinal.
+     *
+     * @param encryptedKey EncryptedKey object to martial
+     * @return the DOM <code>Element</code> representing the passed in
+     * object
+     */
+    public Element martial(EncryptedKey encryptedKey) {
+        return factory.toElement(encryptedKey);
+    }
+
+    /**
+     * Martial an EncryptedKey
+     *
+     * Takes an EncryptedKey object and returns a DOM Element that
+     * represents the appropriate <code>EncryptedKey</code>
+     *
+     * @param context The document that will own the created nodes
+     * @param encryptedKey EncryptedKey object to martial
+     * @return the DOM <code>Element</code> representing the passed in
+     * object
+     */
+    public Element martial(Document context, EncryptedKey encryptedKey) {
+        contextDocument = context;
+        return factory.toElement(encryptedKey);
+    }
+
+    /**
+     * Martial a ReferenceList
+     *
+     * Takes a ReferenceList object and returns a DOM Element that
+     * represents the appropriate <code>ReferenceList</code>
+     *
+     * <p>
+     * <b>Note:</b> This should only be used in cases where the context
+     * document has been passed in via a call to doFinal.
+     *
+     * @param referenceList ReferenceList object to martial
+     * @return the DOM <code>Element</code> representing the passed in
+     * object
+     */
+    public Element martial(ReferenceList referenceList) {
+        return factory.toElement(referenceList);
+    }
+
+    /**
+     * Martial a ReferenceList
+     *
+     * Takes a ReferenceList object and returns a DOM Element that
+     * represents the appropriate <code>ReferenceList</code>
+     *
+     * @param context The document that will own the created nodes
+     * @param referenceList ReferenceList object to martial
+     * @return the DOM <code>Element</code> representing the passed in
+     * object
+     */
+    public Element martial(Document context, ReferenceList referenceList) {
+        contextDocument = context;
+        return factory.toElement(referenceList);
+    }
 
     /**
      * Encrypts an <code>Element</code> and replaces it with its encrypted
@@ -747,25 +804,28 @@
      *   <code>Element</code> having replaced the source <code>Element</code>.
      *  @throws Exception
      */
-
     private Document encryptElement(Element element) throws Exception{
-        logger.log(java.util.logging.Level.FINE, "Encrypting element...");
-        if(null == element)
-            logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
-        if(_cipherMode != ENCRYPT_MODE)
-            logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
-
-                if (_algorithm == null) {
-                throw new XMLEncryptionException("XMLCipher instance without transformation specified");
-                }
-                encryptData(_contextDocument, element, false);
-
-        Element encryptedElement = _factory.toElement(_ed);
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Encrypting element...");
+        }
+        if (null == element) {
+            log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
+        }
+        if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
+        }
+
+        if (algorithm == null) {
+            throw new XMLEncryptionException("XMLCipher instance without transformation specified");
+        }
+        encryptData(contextDocument, element, false);
+
+        Element encryptedElement = factory.toElement(ed);
 
         Node sourceParent = element.getParentNode();
         sourceParent.replaceChild(encryptedElement, element);
 
-        return (_contextDocument);
+        return contextDocument;
     }
 
     /**
@@ -782,25 +842,28 @@
      *   <code>Element</code>.
      * @throws Exception
      */
-    private Document encryptElementContent(Element element) throws
-            /* XMLEncryption */Exception {
-        logger.log(java.util.logging.Level.FINE, "Encrypting element content...");
-        if(null == element)
-            logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
-        if(_cipherMode != ENCRYPT_MODE)
-            logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
-
-                if (_algorithm == null) {
-                throw new XMLEncryptionException("XMLCipher instance without transformation specified");
-                }
-                encryptData(_contextDocument, element, true);
-
-        Element encryptedElement = _factory.toElement(_ed);
+    private Document encryptElementContent(Element element) throws /* XMLEncryption */Exception {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Encrypting element content...");
+        }
+        if (null == element) {
+            log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
+        }
+        if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
+        }
+
+        if (algorithm == null) {
+            throw new XMLEncryptionException("XMLCipher instance without transformation specified");
+        }
+        encryptData(contextDocument, element, true);
+
+        Element encryptedElement = factory.toElement(ed);
 
         removeContent(element);
         element.appendChild(encryptedElement);
 
-        return (_contextDocument);
+        return contextDocument;
     }
 
     /**
@@ -812,19 +875,22 @@
      * @return the processed <code>Document</code>.
      * @throws Exception to indicate any exceptional conditions.
      */
-    public Document doFinal(Document context, Document source) throws
-            /* XMLEncryption */Exception {
-        logger.log(java.util.logging.Level.FINE, "Processing source document...");
-        if(null == context)
-            logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
-        if(null == source)
-            logger.log(java.util.logging.Level.SEVERE, "Source document unexpectedly null...");
-
-        _contextDocument = context;
+    public Document doFinal(Document context, Document source) throws /* XMLEncryption */Exception {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Processing source document...");
+        }
+        if (null == context) {
+            log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
+        }
+        if (null == source) {
+            log.log(java.util.logging.Level.SEVERE, "Source document unexpectedly null...");
+        }
+
+        contextDocument = context;
 
         Document result = null;
 
-        switch (_cipherMode) {
+        switch (cipherMode) {
         case DECRYPT_MODE:
             result = decryptElement(source.getDocumentElement());
             break;
@@ -832,15 +898,13 @@
             result = encryptElement(source.getDocumentElement());
             break;
         case UNWRAP_MODE:
-            break;
         case WRAP_MODE:
             break;
         default:
-            throw new XMLEncryptionException(
-                "empty", new IllegalStateException());
+            throw new XMLEncryptionException("empty", new IllegalStateException());
         }
 
-        return (result);
+        return result;
     }
 
     /**
@@ -852,19 +916,22 @@
      * @return the processed <code>Document</code>.
      * @throws Exception to indicate any exceptional conditions.
      */
-    public Document doFinal(Document context, Element element) throws
-            /* XMLEncryption */Exception {
-        logger.log(java.util.logging.Level.FINE, "Processing source element...");
-        if(null == context)
-            logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
-        if(null == element)
-            logger.log(java.util.logging.Level.SEVERE, "Source element unexpectedly null...");
-
-        _contextDocument = context;
+    public Document doFinal(Document context, Element element) throws /* XMLEncryption */Exception {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Processing source element...");
+        }
+        if (null == context) {
+            log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
+        }
+        if (null == element) {
+            log.log(java.util.logging.Level.SEVERE, "Source element unexpectedly null...");
+        }
+
+        contextDocument = context;
 
         Document result = null;
 
-        switch (_cipherMode) {
+        switch (cipherMode) {
         case DECRYPT_MODE:
             result = decryptElement(element);
             break;
@@ -872,15 +939,13 @@
             result = encryptElement(element);
             break;
         case UNWRAP_MODE:
-            break;
         case WRAP_MODE:
             break;
         default:
-            throw new XMLEncryptionException(
-                "empty", new IllegalStateException());
+            throw new XMLEncryptionException("empty", new IllegalStateException());
         }
 
-        return (result);
+        return result;
     }
 
     /**
@@ -896,18 +961,22 @@
      * @throws Exception to indicate any exceptional conditions.
      */
     public Document doFinal(Document context, Element element, boolean content)
-            throws /* XMLEncryption*/ Exception {
-        logger.log(java.util.logging.Level.FINE, "Processing source element...");
-        if(null == context)
-            logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
-        if(null == element)
-            logger.log(java.util.logging.Level.SEVERE, "Source element unexpectedly null...");
-
-        _contextDocument = context;
+        throws /* XMLEncryption*/ Exception {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Processing source element...");
+        }
+        if (null == context) {
+            log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
+        }
+        if (null == element) {
+            log.log(java.util.logging.Level.SEVERE, "Source element unexpectedly null...");
+        }
+
+        contextDocument = context;
 
         Document result = null;
 
-        switch (_cipherMode) {
+        switch (cipherMode) {
         case DECRYPT_MODE:
             if (content) {
                 result = decryptElementContent(element);
@@ -923,15 +992,13 @@
             }
             break;
         case UNWRAP_MODE:
-            break;
         case WRAP_MODE:
             break;
         default:
-            throw new XMLEncryptionException(
-                "empty", new IllegalStateException());
+            throw new XMLEncryptionException("empty", new IllegalStateException());
         }
 
-        return (result);
+        return result;
     }
 
     /**
@@ -939,7 +1006,7 @@
      * you want to have full control over the contents of the
      * <code>EncryptedData</code> structure.
      *
-     * this does not change the source document in any way.
+     * This does not change the source document in any way.
      *
      * @param context the context <code>Document</code>.
      * @param element the <code>Element</code> that will be encrypted.
@@ -947,7 +1014,7 @@
      * @throws Exception
      */
     public EncryptedData encryptData(Document context, Element element) throws
-            /* XMLEncryption */Exception {
+        /* XMLEncryption */Exception {
         return encryptData(context, element, false);
     }
 
@@ -965,16 +1032,21 @@
      * @return the <code>EncryptedData</code>
      * @throws Exception
      */
-    public EncryptedData encryptData(Document context, String type,
-        InputStream serializedData) throws Exception {
-
-        logger.log(java.util.logging.Level.FINE, "Encrypting element...");
-        if (null == context)
-            logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
-        if (null == serializedData)
-            logger.log(java.util.logging.Level.SEVERE, "Serialized data unexpectedly null...");
-        if (_cipherMode != ENCRYPT_MODE)
-            logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
+    public EncryptedData encryptData(
+        Document context, String type, InputStream serializedData
+    ) throws Exception {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Encrypting element...");
+        }
+        if (null == context) {
+            log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
+        }
+        if (null == serializedData) {
+            log.log(java.util.logging.Level.SEVERE, "Serialized data unexpectedly null...");
+        }
+        if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
+        }
 
         return encryptData(context, null, type, serializedData);
     }
@@ -984,7 +1056,7 @@
      * you want to have full control over the contents of the
      * <code>EncryptedData</code> structure.
      *
-     * this does not change the source document in any way.
+     * This does not change the source document in any way.
      *
      * @param context the context <code>Document</code>.
      * @param element the <code>Element</code> that will be encrypted.
@@ -994,84 +1066,84 @@
      * @throws Exception
      */
     public EncryptedData encryptData(
-        Document context, Element element, boolean contentMode)
-        throws /* XMLEncryption */ Exception {
-
-        logger.log(java.util.logging.Level.FINE, "Encrypting element...");
-        if (null == context)
-            logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
-        if (null == element)
-            logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
-        if (_cipherMode != ENCRYPT_MODE)
-            logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
+        Document context, Element element, boolean contentMode
+    ) throws /* XMLEncryption */ Exception {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Encrypting element...");
+        }
+        if (null == context) {
+            log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
+        }
+        if (null == element) {
+            log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
+        }
+        if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
+        }
 
         if (contentMode) {
-            return encryptData
-                (context, element, EncryptionConstants.TYPE_CONTENT, null);
+            return encryptData(context, element, EncryptionConstants.TYPE_CONTENT, null);
         } else {
-            return encryptData
-                (context, element, EncryptionConstants.TYPE_ELEMENT, null);
+            return encryptData(context, element, EncryptionConstants.TYPE_ELEMENT, null);
         }
     }
 
     private EncryptedData encryptData(
-        Document context, Element element, String type,
-        InputStream serializedData) throws /* XMLEncryption */ Exception {
-
-        _contextDocument = context;
-
-        if (_algorithm == null) {
-            throw new XMLEncryptionException
-                ("XMLCipher instance without transformation specified");
+        Document context, Element element, String type, InputStream serializedData
+    ) throws /* XMLEncryption */ Exception {
+        contextDocument = context;
+
+        if (algorithm == null) {
+            throw new XMLEncryptionException("XMLCipher instance without transformation specified");
         }
 
-        String serializedOctets = null;
+        byte[] serializedOctets = null;
         if (serializedData == null) {
-            if (type == EncryptionConstants.TYPE_CONTENT) {
+            if (type.equals(EncryptionConstants.TYPE_CONTENT)) {
                 NodeList children = element.getChildNodes();
                 if (null != children) {
-                    serializedOctets = _serializer.serialize(children);
+                    serializedOctets = serializer.serializeToByteArray(children);
                 } else {
                     Object exArgs[] = { "Element has no content." };
                     throw new XMLEncryptionException("empty", exArgs);
                 }
             } else {
-                serializedOctets = _serializer.serialize(element);
+                serializedOctets = serializer.serializeToByteArray(element);
             }
-            logger.log(java.util.logging.Level.FINE, "Serialized octets:\n" + serializedOctets);
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "Serialized octets:\n" + new String(serializedOctets, "UTF-8"));
+            }
         }
 
         byte[] encryptedBytes = null;
 
         // Now create the working cipher if none was created already
         Cipher c;
-        if (_contextCipher == null) {
-            String jceAlgorithm = JCEMapper.translateURItoJCEID(_algorithm);
-            logger.log(java.util.logging.Level.FINE, "alg = " + jceAlgorithm);
-
-            try {
-                if (_requestedJCEProvider == null)
-                    c = Cipher.getInstance(jceAlgorithm);
-                else
-                    c = Cipher.getInstance(jceAlgorithm, _requestedJCEProvider);
-            } catch (NoSuchAlgorithmException nsae) {
-                throw new XMLEncryptionException("empty", nsae);
-            } catch (NoSuchProviderException nspre) {
-                throw new XMLEncryptionException("empty", nspre);
-            } catch (NoSuchPaddingException nspae) {
-                throw new XMLEncryptionException("empty", nspae);
-            }
+        if (contextCipher == null) {
+            c = constructCipher(algorithm, null);
         } else {
-            c = _contextCipher;
+            c = contextCipher;
         }
         // Now perform the encryption
 
         try {
-            // Should internally generate an IV
-            // todo - allow user to set an IV
-            c.init(_cipherMode, _key);
+            // The Spec mandates a 96-bit IV for GCM algorithms
+            if (AES_128_GCM.equals(algorithm) || AES_192_GCM.equals(algorithm)
+                || AES_256_GCM.equals(algorithm)) {
+                if (random == null) {
+                    random = SecureRandom.getInstance("SHA1PRNG");
+                }
+                byte[] temp = new byte[12];
+                random.nextBytes(temp);
+                IvParameterSpec paramSpec = new IvParameterSpec(temp);
+                c.init(cipherMode, key, paramSpec);
+            } else {
+                c.init(cipherMode, key);
+            }
         } catch (InvalidKeyException ike) {
             throw new XMLEncryptionException("empty", ike);
+        } catch (NoSuchAlgorithmException ex) {
+            throw new XMLEncryptionException("empty", ex);
         }
 
         try {
@@ -1086,13 +1158,16 @@
                 baos.write(c.doFinal());
                 encryptedBytes = baos.toByteArray();
             } else {
-                encryptedBytes = c.doFinal(serializedOctets.getBytes("UTF-8"));
-                logger.log(java.util.logging.Level.FINE, "Expected cipher.outputSize = " +
-                    Integer.toString(c.getOutputSize(
-                        serializedOctets.getBytes().length)));
+                encryptedBytes = c.doFinal(serializedOctets);
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "Expected cipher.outputSize = " +
+                        Integer.toString(c.getOutputSize(serializedOctets.length)));
+                }
             }
-            logger.log(java.util.logging.Level.FINE, "Actual cipher.outputSize = " +
-                Integer.toString(encryptedBytes.length));
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "Actual cipher.outputSize = "
+                             + Integer.toString(encryptedBytes.length));
+            }
         } catch (IllegalStateException ise) {
             throw new XMLEncryptionException("empty", ise);
         } catch (IllegalBlockSizeException ibse) {
@@ -1106,300 +1181,410 @@
         // Now build up to a properly XML Encryption encoded octet stream
         // IvParameterSpec iv;
         byte[] iv = c.getIV();
-        byte[] finalEncryptedBytes =
-                new byte[iv.length + encryptedBytes.length];
+        byte[] finalEncryptedBytes = new byte[iv.length + encryptedBytes.length];
         System.arraycopy(iv, 0, finalEncryptedBytes, 0, iv.length);
-        System.arraycopy(encryptedBytes, 0, finalEncryptedBytes, iv.length,
-                         encryptedBytes.length);
+        System.arraycopy(encryptedBytes, 0, finalEncryptedBytes, iv.length, encryptedBytes.length);
         String base64EncodedEncryptedOctets = Base64.encode(finalEncryptedBytes);
 
-        logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets);
-        logger.log(java.util.logging.Level.FINE, "Encrypted octets length = " +
-            base64EncodedEncryptedOctets.length());
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets);
+            log.log(java.util.logging.Level.FINE, "Encrypted octets length = " + base64EncodedEncryptedOctets.length());
+        }
 
         try {
-            CipherData cd = _ed.getCipherData();
+            CipherData cd = ed.getCipherData();
             CipherValue cv = cd.getCipherValue();
             // cv.setValue(base64EncodedEncryptedOctets.getBytes());
             cv.setValue(base64EncodedEncryptedOctets);
 
             if (type != null) {
-                _ed.setType(new URI(type).toString());
+                ed.setType(new URI(type).toString());
             }
             EncryptionMethod method =
-                _factory.newEncryptionMethod(new URI(_algorithm).toString());
-            _ed.setEncryptionMethod(method);
-        } catch (URI.MalformedURIException mfue) {
-            throw new XMLEncryptionException("empty", mfue);
+                factory.newEncryptionMethod(new URI(algorithm).toString());
+            method.setDigestAlgorithm(digestAlg);
+            ed.setEncryptionMethod(method);
+        } catch (URISyntaxException ex) {
+            throw new XMLEncryptionException("empty", ex);
         }
-        return (_ed);
+        return ed;
     }
 
     /**
      * Returns an <code>EncryptedData</code> interface. Use this operation if
      * you want to load an <code>EncryptedData</code> structure from a DOM
-         * structure and manipulate the contents
+     * structure and manipulate the contents.
      *
      * @param context the context <code>Document</code>.
      * @param element the <code>Element</code> that will be loaded
      * @throws XMLEncryptionException
-     * @return
+     * @return the <code>EncryptedData</code>
      */
     public EncryptedData loadEncryptedData(Document context, Element element)
-                throws XMLEncryptionException {
-        logger.log(java.util.logging.Level.FINE, "Loading encrypted element...");
-        if(null == context)
-            logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
-        if(null == element)
-            logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
-        if(_cipherMode != DECRYPT_MODE)
-            logger.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
-
-        _contextDocument = context;
-        _ed = _factory.newEncryptedData(element);
-
-                return (_ed);
+        throws XMLEncryptionException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Loading encrypted element...");
+        }
+        if (null == context) {
+            throw new NullPointerException("Context document unexpectedly null...");
+        }
+        if (null == element) {
+            throw new NullPointerException("Element unexpectedly null...");
+        }
+        if (cipherMode != DECRYPT_MODE) {
+            throw new XMLEncryptionException("XMLCipher unexpectedly not in DECRYPT_MODE...");
+        }
+
+        contextDocument = context;
+        ed = factory.newEncryptedData(element);
+
+        return ed;
     }
 
     /**
      * Returns an <code>EncryptedKey</code> interface. Use this operation if
      * you want to load an <code>EncryptedKey</code> structure from a DOM
-         * structure and manipulate the contents.
+     * structure and manipulate the contents.
      *
      * @param context the context <code>Document</code>.
      * @param element the <code>Element</code> that will be loaded
-     * @return
+     * @return the <code>EncryptedKey</code>
      * @throws XMLEncryptionException
      */
-
     public EncryptedKey loadEncryptedKey(Document context, Element element)
-                throws XMLEncryptionException {
-        logger.log(java.util.logging.Level.FINE, "Loading encrypted key...");
-        if(null == context)
-            logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
-        if(null == element)
-            logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
-        if(_cipherMode != UNWRAP_MODE && _cipherMode != DECRYPT_MODE)
-            logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE or DECRYPT_MODE...");
-
-        _contextDocument = context;
-        _ek = _factory.newEncryptedKey(element);
-                return (_ek);
+        throws XMLEncryptionException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Loading encrypted key...");
+        }
+        if (null == context) {
+            throw new NullPointerException("Context document unexpectedly null...");
+        }
+        if (null == element) {
+            throw new NullPointerException("Element unexpectedly null...");
+        }
+        if (cipherMode != UNWRAP_MODE && cipherMode != DECRYPT_MODE) {
+            throw new XMLEncryptionException(
+                "XMLCipher unexpectedly not in UNWRAP_MODE or DECRYPT_MODE..."
+            );
+        }
+
+        contextDocument = context;
+        ek = factory.newEncryptedKey(element);
+        return ek;
     }
 
     /**
      * Returns an <code>EncryptedKey</code> interface. Use this operation if
      * you want to load an <code>EncryptedKey</code> structure from a DOM
-         * structure and manipulate the contents.
-         *
-         * Assumes that the context document is the document that owns the element
+     * structure and manipulate the contents.
+     *
+     * Assumes that the context document is the document that owns the element
      *
      * @param element the <code>Element</code> that will be loaded
-     * @return
+     * @return the <code>EncryptedKey</code>
      * @throws XMLEncryptionException
      */
-
-    public EncryptedKey loadEncryptedKey(Element element)
-                throws XMLEncryptionException {
-
-                return (loadEncryptedKey(element.getOwnerDocument(), element));
+    public EncryptedKey loadEncryptedKey(Element element) throws XMLEncryptionException {
+        return loadEncryptedKey(element.getOwnerDocument(), element);
+    }
+
+    /**
+     * Encrypts a key to an EncryptedKey structure
+     *
+     * @param doc the Context document that will be used to general DOM
+     * @param key Key to encrypt (will use previously set KEK to
+     * perform encryption
+     * @return the <code>EncryptedKey</code>
+     * @throws XMLEncryptionException
+     */
+    public EncryptedKey encryptKey(Document doc, Key key) throws XMLEncryptionException {
+        return encryptKey(doc, key, null, null);
     }
 
     /**
      * Encrypts a key to an EncryptedKey structure
-         *
-         * @param doc the Context document that will be used to general DOM
-         * @param key Key to encrypt (will use previously set KEK to
-         * perform encryption
-     * @return
+     *
+     * @param doc the Context document that will be used to general DOM
+     * @param key Key to encrypt (will use previously set KEK to
+     * perform encryption
+     * @param mgfAlgorithm The xenc11 MGF Algorithm to use
+     * @param oaepParams The OAEPParams to use
+     * @return the <code>EncryptedKey</code>
      * @throws XMLEncryptionException
      */
-
-    public EncryptedKey encryptKey(Document doc, Key key) throws
-            XMLEncryptionException {
-
-        logger.log(java.util.logging.Level.FINE, "Encrypting key ...");
-
-        if(null == key)
-            logger.log(java.util.logging.Level.SEVERE, "Key unexpectedly null...");
-        if(_cipherMode != WRAP_MODE)
-            logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in WRAP_MODE...");
-
-                if (_algorithm == null) {
-
-                        throw new XMLEncryptionException("XMLCipher instance without transformation specified");
-                }
-
-                _contextDocument = doc;
-
-                byte[] encryptedBytes = null;
-                Cipher c;
-
-                if (_contextCipher == null) {
-                        // Now create the working cipher
-
-                        String jceAlgorithm =
-                                JCEMapper.translateURItoJCEID(_algorithm);
-
-                        logger.log(java.util.logging.Level.FINE, "alg = " + jceAlgorithm);
-
-                        try {
-                            if (_requestedJCEProvider == null)
-                                c = Cipher.getInstance(jceAlgorithm);
-                            else
-                                c = Cipher.getInstance(jceAlgorithm, _requestedJCEProvider);
-                        } catch (NoSuchAlgorithmException nsae) {
-                                throw new XMLEncryptionException("empty", nsae);
-                        } catch (NoSuchProviderException nspre) {
-                                throw new XMLEncryptionException("empty", nspre);
-                        } catch (NoSuchPaddingException nspae) {
-                                throw new XMLEncryptionException("empty", nspae);
-                        }
-                } else {
-                        c = _contextCipher;
-                }
-                // Now perform the encryption
-
-                try {
-                        // Should internally generate an IV
-                        // todo - allow user to set an IV
-                        c.init(Cipher.WRAP_MODE, _key);
-                        encryptedBytes = c.wrap(key);
-                } catch (InvalidKeyException ike) {
-                        throw new XMLEncryptionException("empty", ike);
-                } catch (IllegalBlockSizeException ibse) {
-                        throw new XMLEncryptionException("empty", ibse);
-                }
+    public EncryptedKey encryptKey(
+        Document doc,
+        Key key,
+        String mgfAlgorithm,
+        byte[] oaepParams
+    ) throws XMLEncryptionException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Encrypting key ...");
+        }
+
+        if (null == key) {
+            log.log(java.util.logging.Level.SEVERE, "Key unexpectedly null...");
+        }
+        if (cipherMode != WRAP_MODE) {
+            log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in WRAP_MODE...");
+        }
+        if (algorithm == null) {
+            throw new XMLEncryptionException("XMLCipher instance without transformation specified");
+        }
+
+        contextDocument = doc;
+
+        byte[] encryptedBytes = null;
+        Cipher c;
+
+        if (contextCipher == null) {
+            // Now create the working cipher
+            c = constructCipher(algorithm, null);
+        } else {
+            c = contextCipher;
+        }
+        // Now perform the encryption
+
+        try {
+            // Should internally generate an IV
+            // todo - allow user to set an IV
+            OAEPParameterSpec oaepParameters =
+                constructOAEPParameters(
+                    algorithm, digestAlg, mgfAlgorithm, oaepParams
+                );
+            if (oaepParameters == null) {
+                c.init(Cipher.WRAP_MODE, this.key);
+            } else {
+                c.init(Cipher.WRAP_MODE, this.key, oaepParameters);
+            }
+            encryptedBytes = c.wrap(key);
+        } catch (InvalidKeyException ike) {
+            throw new XMLEncryptionException("empty", ike);
+        } catch (IllegalBlockSizeException ibse) {
+            throw new XMLEncryptionException("empty", ibse);
+        } catch (InvalidAlgorithmParameterException e) {
+            throw new XMLEncryptionException("empty", e);
+        }
 
         String base64EncodedEncryptedOctets = Base64.encode(encryptedBytes);
-
-        logger.log(java.util.logging.Level.FINE, "Encrypted key octets:\n" + base64EncodedEncryptedOctets);
-        logger.log(java.util.logging.Level.FINE, "Encrypted key octets length = " +
-            base64EncodedEncryptedOctets.length());
-
-                CipherValue cv = _ek.getCipherData().getCipherValue();
-                cv.setValue(base64EncodedEncryptedOctets);
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Encrypted key octets:\n" + base64EncodedEncryptedOctets);
+            log.log(java.util.logging.Level.FINE, "Encrypted key octets length = " + base64EncodedEncryptedOctets.length());
+        }
+
+        CipherValue cv = ek.getCipherData().getCipherValue();
+        cv.setValue(base64EncodedEncryptedOctets);
 
         try {
-            EncryptionMethod method = _factory.newEncryptionMethod(
-                new URI(_algorithm).toString());
-            _ek.setEncryptionMethod(method);
-        } catch (URI.MalformedURIException mfue) {
-            throw new XMLEncryptionException("empty", mfue);
+            EncryptionMethod method = factory.newEncryptionMethod(new URI(algorithm).toString());
+            method.setDigestAlgorithm(digestAlg);
+            method.setMGFAlgorithm(mgfAlgorithm);
+            method.setOAEPparams(oaepParams);
+            ek.setEncryptionMethod(method);
+        } catch (URISyntaxException ex) {
+            throw new XMLEncryptionException("empty", ex);
         }
-                return _ek;
-
+        return ek;
     }
 
-        /**
-         * Decrypt a key from a passed in EncryptedKey structure
-         *
-         * @param encryptedKey Previously loaded EncryptedKey that needs
-         * to be decrypted.
-         * @param algorithm Algorithm for the decryption
-         * @return a key corresponding to the give type
+    /**
+     * Decrypt a key from a passed in EncryptedKey structure
+     *
+     * @param encryptedKey Previously loaded EncryptedKey that needs
+     * to be decrypted.
+     * @param algorithm Algorithm for the decryption
+     * @return a key corresponding to the given type
      * @throws XMLEncryptionException
-         */
-
-        public Key decryptKey(EncryptedKey encryptedKey, String algorithm) throws
-                    XMLEncryptionException {
-
-        logger.log(java.util.logging.Level.FINE, "Decrypting key from previously loaded EncryptedKey...");
-
-        if(_cipherMode != UNWRAP_MODE)
-            logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE...");
-
-                if (algorithm == null) {
-                        throw new XMLEncryptionException("Cannot decrypt a key without knowing the algorithm");
+     */
+    public Key decryptKey(EncryptedKey encryptedKey, String algorithm)
+        throws XMLEncryptionException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Decrypting key from previously loaded EncryptedKey...");
+        }
+
+        if (cipherMode != UNWRAP_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE...");
+        }
+
+        if (algorithm == null) {
+            throw new XMLEncryptionException("Cannot decrypt a key without knowing the algorithm");
+        }
+
+        if (key == null) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "Trying to find a KEK via key resolvers");
+            }
+
+            KeyInfo ki = encryptedKey.getKeyInfo();
+            if (ki != null) {
+                ki.setSecureValidation(secureValidation);
+                try {
+                    String keyWrapAlg = encryptedKey.getEncryptionMethod().getAlgorithm();
+                    String keyType = JCEMapper.getJCEKeyAlgorithmFromURI(keyWrapAlg);
+                    if ("RSA".equals(keyType)) {
+                        key = ki.getPrivateKey();
+                    } else {
+                        key = ki.getSecretKey();
+                    }
                 }
-
-                if (_key == null) {
-
-                        logger.log(java.util.logging.Level.FINE, "Trying to find a KEK via key resolvers");
-
-                        KeyInfo ki = encryptedKey.getKeyInfo();
-                        if (ki != null) {
-                                try {
-                                        _key = ki.getSecretKey();
-                                }
-                                catch (Exception e) {
-                                }
-                        }
-                        if (_key == null) {
-                                logger.log(java.util.logging.Level.SEVERE, "XMLCipher::decryptKey called without a KEK and cannot resolve");
-                                throw new XMLEncryptionException("Unable to decrypt without a KEK");
-                        }
+                catch (Exception e) {
+                    if (log.isLoggable(java.util.logging.Level.FINE)) {
+                        log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+                    }
                 }
-
-                // Obtain the encrypted octets
-                XMLCipherInput cipherInput = new XMLCipherInput(encryptedKey);
-                byte [] encryptedBytes = cipherInput.getBytes();
-
-                String jceKeyAlgorithm =
-                        JCEMapper.getJCEKeyAlgorithmFromURI(algorithm);
-
-                Cipher c;
-                if (_contextCipher == null) {
-                        // Now create the working cipher
-
-                        String jceAlgorithm =
-                                JCEMapper.translateURItoJCEID(
-                                        encryptedKey.getEncryptionMethod().getAlgorithm());
-
-                        logger.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm);
-
-                        try {
-                            if (_requestedJCEProvider == null)
-                                c = Cipher.getInstance(jceAlgorithm);
-                            else
-                                c = Cipher.getInstance(jceAlgorithm, _requestedJCEProvider);
-                        } catch (NoSuchAlgorithmException nsae) {
-                                throw new XMLEncryptionException("empty", nsae);
-                        } catch (NoSuchProviderException nspre) {
-                                throw new XMLEncryptionException("empty", nspre);
-                        } catch (NoSuchPaddingException nspae) {
-                                throw new XMLEncryptionException("empty", nspae);
-                        }
-                } else {
-                        c = _contextCipher;
+            }
+            if (key == null) {
+                log.log(java.util.logging.Level.SEVERE, "XMLCipher::decryptKey called without a KEK and cannot resolve");
+                throw new XMLEncryptionException("Unable to decrypt without a KEK");
+            }
+        }
+
+        // Obtain the encrypted octets
+        XMLCipherInput cipherInput = new XMLCipherInput(encryptedKey);
+        cipherInput.setSecureValidation(secureValidation);
+        byte[] encryptedBytes = cipherInput.getBytes();
+
+        String jceKeyAlgorithm = JCEMapper.getJCEKeyAlgorithmFromURI(algorithm);
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "JCE Key Algorithm: " + jceKeyAlgorithm);
+        }
+
+        Cipher c;
+        if (contextCipher == null) {
+            // Now create the working cipher
+            c =
+                constructCipher(
+                    encryptedKey.getEncryptionMethod().getAlgorithm(),
+                    encryptedKey.getEncryptionMethod().getDigestAlgorithm()
+                );
+        } else {
+            c = contextCipher;
+        }
+
+        Key ret;
+
+        try {
+            EncryptionMethod encMethod = encryptedKey.getEncryptionMethod();
+            OAEPParameterSpec oaepParameters =
+                constructOAEPParameters(
+                    encMethod.getAlgorithm(), encMethod.getDigestAlgorithm(),
+                    encMethod.getMGFAlgorithm(), encMethod.getOAEPparams()
+                );
+            if (oaepParameters == null) {
+                c.init(Cipher.UNWRAP_MODE, key);
+            } else {
+                c.init(Cipher.UNWRAP_MODE, key, oaepParameters);
+            }
+            ret = c.unwrap(encryptedBytes, jceKeyAlgorithm, Cipher.SECRET_KEY);
+        } catch (InvalidKeyException ike) {
+            throw new XMLEncryptionException("empty", ike);
+        } catch (NoSuchAlgorithmException nsae) {
+            throw new XMLEncryptionException("empty", nsae);
+        } catch (InvalidAlgorithmParameterException e) {
+            throw new XMLEncryptionException("empty", e);
+        }
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Decryption of key type " + algorithm + " OK");
+        }
+
+        return ret;
+    }
+
+    /**
+     * Construct an OAEPParameterSpec object from the given parameters
+     */
+    private OAEPParameterSpec constructOAEPParameters(
+        String encryptionAlgorithm,
+        String digestAlgorithm,
+        String mgfAlgorithm,
+        byte[] oaepParams
+    ) {
+        if (XMLCipher.RSA_OAEP.equals(encryptionAlgorithm)
+            || XMLCipher.RSA_OAEP_11.equals(encryptionAlgorithm)) {
+
+            String jceDigestAlgorithm = "SHA-1";
+            if (digestAlgorithm != null) {
+                jceDigestAlgorithm = JCEMapper.translateURItoJCEID(digestAlgorithm);
+            }
+
+            PSource.PSpecified pSource = PSource.PSpecified.DEFAULT;
+            if (oaepParams != null) {
+                pSource = new PSource.PSpecified(oaepParams);
+            }
+
+            MGF1ParameterSpec mgfParameterSpec = new MGF1ParameterSpec("SHA-1");
+            if (XMLCipher.RSA_OAEP_11.equals(encryptionAlgorithm)) {
+                if (EncryptionConstants.MGF1_SHA256.equals(mgfAlgorithm)) {
+                    mgfParameterSpec = new MGF1ParameterSpec("SHA-256");
+                } else if (EncryptionConstants.MGF1_SHA384.equals(mgfAlgorithm)) {
+                    mgfParameterSpec = new MGF1ParameterSpec("SHA-384");
+                } else if (EncryptionConstants.MGF1_SHA512.equals(mgfAlgorithm)) {
+                    mgfParameterSpec = new MGF1ParameterSpec("SHA-512");
                 }
-
-                Key ret;
-
-                try {
-                        c.init(Cipher.UNWRAP_MODE, _key);
-                        ret = c.unwrap(encryptedBytes, jceKeyAlgorithm, Cipher.SECRET_KEY);
-
-                } catch (InvalidKeyException ike) {
-                        throw new XMLEncryptionException("empty", ike);
-                } catch (NoSuchAlgorithmException nsae) {
-                        throw new XMLEncryptionException("empty", nsae);
-                }
-
-                logger.log(java.util.logging.Level.FINE, "Decryption of key type " + algorithm + " OK");
-
-                return ret;
-
+            }
+            return new OAEPParameterSpec(jceDigestAlgorithm, "MGF1", mgfParameterSpec, pSource);
+        }
+
+        return null;
     }
 
-        /**
-         * Decrypt a key from a passed in EncryptedKey structure.  This version
-         * is used mainly internally, when  the cipher already has an
-         * EncryptedData loaded.  The algorithm URI will be read from the
-         * EncryptedData
-         *
-         * @param encryptedKey Previously loaded EncryptedKey that needs
-         * to be decrypted.
-         * @return a key corresponding to the give type
+    /**
+     * Construct a Cipher object
+     */
+    private Cipher constructCipher(String algorithm, String digestAlgorithm) throws XMLEncryptionException {
+        String jceAlgorithm = JCEMapper.translateURItoJCEID(algorithm);
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm);
+        }
+
+        Cipher c;
+        try {
+            if (requestedJCEProvider == null) {
+                c = Cipher.getInstance(jceAlgorithm);
+            } else {
+                c = Cipher.getInstance(jceAlgorithm, requestedJCEProvider);
+            }
+        } catch (NoSuchAlgorithmException nsae) {
+            // Check to see if an RSA OAEP MGF-1 with SHA-1 algorithm was requested
+            // Some JDKs don't support RSA/ECB/OAEPPadding
+            if (XMLCipher.RSA_OAEP.equals(algorithm)
+                && (digestAlgorithm == null
+                    || MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1.equals(digestAlgorithm))) {
+                try {
+                    if (requestedJCEProvider == null) {
+                        c = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
+                    } else {
+                        c = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", requestedJCEProvider);
+                    }
+                } catch (Exception ex) {
+                    throw new XMLEncryptionException("empty", ex);
+                }
+            } else {
+                throw new XMLEncryptionException("empty", nsae);
+            }
+        } catch (NoSuchProviderException nspre) {
+            throw new XMLEncryptionException("empty", nspre);
+        } catch (NoSuchPaddingException nspae) {
+            throw new XMLEncryptionException("empty", nspae);
+        }
+
+        return c;
+    }
+
+    /**
+     * Decrypt a key from a passed in EncryptedKey structure.  This version
+     * is used mainly internally, when  the cipher already has an
+     * EncryptedData loaded.  The algorithm URI will be read from the
+     * EncryptedData
+     *
+     * @param encryptedKey Previously loaded EncryptedKey that needs
+     * to be decrypted.
+     * @return a key corresponding to the given type
      * @throws XMLEncryptionException
-         */
-
-        public Key decryptKey(EncryptedKey encryptedKey) throws
-                    XMLEncryptionException {
-
-                return decryptKey(encryptedKey, _ed.getEncryptionMethod().getAlgorithm());
-
-        }
+     */
+    public Key decryptKey(EncryptedKey encryptedKey) throws XMLEncryptionException {
+        return decryptKey(encryptedKey, ed.getEncryptionMethod().getAlgorithm());
+    }
 
     /**
      * Removes the contents of a <code>Node</code>.
@@ -1407,7 +1592,7 @@
      * @param node the <code>Node</code> to clear.
      */
     private static void removeContent(Node node) {
-       while (node.hasChildNodes()) {
+        while (node.hasChildNodes()) {
             node.removeChild(node.getFirstChild());
         }
     }
@@ -1419,196 +1604,191 @@
      * @return the <code>Node</code> as a result of the decrypt operation.
      * @throws XMLEncryptionException
      */
-    private Document decryptElement(Element element) throws
-            XMLEncryptionException {
-
-        logger.log(java.util.logging.Level.FINE, "Decrypting element...");
-
-        if(_cipherMode != DECRYPT_MODE)
-            logger.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
-
-                String octets;
-                try {
-                        octets = new String(decryptToByteArray(element), "UTF-8");
-                } catch (UnsupportedEncodingException uee) {
-                        throw new XMLEncryptionException("empty", uee);
-                }
-
-
-        logger.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + octets);
-
-        Node sourceParent =  element.getParentNode();
-
-        DocumentFragment decryptedFragment =
-                        _serializer.deserialize(octets, sourceParent);
-
-
-                // The de-serialiser returns a fragment whose children we need to
-                // take on.
-
-                if (sourceParent != null && sourceParent.getNodeType() == Node.DOCUMENT_NODE) {
-
-                    // If this is a content decryption, this may have problems
-
-                    _contextDocument.removeChild(_contextDocument.getDocumentElement());
-                    _contextDocument.appendChild(decryptedFragment);
-                }
-                else {
-                    sourceParent.replaceChild(decryptedFragment, element);
-
-                }
-
-        return (_contextDocument);
+    private Document decryptElement(Element element) throws XMLEncryptionException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Decrypting element...");
+        }
+
+        if (cipherMode != DECRYPT_MODE) {
+            log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
+        }
+
+        byte[] octets = decryptToByteArray(element);
+
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + new String(octets));
+        }
+
+        Node sourceParent = element.getParentNode();
+        Node decryptedNode = serializer.deserialize(octets, sourceParent);
+
+        // The de-serialiser returns a node whose children we need to take on.
+        if (sourceParent != null && Node.DOCUMENT_NODE == sourceParent.getNodeType()) {
+            // If this is a content decryption, this may have problems
+            contextDocument.removeChild(contextDocument.getDocumentElement());
+            contextDocument.appendChild(decryptedNode);
+        } else if (sourceParent != null) {
+            sourceParent.replaceChild(decryptedNode, element);
+        }
+
+        return contextDocument;
     }
 
-
-        /**
-         *
-         * @param element
-     * @return
+    /**
+     *
+     * @param element
+     * @return the <code>Node</code> as a result of the decrypt operation.
      * @throws XMLEncryptionException
-         */
-    private Document decryptElementContent(Element element) throws
-                XMLEncryptionException {
-        Element e = (Element) element.getElementsByTagNameNS(
+     */
+    private Document decryptElementContent(Element element) throws XMLEncryptionException {
+        Element e =
+            (Element) element.getElementsByTagNameNS(
                 EncryptionConstants.EncryptionSpecNS,
-                EncryptionConstants._TAG_ENCRYPTEDDATA).item(0);
+                EncryptionConstants._TAG_ENCRYPTEDDATA
+            ).item(0);
 
         if (null == e) {
-                throw new XMLEncryptionException("No EncryptedData child element.");
+            throw new XMLEncryptionException("No EncryptedData child element.");
         }
 
-        return (decryptElement(e));
+        return decryptElement(e);
     }
 
-        /**
-         * Decrypt an EncryptedData element to a byte array
-         *
-         * When passed in an EncryptedData node, returns the decryption
-         * as a byte array.
-         *
-         * Does not modify the source document
+    /**
+     * Decrypt an EncryptedData element to a byte array.
+     *
+     * When passed in an EncryptedData node, returns the decryption
+     * as a byte array.
+     *
+     * Does not modify the source document.
      * @param element
-     * @return
+     * @return the bytes resulting from the decryption
      * @throws XMLEncryptionException
-         */
-
-        public byte[] decryptToByteArray(Element element)
-                throws XMLEncryptionException {
-
-        logger.log(java.util.logging.Level.FINE, "Decrypting to ByteArray...");
-
-        if(_cipherMode != DECRYPT_MODE)
-            logger.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
-
-        EncryptedData encryptedData = _factory.newEncryptedData(element);
-
-                if (_key == null) {
-
-                        KeyInfo ki = encryptedData.getKeyInfo();
-
-                        if (ki != null) {
-                                try {
-                                        // Add a EncryptedKey resolver
-                                        ki.registerInternalKeyResolver(
-                                     new EncryptedKeyResolver(encryptedData.
-                                                                                                  getEncryptionMethod().
-                                                                                                  getAlgorithm(),
-                                                                                                  _kek));
-                                        _key = ki.getSecretKey();
-                                } catch (KeyResolverException kre) {
-                                        // We will throw in a second...
-                                }
-                        }
-
-                        if (_key == null) {
-                                logger.log(java.util.logging.Level.SEVERE, "XMLCipher::decryptElement called without a key and unable to resolve");
-
-                                throw new XMLEncryptionException("encryption.nokey");
+     */
+    public byte[] decryptToByteArray(Element element) throws XMLEncryptionException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Decrypting to ByteArray...");
+        }
+
+        if (cipherMode != DECRYPT_MODE) {
+            log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
+        }
+
+        EncryptedData encryptedData = factory.newEncryptedData(element);
+
+        if (key == null) {
+            KeyInfo ki = encryptedData.getKeyInfo();
+            if (ki != null) {
+                try {
+                    // Add an EncryptedKey resolver
+                    String encMethodAlgorithm = encryptedData.getEncryptionMethod().getAlgorithm();
+                    EncryptedKeyResolver resolver = new EncryptedKeyResolver(encMethodAlgorithm, kek);
+                    if (internalKeyResolvers != null) {
+                        int size = internalKeyResolvers.size();
+                        for (int i = 0; i < size; i++) {
+                            resolver.registerInternalKeyResolver(internalKeyResolvers.get(i));
                         }
-                }
-
-                // Obtain the encrypted octets
-                XMLCipherInput cipherInput = new XMLCipherInput(encryptedData);
-                byte [] encryptedBytes = cipherInput.getBytes();
-
-                // Now create the working cipher
-
-                String jceAlgorithm =
-                        JCEMapper.translateURItoJCEID(encryptedData.getEncryptionMethod().getAlgorithm());
-
-                Cipher c;
-                try {
-                    if (_requestedJCEProvider == null)
-                        c = Cipher.getInstance(jceAlgorithm);
-                    else
-                        c = Cipher.getInstance(jceAlgorithm, _requestedJCEProvider);
-                } catch (NoSuchAlgorithmException nsae) {
-                        throw new XMLEncryptionException("empty", nsae);
-                } catch (NoSuchProviderException nspre) {
-                        throw new XMLEncryptionException("empty", nspre);
-                } catch (NoSuchPaddingException nspae) {
-                        throw new XMLEncryptionException("empty", nspae);
+                    }
+                    ki.registerInternalKeyResolver(resolver);
+                    ki.setSecureValidation(secureValidation);
+                    key = ki.getSecretKey();
+                } catch (KeyResolverException kre) {
+                    if (log.isLoggable(java.util.logging.Level.FINE)) {
+                        log.log(java.util.logging.Level.FINE, kre.getMessage(), kre);
+                    }
                 }
-
-                // Calculate the IV length and copy out
-
-                // For now, we only work with Block ciphers, so this will work.
-                // This should probably be put into the JCE mapper.
-
-                int ivLen = c.getBlockSize();
-                byte[] ivBytes = new byte[ivLen];
-
-                // You may be able to pass the entire piece in to IvParameterSpec
-                // and it will only take the first x bytes, but no way to be certain
-                // that this will work for every JCE provider, so lets copy the
-                // necessary bytes into a dedicated array.
-
-                System.arraycopy(encryptedBytes, 0, ivBytes, 0, ivLen);
-                IvParameterSpec iv = new IvParameterSpec(ivBytes);
-
-                try {
-                        c.init(_cipherMode, _key, iv);
-                } catch (InvalidKeyException ike) {
-                        throw new XMLEncryptionException("empty", ike);
-                } catch (InvalidAlgorithmParameterException iape) {
-                        throw new XMLEncryptionException("empty", iape);
-                }
-
-                byte[] plainBytes;
+            }
+
+            if (key == null) {
+                log.log(java.util.logging.Level.SEVERE,
+                    "XMLCipher::decryptElement called without a key and unable to resolve"
+                );
+                throw new XMLEncryptionException("encryption.nokey");
+            }
+        }
+
+        // Obtain the encrypted octets
+        XMLCipherInput cipherInput = new XMLCipherInput(encryptedData);
+        cipherInput.setSecureValidation(secureValidation);
+        byte[] encryptedBytes = cipherInput.getBytes();
+
+        // Now create the working cipher
+        String jceAlgorithm =
+            JCEMapper.translateURItoJCEID(encryptedData.getEncryptionMethod().getAlgorithm());
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm);
+        }
+
+        Cipher c;
+        try {
+            if (requestedJCEProvider == null) {
+                c = Cipher.getInstance(jceAlgorithm);
+            } else {
+                c = Cipher.getInstance(jceAlgorithm, requestedJCEProvider);
+            }
+        } catch (NoSuchAlgorithmException nsae) {
+            throw new XMLEncryptionException("empty", nsae);
+        } catch (NoSuchProviderException nspre) {
+            throw new XMLEncryptionException("empty", nspre);
+        } catch (NoSuchPaddingException nspae) {
+            throw new XMLEncryptionException("empty", nspae);
+        }
+
+        // Calculate the IV length and copy out
+
+        // For now, we only work with Block ciphers, so this will work.
+        // This should probably be put into the JCE mapper.
+
+        int ivLen = c.getBlockSize();
+        String alg = encryptedData.getEncryptionMethod().getAlgorithm();
+        if (AES_128_GCM.equals(alg) || AES_192_GCM.equals(alg) || AES_256_GCM.equals(alg)) {
+            ivLen = 12;
+        }
+        byte[] ivBytes = new byte[ivLen];
+
+        // You may be able to pass the entire piece in to IvParameterSpec
+        // and it will only take the first x bytes, but no way to be certain
+        // that this will work for every JCE provider, so lets copy the
+        // necessary bytes into a dedicated array.
+
+        System.arraycopy(encryptedBytes, 0, ivBytes, 0, ivLen);
+        IvParameterSpec iv = new IvParameterSpec(ivBytes);
 
         try {
-            plainBytes = c.doFinal(encryptedBytes,
-                                                                   ivLen,
-                                                                   encryptedBytes.length - ivLen);
-
+            c.init(cipherMode, key, iv);
+        } catch (InvalidKeyException ike) {
+            throw new XMLEncryptionException("empty", ike);
+        } catch (InvalidAlgorithmParameterException iape) {
+            throw new XMLEncryptionException("empty", iape);
+        }
+
+        try {
+            return c.doFinal(encryptedBytes, ivLen, encryptedBytes.length - ivLen);
         } catch (IllegalBlockSizeException ibse) {
             throw new XMLEncryptionException("empty", ibse);
         } catch (BadPaddingException bpe) {
             throw new XMLEncryptionException("empty", bpe);
         }
-
-        return (plainBytes);
     }
 
-        /*
-         * Expose the interface for creating XML Encryption objects
-         */
+    /*
+     * Expose the interface for creating XML Encryption objects
+     */
 
     /**
      * Creates an <code>EncryptedData</code> <code>Element</code>.
      *
-         * The newEncryptedData and newEncryptedKey methods create fairly complete
-         * elements that are immediately useable.  All the other create* methods
-         * return bare elements that still need to be built upon.
-         *<p>
-         * An EncryptionMethod will still need to be added however
-         *
-         * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of
-         * CipherData this EncryptedData will contain.
+     * The newEncryptedData and newEncryptedKey methods create fairly complete
+     * elements that are immediately useable.  All the other create* methods
+     * return bare elements that still need to be built upon.
+     *<p>
+     * An EncryptionMethod will still need to be added however
+     *
+     * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of
+     * CipherData this EncryptedData will contain.
      * @param value the Base 64 encoded, encrypted text to wrap in the
      *   <code>EncryptedData</code> or the URI to set in the CipherReference
-         * (usage will depend on the <code>type</code>
+     * (usage will depend on the <code>type</code>
      * @return the <code>EncryptedData</code> <code>Element</code>.
      *
      * <!--
@@ -1629,44 +1809,41 @@
      * -->
      * @throws XMLEncryptionException
      */
-
-    public EncryptedData createEncryptedData(int type, String value) throws
-            XMLEncryptionException {
+    public EncryptedData createEncryptedData(int type, String value) throws XMLEncryptionException {
         EncryptedData result = null;
         CipherData data = null;
 
         switch (type) {
-            case CipherData.REFERENCE_TYPE:
-                CipherReference cipherReference = _factory.newCipherReference(
-                    value);
-                data = _factory.newCipherData(type);
-                data.setCipherReference(cipherReference);
-                result = _factory.newEncryptedData(data);
-                                break;
-            case CipherData.VALUE_TYPE:
-                CipherValue cipherValue = _factory.newCipherValue(value);
-                data = _factory.newCipherData(type);
-                data.setCipherValue(cipherValue);
-                result = _factory.newEncryptedData(data);
+        case CipherData.REFERENCE_TYPE:
+            CipherReference cipherReference = factory.newCipherReference(value);
+            data = factory.newCipherData(type);
+            data.setCipherReference(cipherReference);
+            result = factory.newEncryptedData(data);
+            break;
+        case CipherData.VALUE_TYPE:
+            CipherValue cipherValue = factory.newCipherValue(value);
+            data = factory.newCipherData(type);
+            data.setCipherValue(cipherValue);
+            result = factory.newEncryptedData(data);
         }
 
-        return (result);
+        return result;
     }
 
     /**
      * Creates an <code>EncryptedKey</code> <code>Element</code>.
      *
-         * The newEncryptedData and newEncryptedKey methods create fairly complete
-         * elements that are immediately useable.  All the other create* methods
-         * return bare elements that still need to be built upon.
-         *<p>
-         * An EncryptionMethod will still need to be added however
-         *
-         * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of
-         * CipherData this EncryptedData will contain.
+     * The newEncryptedData and newEncryptedKey methods create fairly complete
+     * elements that are immediately useable.  All the other create* methods
+     * return bare elements that still need to be built upon.
+     *<p>
+     * An EncryptionMethod will still need to be added however
+     *
+     * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of
+     * CipherData this EncryptedData will contain.
      * @param value the Base 64 encoded, encrypted text to wrap in the
      *   <code>EncryptedKey</code> or the URI to set in the CipherReference
-         * (usage will depend on the <code>type</code>
+     * (usage will depend on the <code>type</code>
      * @return the <code>EncryptedKey</code> <code>Element</code>.
      *
      * <!--
@@ -1687,331 +1864,128 @@
      * -->
      * @throws XMLEncryptionException
      */
-
-    public EncryptedKey createEncryptedKey(int type, String value) throws
-            XMLEncryptionException {
+    public EncryptedKey createEncryptedKey(int type, String value) throws XMLEncryptionException {
         EncryptedKey result = null;
         CipherData data = null;
 
         switch (type) {
-            case CipherData.REFERENCE_TYPE:
-                CipherReference cipherReference = _factory.newCipherReference(
-                    value);
-                data = _factory.newCipherData(type);
-                data.setCipherReference(cipherReference);
-                result = _factory.newEncryptedKey(data);
-                                break;
-            case CipherData.VALUE_TYPE:
-                CipherValue cipherValue = _factory.newCipherValue(value);
-                data = _factory.newCipherData(type);
-                data.setCipherValue(cipherValue);
-                result = _factory.newEncryptedKey(data);
-        }
-
-        return (result);
-    }
-
-        /**
-         * Create an AgreementMethod object
-         *
-         * @param algorithm Algorithm of the agreement method
-     * @return
-         */
-
-        public AgreementMethod createAgreementMethod(String algorithm) {
-                return (_factory.newAgreementMethod(algorithm));
-        }
-
-        /**
-         * Create a CipherData object
-         *
-         * @param type Type of this CipherData (either VALUE_TUPE or
-         * REFERENCE_TYPE)
-         * @return
-         */
-
-        public CipherData createCipherData(int type) {
-                return (_factory.newCipherData(type));
-        }
-
-        /**
-         * Create a CipherReference object
-         *
-     * @return
-         * @param uri The URI that the reference will refer
-         */
-
-        public CipherReference createCipherReference(String uri) {
-                return (_factory.newCipherReference(uri));
-        }
-
-        /**
-         * Create a CipherValue element
-         *
-         * @param value The value to set the ciphertext to
-     * @return
-         */
-
-        public CipherValue createCipherValue(String value) {
-                return (_factory.newCipherValue(value));
+        case CipherData.REFERENCE_TYPE:
+            CipherReference cipherReference = factory.newCipherReference(value);
+            data = factory.newCipherData(type);
+            data.setCipherReference(cipherReference);
+            result = factory.newEncryptedKey(data);
+            break;
+        case CipherData.VALUE_TYPE:
+            CipherValue cipherValue = factory.newCipherValue(value);
+            data = factory.newCipherData(type);
+            data.setCipherValue(cipherValue);
+            result = factory.newEncryptedKey(data);
         }
 
-        /**
-         * Create an EncryptedMethod object
-         *
-         * @param algorithm Algorithm for the encryption
-     * @return
-         */
-        public EncryptionMethod createEncryptionMethod(String algorithm) {
-                return (_factory.newEncryptionMethod(algorithm));
-        }
-
-        /**
-         * Create an EncryptedProperties element
-         * @return
-         */
-        public EncryptionProperties createEncryptionProperties() {
-                return (_factory.newEncryptionProperties());
-        }
-
-        /**
-         * Create a new EncryptionProperty element
-     * @return
-         */
-        public EncryptionProperty createEncryptionProperty() {
-                return (_factory.newEncryptionProperty());
-        }
-
-        /**
-         * Create a new ReferenceList object
-     * @return
-     * @param type
-         */
-        public ReferenceList createReferenceList(int type) {
-                return (_factory.newReferenceList(type));
-        }
-
-        /**
-         * Create a new Transforms object
-         * <p>
-         * <b>Note</b>: A context document <i>must</i> have been set
-         * elsewhere (possibly via a call to doFinal).  If not, use the
-         * createTransforms(Document) method.
-     * @return
-         */
-
-        public Transforms createTransforms() {
-                return (_factory.newTransforms());
-        }
-
-        /**
-         * Create a new Transforms object
-         *
-         * Because the handling of Transforms is currently done in the signature
-         * code, the creation of a Transforms object <b>requires</b> a
-         * context document.
-         *
-         * @param doc Document that will own the created Transforms node
-     * @return
-         */
-        public Transforms createTransforms(Document doc) {
-                return (_factory.newTransforms(doc));
-        }
+        return result;
+    }
+
+    /**
+     * Create an AgreementMethod object
+     *
+     * @param algorithm Algorithm of the agreement method
+     * @return a new <code>AgreementMethod</code>
+     */
+    public AgreementMethod createAgreementMethod(String algorithm) {
+        return factory.newAgreementMethod(algorithm);
+    }
+
+    /**
+     * Create a CipherData object
+     *
+     * @param type Type of this CipherData (either VALUE_TUPE or
+     * REFERENCE_TYPE)
+     * @return a new <code>CipherData</code>
+     */
+    public CipherData createCipherData(int type) {
+        return factory.newCipherData(type);
+    }
+
+    /**
+     * Create a CipherReference object
+     *
+     * @param uri The URI that the reference will refer
+     * @return a new <code>CipherReference</code>
+     */
+    public CipherReference createCipherReference(String uri) {
+        return factory.newCipherReference(uri);
+    }
+
+    /**
+     * Create a CipherValue element
+     *
+     * @param value The value to set the ciphertext to
+     * @return a new <code>CipherValue</code>
+     */
+    public CipherValue createCipherValue(String value) {
+        return factory.newCipherValue(value);
+    }
 
     /**
-     * Converts <code>String</code>s into <code>Node</code>s and visa versa.
-     * <p>
-     * <b>NOTE:</b> For internal use only.
+     * Create an EncryptionMethod object
      *
-     * @author  Axl Mattheus
+     * @param algorithm Algorithm for the encryption
+     * @return a new <code>EncryptionMethod</code>
+     */
+    public EncryptionMethod createEncryptionMethod(String algorithm) {
+        return factory.newEncryptionMethod(algorithm);
+    }
+
+    /**
+     * Create an EncryptionProperties element
+     * @return a new <code>EncryptionProperties</code>
+     */
+    public EncryptionProperties createEncryptionProperties() {
+        return factory.newEncryptionProperties();
+    }
+
+    /**
+     * Create a new EncryptionProperty element
+     * @return a new <code>EncryptionProperty</code>
+     */
+    public EncryptionProperty createEncryptionProperty() {
+        return factory.newEncryptionProperty();
+    }
+
+    /**
+     * Create a new ReferenceList object
+     * @param type ReferenceList.DATA_REFERENCE or ReferenceList.KEY_REFERENCE
+     * @return a new <code>ReferenceList</code>
      */
-
-    private class Serializer {
-        /**
-         * Initialize the <code>XMLSerializer</code> with the specified context
-         * <code>Document</code>.
-         * <p/>
-         * Setup OutputFormat in a way that the serialization does <b>not</b>
-         * modifiy the contents, that is it shall not do any pretty printing
-         * and so on. This would destroy the original content before
-         * encryption. If that content was signed before encryption and the
-         * serialization modifies the content the signature verification will
-         * fail.
-         */
-        Serializer() {
-        }
-
-        /**
-         * Returns a <code>String</code> representation of the specified
-         * <code>Document</code>.
-         * <p/>
-         * Refer also to comments about setup of format.
-         *
-         * @param document the <code>Document</code> to serialize.
-         * @return the <code>String</code> representation of the serilaized
-         *   <code>Document</code>.
-         * @throws Exception
-         */
-        String serialize(Document document) throws Exception {
-            return canonSerialize(document);
-        }
-
-        /**
-         * Returns a <code>String</code> representation of the specified
-         * <code>Element</code>.
-         * <p/>
-         * Refer also to comments about setup of format.
-         *
-         * @param element the <code>Element</code> to serialize.
-         * @return the <code>String</code> representation of the serilaized
-         *   <code>Element</code>.
-         * @throws Exception
-         */
-                String serialize(Element element) throws Exception {
-            return canonSerialize(element);
-                }
-
-        /**
-         * Returns a <code>String</code> representation of the specified
-         * <code>NodeList</code>.
-         * <p/>
-         * This is a special case because the NodeList may represent a
-         * <code>DocumentFragment</code>. A document fragement may be a
-         * non-valid XML document (refer to appropriate description of
-         * W3C) because it my start with a non-element node, e.g. a text
-         * node.
-         * <p/>
-         * The methods first converts the node list into a document fragment.
-         * Special care is taken to not destroy the current document, thus
-         * the method clones the nodes (deep cloning) before it appends
-         * them to the document fragment.
-         * <p/>
-         * Refer also to comments about setup of format.
-         *
-         * @param content the <code>NodeList</code> to serialize.
-         * @return the <code>String</code> representation of the serilaized
-         *   <code>NodeList</code>.
-         * @throws Exception
-         */
-        String serialize(NodeList content) throws Exception { //XMLEncryptionException {
-            ByteArrayOutputStream baos = new ByteArrayOutputStream();
-            _canon.setWriter(baos);
-            _canon.notReset();
-            for (int i = 0; i < content.getLength(); i++) {
-                _canon.canonicalizeSubtree(content.item(i));
-            }
-            baos.close();
-            return baos.toString("UTF-8");
-        }
-
-        /**
-         * Use the Canoncializer to serialize the node
-         * @param node
-         * @return
-         * @throws Exception
-         */
-                String canonSerialize(Node node) throws Exception {
-                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
-                        _canon.setWriter(baos);
-            _canon.notReset();
-                        _canon.canonicalizeSubtree(node);
-                        baos.close();
-                        return baos.toString("UTF-8");
-                }
-        /**
-         * @param source
-         * @param ctx
-         * @return
-         * @throws XMLEncryptionException
-         *
-         */
-        DocumentFragment deserialize(String source, Node ctx) throws XMLEncryptionException {
-                        DocumentFragment result;
-            final String tagname = "fragment";
-
-                        // Create the context to parse the document against
-                        StringBuffer sb;
-
-                        sb = new StringBuffer();
-                        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><"+tagname);
-
-                        // Run through each node up to the document node and find any
-                        // xmlns: nodes
-
-                        Node wk = ctx;
-
-                        while (wk != null) {
-
-                                NamedNodeMap atts = wk.getAttributes();
-                                int length;
-                                if (atts != null)
-                                        length = atts.getLength();
-                                else
-                                        length = 0;
-
-                                for (int i = 0 ; i < length ; ++i) {
-                                        Node att = atts.item(i);
-                                        if (att.getNodeName().startsWith("xmlns:") ||
-                                                att.getNodeName().equals("xmlns")) {
-
-                                                // Check to see if this node has already been found
-                                                Node p = ctx;
-                                                boolean found = false;
-                                                while (p != wk) {
-                                                        NamedNodeMap tstAtts = p.getAttributes();
-                                                        if (tstAtts != null &&
-                                                                tstAtts.getNamedItem(att.getNodeName()) != null) {
-                                                                found = true;
-                                                                break;
-                                                        }
-                                                        p = p.getParentNode();
-                                                }
-                                                if (found == false) {
-
-                                                        // This is an attribute node
-                                                        sb.append(" " + att.getNodeName() + "=\"" +
-                                                                          att.getNodeValue() + "\"");
-                                                }
-                                        }
-                                }
-                                wk = wk.getParentNode();
-                        }
-                        sb.append(">" + source + "</" + tagname + ">");
-                        String fragment = sb.toString();
-
-            try {
-                DocumentBuilderFactory dbf =
-                    DocumentBuilderFactory.newInstance();
-                dbf.setNamespaceAware(true);
-                dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
-                dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE);
-                DocumentBuilder db = dbf.newDocumentBuilder();
-                Document d = db.parse(
-                    new InputSource(new StringReader(fragment)));
-
-                Element fragElt = (Element) _contextDocument.importNode(
-                                                 d.getDocumentElement(), true);
-                result = _contextDocument.createDocumentFragment();
-                Node child = fragElt.getFirstChild();
-                while (child != null) {
-                    fragElt.removeChild(child);
-                    result.appendChild(child);
-                    child = fragElt.getFirstChild();
-                }
-                // String outp = serialize(d);
-
-            } catch (SAXException se) {
-                throw new XMLEncryptionException("empty", se);
-            } catch (ParserConfigurationException pce) {
-                throw new XMLEncryptionException("empty", pce);
-            } catch (IOException ioe) {
-                throw new XMLEncryptionException("empty", ioe);
-            }
-
-            return (result);
-        }
+    public ReferenceList createReferenceList(int type) {
+        return factory.newReferenceList(type);
+    }
+
+    /**
+     * Create a new Transforms object
+     * <p>
+     * <b>Note</b>: A context document <i>must</i> have been set
+     * elsewhere (possibly via a call to doFinal).  If not, use the
+     * createTransforms(Document) method.
+     * @return a new <code>Transforms</code>
+     */
+    public Transforms createTransforms() {
+        return factory.newTransforms();
     }
 
+    /**
+     * Create a new Transforms object
+     *
+     * Because the handling of Transforms is currently done in the signature
+     * code, the creation of a Transforms object <b>requires</b> a
+     * context document.
+     *
+     * @param doc Document that will own the created Transforms node
+     * @return a new <code>Transforms</code>
+     */
+    public Transforms createTransforms(Document doc) {
+        return factory.newTransforms(doc);
+    }
 
     /**
      *
@@ -2020,201 +1994,110 @@
     private class Factory {
         /**
          * @param algorithm
-         * @return
-         *
+         * @return a new AgreementMethod
          */
         AgreementMethod newAgreementMethod(String algorithm)  {
-            return (new AgreementMethodImpl(algorithm));
-        }
-
-        /**
-         * @param type
-         * @return
-         *
-         */
-        CipherData newCipherData(int type) {
-            return (new CipherDataImpl(type));
-        }
-
-        /**
-         * @param uri
-         * @return
-         *
-         */
-        CipherReference newCipherReference(String uri)  {
-            return (new CipherReferenceImpl(uri));
-        }
-
-        /**
-         * @param value
-         * @return
-         *
-         */
-        CipherValue newCipherValue(String value) {
-            return (new CipherValueImpl(value));
-        }
-
-        /**
-         *
-
-        CipherValue newCipherValue(byte[] value) {
-            return (new CipherValueImpl(value));
-        }
-                */
-        /**
-         * @param data
-         * @return
-         *
-         */
-        EncryptedData newEncryptedData(CipherData data) {
-            return (new EncryptedDataImpl(data));
-        }
-
-        /**
-         * @param data
-         * @return
-         *
-         */
-        EncryptedKey newEncryptedKey(CipherData data) {
-            return (new EncryptedKeyImpl(data));
-        }
-
-        /**
-         * @param algorithm
-         * @return
-         *
-         */
-        EncryptionMethod newEncryptionMethod(String algorithm) {
-            return (new EncryptionMethodImpl(algorithm));
-        }
-
-        /**
-         * @return
-         *
-         */
-        EncryptionProperties newEncryptionProperties() {
-            return (new EncryptionPropertiesImpl());
-        }
-
-        /**
-         * @return
-         *
-         */
-        EncryptionProperty newEncryptionProperty() {
-            return (new EncryptionPropertyImpl());
+            return new AgreementMethodImpl(algorithm);
         }
 
         /**
          * @param type
-         * @return
+         * @return a new CipherData
          *
          */
-        ReferenceList newReferenceList(int type) {
-            return (new ReferenceListImpl(type));
+        CipherData newCipherData(int type) {
+            return new CipherDataImpl(type);
+        }
+
+        /**
+         * @param uri
+         * @return a new CipherReference
+         */
+        CipherReference newCipherReference(String uri)  {
+            return new CipherReferenceImpl(uri);
+        }
+
+        /**
+         * @param value
+         * @return a new CipherValue
+         */
+        CipherValue newCipherValue(String value) {
+            return new CipherValueImpl(value);
+        }
+
+        /*
+        CipherValue newCipherValue(byte[] value) {
+            return new CipherValueImpl(value);
+        }
+         */
+
+        /**
+         * @param data
+         * @return a new EncryptedData
+         */
+        EncryptedData newEncryptedData(CipherData data) {
+            return new EncryptedDataImpl(data);
         }
 
         /**
-         * @return
-         *
+         * @param data
+         * @return a new EncryptedKey
+         */
+        EncryptedKey newEncryptedKey(CipherData data) {
+            return new EncryptedKeyImpl(data);
+        }
+
+        /**
+         * @param algorithm
+         * @return a new EncryptionMethod
+         */
+        EncryptionMethod newEncryptionMethod(String algorithm) {
+            return new EncryptionMethodImpl(algorithm);
+        }
+
+        /**
+         * @return a new EncryptionProperties
+         */
+        EncryptionProperties newEncryptionProperties() {
+            return new EncryptionPropertiesImpl();
+        }
+
+        /**
+         * @return a new EncryptionProperty
+         */
+        EncryptionProperty newEncryptionProperty() {
+            return new EncryptionPropertyImpl();
+        }
+
+        /**
+         * @param type ReferenceList.DATA_REFERENCE or ReferenceList.KEY_REFERENCE
+         * @return a new ReferenceList
+         */
+        ReferenceList newReferenceList(int type) {
+            return new ReferenceListImpl(type);
+        }
+
+        /**
+         * @return a new Transforms
          */
         Transforms newTransforms() {
-            return (new TransformsImpl());
+            return new TransformsImpl();
         }
 
         /**
          * @param doc
-         * @return
-         *
+         * @return a new Transforms
          */
         Transforms newTransforms(Document doc) {
-            return (new TransformsImpl(doc));
+            return new TransformsImpl(doc);
         }
 
         /**
          * @param element
-         * @return
+         * @return a new CipherData
          * @throws XMLEncryptionException
-         *
          */
-        // <element name="AgreementMethod" type="xenc:AgreementMethodType"/>
-        // <complexType name="AgreementMethodType" mixed="true">
-        //     <sequence>
-        //         <element name="KA-Nonce" minOccurs="0" type="base64Binary"/>
-        //         <!-- <element ref="ds:DigestMethod" minOccurs="0"/> -->
-        //         <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
-        //         <element name="OriginatorKeyInfo" minOccurs="0" type="ds:KeyInfoType"/>
-        //         <element name="RecipientKeyInfo" minOccurs="0" type="ds:KeyInfoType"/>
-        //     </sequence>
-        //     <attribute name="Algorithm" type="anyURI" use="required"/>
-        // </complexType>
-        AgreementMethod newAgreementMethod(Element element) throws
-                XMLEncryptionException {
-            if (null == element) {
-                throw new NullPointerException("element is null");
-            }
-
-            String algorithm = element.getAttributeNS(null,
-                EncryptionConstants._ATT_ALGORITHM);
-            AgreementMethod result = newAgreementMethod(algorithm);
-
-            Element kaNonceElement = (Element) element.getElementsByTagNameNS(
-                EncryptionConstants.EncryptionSpecNS,
-                EncryptionConstants._TAG_KA_NONCE).item(0);
-            if (null != kaNonceElement) {
-                result.setKANonce(kaNonceElement.getNodeValue().getBytes());
-            }
-            // TODO: ///////////////////////////////////////////////////////////
-            // Figure out how to make this pesky line work..
-            // <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
-
-            // TODO: Work out how to handle relative URI
-
-            Element originatorKeyInfoElement =
-                (Element) element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_ORIGINATORKEYINFO).item(0);
-            if (null != originatorKeyInfoElement) {
-                try {
-                    result.setOriginatorKeyInfo(
-                        new KeyInfo(originatorKeyInfoElement, null));
-                } catch (XMLSecurityException xse) {
-                    throw new XMLEncryptionException("empty", xse);
-                }
-            }
-
-            // TODO: Work out how to handle relative URI
-
-            Element recipientKeyInfoElement =
-                (Element) element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_RECIPIENTKEYINFO).item(0);
-            if (null != recipientKeyInfoElement) {
-                try {
-                    result.setRecipientKeyInfo(
-                        new KeyInfo(recipientKeyInfoElement, null));
-                } catch (XMLSecurityException xse) {
-                    throw new XMLEncryptionException("empty", xse);
-                }
-            }
-
-            return (result);
-        }
-
-        /**
-         * @param element
-         * @return
-         * @throws XMLEncryptionException
-         *
-         */
-        // <element name='CipherData' type='xenc:CipherDataType'/>
-        // <complexType name='CipherDataType'>
-        //     <choice>
-        //         <element name='CipherValue' type='base64Binary'/>
-        //         <element ref='xenc:CipherReference'/>
-        //     </choice>
-        // </complexType>
-        CipherData newCipherData(Element element) throws
-                XMLEncryptionException {
+        CipherData newCipherData(Element element) throws XMLEncryptionException {
             if (null == element) {
                 throw new NullPointerException("element is null");
             }
@@ -2223,7 +2106,8 @@
             Element e = null;
             if (element.getElementsByTagNameNS(
                 EncryptionConstants.EncryptionSpecNS,
-                EncryptionConstants._TAG_CIPHERVALUE).getLength() > 0) {
+                EncryptionConstants._TAG_CIPHERVALUE).getLength() > 0
+            ) {
                 type = CipherData.VALUE_TYPE;
                 e = (Element) element.getElementsByTagNameNS(
                     EncryptionConstants.EncryptionSpecNS,
@@ -2244,100 +2128,67 @@
                 result.setCipherReference(newCipherReference(e));
             }
 
-            return (result);
+            return result;
         }
 
         /**
          * @param element
-         * @return
+         * @return a new CipherReference
          * @throws XMLEncryptionException
          *
          */
-        // <element name='CipherReference' type='xenc:CipherReferenceType'/>
-        // <complexType name='CipherReferenceType'>
-        //     <sequence>
-        //         <element name='Transforms' type='xenc:TransformsType' minOccurs='0'/>
-        //     </sequence>
-        //     <attribute name='URI' type='anyURI' use='required'/>
-        // </complexType>
-        CipherReference newCipherReference(Element element) throws
-                XMLEncryptionException {
-
-                        Attr URIAttr =
-                                element.getAttributeNodeNS(null, EncryptionConstants._ATT_URI);
-                        CipherReference result = new CipherReferenceImpl(URIAttr);
-
-                        // Find any Transforms
-
-                        NodeList transformsElements = element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_TRANSFORMS);
-            Element transformsElement =
-                                (Element) transformsElements.item(0);
-
-                        if (transformsElement != null) {
-                                logger.log(java.util.logging.Level.FINE, "Creating a DSIG based Transforms element");
-                                try {
-                                        result.setTransforms(new TransformsImpl(transformsElement));
-                                }
-                                catch (XMLSignatureException xse) {
-                                        throw new XMLEncryptionException("empty", xse);
-                                } catch (InvalidTransformException ite) {
-                                        throw new XMLEncryptionException("empty", ite);
-                                } catch (XMLSecurityException xse) {
-                                        throw new XMLEncryptionException("empty", xse);
-                                }
-
-                        }
-
-                        return result;
+        CipherReference newCipherReference(Element element) throws XMLEncryptionException {
+
+            Attr uriAttr =
+                element.getAttributeNodeNS(null, EncryptionConstants._ATT_URI);
+            CipherReference result = new CipherReferenceImpl(uriAttr);
+
+            // Find any Transforms
+            NodeList transformsElements =
+                element.getElementsByTagNameNS(
+                    EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_TRANSFORMS);
+            Element transformsElement = (Element) transformsElements.item(0);
+
+            if (transformsElement != null) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "Creating a DSIG based Transforms element");
+                }
+                try {
+                    result.setTransforms(new TransformsImpl(transformsElement));
+                } catch (XMLSignatureException xse) {
+                    throw new XMLEncryptionException("empty", xse);
+                } catch (InvalidTransformException ite) {
+                    throw new XMLEncryptionException("empty", ite);
+                } catch (XMLSecurityException xse) {
+                    throw new XMLEncryptionException("empty", xse);
+                }
+            }
+
+            return result;
         }
 
         /**
          * @param element
-         * @return
-         *
+         * @return a new CipherValue
          */
         CipherValue newCipherValue(Element element) {
             String value = XMLUtils.getFullTextChildrenFromElement(element);
 
-            CipherValue result = newCipherValue(value);
-
-            return (result);
+            return newCipherValue(value);
         }
 
         /**
          * @param element
-         * @return
+         * @return a new EncryptedData
          * @throws XMLEncryptionException
          *
          */
-        // <complexType name='EncryptedType' abstract='true'>
-        //     <sequence>
-        //         <element name='EncryptionMethod' type='xenc:EncryptionMethodType'
-        //             minOccurs='0'/>
-        //         <element ref='ds:KeyInfo' minOccurs='0'/>
-        //         <element ref='xenc:CipherData'/>
-        //         <element ref='xenc:EncryptionProperties' minOccurs='0'/>
-        //     </sequence>
-        //     <attribute name='Id' type='ID' use='optional'/>
-        //     <attribute name='Type' type='anyURI' use='optional'/>
-        //     <attribute name='MimeType' type='string' use='optional'/>
-        //     <attribute name='Encoding' type='anyURI' use='optional'/>
-        // </complexType>
-        // <element name='EncryptedData' type='xenc:EncryptedDataType'/>
-        // <complexType name='EncryptedDataType'>
-        //     <complexContent>
-        //         <extension base='xenc:EncryptedType'/>
-        //     </complexContent>
-        // </complexType>
-        EncryptedData newEncryptedData(Element element) throws
-                        XMLEncryptionException {
+        EncryptedData newEncryptedData(Element element) throws XMLEncryptionException {
             EncryptedData result = null;
 
-            NodeList dataElements = element.getElementsByTagNameNS(
-                EncryptionConstants.EncryptionSpecNS,
-                EncryptionConstants._TAG_CIPHERDATA);
+            NodeList dataElements =
+                element.getElementsByTagNameNS(
+                    EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CIPHERDATA);
 
             // Need to get the last CipherData found, as earlier ones will
             // be for elements in the KeyInfo lists
@@ -2349,22 +2200,17 @@
 
             result = newEncryptedData(data);
 
-            result.setId(element.getAttributeNS(
-                null, EncryptionConstants._ATT_ID));
-            result.setType(
-                element.getAttributeNS(null, EncryptionConstants._ATT_TYPE));
-            result.setMimeType(element.getAttributeNS(
-                null, EncryptionConstants._ATT_MIMETYPE));
-            result.setEncoding(
-                element.getAttributeNS(null, Constants._ATT_ENCODING));
+            result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID));
+            result.setType(element.getAttributeNS(null, EncryptionConstants._ATT_TYPE));
+            result.setMimeType(element.getAttributeNS(null, EncryptionConstants._ATT_MIMETYPE));
+            result.setEncoding( element.getAttributeNS(null, Constants._ATT_ENCODING));
 
             Element encryptionMethodElement =
                 (Element) element.getElementsByTagNameNS(
                     EncryptionConstants.EncryptionSpecNS,
                     EncryptionConstants._TAG_ENCRYPTIONMETHOD).item(0);
             if (null != encryptionMethodElement) {
-                result.setEncryptionMethod(newEncryptionMethod(
-                    encryptionMethodElement));
+                result.setEncryptionMethod(newEncryptionMethod(encryptionMethodElement));
             }
 
             // BFL 16/7/03 - simple implementation
@@ -2374,12 +2220,8 @@
                 (Element) element.getElementsByTagNameNS(
                     Constants.SignatureSpecNS, Constants._TAG_KEYINFO).item(0);
             if (null != keyInfoElement) {
-                try {
-                    result.setKeyInfo(new KeyInfo(keyInfoElement, null));
-                } catch (XMLSecurityException xse) {
-                    throw new XMLEncryptionException("Error loading Key Info",
-                                                     xse);
-                }
+                KeyInfo ki = newKeyInfo(keyInfoElement);
+                result.setKeyInfo(ki);
             }
 
             // TODO: Implement
@@ -2389,85 +2231,49 @@
                     EncryptionConstants._TAG_ENCRYPTIONPROPERTIES).item(0);
             if (null != encryptionPropertiesElement) {
                 result.setEncryptionProperties(
-                    newEncryptionProperties(encryptionPropertiesElement));
+                    newEncryptionProperties(encryptionPropertiesElement)
+                );
             }
 
-            return (result);
+            return result;
         }
 
         /**
          * @param element
-         * @return
+         * @return a new EncryptedKey
          * @throws XMLEncryptionException
-         *
          */
-        // <complexType name='EncryptedType' abstract='true'>
-        //     <sequence>
-        //         <element name='EncryptionMethod' type='xenc:EncryptionMethodType'
-        //             minOccurs='0'/>
-        //         <element ref='ds:KeyInfo' minOccurs='0'/>
-        //         <element ref='xenc:CipherData'/>
-        //         <element ref='xenc:EncryptionProperties' minOccurs='0'/>
-        //     </sequence>
-        //     <attribute name='Id' type='ID' use='optional'/>
-        //     <attribute name='Type' type='anyURI' use='optional'/>
-        //     <attribute name='MimeType' type='string' use='optional'/>
-        //     <attribute name='Encoding' type='anyURI' use='optional'/>
-        // </complexType>
-        // <element name='EncryptedKey' type='xenc:EncryptedKeyType'/>
-        // <complexType name='EncryptedKeyType'>
-        //     <complexContent>
-        //         <extension base='xenc:EncryptedType'>
-        //             <sequence>
-        //                 <element ref='xenc:ReferenceList' minOccurs='0'/>
-        //                 <element name='CarriedKeyName' type='string' minOccurs='0'/>
-        //             </sequence>
-        //             <attribute name='Recipient' type='string' use='optional'/>
-        //         </extension>
-        //     </complexContent>
-        // </complexType>
-        EncryptedKey newEncryptedKey(Element element) throws
-                XMLEncryptionException {
+        EncryptedKey newEncryptedKey(Element element) throws XMLEncryptionException {
             EncryptedKey result = null;
-            NodeList dataElements = element.getElementsByTagNameNS(
-                EncryptionConstants.EncryptionSpecNS,
-                EncryptionConstants._TAG_CIPHERDATA);
+            NodeList dataElements =
+                element.getElementsByTagNameNS(
+                    EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CIPHERDATA);
             Element dataElement =
                 (Element) dataElements.item(dataElements.getLength() - 1);
 
             CipherData data = newCipherData(dataElement);
             result = newEncryptedKey(data);
 
-            result.setId(element.getAttributeNS(
-                null, EncryptionConstants._ATT_ID));
-            result.setType(
-                element.getAttributeNS(null, EncryptionConstants._ATT_TYPE));
-            result.setMimeType(element.getAttributeNS(
-                null, EncryptionConstants._ATT_MIMETYPE));
-            result.setEncoding(
-                element.getAttributeNS(null, Constants._ATT_ENCODING));
-            result.setRecipient(element.getAttributeNS(
-                null, EncryptionConstants._ATT_RECIPIENT));
+            result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID));
+            result.setType(element.getAttributeNS(null, EncryptionConstants._ATT_TYPE));
+            result.setMimeType(element.getAttributeNS(null, EncryptionConstants._ATT_MIMETYPE));
+            result.setEncoding(element.getAttributeNS(null, Constants._ATT_ENCODING));
+            result.setRecipient(element.getAttributeNS(null, EncryptionConstants._ATT_RECIPIENT));
 
             Element encryptionMethodElement =
                 (Element) element.getElementsByTagNameNS(
                     EncryptionConstants.EncryptionSpecNS,
                     EncryptionConstants._TAG_ENCRYPTIONMETHOD).item(0);
             if (null != encryptionMethodElement) {
-                result.setEncryptionMethod(newEncryptionMethod(
-                    encryptionMethodElement));
+                result.setEncryptionMethod(newEncryptionMethod(encryptionMethodElement));
             }
 
             Element keyInfoElement =
                 (Element) element.getElementsByTagNameNS(
                     Constants.SignatureSpecNS, Constants._TAG_KEYINFO).item(0);
             if (null != keyInfoElement) {
-                try {
-                    result.setKeyInfo(new KeyInfo(keyInfoElement, null));
-                } catch (XMLSecurityException xse) {
-                    throw new XMLEncryptionException
-                        ("Error loading Key Info", xse);
-                }
+                KeyInfo ki = newKeyInfo(keyInfoElement);
+                result.setKeyInfo(ki);
             }
 
             // TODO: Implement
@@ -2477,7 +2283,8 @@
                     EncryptionConstants._TAG_ENCRYPTIONPROPERTIES).item(0);
             if (null != encryptionPropertiesElement) {
                 result.setEncryptionProperties(
-                    newEncryptionProperties(encryptionPropertiesElement));
+                    newEncryptionProperties(encryptionPropertiesElement)
+                );
             }
 
             Element referenceListElement =
@@ -2493,30 +2300,40 @@
                     EncryptionConstants.EncryptionSpecNS,
                     EncryptionConstants._TAG_CARRIEDKEYNAME).item(0);
             if (null != carriedNameElement) {
-                result.setCarriedName
-                    (carriedNameElement.getFirstChild().getNodeValue());
+                result.setCarriedName(carriedNameElement.getFirstChild().getNodeValue());
             }
 
-            return (result);
+            return result;
         }
 
         /**
          * @param element
-         * @return
-         *
+         * @return a new KeyInfo
+         * @throws XMLEncryptionException
          */
-        // <complexType name='EncryptionMethodType' mixed='true'>
-        //     <sequence>
-        //         <element name='KeySize' minOccurs='0' type='xenc:KeySizeType'/>
-        //         <element name='OAEPparams' minOccurs='0' type='base64Binary'/>
-        //         <any namespace='##other' minOccurs='0' maxOccurs='unbounded'/>
-        //     </sequence>
-        //     <attribute name='Algorithm' type='anyURI' use='required'/>
-        // </complexType>
+        KeyInfo newKeyInfo(Element element) throws XMLEncryptionException {
+            try {
+                KeyInfo ki = new KeyInfo(element, null);
+                ki.setSecureValidation(secureValidation);
+                if (internalKeyResolvers != null) {
+                    int size = internalKeyResolvers.size();
+                    for (int i = 0; i < size; i++) {
+                        ki.registerInternalKeyResolver(internalKeyResolvers.get(i));
+                    }
+                }
+                return ki;
+            } catch (XMLSecurityException xse) {
+                throw new XMLEncryptionException("Error loading Key Info", xse);
+            }
+        }
+
+        /**
+         * @param element
+         * @return a new EncryptionMethod
+         */
         EncryptionMethod newEncryptionMethod(Element element) {
-            String algorithm = element.getAttributeNS(
-                null, EncryptionConstants._ATT_ALGORITHM);
-            EncryptionMethod result = newEncryptionMethod(algorithm);
+            String encAlgorithm = element.getAttributeNS(null, EncryptionConstants._ATT_ALGORITHM);
+            EncryptionMethod result = newEncryptionMethod(encAlgorithm);
 
             Element keySizeElement =
                 (Element) element.getElementsByTagNameNS(
@@ -2533,92 +2350,83 @@
                     EncryptionConstants.EncryptionSpecNS,
                     EncryptionConstants._TAG_OAEPPARAMS).item(0);
             if (null != oaepParamsElement) {
-                result.setOAEPparams(
-                    oaepParamsElement.getNodeValue().getBytes());
+                try {
+                    String oaepParams = oaepParamsElement.getFirstChild().getNodeValue();
+                    result.setOAEPparams(Base64.decode(oaepParams.getBytes("UTF-8")));
+                } catch(UnsupportedEncodingException e) {
+                    throw new RuntimeException("UTF-8 not supported", e);
+                } catch (Base64DecodingException e) {
+                    throw new RuntimeException("BASE-64 decoding error", e);
+                }
+            }
+
+            Element digestElement =
+                (Element) element.getElementsByTagNameNS(
+                    Constants.SignatureSpecNS, Constants._TAG_DIGESTMETHOD).item(0);
+            if (digestElement != null) {
+                String digestAlgorithm = digestElement.getAttributeNS(null, "Algorithm");
+                result.setDigestAlgorithm(digestAlgorithm);
+            }
+
+            Element mgfElement =
+                (Element) element.getElementsByTagNameNS(
+                    EncryptionConstants.EncryptionSpec11NS, EncryptionConstants._TAG_MGF).item(0);
+            if (mgfElement != null && !XMLCipher.RSA_OAEP.equals(algorithm)) {
+                String mgfAlgorithm = mgfElement.getAttributeNS(null, "Algorithm");
+                result.setMGFAlgorithm(mgfAlgorithm);
             }
 
             // TODO: Make this mess work
             // <any namespace='##other' minOccurs='0' maxOccurs='unbounded'/>
 
-            return (result);
+            return result;
         }
 
         /**
          * @param element
-         * @return
-         *
+         * @return a new EncryptionProperties
          */
-        // <element name='EncryptionProperties' type='xenc:EncryptionPropertiesType'/>
-        // <complexType name='EncryptionPropertiesType'>
-        //     <sequence>
-        //         <element ref='xenc:EncryptionProperty' maxOccurs='unbounded'/>
-        //     </sequence>
-        //     <attribute name='Id' type='ID' use='optional'/>
-        // </complexType>
         EncryptionProperties newEncryptionProperties(Element element) {
             EncryptionProperties result = newEncryptionProperties();
 
-            result.setId(element.getAttributeNS(
-                null, EncryptionConstants._ATT_ID));
+            result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID));
 
             NodeList encryptionPropertyList =
                 element.getElementsByTagNameNS(
                     EncryptionConstants.EncryptionSpecNS,
                     EncryptionConstants._TAG_ENCRYPTIONPROPERTY);
-            for(int i = 0; i < encryptionPropertyList.getLength(); i++) {
+            for (int i = 0; i < encryptionPropertyList.getLength(); i++) {
                 Node n = encryptionPropertyList.item(i);
                 if (null != n) {
-                    result.addEncryptionProperty(
-                        newEncryptionProperty((Element) n));
+                    result.addEncryptionProperty(newEncryptionProperty((Element) n));
                 }
             }
 
-            return (result);
+            return result;
         }
 
         /**
          * @param element
-         * @return
-         *
+         * @return a new EncryptionProperty
          */
-        // <element name='EncryptionProperty' type='xenc:EncryptionPropertyType'/>
-        // <complexType name='EncryptionPropertyType' mixed='true'>
-        //     <choice maxOccurs='unbounded'>
-        //         <any namespace='##other' processContents='lax'/>
-        //     </choice>
-        //     <attribute name='Target' type='anyURI' use='optional'/>
-        //     <attribute name='Id' type='ID' use='optional'/>
-        //     <anyAttribute namespace="http://www.w3.org/XML/1998/namespace"/>
-        // </complexType>
         EncryptionProperty newEncryptionProperty(Element element) {
             EncryptionProperty result = newEncryptionProperty();
 
-            result.setTarget(
-                element.getAttributeNS(null, EncryptionConstants._ATT_TARGET));
-            result.setId(element.getAttributeNS(
-                null, EncryptionConstants._ATT_ID));
+            result.setTarget(element.getAttributeNS(null, EncryptionConstants._ATT_TARGET));
+            result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID));
             // TODO: Make this lot work...
             // <anyAttribute namespace="http://www.w3.org/XML/1998/namespace"/>
 
             // TODO: Make this work...
             // <any namespace='##other' processContents='lax'/>
 
-            return (result);
+            return result;
         }
 
         /**
          * @param element
-         * @return
-         *
+         * @return a new ReferenceList
          */
-        // <element name='ReferenceList'>
-        //     <complexType>
-        //         <choice minOccurs='1' maxOccurs='unbounded'>
-        //             <element name='DataReference' type='xenc:ReferenceType'/>
-        //             <element name='KeyReference' type='xenc:ReferenceType'/>
-        //         </choice>
-        //     </complexType>
-        // </element>
         ReferenceList newReferenceList(Element element) {
             int type = 0;
             if (null != element.getElementsByTagNameNS(
@@ -2629,84 +2437,38 @@
                 EncryptionConstants.EncryptionSpecNS,
                 EncryptionConstants._TAG_KEYREFERENCE).item(0)) {
                 type = ReferenceList.KEY_REFERENCE;
-            } else {
-                // complain
             }
 
             ReferenceList result = new ReferenceListImpl(type);
             NodeList list = null;
             switch (type) {
             case ReferenceList.DATA_REFERENCE:
-                list = element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_DATAREFERENCE);
+                list =
+                    element.getElementsByTagNameNS(
+                        EncryptionConstants.EncryptionSpecNS,
+                        EncryptionConstants._TAG_DATAREFERENCE);
                 for (int i = 0; i < list.getLength() ; i++) {
                     String uri = ((Element) list.item(i)).getAttribute("URI");
                     result.add(result.newDataReference(uri));
                 }
                 break;
             case ReferenceList.KEY_REFERENCE:
-                list = element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_KEYREFERENCE);
+                list =
+                    element.getElementsByTagNameNS(
+                        EncryptionConstants.EncryptionSpecNS,
+                        EncryptionConstants._TAG_KEYREFERENCE);
                 for (int i = 0; i < list.getLength() ; i++) {
                     String uri = ((Element) list.item(i)).getAttribute("URI");
                     result.add(result.newKeyReference(uri));
                 }
             }
 
-            return (result);
-        }
-
-        /**
-         * @param element
-         * @return
-         *
-         */
-        Transforms newTransforms(Element element) {
-            return (null);
-        }
-
-        /**
-         * @param agreementMethod
-         * @return
-         *
-         */
-        Element toElement(AgreementMethod agreementMethod) {
-            return ((AgreementMethodImpl) agreementMethod).toElement();
-        }
-
-        /**
-         * @param cipherData
-         * @return
-         *
-         */
-        Element toElement(CipherData cipherData) {
-            return ((CipherDataImpl) cipherData).toElement();
-        }
-
-        /**
-         * @param cipherReference
-         * @return
-         *
-         */
-        Element toElement(CipherReference cipherReference) {
-            return ((CipherReferenceImpl) cipherReference).toElement();
-        }
-
-        /**
-         * @param cipherValue
-         * @return
-         *
-         */
-        Element toElement(CipherValue cipherValue) {
-            return ((CipherValueImpl) cipherValue).toElement();
+            return result;
         }
 
         /**
          * @param encryptedData
-         * @return
-         *
+         * @return the XML Element form of that EncryptedData
          */
         Element toElement(EncryptedData encryptedData) {
             return ((EncryptedDataImpl) encryptedData).toElement();
@@ -2714,64 +2476,20 @@
 
         /**
          * @param encryptedKey
-         * @return
-         *
+         * @return the XML Element form of that EncryptedKey
          */
         Element toElement(EncryptedKey encryptedKey) {
             return ((EncryptedKeyImpl) encryptedKey).toElement();
         }
 
         /**
-         * @param encryptionMethod
-         * @return
-         *
-         */
-        Element toElement(EncryptionMethod encryptionMethod) {
-            return ((EncryptionMethodImpl) encryptionMethod).toElement();
-        }
-
-        /**
-         * @param encryptionProperties
-         * @return
-         *
+         * @param referenceList
+         * @return the XML Element form of that ReferenceList
          */
-        Element toElement(EncryptionProperties encryptionProperties) {
-            return ((EncryptionPropertiesImpl) encryptionProperties).toElement();
-        }
-
-        /**
-         * @param encryptionProperty
-         * @return
-         *
-         */
-        Element toElement(EncryptionProperty encryptionProperty) {
-            return ((EncryptionPropertyImpl) encryptionProperty).toElement();
-        }
-
         Element toElement(ReferenceList referenceList) {
             return ((ReferenceListImpl) referenceList).toElement();
         }
 
-        /**
-         * @param transforms
-         * @return
-         *
-         */
-        Element toElement(Transforms transforms) {
-            return ((TransformsImpl) transforms).toElement();
-        }
-
-        // <element name="AgreementMethod" type="xenc:AgreementMethodType"/>
-        // <complexType name="AgreementMethodType" mixed="true">
-        //     <sequence>
-        //         <element name="KA-Nonce" minOccurs="0" type="base64Binary"/>
-        //         <!-- <element ref="ds:DigestMethod" minOccurs="0"/> -->
-        //         <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
-        //         <element name="OriginatorKeyInfo" minOccurs="0" type="ds:KeyInfoType"/>
-        //         <element name="RecipientKeyInfo" minOccurs="0" type="ds:KeyInfoType"/>
-        //     </sequence>
-        //     <attribute name="Algorithm" type="anyURI" use="required"/>
-        // </complexType>
         private class AgreementMethodImpl implements AgreementMethod {
             private byte[] kaNonce = null;
             private List<Element> agreementMethodInformation = null;
@@ -2787,15 +2505,16 @@
                 URI tmpAlgorithm = null;
                 try {
                     tmpAlgorithm = new URI(algorithm);
-                } catch (URI.MalformedURIException fmue) {
-                    //complain?
+                } catch (URISyntaxException ex) {
+                    throw (IllegalArgumentException)
+                    new IllegalArgumentException().initCause(ex);
                 }
                 algorithmURI = tmpAlgorithm.toString();
             }
 
             /** @inheritDoc */
             public byte[] getKANonce() {
-                return (kaNonce);
+                return kaNonce;
             }
 
             /** @inheritDoc */
@@ -2805,7 +2524,7 @@
 
             /** @inheritDoc */
             public Iterator<Element> getAgreementMethodInformation() {
-                return (agreementMethodInformation.iterator());
+                return agreementMethodInformation.iterator();
             }
 
             /** @inheritDoc */
@@ -2820,7 +2539,7 @@
 
             /** @inheritDoc */
             public KeyInfo getOriginatorKeyInfo() {
-                return (originatorKeyInfo);
+                return originatorKeyInfo;
             }
 
             /** @inheritDoc */
@@ -2830,7 +2549,7 @@
 
             /** @inheritDoc */
             public KeyInfo getRecipientKeyInfo() {
-                return (recipientKeyInfo);
+                return recipientKeyInfo;
             }
 
             /** @inheritDoc */
@@ -2840,70 +2559,10 @@
 
             /** @inheritDoc */
             public String getAlgorithm() {
-                return (algorithmURI);
-            }
-
-            /** @param algorithm*/
-            public void setAlgorithm(String algorithm) {
-                URI tmpAlgorithm = null;
-                try {
-                    tmpAlgorithm = new URI(algorithm);
-                } catch (URI.MalformedURIException mfue) {
-                    //complain
-                }
-                algorithmURI = tmpAlgorithm.toString();
-            }
-
-            // <element name="AgreementMethod" type="xenc:AgreementMethodType"/>
-            // <complexType name="AgreementMethodType" mixed="true">
-            //     <sequence>
-            //         <element name="KA-Nonce" minOccurs="0" type="base64Binary"/>
-            //         <!-- <element ref="ds:DigestMethod" minOccurs="0"/> -->
-            //         <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
-            //         <element name="OriginatorKeyInfo" minOccurs="0" type="ds:KeyInfoType"/>
-            //         <element name="RecipientKeyInfo" minOccurs="0" type="ds:KeyInfoType"/>
-            //     </sequence>
-            //     <attribute name="Algorithm" type="anyURI" use="required"/>
-            // </complexType>
-            Element toElement() {
-                Element result = ElementProxy.createElementForFamily(
-                    _contextDocument,
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_AGREEMENTMETHOD);
-                result.setAttributeNS(
-                    null, EncryptionConstants._ATT_ALGORITHM, algorithmURI);
-                if (null != kaNonce) {
-                    result.appendChild(
-                        ElementProxy.createElementForFamily(
-                            _contextDocument,
-                            EncryptionConstants.EncryptionSpecNS,
-                            EncryptionConstants._TAG_KA_NONCE)).appendChild(
-                            _contextDocument.createTextNode(new String(kaNonce)));
-                }
-                if (!agreementMethodInformation.isEmpty()) {
-                    Iterator<Element> itr = agreementMethodInformation.iterator();
-                    while (itr.hasNext()) {
-                        result.appendChild(itr.next());
-                    }
-                }
-                if (null != originatorKeyInfo) {
-                    result.appendChild(originatorKeyInfo.getElement());
-                }
-                if (null != recipientKeyInfo) {
-                    result.appendChild(recipientKeyInfo.getElement());
-                }
-
-                return (result);
+                return algorithmURI;
             }
         }
 
-        // <element name='CipherData' type='xenc:CipherDataType'/>
-        // <complexType name='CipherDataType'>
-        //     <choice>
-        //         <element name='CipherValue' type='base64Binary'/>
-        //         <element ref='xenc:CipherReference'/>
-        //     </choice>
-        // </complexType>
         private class CipherDataImpl implements CipherData {
             private static final String valueMessage =
                 "Data type is reference type.";
@@ -2922,16 +2581,16 @@
 
             /** @inheritDoc */
             public CipherValue getCipherValue() {
-                return (cipherValue);
+                return cipherValue;
             }
 
             /** @inheritDoc */
-            public void setCipherValue(CipherValue value) throws
-                    XMLEncryptionException {
+            public void setCipherValue(CipherValue value) throws XMLEncryptionException {
 
                 if (cipherType == REFERENCE_TYPE) {
-                    throw new XMLEncryptionException("empty",
-                        new UnsupportedOperationException(valueMessage));
+                    throw new XMLEncryptionException(
+                        "empty", new UnsupportedOperationException(valueMessage)
+                    );
                 }
 
                 cipherValue = value;
@@ -2939,15 +2598,16 @@
 
             /** @inheritDoc */
             public CipherReference getCipherReference() {
-                return (cipherReference);
+                return cipherReference;
             }
 
             /** @inheritDoc */
             public void setCipherReference(CipherReference reference) throws
-                    XMLEncryptionException {
+            XMLEncryptionException {
                 if (cipherType == VALUE_TYPE) {
-                    throw new XMLEncryptionException("empty",
-                        new UnsupportedOperationException(referenceMessage));
+                    throw new XMLEncryptionException(
+                        "empty", new UnsupportedOperationException(referenceMessage)
+                    );
                 }
 
                 cipherReference = reference;
@@ -2955,77 +2615,59 @@
 
             /** @inheritDoc */
             public int getDataType() {
-                return (cipherType);
+                return cipherType;
             }
 
-            // <element name='CipherData' type='xenc:CipherDataType'/>
-            // <complexType name='CipherDataType'>
-            //     <choice>
-            //         <element name='CipherValue' type='base64Binary'/>
-            //         <element ref='xenc:CipherReference'/>
-            //     </choice>
-            // </complexType>
             Element toElement() {
-                Element result = ElementProxy.createElementForFamily(
-                    _contextDocument,
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_CIPHERDATA);
+                Element result =
+                    XMLUtils.createElementInEncryptionSpace(
+                        contextDocument, EncryptionConstants._TAG_CIPHERDATA
+                    );
                 if (cipherType == VALUE_TYPE) {
-                    result.appendChild(
-                        ((CipherValueImpl) cipherValue).toElement());
+                    result.appendChild(((CipherValueImpl) cipherValue).toElement());
                 } else if (cipherType == REFERENCE_TYPE) {
-                    result.appendChild(
-                        ((CipherReferenceImpl) cipherReference).toElement());
-                } else {
-                    // complain
+                    result.appendChild(((CipherReferenceImpl) cipherReference).toElement());
                 }
 
-                return (result);
+                return result;
             }
         }
 
-        // <element name='CipherReference' type='xenc:CipherReferenceType'/>
-        // <complexType name='CipherReferenceType'>
-        //     <sequence>
-        //         <element name='Transforms' type='xenc:TransformsType' minOccurs='0'/>
-        //     </sequence>
-        //     <attribute name='URI' type='anyURI' use='required'/>
-        // </complexType>
         private class CipherReferenceImpl implements CipherReference {
             private String referenceURI = null;
             private Transforms referenceTransforms = null;
-                        private Attr referenceNode = null;
+            private Attr referenceNode = null;
 
             /**
              * @param uri
              */
             public CipherReferenceImpl(String uri) {
-                                /* Don't check validity of URI as may be "" */
+                /* Don't check validity of URI as may be "" */
                 referenceURI = uri;
-                                referenceNode = null;
+                referenceNode = null;
             }
 
-                        /**
-                         * @param uri
-                         */
-                        public CipherReferenceImpl(Attr uri) {
-                                referenceURI = uri.getNodeValue();
-                                referenceNode = uri;
-                        }
+            /**
+             * @param uri
+             */
+            public CipherReferenceImpl(Attr uri) {
+                referenceURI = uri.getNodeValue();
+                referenceNode = uri;
+            }
 
             /** @inheritDoc */
             public String getURI() {
-                return (referenceURI);
+                return referenceURI;
             }
 
             /** @inheritDoc */
-                        public Attr getURIAsAttr() {
-                                return (referenceNode);
-                        }
+            public Attr getURIAsAttr() {
+                return referenceNode;
+            }
 
             /** @inheritDoc */
             public Transforms getTransforms() {
-                return (referenceTransforms);
+                return referenceTransforms;
             }
 
             /** @inheritDoc */
@@ -3033,91 +2675,53 @@
                 referenceTransforms = transforms;
             }
 
-            // <element name='CipherReference' type='xenc:CipherReferenceType'/>
-            // <complexType name='CipherReferenceType'>
-            //     <sequence>
-            //         <element name='Transforms' type='xenc:TransformsType' minOccurs='0'/>
-            //     </sequence>
-            //     <attribute name='URI' type='anyURI' use='required'/>
-            // </complexType>
             Element toElement() {
-                Element result = ElementProxy.createElementForFamily(
-                    _contextDocument,
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_CIPHERREFERENCE);
-                result.setAttributeNS(
-                    null, EncryptionConstants._ATT_URI, referenceURI);
+                Element result =
+                    XMLUtils.createElementInEncryptionSpace(
+                        contextDocument, EncryptionConstants._TAG_CIPHERREFERENCE
+                    );
+                result.setAttributeNS(null, EncryptionConstants._ATT_URI, referenceURI);
                 if (null != referenceTransforms) {
-                    result.appendChild(
-                        ((TransformsImpl) referenceTransforms).toElement());
+                    result.appendChild(((TransformsImpl) referenceTransforms).toElement());
                 }
 
-                return (result);
+                return result;
             }
         }
 
         private class CipherValueImpl implements CipherValue {
-                        private String cipherValue = null;
-
-            // public CipherValueImpl(byte[] value) {
-               // cipherValue = value;
-            // }
+            private String cipherValue = null;
 
             /**
              * @param value
              */
             public CipherValueImpl(String value) {
-                                // cipherValue = value.getBytes();
-                                cipherValue = value;
+                cipherValue = value;
             }
 
             /** @inheritDoc */
-                        public String getValue() {
-                return (cipherValue);
+            public String getValue() {
+                return cipherValue;
             }
 
-                        // public void setValue(byte[] value) {
-                        // public void setValue(String value) {
-               // cipherValue = value;
-            // }
-                        /** @inheritDoc */
+            /** @inheritDoc */
             public void setValue(String value) {
-                // cipherValue = value.getBytes();
-                                cipherValue = value;
+                cipherValue = value;
             }
 
             Element toElement() {
-                Element result = ElementProxy.createElementForFamily(
-                    _contextDocument, EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_CIPHERVALUE);
-                result.appendChild(_contextDocument.createTextNode(
-                    cipherValue));
-
-                return (result);
+                Element result =
+                    XMLUtils.createElementInEncryptionSpace(
+                        contextDocument, EncryptionConstants._TAG_CIPHERVALUE
+                    );
+                result.appendChild(contextDocument.createTextNode(cipherValue));
+
+                return result;
             }
         }
 
-        // <complexType name='EncryptedType' abstract='true'>
-        //     <sequence>
-        //         <element name='EncryptionMethod' type='xenc:EncryptionMethodType'
-        //             minOccurs='0'/>
-        //         <element ref='ds:KeyInfo' minOccurs='0'/>
-        //         <element ref='xenc:CipherData'/>
-        //         <element ref='xenc:EncryptionProperties' minOccurs='0'/>
-        //     </sequence>
-        //     <attribute name='Id' type='ID' use='optional'/>
-        //     <attribute name='Type' type='anyURI' use='optional'/>
-        //     <attribute name='MimeType' type='string' use='optional'/>
-        //     <attribute name='Encoding' type='anyURI' use='optional'/>
-        // </complexType>
-        // <element name='EncryptedData' type='xenc:EncryptedDataType'/>
-        // <complexType name='EncryptedDataType'>
-        //     <complexContent>
-        //         <extension base='xenc:EncryptedType'/>
-        //     </complexContent>
-        // </complexType>
-        private class EncryptedDataImpl extends EncryptedTypeImpl implements
-                EncryptedData {
+        private class EncryptedDataImpl extends EncryptedTypeImpl implements EncryptedData {
+
             /**
              * @param data
              */
@@ -3125,94 +2729,49 @@
                 super(data);
             }
 
-            // <complexType name='EncryptedType' abstract='true'>
-            //     <sequence>
-            //         <element name='EncryptionMethod' type='xenc:EncryptionMethodType'
-            //             minOccurs='0'/>
-            //         <element ref='ds:KeyInfo' minOccurs='0'/>
-            //         <element ref='xenc:CipherData'/>
-            //         <element ref='xenc:EncryptionProperties' minOccurs='0'/>
-            //     </sequence>
-            //     <attribute name='Id' type='ID' use='optional'/>
-            //     <attribute name='Type' type='anyURI' use='optional'/>
-            //     <attribute name='MimeType' type='string' use='optional'/>
-            //     <attribute name='Encoding' type='anyURI' use='optional'/>
-            // </complexType>
-            // <element name='EncryptedData' type='xenc:EncryptedDataType'/>
-            // <complexType name='EncryptedDataType'>
-            //     <complexContent>
-            //         <extension base='xenc:EncryptedType'/>
-            //     </complexContent>
-            // </complexType>
             Element toElement() {
-                Element result = ElementProxy.createElementForFamily(
-                    _contextDocument, EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_ENCRYPTEDDATA);
+                Element result =
+                    ElementProxy.createElementForFamily(
+                        contextDocument, EncryptionConstants.EncryptionSpecNS,
+                        EncryptionConstants._TAG_ENCRYPTEDDATA
+                    );
 
                 if (null != super.getId()) {
-                    result.setAttributeNS(
-                        null, EncryptionConstants._ATT_ID, super.getId());
+                    result.setAttributeNS(null, EncryptionConstants._ATT_ID, super.getId());
                 }
                 if (null != super.getType()) {
-                    result.setAttributeNS(
-                        null, EncryptionConstants._ATT_TYPE, super.getType());
+                    result.setAttributeNS(null, EncryptionConstants._ATT_TYPE, super.getType());
                 }
                 if (null != super.getMimeType()) {
                     result.setAttributeNS(
-                        null, EncryptionConstants._ATT_MIMETYPE,
-                        super.getMimeType());
+                        null, EncryptionConstants._ATT_MIMETYPE, super.getMimeType()
+                    );
                 }
                 if (null != super.getEncoding()) {
                     result.setAttributeNS(
-                        null, EncryptionConstants._ATT_ENCODING,
-                        super.getEncoding());
+                        null, EncryptionConstants._ATT_ENCODING, super.getEncoding()
+                    );
                 }
                 if (null != super.getEncryptionMethod()) {
-                    result.appendChild(((EncryptionMethodImpl)
-                        super.getEncryptionMethod()).toElement());
+                    result.appendChild(
+                        ((EncryptionMethodImpl)super.getEncryptionMethod()).toElement()
+                    );
                 }
                 if (null != super.getKeyInfo()) {
-                    result.appendChild(super.getKeyInfo().getElement());
+                    result.appendChild(super.getKeyInfo().getElement().cloneNode(true));
                 }
 
-                result.appendChild(
-                    ((CipherDataImpl) super.getCipherData()).toElement());
+                result.appendChild(((CipherDataImpl) super.getCipherData()).toElement());
                 if (null != super.getEncryptionProperties()) {
                     result.appendChild(((EncryptionPropertiesImpl)
                         super.getEncryptionProperties()).toElement());
                 }
 
-                return (result);
+                return result;
             }
         }
 
-        // <complexType name='EncryptedType' abstract='true'>
-        //     <sequence>
-        //         <element name='EncryptionMethod' type='xenc:EncryptionMethodType'
-        //             minOccurs='0'/>
-        //         <element ref='ds:KeyInfo' minOccurs='0'/>
-        //         <element ref='xenc:CipherData'/>
-        //         <element ref='xenc:EncryptionProperties' minOccurs='0'/>
-        //     </sequence>
-        //     <attribute name='Id' type='ID' use='optional'/>
-        //     <attribute name='Type' type='anyURI' use='optional'/>
-        //     <attribute name='MimeType' type='string' use='optional'/>
-        //     <attribute name='Encoding' type='anyURI' use='optional'/>
-        // </complexType>
-        // <element name='EncryptedKey' type='xenc:EncryptedKeyType'/>
-        // <complexType name='EncryptedKeyType'>
-        //     <complexContent>
-        //         <extension base='xenc:EncryptedType'>
-        //             <sequence>
-        //                 <element ref='xenc:ReferenceList' minOccurs='0'/>
-        //                 <element name='CarriedKeyName' type='string' minOccurs='0'/>
-        //             </sequence>
-        //             <attribute name='Recipient' type='string' use='optional'/>
-        //         </extension>
-        //     </complexContent>
-        // </complexType>
-        private class EncryptedKeyImpl extends EncryptedTypeImpl implements
-                EncryptedKey {
+        private class EncryptedKeyImpl extends EncryptedTypeImpl implements EncryptedKey {
             private String keyRecipient = null;
             private ReferenceList referenceList = null;
             private String carriedName = null;
@@ -3226,7 +2785,7 @@
 
             /** @inheritDoc */
             public String getRecipient() {
-                return (keyRecipient);
+                return keyRecipient;
             }
 
             /** @inheritDoc */
@@ -3236,7 +2795,7 @@
 
             /** @inheritDoc */
             public ReferenceList getReferenceList() {
-                return (referenceList);
+                return referenceList;
             }
 
             /** @inheritDoc */
@@ -3246,7 +2805,7 @@
 
             /** @inheritDoc */
             public String getCarriedName() {
-                return (carriedName);
+                return carriedName;
             }
 
             /** @inheritDoc */
@@ -3254,84 +2813,60 @@
                 carriedName = name;
             }
 
-            // <complexType name='EncryptedType' abstract='true'>
-            //     <sequence>
-            //         <element name='EncryptionMethod' type='xenc:EncryptionMethodType'
-            //             minOccurs='0'/>
-            //         <element ref='ds:KeyInfo' minOccurs='0'/>
-            //         <element ref='xenc:CipherData'/>
-            //         <element ref='xenc:EncryptionProperties' minOccurs='0'/>
-            //     </sequence>
-            //     <attribute name='Id' type='ID' use='optional'/>
-            //     <attribute name='Type' type='anyURI' use='optional'/>
-            //     <attribute name='MimeType' type='string' use='optional'/>
-            //     <attribute name='Encoding' type='anyURI' use='optional'/>
-            // </complexType>
-            // <element name='EncryptedKey' type='xenc:EncryptedKeyType'/>
-            // <complexType name='EncryptedKeyType'>
-            //     <complexContent>
-            //         <extension base='xenc:EncryptedType'>
-            //             <sequence>
-            //                 <element ref='xenc:ReferenceList' minOccurs='0'/>
-            //                 <element name='CarriedKeyName' type='string' minOccurs='0'/>
-            //             </sequence>
-            //             <attribute name='Recipient' type='string' use='optional'/>
-            //         </extension>
-            //     </complexContent>
-            // </complexType>
             Element toElement() {
-                Element result = ElementProxy.createElementForFamily(
-                    _contextDocument, EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_ENCRYPTEDKEY);
+                Element result =
+                    ElementProxy.createElementForFamily(
+                        contextDocument, EncryptionConstants.EncryptionSpecNS,
+                        EncryptionConstants._TAG_ENCRYPTEDKEY
+                    );
 
                 if (null != super.getId()) {
-                    result.setAttributeNS(
-                        null, EncryptionConstants._ATT_ID, super.getId());
+                    result.setAttributeNS(null, EncryptionConstants._ATT_ID, super.getId());
                 }
                 if (null != super.getType()) {
-                    result.setAttributeNS(
-                        null, EncryptionConstants._ATT_TYPE, super.getType());
+                    result.setAttributeNS(null, EncryptionConstants._ATT_TYPE, super.getType());
                 }
                 if (null != super.getMimeType()) {
-                    result.setAttributeNS(null,
-                        EncryptionConstants._ATT_MIMETYPE, super.getMimeType());
+                    result.setAttributeNS(
+                        null, EncryptionConstants._ATT_MIMETYPE, super.getMimeType()
+                    );
                 }
                 if (null != super.getEncoding()) {
-                    result.setAttributeNS(null, Constants._ATT_ENCODING,
-                        super.getEncoding());
+                    result.setAttributeNS(null, Constants._ATT_ENCODING, super.getEncoding());
                 }
                 if (null != getRecipient()) {
-                    result.setAttributeNS(null,
-                        EncryptionConstants._ATT_RECIPIENT, getRecipient());
+                    result.setAttributeNS(
+                        null, EncryptionConstants._ATT_RECIPIENT, getRecipient()
+                    );
                 }
                 if (null != super.getEncryptionMethod()) {
                     result.appendChild(((EncryptionMethodImpl)
                         super.getEncryptionMethod()).toElement());
                 }
                 if (null != super.getKeyInfo()) {
-                    result.appendChild(super.getKeyInfo().getElement());
+                    result.appendChild(super.getKeyInfo().getElement().cloneNode(true));
                 }
-                result.appendChild(
-                    ((CipherDataImpl) super.getCipherData()).toElement());
+                result.appendChild(((CipherDataImpl) super.getCipherData()).toElement());
                 if (null != super.getEncryptionProperties()) {
                     result.appendChild(((EncryptionPropertiesImpl)
                         super.getEncryptionProperties()).toElement());
                 }
                 if (referenceList != null && !referenceList.isEmpty()) {
-                    result.appendChild(((ReferenceListImpl)
-                        getReferenceList()).toElement());
+                    result.appendChild(((ReferenceListImpl)getReferenceList()).toElement());
                 }
                 if (null != carriedName) {
-                    Element element = ElementProxy.createElementForFamily(
-                        _contextDocument,
-                        EncryptionConstants.EncryptionSpecNS,
-                        EncryptionConstants._TAG_CARRIEDKEYNAME);
-                    Node node = _contextDocument.createTextNode(carriedName);
+                    Element element =
+                        ElementProxy.createElementForFamily(
+                            contextDocument,
+                            EncryptionConstants.EncryptionSpecNS,
+                            EncryptionConstants._TAG_CARRIEDKEYNAME
+                        );
+                    Node node = contextDocument.createTextNode(carriedName);
                     element.appendChild(node);
                     result.appendChild(element);
                 }
 
-                return (result);
+                return result;
             }
         }
 
@@ -3345,16 +2880,22 @@
             private CipherData cipherData = null;
             private EncryptionProperties encryptionProperties = null;
 
+            /**
+             * Constructor.
+             * @param data
+             */
             protected EncryptedTypeImpl(CipherData data) {
                 cipherData = data;
             }
+
             /**
              *
-             * @return
+             * @return the Id
              */
             public String getId() {
-                return (id);
+                return id;
             }
+
             /**
              *
              * @param id
@@ -3362,13 +2903,15 @@
             public void setId(String id) {
                 this.id = id;
             }
+
             /**
              *
-             * @return
+             * @return the type
              */
             public String getType() {
-                return (type);
+                return type;
             }
+
             /**
              *
              * @param type
@@ -3380,18 +2923,20 @@
                     URI tmpType = null;
                     try {
                         tmpType = new URI(type);
-                    } catch (URI.MalformedURIException mfue) {
-                        // complain
+                    } catch (URISyntaxException ex) {
+                        throw (IllegalArgumentException)
+                        new IllegalArgumentException().initCause(ex);
                     }
                     this.type = tmpType.toString();
                 }
             }
+
             /**
              *
-             * @return
+             * @return the MimeType
              */
             public String getMimeType() {
-                return (mimeType);
+                return mimeType;
             }
             /**
              *
@@ -3400,13 +2945,15 @@
             public void setMimeType(String type) {
                 mimeType = type;
             }
+
             /**
              *
-             * @return
+             * @return the encoding
              */
             public String getEncoding() {
-                return (encoding);
+                return encoding;
             }
+
             /**
              *
              * @param encoding
@@ -3418,19 +2965,22 @@
                     URI tmpEncoding = null;
                     try {
                         tmpEncoding = new URI(encoding);
-                    } catch (URI.MalformedURIException mfue) {
-                        // complain
+                    } catch (URISyntaxException ex) {
+                        throw (IllegalArgumentException)
+                        new IllegalArgumentException().initCause(ex);
                     }
                     this.encoding = tmpEncoding.toString();
                 }
             }
+
             /**
              *
-             * @return
+             * @return the EncryptionMethod
              */
             public EncryptionMethod getEncryptionMethod() {
-                return (encryptionMethod);
+                return encryptionMethod;
             }
+
             /**
              *
              * @param method
@@ -3438,13 +2988,15 @@
             public void setEncryptionMethod(EncryptionMethod method) {
                 encryptionMethod = method;
             }
+
             /**
              *
-             * @return
+             * @return the KeyInfo
              */
             public KeyInfo getKeyInfo() {
-                return (keyInfo);
+                return keyInfo;
             }
+
             /**
              *
              * @param info
@@ -3452,217 +3004,235 @@
             public void setKeyInfo(KeyInfo info) {
                 keyInfo = info;
             }
+
             /**
              *
-             * @return
+             * @return the CipherData
              */
             public CipherData getCipherData() {
-                return (cipherData);
+                return cipherData;
             }
+
             /**
              *
-             * @return
+             * @return the EncryptionProperties
              */
             public EncryptionProperties getEncryptionProperties() {
-                return (encryptionProperties);
+                return encryptionProperties;
             }
+
             /**
              *
              * @param properties
              */
-            public void setEncryptionProperties(
-                    EncryptionProperties properties) {
+            public void setEncryptionProperties(EncryptionProperties properties) {
                 encryptionProperties = properties;
             }
         }
 
-        // <complexType name='EncryptionMethodType' mixed='true'>
-        //     <sequence>
-        //         <element name='KeySize' minOccurs='0' type='xenc:KeySizeType'/>
-        //         <element name='OAEPparams' minOccurs='0' type='base64Binary'/>
-        //         <any namespace='##other' minOccurs='0' maxOccurs='unbounded'/>
-        //     </sequence>
-        //     <attribute name='Algorithm' type='anyURI' use='required'/>
-        // </complexType>
         private class EncryptionMethodImpl implements EncryptionMethod {
             private String algorithm = null;
             private int keySize = Integer.MIN_VALUE;
             private byte[] oaepParams = null;
             private List<Element> encryptionMethodInformation = null;
+            private String digestAlgorithm = null;
+            private String mgfAlgorithm = null;
+
             /**
-             *
+             * Constructor.
              * @param algorithm
              */
             public EncryptionMethodImpl(String algorithm) {
                 URI tmpAlgorithm = null;
                 try {
                     tmpAlgorithm = new URI(algorithm);
-                } catch (URI.MalformedURIException mfue) {
-                    // complain
+                } catch (URISyntaxException ex) {
+                    throw (IllegalArgumentException)
+                    new IllegalArgumentException().initCause(ex);
                 }
                 this.algorithm = tmpAlgorithm.toString();
                 encryptionMethodInformation = new LinkedList<Element>();
             }
+
             /** @inheritDoc */
             public String getAlgorithm() {
-                return (algorithm);
+                return algorithm;
             }
+
             /** @inheritDoc */
             public int getKeySize() {
-                return (keySize);
+                return keySize;
             }
+
             /** @inheritDoc */
             public void setKeySize(int size) {
                 keySize = size;
             }
+
             /** @inheritDoc */
             public byte[] getOAEPparams() {
-                return (oaepParams);
+                return oaepParams;
             }
+
             /** @inheritDoc */
             public void setOAEPparams(byte[] params) {
                 oaepParams = params;
             }
+
+            /** @inheritDoc */
+            public void setDigestAlgorithm(String digestAlgorithm) {
+                this.digestAlgorithm = digestAlgorithm;
+            }
+
+            /** @inheritDoc */
+            public String getDigestAlgorithm() {
+                return digestAlgorithm;
+            }
+
+            /** @inheritDoc */
+            public void setMGFAlgorithm(String mgfAlgorithm) {
+                this.mgfAlgorithm = mgfAlgorithm;
+            }
+
+            /** @inheritDoc */
+            public String getMGFAlgorithm() {
+                return mgfAlgorithm;
+            }
+
             /** @inheritDoc */
             public Iterator<Element> getEncryptionMethodInformation() {
-                return (encryptionMethodInformation.iterator());
+                return encryptionMethodInformation.iterator();
             }
+
             /** @inheritDoc */
             public void addEncryptionMethodInformation(Element info) {
                 encryptionMethodInformation.add(info);
             }
+
             /** @inheritDoc */
             public void removeEncryptionMethodInformation(Element info) {
                 encryptionMethodInformation.remove(info);
             }
 
-            // <complexType name='EncryptionMethodType' mixed='true'>
-            //     <sequence>
-            //         <element name='KeySize' minOccurs='0' type='xenc:KeySizeType'/>
-            //         <element name='OAEPparams' minOccurs='0' type='base64Binary'/>
-            //         <any namespace='##other' minOccurs='0' maxOccurs='unbounded'/>
-            //     </sequence>
-            //     <attribute name='Algorithm' type='anyURI' use='required'/>
-            // </complexType>
             Element toElement() {
-                Element result = ElementProxy.createElementForFamily(
-                    _contextDocument, EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_ENCRYPTIONMETHOD);
-                result.setAttributeNS(null, EncryptionConstants._ATT_ALGORITHM,
-                    algorithm);
+                Element result =
+                    XMLUtils.createElementInEncryptionSpace(
+                        contextDocument, EncryptionConstants._TAG_ENCRYPTIONMETHOD
+                    );
+                result.setAttributeNS(null, EncryptionConstants._ATT_ALGORITHM, algorithm);
                 if (keySize > 0) {
                     result.appendChild(
-                        ElementProxy.createElementForFamily(_contextDocument,
-                            EncryptionConstants.EncryptionSpecNS,
-                            EncryptionConstants._TAG_KEYSIZE).appendChild(
-                            _contextDocument.createTextNode(
-                                String.valueOf(keySize))));
+                        XMLUtils.createElementInEncryptionSpace(
+                            contextDocument, EncryptionConstants._TAG_KEYSIZE
+                    ).appendChild(contextDocument.createTextNode(String.valueOf(keySize))));
                 }
                 if (null != oaepParams) {
-                    result.appendChild(
-                        ElementProxy.createElementForFamily(_contextDocument,
-                            EncryptionConstants.EncryptionSpecNS,
-                            EncryptionConstants._TAG_OAEPPARAMS).appendChild(
-                            _contextDocument.createTextNode(
-                                new String(oaepParams))));
+                    Element oaepElement =
+                        XMLUtils.createElementInEncryptionSpace(
+                            contextDocument, EncryptionConstants._TAG_OAEPPARAMS
+                        );
+                    oaepElement.appendChild(contextDocument.createTextNode(Base64.encode(oaepParams)));
+                    result.appendChild(oaepElement);
+                }
+                if (digestAlgorithm != null) {
+                    Element digestElement =
+                        XMLUtils.createElementInSignatureSpace(contextDocument, Constants._TAG_DIGESTMETHOD);
+                    digestElement.setAttributeNS(null, "Algorithm", digestAlgorithm);
+                    result.appendChild(digestElement);
                 }
-                if (!encryptionMethodInformation.isEmpty()) {
-                    Iterator<Element> itr = encryptionMethodInformation.iterator();
+                if (mgfAlgorithm != null) {
+                    Element mgfElement =
+                        XMLUtils.createElementInEncryption11Space(
+                            contextDocument, EncryptionConstants._TAG_MGF
+                        );
+                    mgfElement.setAttributeNS(null, "Algorithm", mgfAlgorithm);
+                    mgfElement.setAttributeNS(
+                        Constants.NamespaceSpecNS,
+                        "xmlns:" + ElementProxy.getDefaultPrefix(EncryptionConstants.EncryptionSpec11NS),
+                        EncryptionConstants.EncryptionSpec11NS
+                    );
+                    result.appendChild(mgfElement);
+                }
+                Iterator<Element> itr = encryptionMethodInformation.iterator();
+                while (itr.hasNext()) {
                     result.appendChild(itr.next());
                 }
 
-                return (result);
+                return result;
             }
         }
 
-        // <element name='EncryptionProperties' type='xenc:EncryptionPropertiesType'/>
-        // <complexType name='EncryptionPropertiesType'>
-        //     <sequence>
-        //         <element ref='xenc:EncryptionProperty' maxOccurs='unbounded'/>
-        //     </sequence>
-        //     <attribute name='Id' type='ID' use='optional'/>
-        // </complexType>
         private class EncryptionPropertiesImpl implements EncryptionProperties {
             private String id = null;
             private List<EncryptionProperty> encryptionProperties = null;
+
             /**
-             *
-             *
+             * Constructor.
              */
             public EncryptionPropertiesImpl() {
                 encryptionProperties = new LinkedList<EncryptionProperty>();
             }
+
             /** @inheritDoc */
             public String getId() {
-                return (id);
+                return id;
             }
+
             /** @inheritDoc */
             public void setId(String id) {
                 this.id = id;
             }
+
             /** @inheritDoc */
             public Iterator<EncryptionProperty> getEncryptionProperties() {
-                return (encryptionProperties.iterator());
+                return encryptionProperties.iterator();
             }
+
             /** @inheritDoc */
             public void addEncryptionProperty(EncryptionProperty property) {
                 encryptionProperties.add(property);
             }
+
             /** @inheritDoc */
             public void removeEncryptionProperty(EncryptionProperty property) {
                 encryptionProperties.remove(property);
             }
 
-            // <element name='EncryptionProperties' type='xenc:EncryptionPropertiesType'/>
-            // <complexType name='EncryptionPropertiesType'>
-            //     <sequence>
-            //         <element ref='xenc:EncryptionProperty' maxOccurs='unbounded'/>
-            //     </sequence>
-            //     <attribute name='Id' type='ID' use='optional'/>
-            // </complexType>
             Element toElement() {
-                Element result = ElementProxy.createElementForFamily(
-                    _contextDocument, EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_ENCRYPTIONPROPERTIES);
+                Element result =
+                    XMLUtils.createElementInEncryptionSpace(
+                        contextDocument, EncryptionConstants._TAG_ENCRYPTIONPROPERTIES
+                    );
                 if (null != id) {
                     result.setAttributeNS(null, EncryptionConstants._ATT_ID, id);
                 }
                 Iterator<EncryptionProperty> itr = getEncryptionProperties();
                 while (itr.hasNext()) {
-                    result.appendChild(((EncryptionPropertyImpl)
-                        itr.next()).toElement());
+                    result.appendChild(((EncryptionPropertyImpl)itr.next()).toElement());
                 }
 
-                return (result);
+                return result;
             }
         }
 
-        // <element name='EncryptionProperty' type='xenc:EncryptionPropertyType'/>
-        // <complexType name='EncryptionPropertyType' mixed='true'>
-        //     <choice maxOccurs='unbounded'>
-        //         <any namespace='##other' processContents='lax'/>
-        //     </choice>
-        //     <attribute name='Target' type='anyURI' use='optional'/>
-        //     <attribute name='Id' type='ID' use='optional'/>
-        //     <anyAttribute namespace="http://www.w3.org/XML/1998/namespace"/>
-        // </complexType>
         private class EncryptionPropertyImpl implements EncryptionProperty {
             private String target = null;
             private String id = null;
-            private HashMap<String,String> attributeMap = new HashMap<String,String>();
+            private Map<String, String> attributeMap = new HashMap<String, String>();
             private List<Element> encryptionInformation = null;
 
             /**
-             *
-             *
+             * Constructor.
              */
             public EncryptionPropertyImpl() {
                 encryptionInformation = new LinkedList<Element>();
             }
+
             /** @inheritDoc */
             public String getTarget() {
-                return (target);
+                return target;
             }
+
             /** @inheritDoc */
             public void setTarget(String target) {
                 if (target == null || target.length() == 0) {
@@ -3670,163 +3240,144 @@
                 } else if (target.startsWith("#")) {
                     /*
                      * This is a same document URI reference. Do not parse,
-                     * because com.sun.org.apache.xml.internal.utils.URI considers this an
-                     * illegal URI because it has no scheme.
+                     * because it has no scheme.
                      */
                     this.target = target;
                 } else {
                     URI tmpTarget = null;
                     try {
                         tmpTarget = new URI(target);
-                    } catch (URI.MalformedURIException mfue) {
-                        // complain
+                    } catch (URISyntaxException ex) {
+                        throw (IllegalArgumentException)
+                        new IllegalArgumentException().initCause(ex);
                     }
                     this.target = tmpTarget.toString();
                 }
             }
+
             /** @inheritDoc */
             public String getId() {
-                return (id);
+                return id;
             }
+
             /** @inheritDoc */
             public void setId(String id) {
                 this.id = id;
             }
+
             /** @inheritDoc */
             public String getAttribute(String attribute) {
                 return attributeMap.get(attribute);
             }
+
             /** @inheritDoc */
             public void setAttribute(String attribute, String value) {
                 attributeMap.put(attribute, value);
             }
+
             /** @inheritDoc */
             public Iterator<Element> getEncryptionInformation() {
-                return (encryptionInformation.iterator());
+                return encryptionInformation.iterator();
             }
+
             /** @inheritDoc */
             public void addEncryptionInformation(Element info) {
                 encryptionInformation.add(info);
             }
+
             /** @inheritDoc */
             public void removeEncryptionInformation(Element info) {
                 encryptionInformation.remove(info);
             }
 
-            // <element name='EncryptionProperty' type='xenc:EncryptionPropertyType'/>
-            // <complexType name='EncryptionPropertyType' mixed='true'>
-            //     <choice maxOccurs='unbounded'>
-            //         <any namespace='##other' processContents='lax'/>
-            //     </choice>
-            //     <attribute name='Target' type='anyURI' use='optional'/>
-            //     <attribute name='Id' type='ID' use='optional'/>
-            //     <anyAttribute namespace="http://www.w3.org/XML/1998/namespace"/>
-            // </complexType>
             Element toElement() {
-                Element result = ElementProxy.createElementForFamily(
-                    _contextDocument, EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_ENCRYPTIONPROPERTY);
+                Element result =
+                    XMLUtils.createElementInEncryptionSpace(
+                        contextDocument, EncryptionConstants._TAG_ENCRYPTIONPROPERTY
+                    );
                 if (null != target) {
-                    result.setAttributeNS(null, EncryptionConstants._ATT_TARGET,
-                        target);
+                    result.setAttributeNS(null, EncryptionConstants._ATT_TARGET, target);
                 }
                 if (null != id) {
-                    result.setAttributeNS(null, EncryptionConstants._ATT_ID,
-                        id);
+                    result.setAttributeNS(null, EncryptionConstants._ATT_ID, id);
                 }
                 // TODO: figure out the anyAttribyte stuff...
                 // TODO: figure out the any stuff...
 
-                return (result);
+                return result;
             }
         }
 
-        // <complexType name='TransformsType'>
-        //     <sequence>
-        //         <element ref='ds:Transform' maxOccurs='unbounded'/>
-        //     </sequence>
-        // </complexType>
-        private class TransformsImpl extends
-                       com.sun.org.apache.xml.internal.security.transforms.Transforms
-                       implements Transforms {
-
-                        /**
-                         * Construct Transforms
-                         */
-
-                        public TransformsImpl() {
-                                super(_contextDocument);
-                        }
-                        /**
+        private class TransformsImpl extends com.sun.org.apache.xml.internal.security.transforms.Transforms
+            implements Transforms {
+
+            /**
+             * Construct Transforms
+             */
+            public TransformsImpl() {
+                super(contextDocument);
+            }
+
+            /**
              *
-                         * @param doc
-                         */
-                        public TransformsImpl(Document doc) {
-                                if (doc == null) {
-                                 throw new RuntimeException("Document is null");
-                              }
-
-                              this._doc = doc;
-                              this._constructionElement =  createElementForFamilyLocal(this._doc,
-                                          this.getBaseNamespace(), this.getBaseLocalName());
-                        }
-                        /**
-             *
-                         * @param element
-                         * @throws XMLSignatureException
-                         * @throws InvalidTransformException
-                         * @throws XMLSecurityException
-                         * @throws TransformationException
-                         */
-                        public TransformsImpl(Element element)
-                                throws XMLSignatureException,
-                                   InvalidTransformException,
-                                       XMLSecurityException,
-                                       TransformationException {
-
-                                super(element, "");
-
-                        }
+             * @param doc
+             */
+            public TransformsImpl(Document doc) {
+                if (doc == null) {
+                    throw new RuntimeException("Document is null");
+                }
+
+                this.doc = doc;
+                this.constructionElement =
+                    createElementForFamilyLocal(
+                        this.doc, this.getBaseNamespace(), this.getBaseLocalName()
+                    );
+            }
 
             /**
              *
-             * @return
+             * @param element
+             * @throws XMLSignatureException
+             * @throws InvalidTransformException
+             * @throws XMLSecurityException
+             * @throws TransformationException
              */
-                        public Element toElement() {
-
-                                if (_doc == null)
-                                        _doc = _contextDocument;
-
-                                return getElement();
-                        }
+            public TransformsImpl(Element element)
+                throws XMLSignatureException, InvalidTransformException,
+                    XMLSecurityException, TransformationException {
+                super(element, "");
+            }
+
+            /**
+             *
+             * @return the XML Element form of that Transforms
+             */
+            public Element toElement() {
+                if (doc == null) {
+                    doc = contextDocument;
+                }
+
+                return getElement();
+            }
 
             /** @inheritDoc */
-                        public com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms() {
-                                return (this);
-                        }
-
-
-                        // Over-ride the namespace
+            public com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms() {
+                return this;
+            }
+
+            // Over-ride the namespace
             /** @inheritDoc */
-                        public String getBaseNamespace() {
-                                return EncryptionConstants.EncryptionSpecNS;
-                        }
-
+            public String getBaseNamespace() {
+                return EncryptionConstants.EncryptionSpecNS;
+            }
         }
 
-        //<element name='ReferenceList'>
-        //    <complexType>
-        //        <choice minOccurs='1' maxOccurs='unbounded'>
-        //            <element name='DataReference' type='xenc:ReferenceType'/>
-        //            <element name='KeyReference' type='xenc:ReferenceType'/>
-        //        </choice>
-        //    </complexType>
-        //</element>
         private class ReferenceListImpl implements ReferenceList {
             private Class<?> sentry;
             private List<Reference> references;
+
             /**
-             *
+             * Constructor.
              * @param type
              */
             public ReferenceListImpl(int type) {
@@ -3839,13 +3390,15 @@
                 }
                 references = new LinkedList<Reference>();
             }
+
             /** @inheritDoc */
             public void add(Reference reference) {
                 if (!reference.getClass().equals(sentry)) {
                     throw new IllegalArgumentException();
                 }
-                 references.add(reference);
+                references.add(reference);
             }
+
             /** @inheritDoc */
             public void remove(Reference reference) {
                 if (!reference.getClass().equals(sentry)) {
@@ -3853,39 +3406,45 @@
                 }
                 references.remove(reference);
             }
+
             /** @inheritDoc */
             public int size() {
-                return (references.size());
+                return references.size();
             }
+
             /** @inheritDoc */
             public boolean isEmpty() {
-                return (references.isEmpty());
+                return references.isEmpty();
             }
+
             /** @inheritDoc */
             public Iterator<Reference> getReferences() {
-                return (references.iterator());
+                return references.iterator();
             }
 
             Element toElement() {
-                Element result = ElementProxy.createElementForFamily(
-                    _contextDocument,
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_REFERENCELIST);
+                Element result =
+                    ElementProxy.createElementForFamily(
+                        contextDocument,
+                        EncryptionConstants.EncryptionSpecNS,
+                        EncryptionConstants._TAG_REFERENCELIST
+                    );
                 Iterator<Reference> eachReference = references.iterator();
                 while (eachReference.hasNext()) {
                     Reference reference = eachReference.next();
-                    result.appendChild(
-                        ((ReferenceImpl) reference).toElement());
+                    result.appendChild(((ReferenceImpl) reference).toElement());
                 }
-                return (result);
+                return result;
             }
+
             /** @inheritDoc */
             public Reference newDataReference(String uri) {
-                return (new DataReference(uri));
+                return new DataReference(uri);
             }
+
             /** @inheritDoc */
             public Reference newKeyReference(String uri) {
-                return (new KeyReference(uri));
+                return new KeyReference(uri);
             }
 
             /**
@@ -3898,68 +3457,81 @@
                 private String uri;
                 private List<Element> referenceInformation;
 
-                ReferenceImpl(String _uri) {
-                    this.uri = _uri;
+                ReferenceImpl(String uri) {
+                    this.uri = uri;
                     referenceInformation = new LinkedList<Element>();
                 }
+
+                /** @inheritDoc */
+                public abstract String getType();
+
                 /** @inheritDoc */
                 public String getURI() {
-                    return (uri);
+                    return uri;
                 }
+
                 /** @inheritDoc */
                 public Iterator<Element> getElementRetrievalInformation() {
-                    return (referenceInformation.iterator());
+                    return referenceInformation.iterator();
                 }
+
                 /** @inheritDoc */
-                public void setURI(String _uri) {
-                        this.uri = _uri;
+                public void setURI(String uri) {
+                    this.uri = uri;
                 }
+
                 /** @inheritDoc */
                 public void removeElementRetrievalInformation(Element node) {
                     referenceInformation.remove(node);
                 }
+
                 /** @inheritDoc */
                 public void addElementRetrievalInformation(Element node) {
                     referenceInformation.add(node);
                 }
+
                 /**
-                 *
-                 * @return
+                 * @return the XML Element form of that Reference
                  */
-                public abstract Element toElement();
-
-                Element toElement(String tagName) {
-                    Element result = ElementProxy.createElementForFamily(
-                        _contextDocument,
-                        EncryptionConstants.EncryptionSpecNS,
-                        tagName);
+                public Element toElement() {
+                    String tagName = getType();
+                    Element result =
+                        ElementProxy.createElementForFamily(
+                            contextDocument,
+                            EncryptionConstants.EncryptionSpecNS,
+                            tagName
+                        );
                     result.setAttribute(EncryptionConstants._ATT_URI, uri);
 
                     // TODO: Need to martial referenceInformation
                     // Figure out how to make this work..
                     // <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
 
-                    return (result);
+                    return result;
                 }
             }
 
             private class DataReference extends ReferenceImpl {
+
                 DataReference(String uri) {
                     super(uri);
                 }
+
                 /** @inheritDoc */
-                public Element toElement() {
-                    return super.toElement(EncryptionConstants._TAG_DATAREFERENCE);
+                public String getType() {
+                    return EncryptionConstants._TAG_DATAREFERENCE;
                 }
             }
 
             private class KeyReference extends ReferenceImpl {
+
                 KeyReference(String uri) {
-                    super (uri);
+                    super(uri);
                 }
+
                 /** @inheritDoc */
-                public Element toElement() {
-                    return super.toElement(EncryptionConstants._TAG_KEYREFERENCE);
+                public String getType() {
+                    return EncryptionConstants._TAG_KEYREFERENCE;
                 }
             }
         }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,23 +2,24 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  2003-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
-
 package com.sun.org.apache.xml.internal.security.encryption;
 
 import java.io.IOException;
@@ -32,7 +33,6 @@
 import org.w3c.dom.Attr;
 import com.sun.org.apache.xml.internal.security.utils.Base64;
 
-
 /**
  * <code>XMLCipherInput</code> is used to wrap input passed into the
  * XMLCipher encryption operations.
@@ -50,77 +50,79 @@
 public class XMLCipherInput {
 
     private static java.util.logging.Logger logger =
-        java.util.logging.Logger.getLogger(XMLCipher.class.getName());
+        java.util.logging.Logger.getLogger(XMLCipherInput.class.getName());
+
+    /** The data we are working with */
+    private CipherData cipherData;
 
-        /** The data we are working with */
-        private CipherData _cipherData;
+    /** MODES */
+    private int mode;
 
-        /** MODES */
-        private int _mode;
+    private boolean secureValidation;
 
-        /**
-         * Constructor for processing encrypted octets
-         *
-         * @param data The <code>CipherData</code> object to read the bytes from
-         * @throws XMLEncryptionException {@link XMLEncryptionException}
-         */
-
-        public XMLCipherInput(CipherData data) throws XMLEncryptionException {
-
-                _cipherData = data;
-                _mode = XMLCipher.DECRYPT_MODE;
-                if (_cipherData == null) {
-                        throw new XMLEncryptionException("CipherData is null");
-                }
-
+    /**
+     * Constructor for processing encrypted octets
+     *
+     * @param data The <code>CipherData</code> object to read the bytes from
+     * @throws XMLEncryptionException {@link XMLEncryptionException}
+     */
+    public XMLCipherInput(CipherData data) throws XMLEncryptionException {
+        cipherData = data;
+        mode = XMLCipher.DECRYPT_MODE;
+        if (cipherData == null) {
+            throw new XMLEncryptionException("CipherData is null");
         }
+    }
 
-        /**
-         * Constructor for processing encrypted octets
-         *
-         * @param input The <code>EncryptedType</code> object to read
-         * the bytes from.
-         * @throws XMLEncryptionException {@link XMLEncryptionException}
-         */
-
-        public XMLCipherInput(EncryptedType input) throws XMLEncryptionException {
-
-                _cipherData = ((input == null) ? null : input.getCipherData());
-                _mode = XMLCipher.DECRYPT_MODE;
-                if (_cipherData == null) {
-                        throw new XMLEncryptionException("CipherData is null");
-                }
+    /**
+     * Constructor for processing encrypted octets
+     *
+     * @param input The <code>EncryptedType</code> object to read
+     * the bytes from.
+     * @throws XMLEncryptionException {@link XMLEncryptionException}
+     */
+    public XMLCipherInput(EncryptedType input) throws XMLEncryptionException {
+        cipherData = ((input == null) ? null : input.getCipherData());
+        mode = XMLCipher.DECRYPT_MODE;
+        if (cipherData == null) {
+            throw new XMLEncryptionException("CipherData is null");
+        }
+    }
 
-        }
+    /**
+     * Set whether secure validation is enabled or not. The default is false.
+     */
+    public void setSecureValidation(boolean secureValidation) {
+        this.secureValidation = secureValidation;
+    }
 
-        /**
-         * Dereferences the input and returns it as a single byte array.
-         *
-         * @throws XMLEncryptionException
+    /**
+     * Dereferences the input and returns it as a single byte array.
+     *
+     * @throws XMLEncryptionException
      * @return The decripted bytes.
-         */
-
-        public byte[] getBytes() throws XMLEncryptionException {
-
-                if (_mode == XMLCipher.DECRYPT_MODE) {
-                        return getDecryptBytes();
-                }
-                return null;
+     */
+    public byte[] getBytes() throws XMLEncryptionException {
+        if (mode == XMLCipher.DECRYPT_MODE) {
+            return getDecryptBytes();
         }
+        return null;
+    }
 
     /**
      * Internal method to get bytes in decryption mode
-     * @return the decripted bytes
+     * @return the decrypted bytes
      * @throws XMLEncryptionException
      */
     private byte[] getDecryptBytes() throws XMLEncryptionException {
-
         String base64EncodedEncryptedOctets = null;
 
-        if (_cipherData.getDataType() == CipherData.REFERENCE_TYPE) {
+        if (cipherData.getDataType() == CipherData.REFERENCE_TYPE) {
             // Fun time!
-            logger.log(java.util.logging.Level.FINE, "Found a reference type CipherData");
-            CipherReference cr = _cipherData.getCipherReference();
+            if (logger.isLoggable(java.util.logging.Level.FINE)) {
+                logger.log(java.util.logging.Level.FINE, "Found a reference type CipherData");
+            }
+            CipherReference cr = cipherData.getCipherReference();
 
             // Need to wrap the uri in an Attribute node so that we can
             // Pass to the resource resolvers
@@ -130,25 +132,32 @@
 
             try {
                 ResourceResolver resolver =
-                    ResourceResolver.getInstance(uriAttr, null);
-                input = resolver.resolve(uriAttr, null);
+                    ResourceResolver.getInstance(uriAttr, null, secureValidation);
+                input = resolver.resolve(uriAttr, null, secureValidation);
             } catch (ResourceResolverException ex) {
                 throw new XMLEncryptionException("empty", ex);
             }
 
             if (input != null) {
-                logger.log(java.util.logging.Level.FINE, "Managed to resolve URI \"" + cr.getURI() + "\"");
+                if (logger.isLoggable(java.util.logging.Level.FINE)) {
+                    logger.log(java.util.logging.Level.FINE, "Managed to resolve URI \"" + cr.getURI() + "\"");
+                }
             } else {
-                logger.log(java.util.logging.Level.FINE, "Failed to resolve URI \"" + cr.getURI() + "\"");
+                if (logger.isLoggable(java.util.logging.Level.FINE)) {
+                    logger.log(java.util.logging.Level.FINE, "Failed to resolve URI \"" + cr.getURI() + "\"");
+                }
             }
 
             // Lets see if there are any transforms
             Transforms transforms = cr.getTransforms();
             if (transforms != null) {
-                logger.log(java.util.logging.Level.FINE, "Have transforms in cipher reference");
+                if (logger.isLoggable(java.util.logging.Level.FINE)) {
+                    logger.log(java.util.logging.Level.FINE, "Have transforms in cipher reference");
+                }
                 try {
                     com.sun.org.apache.xml.internal.security.transforms.Transforms dsTransforms =
                         transforms.getDSTransforms();
+                    dsTransforms.setSecureValidation(secureValidation);
                     input = dsTransforms.performTransforms(input);
                 } catch (TransformationException ex) {
                     throw new XMLEncryptionException("empty", ex);
@@ -163,23 +172,21 @@
                 throw new XMLEncryptionException("empty", ex);
             }
 
-        // retrieve the cipher text
-        } else if (_cipherData.getDataType() == CipherData.VALUE_TYPE) {
-            base64EncodedEncryptedOctets =
-                _cipherData.getCipherValue().getValue();
+            // retrieve the cipher text
+        } else if (cipherData.getDataType() == CipherData.VALUE_TYPE) {
+            base64EncodedEncryptedOctets = cipherData.getCipherValue().getValue();
         } else {
             throw new XMLEncryptionException("CipherData.getDataType() returned unexpected value");
         }
 
-        logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets);
+        if (logger.isLoggable(java.util.logging.Level.FINE)) {
+            logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets);
+        }
 
-        byte[] encryptedBytes = null;
         try {
-            encryptedBytes = Base64.decode(base64EncodedEncryptedOctets);
+            return Base64.decode(base64EncodedEncryptedOctets);
         } catch (Base64DecodingException bde) {
             throw new XMLEncryptionException("empty", bde);
         }
-
-        return (encryptedBytes);
     }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,104 +2,85 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
-
 package com.sun.org.apache.xml.internal.security.encryption;
 
-
 /**
  * Constants
  */
 public interface XMLCipherParameters {
 
-    /** */
-    public static final String AES_128 =
+    String AES_128 =
         "http://www.w3.org/2001/04/xmlenc#aes128-cbc";
 
-    /**  */
-    public static final String AES_256 =
+    String AES_256 =
         "http://www.w3.org/2001/04/xmlenc#aes256-cbc";
 
-    /**  */
-    public static final String AES_192 =
+    String AES_192 =
         "http://www.w3.org/2001/04/xmlenc#aes192-cbc";
 
-    /**  */
-    public static final String RSA_1_5 =
+    String RSA_1_5 =
         "http://www.w3.org/2001/04/xmlenc#rsa-1_5";
 
-    /**  */
-    public static final String RSA_OAEP =
+    String RSA_OAEP =
         "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p";
 
-    /**  */
-    public static final String DIFFIE_HELLMAN =
+    String DIFFIE_HELLMAN =
         "http://www.w3.org/2001/04/xmlenc#dh";
 
-    /**  */
-    public static final String TRIPLEDES_KEYWRAP =
+    String TRIPLEDES_KEYWRAP =
         "http://www.w3.org/2001/04/xmlenc#kw-tripledes";
 
-    /**  */
-    public static final String AES_128_KEYWRAP =
+    String AES_128_KEYWRAP =
         "http://www.w3.org/2001/04/xmlenc#kw-aes128";
 
-    /**  */
-    public static final String AES_256_KEYWRAP =
+    String AES_256_KEYWRAP =
         "http://www.w3.org/2001/04/xmlenc#kw-aes256";
 
-    /**  */
-    public static final String AES_192_KEYWRAP =
+    String AES_192_KEYWRAP =
         "http://www.w3.org/2001/04/xmlenc#kw-aes192";
 
-    /**  */
-    public static final String SHA1 =
+    String SHA1 =
         "http://www.w3.org/2000/09/xmldsig#sha1";
 
-    /**  */
-    public static final String SHA256 =
+    String SHA256 =
         "http://www.w3.org/2001/04/xmlenc#sha256";
 
-    /**  */
-    public static final String SHA512 =
+    String SHA512 =
         "http://www.w3.org/2001/04/xmlenc#sha512";
 
-    /**  */
-    public static final String RIPEMD_160 =
+    String RIPEMD_160 =
         "http://www.w3.org/2001/04/xmlenc#ripemd160";
 
-    /**  */
-    public static final String XML_DSIG =
+    String XML_DSIG =
         "http://www.w3.org/2000/09/xmldsig#";
 
-    /**  */
-    public static final String N14C_XML =
+    String N14C_XML =
         "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
 
-    /**  */
-    public static final String N14C_XML_CMMNTS =
+    String N14C_XML_CMMNTS =
         "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments";
 
-    /**  */
-    public static final String EXCL_XML_N14C =
+    String EXCL_XML_N14C =
         "http://www.w3.org/2001/10/xml-exc-c14n#";
 
-    /**  */
-    public static final String EXCL_XML_N14C_CMMNTS =
+    String EXCL_XML_N14C_CMMNTS =
         "http://www.w3.org/2001/10/xml-exc-c14n#WithComments";
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  2003-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.encryption;
 
@@ -26,49 +28,53 @@
  *
  */
 public class XMLEncryptionException extends XMLSecurityException {
-        /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
-        /**
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
+
+    /**
+     *
+     *
+     */
+    public XMLEncryptionException() {
+        super();
+    }
+
+    /**
+     *
+     * @param msgID
+     */
+    public XMLEncryptionException(String msgID) {
+        super(msgID);
+    }
+
+    /**
      *
-         *
-         */
-   public XMLEncryptionException() {
-      super();
-   }
-   /**
-    *
-    * @param _msgID
-    */
-   public XMLEncryptionException(String _msgID) {
-      super(_msgID);
-   }
-   /**
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public XMLEncryptionException(String _msgID, Object exArgs[]) {
-      super(_msgID, exArgs);
-   }
-   /**
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public XMLEncryptionException(String _msgID,
-                                              Exception _originalException) {
-      super(_msgID, _originalException);
-   }
-   /**
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public XMLEncryptionException(String _msgID, Object exArgs[],
-                                              Exception _originalException) {
-      super(_msgID, exArgs, _originalException);
-   }
+     * @param msgID
+     * @param exArgs
+     */
+    public XMLEncryptionException(String msgID, Object exArgs[]) {
+        super(msgID, exArgs);
+    }
+
+    /**
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public XMLEncryptionException(String msgID, Exception originalException) {
+        super(msgID, originalException);
+
+    }
+
+    /**
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public XMLEncryptionException(String msgID, Object exArgs[], Exception originalException) {
+        super(msgID, exArgs, originalException);
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,88 +2,80 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.exceptions;
 
-
-
-/**
- *
- *
- *
- *
- * @author Christian Geuer-Pollmann
- *
- */
 public class AlgorithmAlreadyRegisteredException extends XMLSecurityException {
-
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
 
-   /**
-    * Constructor AlgorithmAlreadyRegisteredException
-    *
-    */
-   public AlgorithmAlreadyRegisteredException() {
-      super();
-   }
+    /**
+     * Constructor AlgorithmAlreadyRegisteredException
+     *
+     */
+    public AlgorithmAlreadyRegisteredException() {
+        super();
+    }
 
-   /**
-    * Constructor AlgorithmAlreadyRegisteredException
-    *
-    * @param _msgID
-    */
-   public AlgorithmAlreadyRegisteredException(String _msgID) {
-      super(_msgID);
-   }
+    /**
+     * Constructor AlgorithmAlreadyRegisteredException
+     *
+     * @param msgID
+     */
+    public AlgorithmAlreadyRegisteredException(String msgID) {
+        super(msgID);
+    }
 
-   /**
-    * Constructor AlgorithmAlreadyRegisteredException
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public AlgorithmAlreadyRegisteredException(String _msgID, Object exArgs[]) {
-      super(_msgID, exArgs);
-   }
+    /**
+     * Constructor AlgorithmAlreadyRegisteredException
+     *
+     * @param msgID
+     * @param exArgs
+     */
+    public AlgorithmAlreadyRegisteredException(String msgID, Object exArgs[]) {
+        super(msgID, exArgs);
+    }
 
-   /**
-    * Constructor AlgorithmAlreadyRegisteredException
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public AlgorithmAlreadyRegisteredException(String _msgID,
-                                              Exception _originalException) {
-      super(_msgID, _originalException);
-   }
+    /**
+     * Constructor AlgorithmAlreadyRegisteredException
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public AlgorithmAlreadyRegisteredException(String msgID, Exception originalException) {
+        super(msgID, originalException);
+    }
 
-   /**
-    * Constructor AlgorithmAlreadyRegisteredException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public AlgorithmAlreadyRegisteredException(String _msgID, Object exArgs[],
-                                              Exception _originalException) {
-      super(_msgID, exArgs, _originalException);
-   }
+    /**
+     * Constructor AlgorithmAlreadyRegisteredException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public AlgorithmAlreadyRegisteredException(
+        String msgID, Object exArgs[], Exception originalException
+    ) {
+        super(msgID, exArgs, originalException);
+    }
+
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.exceptions;
 
-
-
 /**
  * This Exception is thrown if decoding of Base64 data fails.
  *
@@ -29,58 +29,54 @@
  */
 public class Base64DecodingException extends XMLSecurityException {
 
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
+    private static final long serialVersionUID = 1L;
 
-   /**
-    * Constructor Base64DecodingException
-    *
-    */
-   public Base64DecodingException() {
-      super();
-   }
+    /**
+     * Constructor Base64DecodingException
+     *
+     */
+    public Base64DecodingException() {
+        super();
+    }
 
-   /**
-    * Constructor Base64DecodingException
-    *
-    * @param _msgID
-    */
-   public Base64DecodingException(String _msgID) {
-      super(_msgID);
-   }
+    /**
+     * Constructor Base64DecodingException
+     *
+     * @param msgID
+     */
+    public Base64DecodingException(String msgID) {
+        super(msgID);
+    }
 
-   /**
-    * Constructor Base64DecodingException
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public Base64DecodingException(String _msgID, Object exArgs[]) {
-      super(_msgID, exArgs);
-   }
+    /**
+     * Constructor Base64DecodingException
+     *
+     * @param msgID
+     * @param exArgs
+     */
+    public Base64DecodingException(String msgID, Object exArgs[]) {
+        super(msgID, exArgs);
+    }
 
-   /**
-    * Constructor Base64DecodingException
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public Base64DecodingException(String _msgID,
-                                              Exception _originalException) {
-      super(_msgID, _originalException);
-   }
+    /**
+     * Constructor Base64DecodingException
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public Base64DecodingException(String msgID, Exception originalException) {
+        super(msgID, originalException);
+    }
 
-   /**
-    * Constructor Base64DecodingException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public Base64DecodingException(String _msgID, Object exArgs[],
-                                              Exception _originalException) {
-      super(_msgID, exArgs, _originalException);
-   }
+    /**
+     * Constructor Base64DecodingException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public Base64DecodingException(String msgID, Object exArgs[], Exception originalException) {
+        super(msgID, exArgs, originalException);
+    }
+
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.exceptions;
 
-
-
 import java.io.PrintStream;
 import java.io.PrintWriter;
 import java.text.MessageFormat;
@@ -29,7 +29,6 @@
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.I18n;
 
-
 /**
  * The mother of all Exceptions in this bundle. It allows exceptions to have
  * their messages translated to the different locales.
@@ -64,186 +63,154 @@
  */
 public class XMLSecurityException extends Exception {
 
-
-
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
-
-   /** Field originalException */
-   protected Exception originalException = null;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
 
-   /** Field msgID */
-   protected String msgID;
-
-   /**
-    * Constructor XMLSecurityException
-    *
-    */
-   public XMLSecurityException() {
-
-      super("Missing message string");
+    /** Field msgID */
+    protected String msgID;
 
-      this.msgID = null;
-      this.originalException = null;
-   }
+    /**
+     * Constructor XMLSecurityException
+     *
+     */
+    public XMLSecurityException() {
+        super("Missing message string");
 
-   /**
-    * Constructor XMLSecurityException
-    *
-    * @param _msgID
-    */
-   public XMLSecurityException(String _msgID) {
+        this.msgID = null;
+    }
 
-      super(I18n.getExceptionMessage(_msgID));
-
-      this.msgID = _msgID;
-      this.originalException = null;
-   }
+    /**
+     * Constructor XMLSecurityException
+     *
+     * @param msgID
+     */
+    public XMLSecurityException(String msgID) {
+        super(I18n.getExceptionMessage(msgID));
 
-   /**
-    * Constructor XMLSecurityException
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public XMLSecurityException(String _msgID, Object exArgs[]) {
+        this.msgID = msgID;
+    }
 
-      super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs));
-
-      this.msgID = _msgID;
-      this.originalException = null;
-   }
+    /**
+     * Constructor XMLSecurityException
+     *
+     * @param msgID
+     * @param exArgs
+     */
+    public XMLSecurityException(String msgID, Object exArgs[]) {
 
-   /**
-    * Constructor XMLSecurityException
-    *
-    * @param _originalException
-    */
-   public XMLSecurityException(Exception _originalException) {
+        super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs));
 
-      super("Missing message ID to locate message string in resource bundle \""
-            + Constants.exceptionMessagesResourceBundleBase
-            + "\". Original Exception was a "
-            + _originalException.getClass().getName() + " and message "
-            + _originalException.getMessage());
-
-      this.originalException = _originalException;
-   }
+        this.msgID = msgID;
+    }
 
-   /**
-    * Constructor XMLSecurityException
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public XMLSecurityException(String _msgID, Exception _originalException) {
-
-      super(I18n.getExceptionMessage(_msgID, _originalException));
+    /**
+     * Constructor XMLSecurityException
+     *
+     * @param originalException
+     */
+    public XMLSecurityException(Exception originalException) {
 
-      this.msgID = _msgID;
-      this.originalException = _originalException;
-   }
+        super("Missing message ID to locate message string in resource bundle \""
+              + Constants.exceptionMessagesResourceBundleBase
+              + "\". Original Exception was a "
+              + originalException.getClass().getName() + " and message "
+              + originalException.getMessage(), originalException);
+    }
 
-   /**
-    * Constructor XMLSecurityException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public XMLSecurityException(String _msgID, Object exArgs[],
-                               Exception _originalException) {
+    /**
+     * Constructor XMLSecurityException
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public XMLSecurityException(String msgID, Exception originalException) {
+        super(I18n.getExceptionMessage(msgID, originalException), originalException);
+
+        this.msgID = msgID;
+    }
 
-      super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs));
-
-      this.msgID = _msgID;
-      this.originalException = _originalException;
-   }
+    /**
+     * Constructor XMLSecurityException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public XMLSecurityException(String msgID, Object exArgs[], Exception originalException) {
+        super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs), originalException);
 
-   /**
-    * Method getMsgID
-    *
-    * @return the messageId
-    */
-   public String getMsgID() {
-
-      if (msgID == null) {
-         return "Missing message ID";
-      }
-      return msgID;
-   }
-
-   /** @inheritDoc */
-   public String toString() {
+        this.msgID = msgID;
+    }
 
-      String s = this.getClass().getName();
-      String message = super.getLocalizedMessage();
-
-      if (message != null) {
-         message = s + ": " + message;
-      } else {
-         message = s;
-      }
+    /**
+     * Method getMsgID
+     *
+     * @return the messageId
+     */
+    public String getMsgID() {
+        if (msgID == null) {
+            return "Missing message ID";
+        }
+        return msgID;
+    }
 
-      if (originalException != null) {
-         message = message + "\nOriginal Exception was "
-                   + originalException.toString();
-      }
+    /** @inheritDoc */
+    public String toString() {
+        String s = this.getClass().getName();
+        String message = super.getLocalizedMessage();
 
-      return message;
-   }
+        if (message != null) {
+            message = s + ": " + message;
+        } else {
+            message = s;
+        }
 
-   /**
-    * Method printStackTrace
-    *
-    */
-   public void printStackTrace() {
+        if (super.getCause() != null) {
+            message = message + "\nOriginal Exception was " + super.getCause().toString();
+        }
 
-      synchronized (System.err) {
-         super.printStackTrace(System.err);
-
-         if (this.originalException != null) {
-            this.originalException.printStackTrace(System.err);
-         }
-      }
-   }
+        return message;
+    }
 
-   /**
-    * Method printStackTrace
-    *
-    * @param printwriter
-    */
-   public void printStackTrace(PrintWriter printwriter) {
+    /**
+     * Method printStackTrace
+     *
+     */
+    public void printStackTrace() {
+        synchronized (System.err) {
+            super.printStackTrace(System.err);
+        }
+    }
 
-      super.printStackTrace(printwriter);
-
-      if (this.originalException != null) {
-         this.originalException.printStackTrace(printwriter);
-      }
-   }
+    /**
+     * Method printStackTrace
+     *
+     * @param printwriter
+     */
+    public void printStackTrace(PrintWriter printwriter) {
+        super.printStackTrace(printwriter);
+    }
 
-   /**
-    * Method printStackTrace
-    *
-    * @param printstream
-    */
-   public void printStackTrace(PrintStream printstream) {
-
-      super.printStackTrace(printstream);
+    /**
+     * Method printStackTrace
+     *
+     * @param printstream
+     */
+    public void printStackTrace(PrintStream printstream) {
+        super.printStackTrace(printstream);
+    }
 
-      if (this.originalException != null) {
-         this.originalException.printStackTrace(printstream);
-      }
-   }
-
-   /**
-    * Method getOriginalException
-    *
-    * @return the original exception
-    */
-   public Exception getOriginalException() {
-      return originalException;
-   }
+    /**
+     * Method getOriginalException
+     *
+     * @return the original exception
+     */
+    public Exception getOriginalException() {
+        if (this.getCause() instanceof Exception) {
+            return (Exception)this.getCause();
+        }
+        return null;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,3 +1,25 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
 package com.sun.org.apache.xml.internal.security.exceptions;
 
 import java.io.PrintStream;
@@ -39,186 +61,152 @@
  *
  * @author Christian Geuer-Pollmann
  */
-public class XMLSecurityRuntimeException
-        extends RuntimeException {
-   /**
-     *
-     */
+public class XMLSecurityRuntimeException extends RuntimeException {
+
     private static final long serialVersionUID = 1L;
 
-   /** Field originalException */
-   protected Exception originalException = null;
-
-   /** Field msgID */
-   protected String msgID;
+    /** Field msgID */
+    protected String msgID;
 
-   /**
-    * Constructor XMLSecurityRuntimeException
-    *
-    */
-   public XMLSecurityRuntimeException() {
+    /**
+     * Constructor XMLSecurityRuntimeException
+     *
+     */
+    public XMLSecurityRuntimeException() {
+        super("Missing message string");
 
-      super("Missing message string");
-
-      this.msgID = null;
-      this.originalException = null;
-   }
+        this.msgID = null;
+    }
 
-   /**
-    * Constructor XMLSecurityRuntimeException
-    *
-    * @param _msgID
-    */
-   public XMLSecurityRuntimeException(String _msgID) {
-
-      super(I18n.getExceptionMessage(_msgID));
+    /**
+     * Constructor XMLSecurityRuntimeException
+     *
+     * @param msgID
+     */
+    public XMLSecurityRuntimeException(String msgID) {
+        super(I18n.getExceptionMessage(msgID));
 
-      this.msgID = _msgID;
-      this.originalException = null;
-   }
+        this.msgID = msgID;
+    }
 
-   /**
-    * Constructor XMLSecurityRuntimeException
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public XMLSecurityRuntimeException(String _msgID, Object exArgs[]) {
-
-      super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs));
+    /**
+     * Constructor XMLSecurityRuntimeException
+     *
+     * @param msgID
+     * @param exArgs
+     */
+    public XMLSecurityRuntimeException(String msgID, Object exArgs[]) {
+        super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs));
 
-      this.msgID = _msgID;
-      this.originalException = null;
-   }
+        this.msgID = msgID;
+    }
 
-   /**
-    * Constructor XMLSecurityRuntimeException
-    *
-    * @param _originalException
-    */
-   public XMLSecurityRuntimeException(Exception _originalException) {
-
-      super("Missing message ID to locate message string in resource bundle \""
-            + Constants.exceptionMessagesResourceBundleBase
-            + "\". Original Exception was a "
-            + _originalException.getClass().getName() + " and message "
-            + _originalException.getMessage());
-
-      this.originalException = _originalException;
-   }
+    /**
+     * Constructor XMLSecurityRuntimeException
+     *
+     * @param originalException
+     */
+    public XMLSecurityRuntimeException(Exception originalException) {
+        super("Missing message ID to locate message string in resource bundle \""
+              + Constants.exceptionMessagesResourceBundleBase
+              + "\". Original Exception was a "
+              + originalException.getClass().getName() + " and message "
+              + originalException.getMessage(), originalException);
+    }
 
-   /**
-    * Constructor XMLSecurityRuntimeException
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public XMLSecurityRuntimeException(String _msgID, Exception _originalException) {
-
-      super(I18n.getExceptionMessage(_msgID, _originalException));
+    /**
+     * Constructor XMLSecurityRuntimeException
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public XMLSecurityRuntimeException(String msgID, Exception originalException) {
+        super(I18n.getExceptionMessage(msgID, originalException), originalException);
 
-      this.msgID = _msgID;
-      this.originalException = _originalException;
-   }
+        this.msgID = msgID;
+    }
 
-   /**
-    * Constructor XMLSecurityRuntimeException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public XMLSecurityRuntimeException(String _msgID, Object exArgs[],
-                               Exception _originalException) {
-
-      super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs));
+    /**
+     * Constructor XMLSecurityRuntimeException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public XMLSecurityRuntimeException(String msgID, Object exArgs[], Exception originalException) {
+        super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs));
 
-      this.msgID = _msgID;
-      this.originalException = _originalException;
-   }
+        this.msgID = msgID;
+    }
 
-   /**
-    * Method getMsgID
-    *
-    * @return the messageId
-    */
-   public String getMsgID() {
-
-      if (msgID == null) {
-         return "Missing message ID";
-      }
-      return msgID;
-   }
-
-   /** @inheritDoc */
-   public String toString() {
+    /**
+     * Method getMsgID
+     *
+     * @return the messageId
+     */
+    public String getMsgID() {
+        if (msgID == null) {
+            return "Missing message ID";
+        }
+        return msgID;
+    }
 
-      String s = this.getClass().getName();
-      String message = super.getLocalizedMessage();
-
-      if (message != null) {
-         message = s + ": " + message;
-      } else {
-         message = s;
-      }
+    /** @inheritDoc */
+    public String toString() {
+        String s = this.getClass().getName();
+        String message = super.getLocalizedMessage();
 
-      if (originalException != null) {
-         message = message + "\nOriginal Exception was "
-                   + originalException.toString();
-      }
+        if (message != null) {
+            message = s + ": " + message;
+        } else {
+            message = s;
+        }
 
-      return message;
-   }
+        if (this.getCause() != null) {
+            message = message + "\nOriginal Exception was " + this.getCause().toString();
+        }
 
-   /**
-    * Method printStackTrace
-    *
-    */
-   public void printStackTrace() {
+        return message;
+    }
 
-      synchronized (System.err) {
-         super.printStackTrace(System.err);
-
-         if (this.originalException != null) {
-            this.originalException.printStackTrace(System.err);
-         }
-      }
-   }
+    /**
+     * Method printStackTrace
+     *
+     */
+    public void printStackTrace() {
+        synchronized (System.err) {
+            super.printStackTrace(System.err);
+        }
+    }
 
-   /**
-    * Method printStackTrace
-    *
-    * @param printwriter
-    */
-   public void printStackTrace(PrintWriter printwriter) {
-
-      super.printStackTrace(printwriter);
-
-      if (this.originalException != null) {
-         this.originalException.printStackTrace(printwriter);
-      }
-   }
+    /**
+     * Method printStackTrace
+     *
+     * @param printwriter
+     */
+    public void printStackTrace(PrintWriter printwriter) {
+        super.printStackTrace(printwriter);
+    }
 
-   /**
-    * Method printStackTrace
-    *
-    * @param printstream
-    */
-   public void printStackTrace(PrintStream printstream) {
-
-      super.printStackTrace(printstream);
+    /**
+     * Method printStackTrace
+     *
+     * @param printstream
+     */
+    public void printStackTrace(PrintStream printstream) {
+        super.printStackTrace(printstream);
+    }
 
-      if (this.originalException != null) {
-         this.originalException.printStackTrace(printstream);
-      }
-   }
+    /**
+     * Method getOriginalException
+     *
+     * @return the original exception
+     */
+    public Exception getOriginalException() {
+        if (this.getCause() instanceof Exception) {
+            return (Exception)this.getCause();
+        }
+        return null;
+    }
 
-   /**
-    * Method getOriginalException
-    *
-    * @return the original exception
-    */
-   public Exception getOriginalException() {
-      return originalException;
-   }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,89 +2,83 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys;
 
-
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 
+public class ContentHandlerAlreadyRegisteredException extends XMLSecurityException {
 
-/**
- *
- * @author $Author: mullan $
- */
-public class ContentHandlerAlreadyRegisteredException
-        extends XMLSecurityException {
-
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
 
-   /**
-    * Constructor ContentHandlerAlreadyRegisteredException
-    *
-    */
-   public ContentHandlerAlreadyRegisteredException() {
-      super();
-   }
+    /**
+     * Constructor ContentHandlerAlreadyRegisteredException
+     *
+     */
+    public ContentHandlerAlreadyRegisteredException() {
+        super();
+    }
 
-   /**
-    * Constructor ContentHandlerAlreadyRegisteredException
-    *
-    * @param _msgID
-    */
-   public ContentHandlerAlreadyRegisteredException(String _msgID) {
-      super(_msgID);
-   }
+    /**
+     * Constructor ContentHandlerAlreadyRegisteredException
+     *
+     * @param msgID
+     */
+    public ContentHandlerAlreadyRegisteredException(String msgID) {
+        super(msgID);
+    }
 
-   /**
-    * Constructor ContentHandlerAlreadyRegisteredException
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public ContentHandlerAlreadyRegisteredException(String _msgID,
-           Object exArgs[]) {
-      super(_msgID, exArgs);
-   }
+    /**
+     * Constructor ContentHandlerAlreadyRegisteredException
+     *
+     * @param msgID
+     * @param exArgs
+     */
+    public ContentHandlerAlreadyRegisteredException(String msgID, Object exArgs[]) {
+        super(msgID, exArgs);
+    }
 
-   /**
-    * Constructor ContentHandlerAlreadyRegisteredException
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public ContentHandlerAlreadyRegisteredException(String _msgID,
-           Exception _originalException) {
-      super(_msgID, _originalException);
-   }
+    /**
+     * Constructor ContentHandlerAlreadyRegisteredException
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public ContentHandlerAlreadyRegisteredException(String msgID, Exception originalException) {
+        super(msgID, originalException);
+    }
 
-   /**
-    * Constructor ContentHandlerAlreadyRegisteredException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public ContentHandlerAlreadyRegisteredException(String _msgID,
-           Object exArgs[], Exception _originalException) {
-      super(_msgID, exArgs, _originalException);
-   }
+    /**
+     * Constructor ContentHandlerAlreadyRegisteredException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public ContentHandlerAlreadyRegisteredException(
+        String msgID, Object exArgs[], Exception originalException
+    ) {
+        super(msgID, exArgs, originalException);
+    }
+
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,30 +2,30 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys;
 
-
-
+import java.security.PrivateKey;
 import java.security.PublicKey;
 import java.security.cert.X509Certificate;
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
 
@@ -35,6 +35,8 @@
 import com.sun.org.apache.xml.internal.security.encryption.XMLCipher;
 import com.sun.org.apache.xml.internal.security.encryption.XMLEncryptionException;
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+import com.sun.org.apache.xml.internal.security.keys.content.DEREncodedKeyValue;
+import com.sun.org.apache.xml.internal.security.keys.content.KeyInfoReference;
 import com.sun.org.apache.xml.internal.security.keys.content.KeyName;
 import com.sun.org.apache.xml.internal.security.keys.content.KeyValue;
 import com.sun.org.apache.xml.internal.security.keys.content.MgmtData;
@@ -49,9 +51,8 @@
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
 import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
 import com.sun.org.apache.xml.internal.security.transforms.Transforms;
+import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants;
-import com.sun.org.apache.xml.internal.security.utils.Constants;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Attr;
@@ -60,7 +61,6 @@
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 
-
 /**
  * This class stand for KeyInfo Element that may contain keys, names,
  * certificates and other public key management information,
@@ -91,639 +91,769 @@
  * The <CODE>containsXXX()</CODE> methods return <I>whether</I> the KeyInfo
  * contains the corresponding type.
  *
- * @author $Author: mullan $
  */
 public class KeyInfo extends SignatureElementProxy {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(KeyInfo.class.getName());
-    List<X509Data> x509Datas=null;
-    List<EncryptedKey> encryptedKeys=null;
+
+    // We need at least one StorageResolver otherwise
+    // the KeyResolvers would not be called.
+    // The default StorageResolver is null.
 
-    static final List<StorageResolver> nullList;
+    private List<X509Data> x509Datas = null;
+    private List<EncryptedKey> encryptedKeys = null;
+
+    private static final List<StorageResolver> nullList;
     static {
         List<StorageResolver> list = new ArrayList<StorageResolver>(1);
         list.add(null);
-        nullList = Collections.unmodifiableList(list);
+        nullList = java.util.Collections.unmodifiableList(list);
+    }
+
+    /** Field storageResolvers */
+    private List<StorageResolver> storageResolvers = nullList;
+
+    /**
+     * Stores the individual (per-KeyInfo) {@link KeyResolverSpi}s
+     */
+    private List<KeyResolverSpi> internalKeyResolvers = new ArrayList<KeyResolverSpi>();
+
+    private boolean secureValidation;
+
+    /**
+     * Constructor KeyInfo
+     * @param doc
+     */
+    public KeyInfo(Document doc) {
+        super(doc);
+
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
+
+    /**
+     * Constructor KeyInfo
+     *
+     * @param element
+     * @param baseURI
+     * @throws XMLSecurityException
+     */
+    public KeyInfo(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
+
+        Attr attr = element.getAttributeNodeNS(null, "Id");
+        if (attr != null) {
+            element.setIdAttributeNode(attr, true);
+        }
+    }
+
+    /**
+     * Set whether secure processing is enabled or not. The default is false.
+     */
+    public void setSecureValidation(boolean secureValidation) {
+        this.secureValidation = secureValidation;
+    }
+
+    /**
+     * Sets the <code>Id</code> attribute
+     *
+     * @param Id ID
+     */
+    public void setId(String id) {
+        if (id != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
+            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+        }
+    }
+
+    /**
+     * Returns the <code>Id</code> attribute
+     *
+     * @return the <code>Id</code> attribute
+     */
+    public String getId() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+    }
+
+    /**
+     * Method addKeyName
+     *
+     * @param keynameString
+     */
+    public void addKeyName(String keynameString) {
+        this.add(new KeyName(this.doc, keynameString));
+    }
+
+    /**
+     * Method add
+     *
+     * @param keyname
+     */
+    public void add(KeyName keyname) {
+        this.constructionElement.appendChild(keyname.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
+
+    /**
+     * Method addKeyValue
+     *
+     * @param pk
+     */
+    public void addKeyValue(PublicKey pk) {
+        this.add(new KeyValue(this.doc, pk));
+    }
+
+    /**
+     * Method addKeyValue
+     *
+     * @param unknownKeyValueElement
+     */
+    public void addKeyValue(Element unknownKeyValueElement) {
+        this.add(new KeyValue(this.doc, unknownKeyValueElement));
+    }
+
+    /**
+     * Method add
+     *
+     * @param dsakeyvalue
+     */
+    public void add(DSAKeyValue dsakeyvalue) {
+        this.add(new KeyValue(this.doc, dsakeyvalue));
+    }
+
+    /**
+     * Method add
+     *
+     * @param rsakeyvalue
+     */
+    public void add(RSAKeyValue rsakeyvalue) {
+        this.add(new KeyValue(this.doc, rsakeyvalue));
+    }
+
+    /**
+     * Method add
+     *
+     * @param pk
+     */
+    public void add(PublicKey pk) {
+        this.add(new KeyValue(this.doc, pk));
+    }
+
+    /**
+     * Method add
+     *
+     * @param keyvalue
+     */
+    public void add(KeyValue keyvalue) {
+        this.constructionElement.appendChild(keyvalue.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
+
+    /**
+     * Method addMgmtData
+     *
+     * @param mgmtdata
+     */
+    public void addMgmtData(String mgmtdata) {
+        this.add(new MgmtData(this.doc, mgmtdata));
+    }
+
+    /**
+     * Method add
+     *
+     * @param mgmtdata
+     */
+    public void add(MgmtData mgmtdata) {
+        this.constructionElement.appendChild(mgmtdata.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
+
+    /**
+     * Method addPGPData
+     *
+     * @param pgpdata
+     */
+    public void add(PGPData pgpdata) {
+        this.constructionElement.appendChild(pgpdata.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
+
+    /**
+     * Method addRetrievalMethod
+     *
+     * @param uri
+     * @param transforms
+     * @param Type
+     */
+    public void addRetrievalMethod(String uri, Transforms transforms, String Type) {
+        this.add(new RetrievalMethod(this.doc, uri, transforms, Type));
+    }
+
+    /**
+     * Method add
+     *
+     * @param retrievalmethod
+     */
+    public void add(RetrievalMethod retrievalmethod) {
+        this.constructionElement.appendChild(retrievalmethod.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
     }
 
-   /**
-    * Constructor KeyInfo
-    * @param doc
-    */
-   public KeyInfo(Document doc) {
-
-      super(doc);
-
-      XMLUtils.addReturnToElement(this._constructionElement);
-
-   }
-
-   /**
-    * Constructor KeyInfo
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public KeyInfo(Element element, String BaseURI) throws XMLSecurityException {
-      super(element, BaseURI);
+    /**
+     * Method add
+     *
+     * @param spkidata
+     */
+    public void add(SPKIData spkidata) {
+        this.constructionElement.appendChild(spkidata.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-      Attr attr = element.getAttributeNodeNS(null, "Id");
-      if (attr != null) {
-          element.setIdAttributeNode(attr, true);
-      }
-   }
-
-   /**
-    * Sets the <code>Id</code> attribute
-    *
-    * @param Id ID
-    */
-   public void setId(String Id) {
+    /**
+     * Method addX509Data
+     *
+     * @param x509data
+     */
+    public void add(X509Data x509data) {
+        if (x509Datas == null) {
+            x509Datas = new ArrayList<X509Data>();
+        }
+        x509Datas.add(x509data);
+        this.constructionElement.appendChild(x509data.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-      if (Id != null) {
-          setLocalIdAttribute(Constants._ATT_ID, Id);
-      }
-   }
+    /**
+     * Method addEncryptedKey
+     *
+     * @param encryptedKey
+     * @throws XMLEncryptionException
+     */
 
-   /**
-    * Returns the <code>Id</code> attribute
-    *
-    * @return the <code>Id</code> attribute
-    */
-   public String getId() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
-   }
+    public void add(EncryptedKey encryptedKey) throws XMLEncryptionException {
+        if (encryptedKeys == null) {
+            encryptedKeys = new ArrayList<EncryptedKey>();
+        }
+        encryptedKeys.add(encryptedKey);
+        XMLCipher cipher = XMLCipher.getInstance();
+        this.constructionElement.appendChild(cipher.martial(encryptedKey));
+    }
 
-   /**
-    * Method addKeyName
-    *
-    * @param keynameString
-    */
-   public void addKeyName(String keynameString) {
-      this.add(new KeyName(this._doc, keynameString));
-   }
+    /**
+     * Method addDEREncodedKeyValue
+     *
+     * @param pk
+     * @throws XMLSecurityException
+     */
+    public void addDEREncodedKeyValue(PublicKey pk) throws XMLSecurityException {
+        this.add(new DEREncodedKeyValue(this.doc, pk));
+    }
 
-   /**
-    * Method add
-    *
-    * @param keyname
-    */
-   public void add(KeyName keyname) {
-
-         this._constructionElement.appendChild(keyname.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-   }
+    /**
+     * Method add
+     *
+     * @param derEncodedKeyValue
+     */
+    public void add(DEREncodedKeyValue derEncodedKeyValue) {
+        this.constructionElement.appendChild(derEncodedKeyValue.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-   /**
-    * Method addKeyValue
-    *
-    * @param pk
-    */
-   public void addKeyValue(PublicKey pk) {
-      this.add(new KeyValue(this._doc, pk));
-   }
-
-   /**
-    * Method addKeyValue
-    *
-    * @param unknownKeyValueElement
-    */
-   public void addKeyValue(Element unknownKeyValueElement) {
-      this.add(new KeyValue(this._doc, unknownKeyValueElement));
-   }
+    /**
+     * Method addKeyInfoReference
+     *
+     * @param URI
+     * @throws XMLSecurityException
+     */
+    public void addKeyInfoReference(String URI) throws XMLSecurityException {
+        this.add(new KeyInfoReference(this.doc, URI));
+    }
 
-   /**
-    * Method add
-    *
-    * @param dsakeyvalue
-    */
-   public void add(DSAKeyValue dsakeyvalue) {
-      this.add(new KeyValue(this._doc, dsakeyvalue));
-   }
+    /**
+     * Method add
+     *
+     * @param keyInfoReference
+     */
+    public void add(KeyInfoReference keyInfoReference) {
+        this.constructionElement.appendChild(keyInfoReference.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-   /**
-    * Method add
-    *
-    * @param rsakeyvalue
-    */
-   public void add(RSAKeyValue rsakeyvalue) {
-      this.add(new KeyValue(this._doc, rsakeyvalue));
-   }
+    /**
+     * Method addUnknownElement
+     *
+     * @param element
+     */
+    public void addUnknownElement(Element element) {
+        this.constructionElement.appendChild(element);
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-   /**
-    * Method add
-    *
-    * @param pk
-    */
-   public void add(PublicKey pk) {
-      this.add(new KeyValue(this._doc, pk));
-   }
+    /**
+     * Method lengthKeyName
+     *
+     * @return the number of the KeyName tags
+     */
+    public int lengthKeyName() {
+        return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYNAME);
+    }
 
-   /**
-    * Method add
-    *
-    * @param keyvalue
-    */
-   public void add(KeyValue keyvalue) {
-         this._constructionElement.appendChild(keyvalue.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-   }
+    /**
+     * Method lengthKeyValue
+     *
+     *@return the number of the KeyValue tags
+     */
+    public int lengthKeyValue() {
+        return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYVALUE);
+    }
 
-   /**
-    * Method addMgmtData
-    *
-    * @param mgmtdata
-    */
-   public void addMgmtData(String mgmtdata) {
-      this.add(new MgmtData(this._doc, mgmtdata));
-   }
+    /**
+     * Method lengthMgmtData
+     *
+     *@return the number of the MgmtData tags
+     */
+    public int lengthMgmtData() {
+        return this.length(Constants.SignatureSpecNS, Constants._TAG_MGMTDATA);
+    }
 
-   /**
-    * Method add
-    *
-    * @param mgmtdata
-    */
-   public void add(MgmtData mgmtdata) {
-         this._constructionElement.appendChild(mgmtdata.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-   }
+    /**
+     * Method lengthPGPData
+     *
+     *@return the number of the PGPDat. tags
+     */
+    public int lengthPGPData() {
+        return this.length(Constants.SignatureSpecNS, Constants._TAG_PGPDATA);
+    }
 
-   /**
-    * Method addPGPData
-    *
-    * @param pgpdata
-    */
-   public void add(PGPData pgpdata) {
-         this._constructionElement.appendChild(pgpdata.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-   }
+    /**
+     * Method lengthRetrievalMethod
+     *
+     *@return the number of the RetrievalMethod tags
+     */
+    public int lengthRetrievalMethod() {
+        return this.length(Constants.SignatureSpecNS, Constants._TAG_RETRIEVALMETHOD);
+    }
 
-   /**
-    * Method addRetrievalMethod
-    *
-    * @param URI
-    * @param transforms
-    * @param Type
-    */
-   public void addRetrievalMethod(String URI, Transforms transforms,
-                                  String Type) {
-      this.add(new RetrievalMethod(this._doc, URI, transforms, Type));
-   }
+    /**
+     * Method lengthSPKIData
+     *
+     *@return the number of the SPKIData tags
+     */
+    public int lengthSPKIData() {
+        return this.length(Constants.SignatureSpecNS, Constants._TAG_SPKIDATA);
+    }
 
-   /**
-    * Method add
-    *
-    * @param retrievalmethod
-    */
-   public void add(RetrievalMethod retrievalmethod) {
-         this._constructionElement.appendChild(retrievalmethod.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-   }
+    /**
+     * Method lengthX509Data
+     *
+     *@return the number of the X509Data tags
+     */
+    public int lengthX509Data() {
+        if (x509Datas != null) {
+            return x509Datas.size();
+        }
+        return this.length(Constants.SignatureSpecNS, Constants._TAG_X509DATA);
+    }
+
+    /**
+     * Method lengthDEREncodedKeyValue
+     *
+     *@return the number of the DEREncodedKeyValue tags
+     */
+    public int lengthDEREncodedKeyValue() {
+        return this.length(Constants.SignatureSpec11NS, Constants._TAG_DERENCODEDKEYVALUE);
+    }
 
-   /**
-    * Method add
-    *
-    * @param spkidata
-    */
-   public void add(SPKIData spkidata) {
-         this._constructionElement.appendChild(spkidata.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-   }
+    /**
+     * Method lengthKeyInfoReference
+     *
+     *@return the number of the KeyInfoReference tags
+     */
+    public int lengthKeyInfoReference() {
+        return this.length(Constants.SignatureSpec11NS, Constants._TAG_KEYINFOREFERENCE);
+    }
 
-   /**
-    * Method addX509Data
-    *
-    * @param x509data
-    */
-   public void add(X509Data x509data) {
-          if (x509Datas==null)
-                  x509Datas=new ArrayList<X509Data>();
-          x509Datas.add(x509data);
-         this._constructionElement.appendChild(x509data.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-   }
+    /**
+     * Method lengthUnknownElement
+     * NOTE possibly buggy.
+     * @return the number of the UnknownElement tags
+     */
+    public int lengthUnknownElement() {
+        int res = 0;
+        NodeList nl = this.constructionElement.getChildNodes();
 
-        /**
-         * Method addEncryptedKey
-         *
-         * @param encryptedKey
-         * @throws XMLEncryptionException
-         */
+        for (int i = 0; i < nl.getLength(); i++) {
+            Node current = nl.item(i);
 
-        public void add(EncryptedKey encryptedKey)
-                throws XMLEncryptionException {
-                        if (encryptedKeys==null)
-                                encryptedKeys=new ArrayList<EncryptedKey>();
-                        encryptedKeys.add(encryptedKey);
-                        XMLCipher cipher = XMLCipher.getInstance();
-                        this._constructionElement.appendChild(cipher.martial(encryptedKey));
+            /**
+             * $todo$ using this method, we don't see unknown Elements
+             *  from Signature NS; revisit
+             */
+            if ((current.getNodeType() == Node.ELEMENT_NODE)
+                && current.getNamespaceURI().equals(Constants.SignatureSpecNS)) {
+                res++;
+            }
         }
 
-   /**
-    * Method addUnknownElement
-    *
-    * @param element
-    */
-   public void addUnknownElement(Element element) {
-         this._constructionElement.appendChild(element);
-         XMLUtils.addReturnToElement(this._constructionElement);
-   }
+        return res;
+    }
 
-   /**
-    * Method lengthKeyName
-    *
-    * @return the number of the KeyName tags
-    */
-   public int lengthKeyName() {
-      return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYNAME);
-   }
-
-   /**
-    * Method lengthKeyValue
-    *
-    *@return the number of the KeyValue tags
-    */
-   public int lengthKeyValue() {
-      return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYVALUE);
-   }
-
-   /**
-    * Method lengthMgmtData
-    *
-    *@return the number of the MgmtData tags
-    */
-   public int lengthMgmtData() {
-      return this.length(Constants.SignatureSpecNS, Constants._TAG_MGMTDATA);
-   }
+    /**
+     * Method itemKeyName
+     *
+     * @param i
+     * @return the asked KeyName element, null if the index is too big
+     * @throws XMLSecurityException
+     */
+    public KeyName itemKeyName(int i) throws XMLSecurityException {
+        Element e =
+            XMLUtils.selectDsNode(
+                this.constructionElement.getFirstChild(), Constants._TAG_KEYNAME, i);
 
-   /**
-    * Method lengthPGPData
-    *
-    *@return the number of the PGPDat. tags
-    */
-   public int lengthPGPData() {
-      return this.length(Constants.SignatureSpecNS, Constants._TAG_PGPDATA);
-   }
-
-   /**
-    * Method lengthRetrievalMethod
-    *
-    *@return the number of the RetrievalMethod tags
-    */
-   public int lengthRetrievalMethod() {
-      return this.length(Constants.SignatureSpecNS,
-                         Constants._TAG_RETRIEVALMETHOD);
-   }
+        if (e != null) {
+            return new KeyName(e, this.baseURI);
+        }
+        return null;
+    }
 
-   /**
-    * Method lengthSPKIData
-    *
-    *@return the number of the SPKIData tags
-    */
-   public int lengthSPKIData() {
-      return this.length(Constants.SignatureSpecNS, Constants._TAG_SPKIDATA);
-   }
-
-   /**
-    * Method lengthX509Data
-    *
-    *@return the number of the X509Data tags
-    */
-   public int lengthX509Data() {
-           if (x509Datas!=null) {
-                   return x509Datas.size();
-           }
-      return this.length(Constants.SignatureSpecNS, Constants._TAG_X509DATA);
-   }
-
-   /**
-    * Method lengthUnknownElement
-    * NOTE posibly buggy.
-    *@return the number of the UnknownElement tags
-    */
-   public int lengthUnknownElement() {
-
-      int res = 0;
-      NodeList nl = this._constructionElement.getChildNodes();
-
-      for (int i = 0; i < nl.getLength(); i++) {
-         Node current = nl.item(i);
+    /**
+     * Method itemKeyValue
+     *
+     * @param i
+     * @return the asked KeyValue element, null if the index is too big
+     * @throws XMLSecurityException
+     */
+    public KeyValue itemKeyValue(int i) throws XMLSecurityException {
+        Element e =
+            XMLUtils.selectDsNode(
+                this.constructionElement.getFirstChild(), Constants._TAG_KEYVALUE, i);
 
-         /**
-          * $todo$ using this method, we don't see unknown Elements
-          *  from Signature NS; revisit
-          */
-         if ((current.getNodeType() == Node.ELEMENT_NODE)
-                 && current.getNamespaceURI()
-                    .equals(Constants.SignatureSpecNS)) {
-            res++;
-         }
-      }
-
-      return res;
-   }
-
-   /**
-    * Method itemKeyName
-    *
-    * @param i
-    * @return the asked KeyName element, null if the index is too big
-    * @throws XMLSecurityException
-    */
-   public KeyName itemKeyName(int i) throws XMLSecurityException {
+        if (e != null) {
+            return new KeyValue(e, this.baseURI);
+        }
+        return null;
+    }
 
-      Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
-                                                Constants._TAG_KEYNAME,i);
-
-      if (e != null) {
-         return new KeyName(e, this._baseURI);
-      }
-      return null;
-   }
-
-   /**
-    * Method itemKeyValue
-    *
-    * @param i
-    * @return the asked KeyValue element, null if the index is too big
-    * @throws XMLSecurityException
-    */
-   public KeyValue itemKeyValue(int i) throws XMLSecurityException {
-
-      Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
-                                                Constants._TAG_KEYVALUE,i);
-
-      if (e != null) {
-         return new KeyValue(e, this._baseURI);
-      }
-      return null;
-   }
+    /**
+     * Method itemMgmtData
+     *
+     * @param i
+     * @return the asked MgmtData element, null if the index is too big
+     * @throws XMLSecurityException
+     */
+    public MgmtData itemMgmtData(int i) throws XMLSecurityException {
+        Element e =
+            XMLUtils.selectDsNode(
+                this.constructionElement.getFirstChild(), Constants._TAG_MGMTDATA, i);
 
-   /**
-    * Method itemMgmtData
-    *
-    * @param i
-    *@return the asked MgmtData element, null if the index is too big
-    * @throws XMLSecurityException
-    */
-   public MgmtData itemMgmtData(int i) throws XMLSecurityException {
-
-      Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
-                                                Constants._TAG_MGMTDATA,i);
-
-      if (e != null) {
-         return new MgmtData(e, this._baseURI);
-      }
-       return null;
-   }
-
-   /**
-    * Method itemPGPData
-    *
-    * @param i
-    *@return the asked PGPData element, null if the index is too big
-    * @throws XMLSecurityException
-    */
-   public PGPData itemPGPData(int i) throws XMLSecurityException {
+        if (e != null) {
+            return new MgmtData(e, this.baseURI);
+        }
+        return null;
+    }
 
-      Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
-                                                Constants._TAG_PGPDATA,i);
-
-      if (e != null) {
-         return new PGPData(e, this._baseURI);
-      }
-      return null;
-   }
+    /**
+     * Method itemPGPData
+     *
+     * @param i
+     * @return the asked PGPData element, null if the index is too big
+     * @throws XMLSecurityException
+     */
+    public PGPData itemPGPData(int i) throws XMLSecurityException {
+        Element e =
+            XMLUtils.selectDsNode(
+                this.constructionElement.getFirstChild(), Constants._TAG_PGPDATA, i);
 
-   /**
-    * Method itemRetrievalMethod
-    *
-    * @param i
-    *@return the asked RetrievalMethod element, null if the index is too big
-    * @throws XMLSecurityException
-    */
-   public RetrievalMethod itemRetrievalMethod(int i)
-           throws XMLSecurityException {
-
-      Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
-                                                Constants._TAG_RETRIEVALMETHOD,i);
-
-      if (e != null) {
-         return new RetrievalMethod(e, this._baseURI);
-      }
-      return null;
-   }
+        if (e != null) {
+            return new PGPData(e, this.baseURI);
+        }
+        return null;
+    }
 
-   /**
-    * Method itemSPKIData
-    *
-    * @param i
-    *@return the asked SPKIData element, null if the index is too big
-    * @throws XMLSecurityException
-    */
-   public SPKIData itemSPKIData(int i) throws XMLSecurityException {
-
-      Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
-                                                Constants._TAG_SPKIDATA,i);
-
-      if (e != null) {
-         return new SPKIData(e, this._baseURI);
-      }
-      return null;
-   }
+    /**
+     * Method itemRetrievalMethod
+     *
+     * @param i
+     *@return the asked RetrievalMethod element, null if the index is too big
+     * @throws XMLSecurityException
+     */
+    public RetrievalMethod itemRetrievalMethod(int i) throws XMLSecurityException {
+        Element e =
+            XMLUtils.selectDsNode(
+                this.constructionElement.getFirstChild(), Constants._TAG_RETRIEVALMETHOD, i);
 
-   /**
-    * Method itemX509Data
-    *@return the asked X509Data element, null if the index is too big
-    * @param i
-    *
-    * @throws XMLSecurityException
-    */
-   public X509Data itemX509Data(int i) throws XMLSecurityException {
-           if (x509Datas!=null) {
-                   return x509Datas.get(i);
-           }
-      Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
-                                                Constants._TAG_X509DATA,i);
-
-      if (e != null) {
-         return new X509Data(e, this._baseURI);
-      }
-      return null;
-   }
-
-   /**
-        * Method itemEncryptedKey
-        *
-        * @param i
-        * @return the asked EncryptedKey element, null if the index is too big
-        * @throws XMLSecurityException
-        */
+        if (e != null) {
+            return new RetrievalMethod(e, this.baseURI);
+        }
+        return null;
+    }
 
-        public EncryptedKey itemEncryptedKey(int i) throws XMLSecurityException {
-                if (encryptedKeys!=null) {
-                        return encryptedKeys.get(i);
-                }
-                Element e =
-                        XMLUtils.selectXencNode(this._constructionElement.getFirstChild(),
-                                                                                  EncryptionConstants._TAG_ENCRYPTEDKEY,i);
-
-                if (e != null) {
-                        XMLCipher cipher = XMLCipher.getInstance();
-                        cipher.init(XMLCipher.UNWRAP_MODE, null);
-                        return cipher.loadEncryptedKey(e);
-                }
-                return null;
-   }
-
-   /**
-    * Method itemUnknownElement
-    *
-    * @param i index
-    * @return the element number of the unknown elemens
-    */
-   public Element itemUnknownElement(int i) {
+    /**
+     * Method itemSPKIData
+     *
+     * @param i
+     * @return the asked SPKIData element, null if the index is too big
+     * @throws XMLSecurityException
+     */
+    public SPKIData itemSPKIData(int i) throws XMLSecurityException {
+        Element e =
+            XMLUtils.selectDsNode(
+                this.constructionElement.getFirstChild(), Constants._TAG_SPKIDATA, i);
 
-      NodeList nl = this._constructionElement.getChildNodes();
-      int res = 0;
-
-      for (int j = 0; j < nl.getLength(); j++) {
-         Node current = nl.item(j);
-
-         /**
-          * $todo$ using this method, we don't see unknown Elements
-          *  from Signature NS; revisit
-          */
-         if ((current.getNodeType() == Node.ELEMENT_NODE)
-                 && current.getNamespaceURI()
-                    .equals(Constants.SignatureSpecNS)) {
-            res++;
-
-            if (res == i) {
-               return (Element) current;
-            }
-         }
-      }
-
-      return null;
-   }
+        if (e != null) {
+            return new SPKIData(e, this.baseURI);
+        }
+        return null;
+    }
 
-   /**
-    * Method isEmpty
-    *
-    * @return true if the element has no descedants.
-    */
-   public boolean isEmpty() {
-      return this._constructionElement.getFirstChild()==null;
-   }
-
-   /**
-    * Method containsKeyName
-    *
-    * @return If the KeyInfo contains a KeyName node
-    */
-   public boolean containsKeyName() {
-      return this.lengthKeyName() > 0;
-   }
-
-   /**
-    * Method containsKeyValue
-    *
-    * @return If the KeyInfo contains a KeyValue node
-    */
-   public boolean containsKeyValue() {
-      return this.lengthKeyValue() > 0;
-   }
+    /**
+     * Method itemX509Data
+     *
+     * @param i
+     * @return the asked X509Data element, null if the index is too big
+     * @throws XMLSecurityException
+     */
+    public X509Data itemX509Data(int i) throws XMLSecurityException {
+        if (x509Datas != null) {
+            return x509Datas.get(i);
+        }
+        Element e =
+            XMLUtils.selectDsNode(
+                this.constructionElement.getFirstChild(), Constants._TAG_X509DATA, i);
 
-   /**
-    * Method containsMgmtData
-    *
-    * @return If the KeyInfo contains a MgmtData node
-    */
-   public boolean containsMgmtData() {
-      return this.lengthMgmtData() > 0;
-   }
-
-   /**
-    * Method containsPGPData
-    *
-    * @return If the KeyInfo contains a PGPData node
-    */
-   public boolean containsPGPData() {
-      return this.lengthPGPData() > 0;
-   }
-
-   /**
-    * Method containsRetrievalMethod
-    *
-    * @return If the KeyInfo contains a RetrievalMethod node
-    */
-   public boolean containsRetrievalMethod() {
-      return this.lengthRetrievalMethod() > 0;
-   }
+        if (e != null) {
+            return new X509Data(e, this.baseURI);
+        }
+        return null;
+    }
 
-   /**
-    * Method containsSPKIData
-    *
-    * @return If the KeyInfo contains a SPKIData node
-    */
-   public boolean containsSPKIData() {
-      return this.lengthSPKIData() > 0;
-   }
-
-   /**
-    * Method containsUnknownElement
-    *
-    * @return If the KeyInfo contains a UnknownElement node
-    */
-   public boolean containsUnknownElement() {
-      return this.lengthUnknownElement() > 0;
-   }
-
-   /**
-    * Method containsX509Data
-    *
-    * @return If the KeyInfo contains a X509Data node
-    */
-   public boolean containsX509Data() {
-      return this.lengthX509Data() > 0;
-   }
+    /**
+     * Method itemEncryptedKey
+     *
+     * @param i
+     * @return the asked EncryptedKey element, null if the index is too big
+     * @throws XMLSecurityException
+     */
+    public EncryptedKey itemEncryptedKey(int i) throws XMLSecurityException {
+        if (encryptedKeys != null) {
+            return encryptedKeys.get(i);
+        }
+        Element e =
+            XMLUtils.selectXencNode(
+                this.constructionElement.getFirstChild(), EncryptionConstants._TAG_ENCRYPTEDKEY, i);
 
-   /**
-    * This method returns the public key.
-    *
-    * @return If the KeyInfo contains a PublicKey node
-    * @throws KeyResolverException
-    */
-
-   public PublicKey getPublicKey() throws KeyResolverException {
-
-      PublicKey pk = this.getPublicKeyFromInternalResolvers();
-
-      if (pk != null) {
-         log.log(java.util.logging.Level.FINE, "I could find a key using the per-KeyInfo key resolvers");
+        if (e != null) {
+            XMLCipher cipher = XMLCipher.getInstance();
+            cipher.init(XMLCipher.UNWRAP_MODE, null);
+            return cipher.loadEncryptedKey(e);
+        }
+        return null;
+    }
 
-         return pk;
-      }
-      log.log(java.util.logging.Level.FINE, "I couldn't find a key using the per-KeyInfo key resolvers");
-
-      pk = this.getPublicKeyFromStaticResolvers();
+    /**
+     * Method itemDEREncodedKeyValue
+     *
+     * @param i
+     * @return the asked DEREncodedKeyValue element, null if the index is too big
+     * @throws XMLSecurityException
+     */
+    public DEREncodedKeyValue itemDEREncodedKeyValue(int i) throws XMLSecurityException {
+        Element e =
+            XMLUtils.selectDs11Node(
+                this.constructionElement.getFirstChild(), Constants._TAG_DERENCODEDKEYVALUE, i);
 
-      if (pk != null) {
-         log.log(java.util.logging.Level.FINE, "I could find a key using the system-wide key resolvers");
-
-         return pk;
-      }
-      log.log(java.util.logging.Level.FINE, "I couldn't find a key using the system-wide key resolvers");
-
-      return null;
-   }
+        if (e != null) {
+            return new DEREncodedKeyValue(e, this.baseURI);
+        }
+        return null;
+    }
 
     /**
-     * Searches the library wide keyresolvers for public keys
+     * Method itemKeyInfoReference
+     *
+     * @param i
+     * @return the asked KeyInfoReference element, null if the index is too big
+     * @throws XMLSecurityException
+     */
+    public KeyInfoReference itemKeyInfoReference(int i) throws XMLSecurityException {
+        Element e =
+            XMLUtils.selectDs11Node(
+                this.constructionElement.getFirstChild(), Constants._TAG_KEYINFOREFERENCE, i);
+
+        if (e != null) {
+            return new KeyInfoReference(e, this.baseURI);
+        }
+        return null;
+    }
+
+    /**
+     * Method itemUnknownElement
+     *
+     * @param i index
+     * @return the element number of the unknown elements
+     */
+    public Element itemUnknownElement(int i) {
+        NodeList nl = this.constructionElement.getChildNodes();
+        int res = 0;
+
+        for (int j = 0; j < nl.getLength(); j++) {
+            Node current = nl.item(j);
+
+            /**
+             * $todo$ using this method, we don't see unknown Elements
+             *  from Signature NS; revisit
+             */
+            if ((current.getNodeType() == Node.ELEMENT_NODE)
+                && current.getNamespaceURI().equals(Constants.SignatureSpecNS)) {
+                res++;
+
+                if (res == i) {
+                    return (Element) current;
+                }
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * Method isEmpty
+     *
+     * @return true if the element has no descendants.
+     */
+    public boolean isEmpty() {
+        return this.constructionElement.getFirstChild() == null;
+    }
+
+    /**
+     * Method containsKeyName
+     *
+     * @return If the KeyInfo contains a KeyName node
+     */
+    public boolean containsKeyName() {
+        return this.lengthKeyName() > 0;
+    }
+
+    /**
+     * Method containsKeyValue
+     *
+     * @return If the KeyInfo contains a KeyValue node
+     */
+    public boolean containsKeyValue() {
+        return this.lengthKeyValue() > 0;
+    }
+
+    /**
+     * Method containsMgmtData
+     *
+     * @return If the KeyInfo contains a MgmtData node
+     */
+    public boolean containsMgmtData() {
+        return this.lengthMgmtData() > 0;
+    }
+
+    /**
+     * Method containsPGPData
+     *
+     * @return If the KeyInfo contains a PGPData node
+     */
+    public boolean containsPGPData() {
+        return this.lengthPGPData() > 0;
+    }
+
+    /**
+     * Method containsRetrievalMethod
+     *
+     * @return If the KeyInfo contains a RetrievalMethod node
+     */
+    public boolean containsRetrievalMethod() {
+        return this.lengthRetrievalMethod() > 0;
+    }
+
+    /**
+     * Method containsSPKIData
+     *
+     * @return If the KeyInfo contains a SPKIData node
+     */
+    public boolean containsSPKIData() {
+        return this.lengthSPKIData() > 0;
+    }
+
+    /**
+     * Method containsUnknownElement
+     *
+     * @return If the KeyInfo contains a UnknownElement node
+     */
+    public boolean containsUnknownElement() {
+        return this.lengthUnknownElement() > 0;
+    }
+
+    /**
+     * Method containsX509Data
+     *
+     * @return If the KeyInfo contains a X509Data node
+     */
+    public boolean containsX509Data() {
+        return this.lengthX509Data() > 0;
+    }
+
+    /**
+     * Method containsDEREncodedKeyValue
+     *
+     * @return If the KeyInfo contains a DEREncodedKeyValue node
+     */
+    public boolean containsDEREncodedKeyValue() {
+        return this.lengthDEREncodedKeyValue() > 0;
+    }
+
+    /**
+     * Method containsKeyInfoReference
+     *
+     * @return If the KeyInfo contains a KeyInfoReference node
+     */
+    public boolean containsKeyInfoReference() {
+        return this.lengthKeyInfoReference() > 0;
+    }
+
+    /**
+     * This method returns the public key.
+     *
+     * @return If the KeyInfo contains a PublicKey node
+     * @throws KeyResolverException
+     */
+    public PublicKey getPublicKey() throws KeyResolverException {
+        PublicKey pk = this.getPublicKeyFromInternalResolvers();
+
+        if (pk != null) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "I could find a key using the per-KeyInfo key resolvers");
+            }
+
+            return pk;
+        }
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "I couldn't find a key using the per-KeyInfo key resolvers");
+        }
+
+        pk = this.getPublicKeyFromStaticResolvers();
+
+        if (pk != null) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "I could find a key using the system-wide key resolvers");
+            }
+
+            return pk;
+        }
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "I couldn't find a key using the system-wide key resolvers");
+        }
+
+        return null;
+    }
+
+    /**
+     * Searches the library wide KeyResolvers for public keys
      *
      * @return The public key contained in this Node.
      * @throws KeyResolverException
@@ -732,11 +862,12 @@
         Iterator<KeyResolverSpi> it = KeyResolver.iterator();
         while (it.hasNext()) {
             KeyResolverSpi keyResolver = it.next();
-            Node currentChild = this._constructionElement.getFirstChild();
+            keyResolver.setSecureValidation(secureValidation);
+            Node currentChild = this.constructionElement.getFirstChild();
             String uri = this.getBaseURI();
             while (currentChild != null) {
                 if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
-                    for (StorageResolver storage : _storageResolvers) {
+                    for (StorageResolver storage : storageResolvers) {
                         PublicKey pk =
                             keyResolver.engineLookupAndResolvePublicKey(
                                 (Element) currentChild, uri, storage
@@ -753,78 +884,77 @@
         return null;
     }
 
-   /**
-    * Searches the per-KeyInfo keyresolvers for public keys
-    *
-    * @return The publick contained in this Node.
-    * @throws KeyResolverException
-    */
-   PublicKey getPublicKeyFromInternalResolvers() throws KeyResolverException {
-          int length=lengthInternalKeyResolver();
-          int storageLength=this._storageResolvers.size();
-      for (int i = 0; i < length; i++) {
-         KeyResolverSpi keyResolver = this.itemInternalKeyResolver(i);
-         if (log.isLoggable(java.util.logging.Level.FINE))
+    /**
+     * Searches the per-KeyInfo KeyResolvers for public keys
+     *
+     * @return The public key contained in this Node.
+     * @throws KeyResolverException
+     */
+    PublicKey getPublicKeyFromInternalResolvers() throws KeyResolverException {
+        for (KeyResolverSpi keyResolver : internalKeyResolvers) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
                 log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName());
+            }
+            keyResolver.setSecureValidation(secureValidation);
+            Node currentChild = this.constructionElement.getFirstChild();
+            String uri = this.getBaseURI();
+            while (currentChild != null)      {
+                if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
+                    for (StorageResolver storage : storageResolvers) {
+                        PublicKey pk =
+                            keyResolver.engineLookupAndResolvePublicKey(
+                                (Element) currentChild, uri, storage
+                            );
 
-         Node currentChild=this._constructionElement.getFirstChild();
-         String uri=this.getBaseURI();
-         while (currentChild!=null)      {
-            if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
-               for (int k = 0; k < storageLength; k++) {
-                   StorageResolver storage =
-                       this._storageResolvers.get(k);
-                   PublicKey pk = keyResolver
-                           .engineLookupAndResolvePublicKey((Element) currentChild, uri, storage);
+                        if (pk != null) {
+                            return pk;
+                        }
+                    }
+                }
+                currentChild = currentChild.getNextSibling();
+            }
+        }
 
-                     if (pk != null) {
-                         return pk;
-                     }
-                  }
-            }
-            currentChild=currentChild.getNextSibling();
-         }
-      }
-
-      return null;
-   }
+        return null;
+    }
 
-   /**
-    * Method getX509Certificate
-    *
-    * @return The certificate contined in this KeyInfo
-    * @throws KeyResolverException
-    */
-   public X509Certificate getX509Certificate() throws KeyResolverException {
+    /**
+     * Method getX509Certificate
+     *
+     * @return The certificate contained in this KeyInfo
+     * @throws KeyResolverException
+     */
+    public X509Certificate getX509Certificate() throws KeyResolverException {
+        // First search using the individual resolvers from the user
+        X509Certificate cert = this.getX509CertificateFromInternalResolvers();
 
-      // First search using the individual resolvers from the user
-      X509Certificate cert = this.getX509CertificateFromInternalResolvers();
-
-      if (cert != null) {
-         log.log(java.util.logging.Level.FINE,
-            "I could find a X509Certificate using the per-KeyInfo key resolvers");
+        if (cert != null) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "I could find a X509Certificate using the per-KeyInfo key resolvers");
+            }
 
-         return cert;
-      }
-      log.log(java.util.logging.Level.FINE,
-            "I couldn't find a X509Certificate using the per-KeyInfo key resolvers");
+            return cert;
+        }
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "I couldn't find a X509Certificate using the per-KeyInfo key resolvers");
+        }
 
-
-      // Then use the system-wide Resolvers
-      cert = this.getX509CertificateFromStaticResolvers();
+        // Then use the system-wide Resolvers
+        cert = this.getX509CertificateFromStaticResolvers();
 
-      if (cert != null) {
-         log.log(java.util.logging.Level.FINE,
-            "I could find a X509Certificate using the system-wide key resolvers");
+        if (cert != null) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "I could find a X509Certificate using the system-wide key resolvers");
+            }
 
-         return cert;
-      }
-      log.log(java.util.logging.Level.FINE,
-            "I couldn't find a X509Certificate using the system-wide key resolvers");
+            return cert;
+        }
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "I couldn't find a X509Certificate using the system-wide key resolvers");
+        }
 
-
-      return null;
-   }
+        return null;
+    }
 
     /**
      * This method uses each System-wide {@link KeyResolver} to search the
@@ -846,6 +976,7 @@
         Iterator<KeyResolverSpi> it = KeyResolver.iterator();
         while (it.hasNext()) {
             KeyResolverSpi keyResolver = it.next();
+            keyResolver.setSecureValidation(secureValidation);
             X509Certificate cert = applyCurrentResolver(uri, keyResolver);
             if (cert != null) {
                 return cert;
@@ -857,10 +988,10 @@
     private X509Certificate applyCurrentResolver(
         String uri, KeyResolverSpi keyResolver
     ) throws KeyResolverException {
-        Node currentChild = this._constructionElement.getFirstChild();
+        Node currentChild = this.constructionElement.getFirstChild();
         while (currentChild != null)      {
             if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
-                for (StorageResolver storage : _storageResolvers) {
+                for (StorageResolver storage : storageResolvers) {
                     X509Certificate cert =
                         keyResolver.engineLookupResolveX509Certificate(
                             (Element) currentChild, uri, storage
@@ -879,7 +1010,7 @@
     /**
      * Method getX509CertificateFromInternalResolvers
      *
-     * @return The certificate contined in this KeyInfo
+     * @return The certificate contained in this KeyInfo
      * @throws KeyResolverException
      */
     X509Certificate getX509CertificateFromInternalResolvers()
@@ -891,10 +1022,11 @@
             );
         }
         String uri = this.getBaseURI();
-        for (KeyResolverSpi keyResolver : _internalKeyResolvers) {
+        for (KeyResolverSpi keyResolver : internalKeyResolvers) {
             if (log.isLoggable(java.util.logging.Level.FINE)) {
                 log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName());
             }
+            keyResolver.setSecureValidation(secureValidation);
             X509Certificate cert = applyCurrentResolver(uri, keyResolver);
             if (cert != null) {
                 return cert;
@@ -904,189 +1036,252 @@
         return null;
     }
 
-   /**
-    * This method returns a secret (symmetric) key. This is for XML Encryption.
-    * @return the secret key contained in this KeyInfo
-    * @throws KeyResolverException
-    */
-   public SecretKey getSecretKey() throws KeyResolverException {
-      SecretKey sk = this.getSecretKeyFromInternalResolvers();
+    /**
+     * This method returns a secret (symmetric) key. This is for XML Encryption.
+     * @return the secret key contained in this KeyInfo
+     * @throws KeyResolverException
+     */
+    public SecretKey getSecretKey() throws KeyResolverException {
+        SecretKey sk = this.getSecretKeyFromInternalResolvers();
+
+        if (sk != null) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "I could find a secret key using the per-KeyInfo key resolvers");
+            }
+
+            return sk;
+        }
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the per-KeyInfo key resolvers");
+        }
+
+        sk = this.getSecretKeyFromStaticResolvers();
+
+        if (sk != null) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "I could find a secret key using the system-wide key resolvers");
+            }
+
+            return sk;
+        }
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the system-wide key resolvers");
+        }
+
+        return null;
+    }
+
+    /**
+     * Searches the library wide KeyResolvers for Secret keys
+     *
+     * @return the secret key contained in this KeyInfo
+     * @throws KeyResolverException
+     */
+    SecretKey getSecretKeyFromStaticResolvers() throws KeyResolverException {
+        Iterator<KeyResolverSpi> it = KeyResolver.iterator();
+        while (it.hasNext()) {
+            KeyResolverSpi keyResolver = it.next();
+            keyResolver.setSecureValidation(secureValidation);
+
+            Node currentChild = this.constructionElement.getFirstChild();
+            String uri = this.getBaseURI();
+            while (currentChild != null)      {
+                if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
+                    for (StorageResolver storage : storageResolvers) {
+                        SecretKey sk =
+                            keyResolver.engineLookupAndResolveSecretKey(
+                                (Element) currentChild, uri, storage
+                            );
 
-      if (sk != null) {
-         log.log(java.util.logging.Level.FINE, "I could find a secret key using the per-KeyInfo key resolvers");
+                        if (sk != null) {
+                            return sk;
+                        }
+                    }
+                }
+                currentChild = currentChild.getNextSibling();
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Searches the per-KeyInfo KeyResolvers for secret keys
+     *
+     * @return the secret key contained in this KeyInfo
+     * @throws KeyResolverException
+     */
+
+    SecretKey getSecretKeyFromInternalResolvers() throws KeyResolverException {
+        for (KeyResolverSpi keyResolver : internalKeyResolvers) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName());
+            }
+            keyResolver.setSecureValidation(secureValidation);
+            Node currentChild = this.constructionElement.getFirstChild();
+            String uri = this.getBaseURI();
+            while (currentChild != null)      {
+                if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
+                    for (StorageResolver storage : storageResolvers) {
+                        SecretKey sk =
+                            keyResolver.engineLookupAndResolveSecretKey(
+                                (Element) currentChild, uri, storage
+                            );
+
+                        if (sk != null) {
+                            return sk;
+                        }
+                    }
+                }
+                currentChild = currentChild.getNextSibling();
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * This method returns a private key. This is for Key Transport in XML Encryption.
+     * @return the private key contained in this KeyInfo
+     * @throws KeyResolverException
+     */
+    public PrivateKey getPrivateKey() throws KeyResolverException {
+        PrivateKey pk = this.getPrivateKeyFromInternalResolvers();
+
+        if (pk != null) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "I could find a private key using the per-KeyInfo key resolvers");
+            }
+            return pk;
+        }
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the per-KeyInfo key resolvers");
+        }
 
-         return sk;
-      }
-      log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the per-KeyInfo key resolvers");
+        pk = this.getPrivateKeyFromStaticResolvers();
+        if (pk != null) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "I could find a private key using the system-wide key resolvers");
+            }
+            return pk;
+        }
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "I couldn't find a private key using the system-wide key resolvers");
+        }
+
+        return null;
+    }
 
+    /**
+     * Searches the library wide KeyResolvers for Private keys
+     *
+     * @return the private key contained in this KeyInfo
+     * @throws KeyResolverException
+     */
+    PrivateKey getPrivateKeyFromStaticResolvers() throws KeyResolverException {
+        Iterator<KeyResolverSpi> it = KeyResolver.iterator();
+        while (it.hasNext()) {
+            KeyResolverSpi keyResolver = it.next();
+            keyResolver.setSecureValidation(secureValidation);
 
-      sk = this.getSecretKeyFromStaticResolvers();
+            Node currentChild = this.constructionElement.getFirstChild();
+            String uri = this.getBaseURI();
+            while (currentChild != null)      {
+                if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
+                    // not using StorageResolvers at the moment
+                    // since they cannot return private keys
+                    PrivateKey pk =
+                        keyResolver.engineLookupAndResolvePrivateKey(
+                            (Element) currentChild, uri, null
+                        );
+
+                    if (pk != null) {
+                        return pk;
+                    }
+                }
+                currentChild = currentChild.getNextSibling();
+            }
+        }
+        return null;
+    }
 
-      if (sk != null) {
-         log.log(java.util.logging.Level.FINE, "I could find a secret key using the system-wide key resolvers");
+    /**
+     * Searches the per-KeyInfo KeyResolvers for private keys
+     *
+     * @return the private key contained in this KeyInfo
+     * @throws KeyResolverException
+     */
+    PrivateKey getPrivateKeyFromInternalResolvers() throws KeyResolverException {
+        for (KeyResolverSpi keyResolver : internalKeyResolvers) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName());
+            }
+            keyResolver.setSecureValidation(secureValidation);
+            Node currentChild = this.constructionElement.getFirstChild();
+            String uri = this.getBaseURI();
+            while (currentChild != null) {
+                if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
+                    // not using StorageResolvers at the moment
+                    // since they cannot return private keys
+                    PrivateKey pk =
+                        keyResolver.engineLookupAndResolvePrivateKey(
+                            (Element) currentChild, uri, null
+                        );
+
+                    if (pk != null) {
+                        return pk;
+                    }
+                }
+                currentChild = currentChild.getNextSibling();
+            }
+        }
+
+        return null;
+    }
 
-         return sk;
-      }
-      log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the system-wide key resolvers");
+    /**
+     * This method is used to add a custom {@link KeyResolverSpi} to a KeyInfo
+     * object.
+     *
+     * @param realKeyResolver
+     */
+    public void registerInternalKeyResolver(KeyResolverSpi realKeyResolver) {
+        this.internalKeyResolvers.add(realKeyResolver);
+    }
+
+    /**
+     * Method lengthInternalKeyResolver
+     * @return the length of the key
+     */
+    int lengthInternalKeyResolver() {
+        return this.internalKeyResolvers.size();
+    }
+
+    /**
+     * Method itemInternalKeyResolver
+     *
+     * @param i the index
+     * @return the KeyResolverSpi for the index.
+     */
+    KeyResolverSpi itemInternalKeyResolver(int i) {
+        return this.internalKeyResolvers.get(i);
+    }
+
+    /**
+     * Method addStorageResolver
+     *
+     * @param storageResolver
+     */
+    public void addStorageResolver(StorageResolver storageResolver) {
+        if (storageResolvers == nullList) {
+            // Replace the default null StorageResolver
+            storageResolvers = new ArrayList<StorageResolver>();
+        }
+        this.storageResolvers.add(storageResolver);
+    }
 
 
-      return null;
-   }
-
-   /**
-    * Searches the library wide keyresolvers for Secret keys
-    *
-    * @return the secret key contained in this KeyInfo
-    * @throws KeyResolverException
-    */
-
-   SecretKey getSecretKeyFromStaticResolvers() throws KeyResolverException {
-          final int length=KeyResolver.length();
-          int storageLength=this._storageResolvers.size();
-          Iterator<KeyResolverSpi> it = KeyResolver.iterator();
-      for (int i = 0; i < length; i++) {
-         KeyResolverSpi keyResolver = it.next();
-
-         Node currentChild=this._constructionElement.getFirstChild();
-         String uri=this.getBaseURI();
-         while (currentChild!=null)      {
-            if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
-                  for (int k = 0; k < storageLength; k++) {
-                     StorageResolver storage =
-                        this._storageResolvers.get(k);
-
-                     SecretKey sk =
-                           keyResolver.engineLookupAndResolveSecretKey((Element) currentChild,
-                                                        uri,
-                                                        storage);
-
-                     if (sk != null) {
-                        return sk;
-                     }
-                  }
-            }
-            currentChild=currentChild.getNextSibling();
-         }
-      }
-      return null;
-   }
-
-   /**
-    * Searches the per-KeyInfo keyresolvers for secret keys
-    *
-    * @return the secret key contained in this KeyInfo
-    * @throws KeyResolverException
-    */
-
-   SecretKey getSecretKeyFromInternalResolvers() throws KeyResolverException {
-           int storageLength=this._storageResolvers.size();
-      for (int i = 0; i < this.lengthInternalKeyResolver(); i++) {
-         KeyResolverSpi keyResolver = this.itemInternalKeyResolver(i);
-         if (log.isLoggable(java.util.logging.Level.FINE))
-                log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName());
-
-         Node currentChild=this._constructionElement.getFirstChild();
-         String uri=this.getBaseURI();
-         while (currentChild!=null)      {
-            if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
-               for (int k = 0; k < storageLength; k++) {
-                     StorageResolver storage =
-                        this._storageResolvers.get(k);
-
-                     SecretKey sk = keyResolver
-                           .engineLookupAndResolveSecretKey((Element) currentChild, uri, storage);
-
-                     if (sk != null) {
-                        return sk;
-                     }
-                }
-             }
-            currentChild=currentChild.getNextSibling();
-         }
-      }
-
-      return null;
-   }
-
-   /**
-    * Stores the individual (per-KeyInfo) {@link KeyResolver}s
-    */
-   List<KeyResolverSpi> _internalKeyResolvers = new ArrayList<KeyResolverSpi>();
-
-   /**
-    * This method is used to add a custom {@link KeyResolverSpi} to a KeyInfo
-    * object.
-    *
-    * @param realKeyResolver
-    */
-   public void registerInternalKeyResolver(KeyResolverSpi realKeyResolver) {
-           if (_internalKeyResolvers==null) {
-                   _internalKeyResolvers=new ArrayList<KeyResolverSpi>();
-           }
-      this._internalKeyResolvers.add(realKeyResolver);
-   }
-
-   /**
-    * Method lengthInternalKeyResolver
-    * @return the length of the key
-    */
-   int lengthInternalKeyResolver() {
-           if (_internalKeyResolvers==null)
-                   return 0;
-      return this._internalKeyResolvers.size();
-   }
-
-   /**
-    * Method itemInternalKeyResolver
-    *
-    * @param i the index
-    * @return the KeyResolverSpi for the index.
-    */
-   KeyResolverSpi itemInternalKeyResolver(int i) {
-      return this._internalKeyResolvers.get(i);
-   }
-
-   /** Field _storageResolvers */
-   private List<StorageResolver> _storageResolvers = nullList;
-
-   /**
-    * Method addStorageResolver
-    *
-    * @param storageResolver
-    */
-   public void addStorageResolver(StorageResolver storageResolver) {
-           if  (_storageResolvers == nullList  ){
-                   _storageResolvers=new ArrayList<StorageResolver>();
-           }
-         this._storageResolvers.add(storageResolver);
-
-   }
-
-   //J-
-   static boolean _alreadyInitialized = false;
-   /** init the keyinfo (Still needed?)*/
-   public static void init() {
-
-      if (!KeyInfo._alreadyInitialized) {
-         if (KeyInfo.log == null) {
-
-            /**
-             * $todo$ why the hell does the static initialization from the
-             *  start not work ?
-             */
-            KeyInfo.log =
-                    java.util.logging.Logger.getLogger(KeyInfo.class.getName());
-
-            log.log(java.util.logging.Level.SEVERE, "Had to assign log in the init() function");
-         }
-
-         // KeyInfo._contentHandlerHash = new HashMap(10);
-         KeyInfo._alreadyInitialized = true;
-      }
-   }
-
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_KEYINFO;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_KEYINFO;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys;
 
-
-
 import java.io.PrintStream;
 import java.security.PublicKey;
 
@@ -31,57 +31,53 @@
 import com.sun.org.apache.xml.internal.security.keys.content.MgmtData;
 import com.sun.org.apache.xml.internal.security.keys.content.X509Data;
 
-
 /**
  * Utility class for for <CODE>com.sun.org.apache.xml.internal.security.keys</CODE> package.
  *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  */
 public class KeyUtils {
 
-   private KeyUtils() {
-      // no instantiation
-   }
+    private KeyUtils() {
+        // no instantiation
+    }
 
-   /**
-    * Method prinoutKeyInfo
-    *
-    * @param ki
-    * @param os
-    * @throws XMLSecurityException
-    */
-   public static void prinoutKeyInfo(KeyInfo ki, PrintStream os)
-           throws XMLSecurityException {
+    /**
+     * Method prinoutKeyInfo
+     *
+     * @param ki
+     * @param os
+     * @throws XMLSecurityException
+     */
+    public static void prinoutKeyInfo(KeyInfo ki, PrintStream os)
+        throws XMLSecurityException {
 
-      for (int i = 0; i < ki.lengthKeyName(); i++) {
-         KeyName x = ki.itemKeyName(i);
+        for (int i = 0; i < ki.lengthKeyName(); i++) {
+            KeyName x = ki.itemKeyName(i);
 
-         os.println("KeyName(" + i + ")=\"" + x.getKeyName() + "\"");
-      }
+            os.println("KeyName(" + i + ")=\"" + x.getKeyName() + "\"");
+        }
 
-      for (int i = 0; i < ki.lengthKeyValue(); i++) {
-         KeyValue x = ki.itemKeyValue(i);
-         PublicKey pk = x.getPublicKey();
+        for (int i = 0; i < ki.lengthKeyValue(); i++) {
+            KeyValue x = ki.itemKeyValue(i);
+            PublicKey pk = x.getPublicKey();
 
-         os.println("KeyValue Nr. " + i);
-         os.println(pk);
-      }
+            os.println("KeyValue Nr. " + i);
+            os.println(pk);
+        }
 
-      for (int i = 0; i < ki.lengthMgmtData(); i++) {
-         MgmtData x = ki.itemMgmtData(i);
+        for (int i = 0; i < ki.lengthMgmtData(); i++) {
+            MgmtData x = ki.itemMgmtData(i);
 
-         os.println("MgmtData(" + i + ")=\"" + x.getMgmtData() + "\"");
-      }
+            os.println("MgmtData(" + i + ")=\"" + x.getMgmtData() + "\"");
+        }
 
-      for (int i = 0; i < ki.lengthX509Data(); i++) {
-         X509Data x = ki.itemX509Data(i);
+        for (int i = 0; i < ki.lengthX509Data(); i++) {
+            X509Data x = ki.itemX509Data(i);
 
-         os.println("X509Data(" + i + ")=\"" + (x.containsCertificate()
-                                                ? "Certificate "
-                                                : "") + (x
-                                                   .containsIssuerSerial()
-                                                         ? "IssuerSerial "
-                                                         : "") + "\"");
-      }
-   }
+            os.println("X509Data(" + i + ")=\"" + (x.containsCertificate()
+                ? "Certificate " : "") + (x.containsIssuerSerial()
+                ? "IssuerSerial " : "") + "\"");
+        }
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,158 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.keys.content;
+
+import java.security.KeyFactory;
+import java.security.NoSuchAlgorithmException;
+import java.security.PublicKey;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.X509EncodedKeySpec;
+
+import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+import com.sun.org.apache.xml.internal.security.utils.Constants;
+import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * Provides content model support for the <code>dsig11:DEREncodedKeyvalue</code> element.
+ *
+ * @author Brent Putman (putmanb@georgetown.edu)
+ */
+public class DEREncodedKeyValue extends Signature11ElementProxy implements KeyInfoContent {
+
+    /** JCA algorithm key types supported by this implementation. */
+    public static final String supportedKeyTypes[] = { "RSA", "DSA", "EC"};
+
+    /**
+     * Constructor DEREncodedKeyValue
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public DEREncodedKeyValue(Element element, String BaseURI) throws XMLSecurityException {
+        super(element, BaseURI);
+    }
+
+    /**
+     * Constructor DEREncodedKeyValue
+     *
+     * @param doc
+     * @param publicKey
+     * @throws XMLSecurityException
+     */
+    public DEREncodedKeyValue(Document doc, PublicKey publicKey) throws XMLSecurityException {
+        super(doc);
+
+        this.addBase64Text(getEncodedDER(publicKey));
+    }
+
+    /**
+     * Constructor DEREncodedKeyValue
+     *
+     * @param doc
+     * @param base64EncodedKey
+     */
+    public DEREncodedKeyValue(Document doc, byte[] encodedKey) {
+        super(doc);
+
+        this.addBase64Text(encodedKey);
+    }
+
+    /**
+     * Sets the <code>Id</code> attribute
+     *
+     * @param Id ID
+     */
+    public void setId(String id) {
+        if (id != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
+            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+        } else {
+            this.constructionElement.removeAttributeNS(null, Constants._ATT_ID);
+        }
+    }
+
+    /**
+     * Returns the <code>Id</code> attribute
+     *
+     * @return the <code>Id</code> attribute
+     */
+    public String getId() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+    }
+
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_DERENCODEDKEYVALUE;
+    }
+
+    /**
+     * Method getPublicKey
+     *
+     * @return the public key
+     * @throws XMLSecurityException
+     */
+    public PublicKey getPublicKey() throws XMLSecurityException {
+        byte[] encodedKey = getBytesFromTextChild();
+
+        // Iterate over the supported key types until one produces a public key.
+        for (String keyType : supportedKeyTypes) {
+            try {
+                KeyFactory keyFactory = KeyFactory.getInstance(keyType);
+                X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey);
+                PublicKey publicKey = keyFactory.generatePublic(keySpec);
+                if (publicKey != null) {
+                    return publicKey;
+                }
+            } catch (NoSuchAlgorithmException e) {
+                // Do nothing, try the next type
+            } catch (InvalidKeySpecException e) {
+                // Do nothing, try the next type
+            }
+        }
+        throw new XMLSecurityException("DEREncodedKeyValue.UnsupportedEncodedKey");
+    }
+
+    /**
+     * Method getEncodedDER
+     *
+     * @return the public key
+     * @throws XMLSecurityException
+     */
+    protected byte[] getEncodedDER(PublicKey publicKey) throws XMLSecurityException {
+        try {
+            KeyFactory keyFactory = KeyFactory.getInstance(publicKey.getAlgorithm());
+            X509EncodedKeySpec keySpec = keyFactory.getKeySpec(publicKey, X509EncodedKeySpec.class);
+            return keySpec.getEncoded();
+        } catch (NoSuchAlgorithmException e) {
+            Object exArgs[] = { publicKey.getAlgorithm(), publicKey.getFormat(), publicKey.getClass().getName() };
+            throw new XMLSecurityException("DEREncodedKeyValue.UnsupportedPublicKey", exArgs, e);
+        } catch (InvalidKeySpecException e) {
+            Object exArgs[] = { publicKey.getAlgorithm(), publicKey.getFormat(), publicKey.getClass().getName() };
+            throw new XMLSecurityException("DEREncodedKeyValue.UnsupportedPublicKey", exArgs, e);
+        }
+    }
+
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,32 +2,30 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.content;
 
-
-
-
-
 /**
- * Empty interface just to identify Elements that can be cildren of ds:KeyInfo.
+ * Empty interface just to identify Elements that can be children of ds:KeyInfo.
  *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  */
 public interface KeyInfoContent {
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,107 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.keys.content;
+
+import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+import com.sun.org.apache.xml.internal.security.utils.Constants;
+import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * Provides content model support for the <code>dsig11:KeyInfoReference</code> element.
+ *
+ * @author Brent Putman (putmanb@georgetown.edu)
+ */
+public class KeyInfoReference extends Signature11ElementProxy implements KeyInfoContent {
+
+    /**
+     * Constructor RetrievalMethod
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public KeyInfoReference(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
+    }
+
+    /**
+     * Constructor RetrievalMethod
+     *
+     * @param doc
+     * @param URI
+     */
+    public KeyInfoReference(Document doc, String URI) {
+        super(doc);
+
+        this.constructionElement.setAttributeNS(null, Constants._ATT_URI, URI);
+    }
+
+    /**
+     * Method getURIAttr
+     *
+     * @return the URI attribute
+     */
+    public Attr getURIAttr() {
+        return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI);
+    }
+
+    /**
+     * Method getURI
+     *
+     * @return URI string
+     */
+    public String getURI() {
+        return this.getURIAttr().getNodeValue();
+    }
+
+    /**
+     * Sets the <code>Id</code> attribute
+     *
+     * @param Id ID
+     */
+    public void setId(String id) {
+        if (id != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
+            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+        } else {
+            this.constructionElement.removeAttributeNS(null, Constants._ATT_ID);
+        }
+    }
+
+    /**
+     * Returns the <code>Id</code> attribute
+     *
+     * @return the <code>Id</code> attribute
+     */
+    public String getId() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+    }
+
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_KEYINFOREFERENCE;
+    }
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.content;
 
@@ -27,46 +29,44 @@
 import org.w3c.dom.Element;
 
 /**
- *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  */
 public class KeyName extends SignatureElementProxy implements KeyInfoContent {
 
-   /**
-    * Constructor KeyName
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public KeyName(Element element, String BaseURI) throws XMLSecurityException {
-      super(element, BaseURI);
-   }
-
-   /**
-    * Constructor KeyName
-    *
-    * @param doc
-    * @param keyName
-    */
-   public KeyName(Document doc, String keyName) {
+    /**
+     * Constructor KeyName
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public KeyName(Element element, String BaseURI) throws XMLSecurityException {
+        super(element, BaseURI);
+    }
 
-      super(doc);
+    /**
+     * Constructor KeyName
+     *
+     * @param doc
+     * @param keyName
+     */
+    public KeyName(Document doc, String keyName) {
+        super(doc);
 
-      this.addText(keyName);
-   }
+        this.addText(keyName);
+    }
 
-   /**
-    * Method getKeyName
-    *
-    * @return key name
-    */
-   public String getKeyName() {
-      return this.getTextFromTextChild();
-   }
+    /**
+     * Method getKeyName
+     *
+     * @return key name
+     */
+    public String getKeyName() {
+        return this.getTextFromTextChild();
+    }
 
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_KEYNAME;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_KEYNAME;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.content;
 
@@ -39,7 +41,7 @@
  * keys values represented as PCDATA or element types from an external
  * namespace.
  *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  */
 public class KeyValue extends SignatureElementProxy implements KeyInfoContent {
 
@@ -50,12 +52,11 @@
      * @param dsaKeyValue
      */
     public KeyValue(Document doc, DSAKeyValue dsaKeyValue) {
-
         super(doc);
 
-        XMLUtils.addReturnToElement(this._constructionElement);
-        this._constructionElement.appendChild(dsaKeyValue.getElement());
-        XMLUtils.addReturnToElement(this._constructionElement);
+        XMLUtils.addReturnToElement(this.constructionElement);
+        this.constructionElement.appendChild(dsaKeyValue.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
     }
 
     /**
@@ -65,12 +66,11 @@
      * @param rsaKeyValue
      */
     public KeyValue(Document doc, RSAKeyValue rsaKeyValue) {
-
         super(doc);
 
-        XMLUtils.addReturnToElement(this._constructionElement);
-        this._constructionElement.appendChild(rsaKeyValue.getElement());
-        XMLUtils.addReturnToElement(this._constructionElement);
+        XMLUtils.addReturnToElement(this.constructionElement);
+        this.constructionElement.appendChild(rsaKeyValue.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
     }
 
     /**
@@ -80,12 +80,11 @@
      * @param unknownKeyValue
      */
     public KeyValue(Document doc, Element unknownKeyValue) {
-
         super(doc);
 
-        XMLUtils.addReturnToElement(this._constructionElement);
-        this._constructionElement.appendChild(unknownKeyValue);
-        XMLUtils.addReturnToElement(this._constructionElement);
+        XMLUtils.addReturnToElement(this.constructionElement);
+        this.constructionElement.appendChild(unknownKeyValue);
+        XMLUtils.addReturnToElement(this.constructionElement);
     }
 
     /**
@@ -95,21 +94,20 @@
      * @param pk
      */
     public KeyValue(Document doc, PublicKey pk) {
-
         super(doc);
 
-        XMLUtils.addReturnToElement(this._constructionElement);
+        XMLUtils.addReturnToElement(this.constructionElement);
 
         if (pk instanceof java.security.interfaces.DSAPublicKey) {
-            DSAKeyValue dsa = new DSAKeyValue(this._doc, pk);
+            DSAKeyValue dsa = new DSAKeyValue(this.doc, pk);
 
-            this._constructionElement.appendChild(dsa.getElement());
-            XMLUtils.addReturnToElement(this._constructionElement);
+            this.constructionElement.appendChild(dsa.getElement());
+            XMLUtils.addReturnToElement(this.constructionElement);
         } else if (pk instanceof java.security.interfaces.RSAPublicKey) {
-            RSAKeyValue rsa = new RSAKeyValue(this._doc, pk);
+            RSAKeyValue rsa = new RSAKeyValue(this.doc, pk);
 
-            this._constructionElement.appendChild(rsa.getElement());
-            XMLUtils.addReturnToElement(this._constructionElement);
+            this.constructionElement.appendChild(rsa.getElement());
+            XMLUtils.addReturnToElement(this.constructionElement);
         }
     }
 
@@ -120,8 +118,7 @@
      * @param BaseURI
      * @throws XMLSecurityException
      */
-    public KeyValue(Element element, String BaseURI)
-           throws XMLSecurityException {
+    public KeyValue(Element element, String BaseURI) throws XMLSecurityException {
         super(element, BaseURI);
     }
 
@@ -132,22 +129,21 @@
      * @throws XMLSecurityException
      */
     public PublicKey getPublicKey() throws XMLSecurityException {
-
-        Element rsa = XMLUtils.selectDsNode
-            (this._constructionElement.getFirstChild(),
-             Constants._TAG_RSAKEYVALUE,0);
+        Element rsa =
+            XMLUtils.selectDsNode(
+                this.constructionElement.getFirstChild(), Constants._TAG_RSAKEYVALUE, 0);
 
         if (rsa != null) {
-            RSAKeyValue kv = new RSAKeyValue(rsa, this._baseURI);
+            RSAKeyValue kv = new RSAKeyValue(rsa, this.baseURI);
             return kv.getPublicKey();
         }
 
-        Element dsa = XMLUtils.selectDsNode
-            (this._constructionElement.getFirstChild(),
-             Constants._TAG_DSAKEYVALUE,0);
+        Element dsa =
+            XMLUtils.selectDsNode(
+                this.constructionElement.getFirstChild(), Constants._TAG_DSAKEYVALUE, 0);
 
         if (dsa != null) {
-            DSAKeyValue kv = new DSAKeyValue(dsa, this._baseURI);
+            DSAKeyValue kv = new DSAKeyValue(dsa, this.baseURI);
             return kv.getPublicKey();
         }
 
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.content;
 
@@ -27,47 +29,45 @@
 import org.w3c.dom.Element;
 
 /**
- *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  */
 public class MgmtData extends SignatureElementProxy implements KeyInfoContent {
 
-   /**
-    * Constructor MgmtData
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public MgmtData(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
-   }
-
-   /**
-    * Constructor MgmtData
-    *
-    * @param doc
-    * @param mgmtData
-    */
-   public MgmtData(Document doc, String mgmtData) {
+    /**
+     * Constructor MgmtData
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public MgmtData(Element element, String BaseURI)
+        throws XMLSecurityException {
+        super(element, BaseURI);
+    }
 
-      super(doc);
+    /**
+     * Constructor MgmtData
+     *
+     * @param doc
+     * @param mgmtData
+     */
+    public MgmtData(Document doc, String mgmtData) {
+        super(doc);
 
-      this.addText(mgmtData);
-   }
+        this.addText(mgmtData);
+    }
 
-   /**
-    * Method getMgmtData
-    *
-    * @return the managment data
-    */
-   public String getMgmtData() {
-      return this.getTextFromTextChild();
-   }
+    /**
+     * Method getMgmtData
+     *
+     * @return the managment data
+     */
+    public String getMgmtData() {
+        return this.getTextFromTextChild();
+    }
 
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_MGMTDATA;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_MGMTDATA;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.content;
 
@@ -26,25 +28,24 @@
 import org.w3c.dom.Element;
 
 /**
- *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  * $todo$ Implement
  */
 public class PGPData extends SignatureElementProxy implements KeyInfoContent {
 
-   /**
-    * Constructor PGPData
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public PGPData(Element element, String BaseURI) throws XMLSecurityException {
-      super(element, BaseURI);
-   }
+    /**
+     * Constructor PGPData
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public PGPData(Element element, String BaseURI) throws XMLSecurityException {
+        super(element, BaseURI);
+    }
 
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_PGPDATA;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_PGPDATA;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.content;
 
@@ -30,118 +32,104 @@
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-/**
- *
- * @author $Author: mullan $
- */
-public class RetrievalMethod extends SignatureElementProxy
-        implements KeyInfoContent {
+public class RetrievalMethod extends SignatureElementProxy implements KeyInfoContent {
 
-   //J-
     /** DSA retrieval */
-   public static final String TYPE_DSA     = Constants.SignatureSpecNS + "DSAKeyValue";
-   /** RSA retrieval */
-   public static final String TYPE_RSA     = Constants.SignatureSpecNS + "RSAKeyValue";
-   /** PGP retrieval */
-   public static final String TYPE_PGP     = Constants.SignatureSpecNS + "PGPData";
-   /** SPKI retrieval */
-   public static final String TYPE_SPKI    = Constants.SignatureSpecNS + "SPKIData";
-   /** MGMT retrieval */
-   public static final String TYPE_MGMT    = Constants.SignatureSpecNS + "MgmtData";
-   /** X509 retrieval */
-   public static final String TYPE_X509    = Constants.SignatureSpecNS + "X509Data";
-   /** RAWX509 retrieval */
-   public static final String TYPE_RAWX509 = Constants.SignatureSpecNS + "rawX509Certificate";
-   //J+
+    public static final String TYPE_DSA     = Constants.SignatureSpecNS + "DSAKeyValue";
+    /** RSA retrieval */
+    public static final String TYPE_RSA     = Constants.SignatureSpecNS + "RSAKeyValue";
+    /** PGP retrieval */
+    public static final String TYPE_PGP     = Constants.SignatureSpecNS + "PGPData";
+    /** SPKI retrieval */
+    public static final String TYPE_SPKI    = Constants.SignatureSpecNS + "SPKIData";
+    /** MGMT retrieval */
+    public static final String TYPE_MGMT    = Constants.SignatureSpecNS + "MgmtData";
+    /** X509 retrieval */
+    public static final String TYPE_X509    = Constants.SignatureSpecNS + "X509Data";
+    /** RAWX509 retrieval */
+    public static final String TYPE_RAWX509 = Constants.SignatureSpecNS + "rawX509Certificate";
 
-   /**
-    * Constructor RetrievalMethod
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public RetrievalMethod(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
-   }
+    /**
+     * Constructor RetrievalMethod
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public RetrievalMethod(Element element, String BaseURI) throws XMLSecurityException {
+        super(element, BaseURI);
+    }
 
-   /**
-    * Constructor RetrievalMethod
-    *
-    * @param doc
-    * @param URI
-    * @param transforms
-    * @param Type
-    */
-   public RetrievalMethod(Document doc, String URI, Transforms transforms,
-                          String Type) {
+    /**
+     * Constructor RetrievalMethod
+     *
+     * @param doc
+     * @param URI
+     * @param transforms
+     * @param Type
+     */
+    public RetrievalMethod(Document doc, String URI, Transforms transforms, String Type) {
+        super(doc);
 
-      super(doc);
+        this.constructionElement.setAttributeNS(null, Constants._ATT_URI, URI);
 
-      this._constructionElement.setAttributeNS(null, Constants._ATT_URI, URI);
+        if (Type != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_TYPE, Type);
+        }
 
-      if (Type != null) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_TYPE, Type);
-      }
+        if (transforms != null) {
+            this.constructionElement.appendChild(transforms.getElement());
+            XMLUtils.addReturnToElement(this.constructionElement);
+        }
+    }
 
-      if (transforms != null) {
-         this._constructionElement.appendChild(transforms.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-      }
-   }
-
-   /**
-    * Method getURIAttr
-    *
-    * @return the URI attribute
-    */
-   public Attr getURIAttr() {
-      return this._constructionElement.getAttributeNodeNS(null, Constants._ATT_URI);
-   }
+    /**
+     * Method getURIAttr
+     *
+     * @return the URI attribute
+     */
+    public Attr getURIAttr() {
+        return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI);
+    }
 
-   /**
-    * Method getURI
-    *
-    *
-    * @return URI string
-    */
-   public String getURI() {
-      return this.getURIAttr().getNodeValue();
-   }
+    /**
+     * Method getURI
+     *
+     * @return URI string
+     */
+    public String getURI() {
+        return this.getURIAttr().getNodeValue();
+    }
 
-   /** @return the type*/
-   public String getType() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_TYPE);
-   }
+    /** @return the type*/
+    public String getType() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_TYPE);
+    }
 
-   /**
-    * Method getTransforms
-    *
-    *
-    * @throws XMLSecurityException
-    * @return the transforamitons
-    */
-   public Transforms getTransforms() throws XMLSecurityException {
-
-      try {
-       Element transformsElem =
-             XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
-                                                Constants
-                                                   ._TAG_TRANSFORMS, 0);
+    /**
+     * Method getTransforms
+     *
+     * @throws XMLSecurityException
+     * @return the transformations
+     */
+    public Transforms getTransforms() throws XMLSecurityException {
+        try {
+            Element transformsElem =
+                XMLUtils.selectDsNode(
+                    this.constructionElement.getFirstChild(), Constants._TAG_TRANSFORMS, 0);
 
-         if (transformsElem != null) {
-            return new Transforms(transformsElem, this._baseURI);
-         }
+            if (transformsElem != null) {
+                return new Transforms(transformsElem, this.baseURI);
+            }
 
-         return null;
-      } catch (XMLSignatureException ex) {
-         throw new XMLSecurityException("empty", ex);
-      }
-   }
+            return null;
+        } catch (XMLSignatureException ex) {
+            throw new XMLSecurityException("empty", ex);
+        }
+    }
 
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_RETRIEVALMETHOD;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_RETRIEVALMETHOD;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.content;
 
@@ -26,26 +28,25 @@
 import org.w3c.dom.Element;
 
 /**
- *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  * $todo$ implement
  */
 public class SPKIData extends SignatureElementProxy implements KeyInfoContent {
 
-   /**
-    * Constructor SPKIData
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public SPKIData(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
-   }
+    /**
+     * Constructor SPKIData
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public SPKIData(Element element, String BaseURI)
+        throws XMLSecurityException {
+        super(element, BaseURI);
+    }
 
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_SPKIDATA;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_SPKIDATA;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,32 +2,33 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.content;
 
-
-
 import java.math.BigInteger;
 import java.security.cert.X509Certificate;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509CRL;
 import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate;
+import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Digest;
 import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509IssuerSerial;
 import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI;
 import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SubjectName;
@@ -38,447 +39,501 @@
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
-
-/**
- *
- * @author $Author: mullan $
- */
 public class X509Data extends SignatureElementProxy implements KeyInfoContent {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(X509Data.class.getName());
 
-   /**
-    * Constructor X509Data
-    *
-    * @param doc
-    */
-   public X509Data(Document doc) {
-
-      super(doc);
+    /**
+     * Constructor X509Data
+     *
+     * @param doc
+     */
+    public X509Data(Document doc) {
+        super(doc);
 
-      XMLUtils.addReturnToElement(this._constructionElement);
-   }
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-   /**
-    * Constructor X509Data
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public X509Data(Element element, String BaseURI)
-           throws XMLSecurityException {
+    /**
+     * Constructor X509Data
+     *
+     * @param element
+     * @param baseURI
+     * @throws XMLSecurityException
+     */
+    public X509Data(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
 
-      super(element, BaseURI);
-      Node sibling=this._constructionElement.getFirstChild();
-      while (sibling!=null) {
-         if (sibling.getNodeType()!=Node.ELEMENT_NODE) {
-                sibling=sibling.getNextSibling();
-            continue;
-         }
-         return;
-      }
-      /* No Elements found */
-      Object exArgs[] = { "Elements", Constants._TAG_X509DATA };
-      throw new XMLSecurityException("xml.WrongContent", exArgs);
-   }
+        Node sibling = this.constructionElement.getFirstChild();
+        while (sibling != null) {
+            if (sibling.getNodeType() != Node.ELEMENT_NODE) {
+                sibling = sibling.getNextSibling();
+                continue;
+            }
+            return;
+        }
+        /* No Elements found */
+        Object exArgs[] = { "Elements", Constants._TAG_X509DATA };
+        throw new XMLSecurityException("xml.WrongContent", exArgs);
+    }
 
-   /**
-    * Method addIssuerSerial
-    *
-    * @param X509IssuerName
-    * @param X509SerialNumber
-    */
-   public void addIssuerSerial(String X509IssuerName,
-                               BigInteger X509SerialNumber) {
-      this.add(new XMLX509IssuerSerial(this._doc, X509IssuerName,
-                                       X509SerialNumber));
-   }
+    /**
+     * Method addIssuerSerial
+     *
+     * @param X509IssuerName
+     * @param X509SerialNumber
+     */
+    public void addIssuerSerial(String X509IssuerName, BigInteger X509SerialNumber) {
+        this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber));
+    }
+
+    /**
+     * Method addIssuerSerial
+     *
+     * @param X509IssuerName
+     * @param X509SerialNumber
+     */
+    public void addIssuerSerial(String X509IssuerName, String X509SerialNumber) {
+        this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber));
+    }
 
-   /**
-    * Method addIssuerSerial
-    *
-    * @param X509IssuerName
-    * @param X509SerialNumber
-    */
-   public void addIssuerSerial(String X509IssuerName, String X509SerialNumber) {
-      this.add(new XMLX509IssuerSerial(this._doc, X509IssuerName,
-                                       X509SerialNumber));
-   }
+    /**
+     * Method addIssuerSerial
+     *
+     * @param X509IssuerName
+     * @param X509SerialNumber
+     */
+    public void addIssuerSerial(String X509IssuerName, int X509SerialNumber) {
+        this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber));
+    }
 
-   /**
-    * Method addIssuerSerial
-    *
-    * @param X509IssuerName
-    * @param X509SerialNumber
-    */
-   public void addIssuerSerial(String X509IssuerName, int X509SerialNumber) {
-      this.add(new XMLX509IssuerSerial(this._doc, X509IssuerName,
-                                       X509SerialNumber));
-   }
+    /**
+     * Method add
+     *
+     * @param xmlX509IssuerSerial
+     */
+    public void add(XMLX509IssuerSerial xmlX509IssuerSerial) {
+
+        this.constructionElement.appendChild(xmlX509IssuerSerial.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
+
+    /**
+     * Method addSKI
+     *
+     * @param skiBytes
+     */
+    public void addSKI(byte[] skiBytes) {
+        this.add(new XMLX509SKI(this.doc, skiBytes));
+    }
 
-   /**
-    * Method add
-    *
-    * @param xmlX509IssuerSerial
-    */
-   public void add(XMLX509IssuerSerial xmlX509IssuerSerial) {
-
-         this._constructionElement
-            .appendChild(xmlX509IssuerSerial.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-   }
+    /**
+     * Method addSKI
+     *
+     * @param x509certificate
+     * @throws XMLSecurityException
+     */
+    public void addSKI(X509Certificate x509certificate)
+        throws XMLSecurityException {
+        this.add(new XMLX509SKI(this.doc, x509certificate));
+    }
 
-   /**
-    * Method addSKI
-    *
-    * @param skiBytes
-    */
-   public void addSKI(byte[] skiBytes) {
-      this.add(new XMLX509SKI(this._doc, skiBytes));
-   }
+    /**
+     * Method add
+     *
+     * @param xmlX509SKI
+     */
+    public void add(XMLX509SKI xmlX509SKI) {
+        this.constructionElement.appendChild(xmlX509SKI.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-   /**
-    * Method addSKI
-    *
-    * @param x509certificate
-    * @throws XMLSecurityException
-    */
-   public void addSKI(X509Certificate x509certificate)
-           throws XMLSecurityException {
-      this.add(new XMLX509SKI(this._doc, x509certificate));
-   }
+    /**
+     * Method addSubjectName
+     *
+     * @param subjectName
+     */
+    public void addSubjectName(String subjectName) {
+        this.add(new XMLX509SubjectName(this.doc, subjectName));
+    }
 
-   /**
-    * Method add
-    *
-    * @param xmlX509SKI
-    */
-   public void add(XMLX509SKI xmlX509SKI) {
-         this._constructionElement.appendChild(xmlX509SKI.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-   }
+    /**
+     * Method addSubjectName
+     *
+     * @param x509certificate
+     */
+    public void addSubjectName(X509Certificate x509certificate) {
+        this.add(new XMLX509SubjectName(this.doc, x509certificate));
+    }
 
-   /**
-    * Method addSubjectName
-    *
-    * @param subjectName
-    */
-   public void addSubjectName(String subjectName) {
-      this.add(new XMLX509SubjectName(this._doc, subjectName));
-   }
+    /**
+     * Method add
+     *
+     * @param xmlX509SubjectName
+     */
+    public void add(XMLX509SubjectName xmlX509SubjectName) {
+        this.constructionElement.appendChild(xmlX509SubjectName.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-   /**
-    * Method addSubjectName
-    *
-    * @param x509certificate
-    */
-   public void addSubjectName(X509Certificate x509certificate) {
-      this.add(new XMLX509SubjectName(this._doc, x509certificate));
-   }
+    /**
+     * Method addCertificate
+     *
+     * @param x509certificate
+     * @throws XMLSecurityException
+     */
+    public void addCertificate(X509Certificate x509certificate)
+        throws XMLSecurityException {
+        this.add(new XMLX509Certificate(this.doc, x509certificate));
+    }
 
-   /**
-    * Method add
-    *
-    * @param xmlX509SubjectName
-    */
-   public void add(XMLX509SubjectName xmlX509SubjectName) {
-         this._constructionElement.appendChild(xmlX509SubjectName.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-   }
+    /**
+     * Method addCertificate
+     *
+     * @param x509certificateBytes
+     */
+    public void addCertificate(byte[] x509certificateBytes) {
+        this.add(new XMLX509Certificate(this.doc, x509certificateBytes));
+    }
 
-   /**
-    * Method addCertificate
-    *
-    * @param x509certificate
-    * @throws XMLSecurityException
-    */
-   public void addCertificate(X509Certificate x509certificate)
-           throws XMLSecurityException {
-      this.add(new XMLX509Certificate(this._doc, x509certificate));
-   }
+    /**
+     * Method add
+     *
+     * @param xmlX509Certificate
+     */
+    public void add(XMLX509Certificate xmlX509Certificate) {
+        this.constructionElement.appendChild(xmlX509Certificate.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
+
+    /**
+     * Method addCRL
+     *
+     * @param crlBytes
+     */
+    public void addCRL(byte[] crlBytes) {
+        this.add(new XMLX509CRL(this.doc, crlBytes));
+    }
 
-   /**
-    * Method addCertificate
-    *
-    * @param x509certificateBytes
-    */
-   public void addCertificate(byte[] x509certificateBytes) {
-      this.add(new XMLX509Certificate(this._doc, x509certificateBytes));
-   }
+    /**
+     * Method add
+     *
+     * @param xmlX509CRL
+     */
+    public void add(XMLX509CRL xmlX509CRL) {
+        this.constructionElement.appendChild(xmlX509CRL.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-   /**
-    * Method add
-    *
-    * @param xmlX509Certificate
-    */
-   public void add(XMLX509Certificate xmlX509Certificate) {
-         this._constructionElement.appendChild(xmlX509Certificate.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-   }
+    /**
+     * Method addDigest
+     *
+     * @param x509certificate
+     * @param algorithmURI
+     * @throws XMLSecurityException
+     */
+    public void addDigest(X509Certificate x509certificate, String algorithmURI)
+        throws XMLSecurityException {
+        this.add(new XMLX509Digest(this.doc, x509certificate, algorithmURI));
+    }
 
-   /**
-    * Method addCRL
-    *
-    * @param crlBytes
-    */
-   public void addCRL(byte[] crlBytes) {
-      this.add(new XMLX509CRL(this._doc, crlBytes));
-   }
+    /**
+     * Method addDigest
+     *
+     * @param x509CertificateDigestByes
+     * @param algorithmURI
+     */
+    public void addDigest(byte[] x509certificateDigestBytes, String algorithmURI) {
+        this.add(new XMLX509Digest(this.doc, x509certificateDigestBytes, algorithmURI));
+    }
 
-   /**
-    * Method add
-    *
-    * @param xmlX509CRL
-    */
-   public void add(XMLX509CRL xmlX509CRL) {
-         this._constructionElement.appendChild(xmlX509CRL.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-   }
+    /**
+     * Method add
+     *
+     * @param XMLX509Digest
+     */
+    public void add(XMLX509Digest xmlX509Digest) {
+        this.constructionElement.appendChild(xmlX509Digest.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-   /**
-    * Method addUnknownElement
-    *
-    * @param element
-    */
-   public void addUnknownElement(Element element) {
-         this._constructionElement.appendChild(element);
-         XMLUtils.addReturnToElement(this._constructionElement);
-   }
+    /**
+     * Method addUnknownElement
+     *
+     * @param element
+     */
+    public void addUnknownElement(Element element) {
+        this.constructionElement.appendChild(element);
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-   /**
-    * Method lengthIssuerSerial
-    *
-    * @return the number of IssuerSerial elements in this X509Data
-    */
-   public int lengthIssuerSerial() {
-      return this.length(Constants.SignatureSpecNS,
-                         Constants._TAG_X509ISSUERSERIAL);
-   }
+    /**
+     * Method lengthIssuerSerial
+     *
+     * @return the number of IssuerSerial elements in this X509Data
+     */
+    public int lengthIssuerSerial() {
+        return this.length(Constants.SignatureSpecNS, Constants._TAG_X509ISSUERSERIAL);
+    }
+
+    /**
+     * Method lengthSKI
+     *
+     * @return the number of SKI elements in this X509Data
+     */
+    public int lengthSKI() {
+        return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SKI);
+    }
 
-   /**
-    * Method lengthSKI
-    *
-    * @return the number of SKI elements in this X509Data
-    */
-   public int lengthSKI() {
-      return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SKI);
-   }
+    /**
+     * Method lengthSubjectName
+     *
+     * @return the number of SubjectName elements in this X509Data
+     */
+    public int lengthSubjectName() {
+        return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SUBJECTNAME);
+    }
 
-   /**
-    * Method lengthSubjectName
-    *
-    * @return the number of SubjectName elements in this X509Data
-    */
-   public int lengthSubjectName() {
-      return this.length(Constants.SignatureSpecNS,
-                         Constants._TAG_X509SUBJECTNAME);
-   }
+    /**
+     * Method lengthCertificate
+     *
+     * @return the number of Certificate elements in this X509Data
+     */
+    public int lengthCertificate() {
+        return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CERTIFICATE);
+    }
+
+    /**
+     * Method lengthCRL
+     *
+     * @return the number of CRL elements in this X509Data
+     */
+    public int lengthCRL() {
+        return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CRL);
+    }
 
-   /**
-    * Method lengthCertificate
-    *
-    * @return the number of Certificate elements in this X509Data
-    */
-   public int lengthCertificate() {
-      return this.length(Constants.SignatureSpecNS,
-                         Constants._TAG_X509CERTIFICATE);
-   }
+    /**
+     * Method lengthDigest
+     *
+     * @return the number of X509Digest elements in this X509Data
+     */
+    public int lengthDigest() {
+        return this.length(Constants.SignatureSpec11NS, Constants._TAG_X509DIGEST);
+    }
 
-   /**
-    * Method lengthCRL
-    *
-    * @return the number of CRL elements in this X509Data
-    */
-   public int lengthCRL() {
-      return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CRL);
-   }
+    /**
+     * Method lengthUnknownElement
+     *
+     * @return the number of UnknownElement elements in this X509Data
+     */
+    public int lengthUnknownElement() {
+        int result = 0;
+        Node n = this.constructionElement.getFirstChild();
+        while (n != null){
+            if ((n.getNodeType() == Node.ELEMENT_NODE)
+                && !n.getNamespaceURI().equals(Constants.SignatureSpecNS)) {
+                result++;
+            }
+            n = n.getNextSibling();
+        }
 
-   /**
-    * Method lengthUnknownElement
-    *
-    * @return the number of UnknownElement elements in this X509Data
-    */
-   public int lengthUnknownElement() {
-
-      int result = 0;
-      Node n=this._constructionElement.getFirstChild();
-      while (n!=null){
+        return result;
+    }
 
-         if ((n.getNodeType() == Node.ELEMENT_NODE)
-                 &&!n.getNamespaceURI().equals(Constants.SignatureSpecNS)) {
-            result += 1;
-         }
-         n=n.getNextSibling();
-      }
-
-      return result;
-   }
+    /**
+     * Method itemIssuerSerial
+     *
+     * @param i
+     * @return the X509IssuerSerial, null if not present
+     * @throws XMLSecurityException
+     */
+    public XMLX509IssuerSerial itemIssuerSerial(int i) throws XMLSecurityException {
+        Element e =
+            XMLUtils.selectDsNode(
+                this.constructionElement.getFirstChild(), Constants._TAG_X509ISSUERSERIAL, i);
 
-   /**
-    * Method itemIssuerSerial
-    *
-    * @param i
-    * @return the X509IssuerSerial, null if not present
-    * @throws XMLSecurityException
-    */
-   public XMLX509IssuerSerial itemIssuerSerial(int i)
-           throws XMLSecurityException {
+        if (e != null) {
+            return new XMLX509IssuerSerial(e, this.baseURI);
+        }
+        return null;
+    }
 
-      Element e =
-        XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
-                                       Constants._TAG_X509ISSUERSERIAL,i);
+    /**
+     * Method itemSKI
+     *
+     * @param i
+     * @return the X509SKI, null if not present
+     * @throws XMLSecurityException
+     */
+    public XMLX509SKI itemSKI(int i) throws XMLSecurityException {
 
-      if (e != null) {
-         return new XMLX509IssuerSerial(e, this._baseURI);
-      }
-      return null;
-   }
+        Element e =
+            XMLUtils.selectDsNode(
+                this.constructionElement.getFirstChild(), Constants._TAG_X509SKI, i);
 
-   /**
-    * Method itemSKI
-    *
-    * @param i
-    * @return the X509SKI, null if not present
-    * @throws XMLSecurityException
-    */
-   public XMLX509SKI itemSKI(int i) throws XMLSecurityException {
+        if (e != null) {
+            return new XMLX509SKI(e, this.baseURI);
+        }
+        return null;
+    }
 
-      Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
-                                                Constants._TAG_X509SKI,i);
+    /**
+     * Method itemSubjectName
+     *
+     * @param i
+     * @return the X509SubjectName, null if not present
+     * @throws XMLSecurityException
+     */
+    public XMLX509SubjectName itemSubjectName(int i) throws XMLSecurityException {
+
+        Element e =
+            XMLUtils.selectDsNode(
+                this.constructionElement.getFirstChild(), Constants._TAG_X509SUBJECTNAME, i);
 
-      if (e != null) {
-         return new XMLX509SKI(e, this._baseURI);
-      }
-      return null;
-   }
+        if (e != null) {
+            return new XMLX509SubjectName(e, this.baseURI);
+        }
+        return null;
+    }
 
-   /**
-    * Method itemSubjectName
-    *
-    * @param i
-    * @return the X509SubjectName, null if not present
-    * @throws XMLSecurityException
-    */
-   public XMLX509SubjectName itemSubjectName(int i)
-           throws XMLSecurityException {
+    /**
+     * Method itemCertificate
+     *
+     * @param i
+     * @return the X509Certifacte, null if not present
+     * @throws XMLSecurityException
+     */
+    public XMLX509Certificate itemCertificate(int i) throws XMLSecurityException {
 
-      Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
-                                                Constants._TAG_X509SUBJECTNAME,i);
+        Element e =
+            XMLUtils.selectDsNode(
+                this.constructionElement.getFirstChild(), Constants._TAG_X509CERTIFICATE, i);
 
-      if (e != null) {
-         return new XMLX509SubjectName(e, this._baseURI);
-      }
-       return null;
-   }
+        if (e != null) {
+            return new XMLX509Certificate(e, this.baseURI);
+        }
+        return null;
+    }
 
-   /**
-    * Method itemCertificate
-    *
-    * @param i
-    * @return the X509Certifacte, null if not present
-    * @throws XMLSecurityException
-    */
-   public XMLX509Certificate itemCertificate(int i)
-           throws XMLSecurityException {
+    /**
+     * Method itemCRL
+     *
+     * @param i
+     * @return the X509CRL, null if not present
+     * @throws XMLSecurityException
+     */
+    public XMLX509CRL itemCRL(int i) throws XMLSecurityException {
 
-      Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
-                                                Constants._TAG_X509CERTIFICATE,i);
+        Element e =
+            XMLUtils.selectDsNode(
+                this.constructionElement.getFirstChild(), Constants._TAG_X509CRL, i);
 
-      if (e != null) {
-         return new XMLX509Certificate(e, this._baseURI);
-      }
-       return null;
-   }
+        if (e != null) {
+            return new XMLX509CRL(e, this.baseURI);
+        }
+        return null;
+    }
 
-   /**
-    * Method itemCRL
-    *
-    * @param i
-    * @return the X509CRL, null if not present
-    * @throws XMLSecurityException
-    */
-   public XMLX509CRL itemCRL(int i) throws XMLSecurityException {
+    /**
+     * Method itemDigest
+     *
+     * @param i
+     * @return the X509Digest, null if not present
+     * @throws XMLSecurityException
+     */
+    public XMLX509Digest itemDigest(int i) throws XMLSecurityException {
 
-      Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
-                                                Constants._TAG_X509CRL,i);
+        Element e =
+            XMLUtils.selectDs11Node(
+                this.constructionElement.getFirstChild(), Constants._TAG_X509DIGEST, i);
 
-      if (e != null) {
-         return new XMLX509CRL(e, this._baseURI);
-      }
-       return null;
-   }
+        if (e != null) {
+            return new XMLX509Digest(e, this.baseURI);
+        }
+        return null;
+    }
 
-   /**
-    * Method itemUnknownElement
-    *
-    * @param i
-    * @return the Unknown Element at i
-    * TODO implement
-    **/
-   public Element itemUnknownElement(int i) {
-          log.log(java.util.logging.Level.FINE, "itemUnknownElement not implemented:"+i);
-      return null;
-   }
+    /**
+     * Method itemUnknownElement
+     *
+     * @param i
+     * @return the Unknown Element at i
+     * TODO implement
+     **/
+    public Element itemUnknownElement(int i) {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "itemUnknownElement not implemented:" + i);
+        }
+        return null;
+    }
 
-   /**
-    * Method containsIssuerSerial
-    *
-    * @return true if this X509Data contains a IssuerSerial
-    */
-   public boolean containsIssuerSerial() {
-      return this.lengthIssuerSerial() > 0;
-   }
+    /**
+     * Method containsIssuerSerial
+     *
+     * @return true if this X509Data contains a IssuerSerial
+     */
+    public boolean containsIssuerSerial() {
+        return this.lengthIssuerSerial() > 0;
+    }
 
-   /**
-    * Method containsSKI
-    *
-    * @return true if this X509Data contains a SKI
-    */
-   public boolean containsSKI() {
-      return this.lengthSKI() > 0;
-   }
+    /**
+     * Method containsSKI
+     *
+     * @return true if this X509Data contains a SKI
+     */
+    public boolean containsSKI() {
+        return this.lengthSKI() > 0;
+    }
 
-   /**
-    * Method containsSubjectName
-    *
-    * @return true if this X509Data contains a SubjectName
-    */
-   public boolean containsSubjectName() {
-      return this.lengthSubjectName() > 0;
-   }
+    /**
+     * Method containsSubjectName
+     *
+     * @return true if this X509Data contains a SubjectName
+     */
+    public boolean containsSubjectName() {
+        return this.lengthSubjectName() > 0;
+    }
 
-   /**
-    * Method containsCertificate
-    *
-    * @return true if this X509Data contains a Certificate
-    */
-   public boolean containsCertificate() {
-      return this.lengthCertificate() > 0;
-   }
+    /**
+     * Method containsCertificate
+     *
+     * @return true if this X509Data contains a Certificate
+     */
+    public boolean containsCertificate() {
+        return this.lengthCertificate() > 0;
+    }
+
+    /**
+     * Method containsDigest
+     *
+     * @return true if this X509Data contains an X509Digest
+     */
+    public boolean containsDigest() {
+        return this.lengthDigest() > 0;
+    }
 
-   /**
-    * Method containsCRL
-    *
-    * @return true if this X509Data contains a CRL
-    */
-   public boolean containsCRL() {
-      return this.lengthCRL() > 0;
-   }
+    /**
+     * Method containsCRL
+     *
+     * @return true if this X509Data contains a CRL
+     */
+    public boolean containsCRL() {
+        return this.lengthCRL() > 0;
+    }
 
-   /**
-    * Method containsUnknownElement
-    *
-    * @return true if this X509Data contains an UnknownElement
-    */
-   public boolean containsUnknownElement() {
-      return this.lengthUnknownElement() > 0;
-   }
+    /**
+     * Method containsUnknownElement
+     *
+     * @return true if this X509Data contains an UnknownElement
+     */
+    public boolean containsUnknownElement() {
+        return this.lengthUnknownElement() > 0;
+    }
 
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_X509DATA;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_X509DATA;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.content.keyvalues;
 
@@ -37,104 +39,93 @@
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-/**
- *
- * @author $Author: mullan $
- */
-public class DSAKeyValue extends SignatureElementProxy
-        implements KeyValueContent {
+public class DSAKeyValue extends SignatureElementProxy implements KeyValueContent {
 
-   /**
-    * Constructor DSAKeyValue
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public DSAKeyValue(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
-   }
+    /**
+     * Constructor DSAKeyValue
+     *
+     * @param element
+     * @param baseURI
+     * @throws XMLSecurityException
+     */
+    public DSAKeyValue(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
+    }
 
-   /**
-    * Constructor DSAKeyValue
-    *
-    * @param doc
-    * @param P
-    * @param Q
-    * @param G
-    * @param Y
-    */
-   public DSAKeyValue(Document doc, BigInteger P, BigInteger Q, BigInteger G,
-                      BigInteger Y) {
-
-      super(doc);
+    /**
+     * Constructor DSAKeyValue
+     *
+     * @param doc
+     * @param P
+     * @param Q
+     * @param G
+     * @param Y
+     */
+    public DSAKeyValue(Document doc, BigInteger P, BigInteger Q, BigInteger G, BigInteger Y) {
+        super(doc);
 
-      XMLUtils.addReturnToElement(this._constructionElement);
-      this.addBigIntegerElement(P, Constants._TAG_P);
-      this.addBigIntegerElement(Q, Constants._TAG_Q);
-      this.addBigIntegerElement(G, Constants._TAG_G);
-      this.addBigIntegerElement(Y, Constants._TAG_Y);
-   }
+        XMLUtils.addReturnToElement(this.constructionElement);
+        this.addBigIntegerElement(P, Constants._TAG_P);
+        this.addBigIntegerElement(Q, Constants._TAG_Q);
+        this.addBigIntegerElement(G, Constants._TAG_G);
+        this.addBigIntegerElement(Y, Constants._TAG_Y);
+    }
 
-   /**
-    * Constructor DSAKeyValue
-    *
-    * @param doc
-    * @param key
-    * @throws IllegalArgumentException
-    */
-   public DSAKeyValue(Document doc, Key key) throws IllegalArgumentException {
+    /**
+     * Constructor DSAKeyValue
+     *
+     * @param doc
+     * @param key
+     * @throws IllegalArgumentException
+     */
+    public DSAKeyValue(Document doc, Key key) throws IllegalArgumentException {
+        super(doc);
 
-      super(doc);
+        XMLUtils.addReturnToElement(this.constructionElement);
 
-      XMLUtils.addReturnToElement(this._constructionElement);
+        if (key instanceof java.security.interfaces.DSAPublicKey) {
+            this.addBigIntegerElement(((DSAPublicKey) key).getParams().getP(), Constants._TAG_P);
+            this.addBigIntegerElement(((DSAPublicKey) key).getParams().getQ(), Constants._TAG_Q);
+            this.addBigIntegerElement(((DSAPublicKey) key).getParams().getG(), Constants._TAG_G);
+            this.addBigIntegerElement(((DSAPublicKey) key).getY(), Constants._TAG_Y);
+        } else {
+            Object exArgs[] = { Constants._TAG_DSAKEYVALUE, key.getClass().getName() };
 
-      if (key instanceof java.security.interfaces.DSAPublicKey) {
-         this.addBigIntegerElement(((DSAPublicKey) key).getParams().getP(),
-                                   Constants._TAG_P);
-         this.addBigIntegerElement(((DSAPublicKey) key).getParams().getQ(),
-                                   Constants._TAG_Q);
-         this.addBigIntegerElement(((DSAPublicKey) key).getParams().getG(),
-                                   Constants._TAG_G);
-         this.addBigIntegerElement(((DSAPublicKey) key).getY(),
-                                   Constants._TAG_Y);
-      } else {
-         Object exArgs[] = { Constants._TAG_DSAKEYVALUE,
-                             key.getClass().getName() };
-
-         throw new IllegalArgumentException(I18n
-            .translate("KeyValue.IllegalArgument", exArgs));
-      }
-   }
-
-   /** @inheritDoc */
-   public PublicKey getPublicKey() throws XMLSecurityException {
+            throw new IllegalArgumentException(I18n.translate("KeyValue.IllegalArgument", exArgs));
+        }
+    }
 
-      try {
-         DSAPublicKeySpec pkspec =
-            new DSAPublicKeySpec(this
-               .getBigIntegerFromChildElement(Constants._TAG_Y, Constants
-               .SignatureSpecNS), this
-                  .getBigIntegerFromChildElement(Constants._TAG_P, Constants
-                  .SignatureSpecNS), this
-                     .getBigIntegerFromChildElement(Constants._TAG_Q, Constants
-                     .SignatureSpecNS), this
-                        .getBigIntegerFromChildElement(Constants
-                           ._TAG_G, Constants.SignatureSpecNS));
-         KeyFactory dsaFactory = KeyFactory.getInstance("DSA");
-         PublicKey pk = dsaFactory.generatePublic(pkspec);
+    /** @inheritDoc */
+    public PublicKey getPublicKey() throws XMLSecurityException {
+        try {
+            DSAPublicKeySpec pkspec =
+                new DSAPublicKeySpec(
+                    this.getBigIntegerFromChildElement(
+                        Constants._TAG_Y, Constants.SignatureSpecNS
+                    ),
+                    this.getBigIntegerFromChildElement(
+                        Constants._TAG_P, Constants.SignatureSpecNS
+                    ),
+                    this.getBigIntegerFromChildElement(
+                        Constants._TAG_Q, Constants.SignatureSpecNS
+                    ),
+                    this.getBigIntegerFromChildElement(
+                        Constants._TAG_G, Constants.SignatureSpecNS
+                    )
+                );
+            KeyFactory dsaFactory = KeyFactory.getInstance("DSA");
+            PublicKey pk = dsaFactory.generatePublic(pkspec);
 
-         return pk;
-      } catch (NoSuchAlgorithmException ex) {
-         throw new XMLSecurityException("empty", ex);
-      } catch (InvalidKeySpecException ex) {
-         throw new XMLSecurityException("empty", ex);
-      }
-   }
+            return pk;
+        } catch (NoSuchAlgorithmException ex) {
+            throw new XMLSecurityException("empty", ex);
+        } catch (InvalidKeySpecException ex) {
+            throw new XMLSecurityException("empty", ex);
+        }
+    }
 
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_DSAKEYVALUE;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_DSAKEYVALUE;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,46 +2,38 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.content.keyvalues;
 
-
-
 import java.security.PublicKey;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 
-/**
- *
- *
- *
- *
- * @author $Author: mullan $
- *
- */
 public interface KeyValueContent {
 
-   /**
-    * Method getPublicKey
-    *
-    * @return the public key
-    * @throws XMLSecurityException
-    */
-   public PublicKey getPublicKey()
-      throws XMLSecurityException;
+    /**
+     * Method getPublicKey
+     *
+     * @return the public key
+     * @throws XMLSecurityException
+     */
+    PublicKey getPublicKey() throws XMLSecurityException;
+
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.content.keyvalues;
 
@@ -37,93 +39,86 @@
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-/**
- *
- * @author $Author: mullan $
- */
-public class RSAKeyValue extends SignatureElementProxy
-        implements KeyValueContent {
+public class RSAKeyValue extends SignatureElementProxy implements KeyValueContent {
 
-   /**
-    * Constructor RSAKeyValue
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public RSAKeyValue(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
-   }
+    /**
+     * Constructor RSAKeyValue
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public RSAKeyValue(Element element, String BaseURI) throws XMLSecurityException {
+        super(element, BaseURI);
+    }
 
-   /**
-    * Constructor RSAKeyValue
-    *
-    * @param doc
-    * @param modulus
-    * @param exponent
-    */
-   public RSAKeyValue(Document doc, BigInteger modulus, BigInteger exponent) {
-
-      super(doc);
+    /**
+     * Constructor RSAKeyValue
+     *
+     * @param doc
+     * @param modulus
+     * @param exponent
+     */
+    public RSAKeyValue(Document doc, BigInteger modulus, BigInteger exponent) {
+        super(doc);
 
-      XMLUtils.addReturnToElement(this._constructionElement);
-      this.addBigIntegerElement(modulus, Constants._TAG_MODULUS);
-      this.addBigIntegerElement(exponent, Constants._TAG_EXPONENT);
-   }
+        XMLUtils.addReturnToElement(this.constructionElement);
+        this.addBigIntegerElement(modulus, Constants._TAG_MODULUS);
+        this.addBigIntegerElement(exponent, Constants._TAG_EXPONENT);
+    }
 
-   /**
-    * Constructor RSAKeyValue
-    *
-    * @param doc
-    * @param key
-    * @throws IllegalArgumentException
-    */
-   public RSAKeyValue(Document doc, Key key) throws IllegalArgumentException {
+    /**
+     * Constructor RSAKeyValue
+     *
+     * @param doc
+     * @param key
+     * @throws IllegalArgumentException
+     */
+    public RSAKeyValue(Document doc, Key key) throws IllegalArgumentException {
+        super(doc);
+
+        XMLUtils.addReturnToElement(this.constructionElement);
 
-      super(doc);
-
-      XMLUtils.addReturnToElement(this._constructionElement);
+        if (key instanceof java.security.interfaces.RSAPublicKey ) {
+            this.addBigIntegerElement(
+                ((RSAPublicKey) key).getModulus(), Constants._TAG_MODULUS
+            );
+            this.addBigIntegerElement(
+                ((RSAPublicKey) key).getPublicExponent(), Constants._TAG_EXPONENT
+            );
+        } else {
+            Object exArgs[] = { Constants._TAG_RSAKEYVALUE, key.getClass().getName() };
 
-      if (key instanceof java.security.interfaces.RSAPublicKey ) {
-         this.addBigIntegerElement(((RSAPublicKey) key).getModulus(),
-                                   Constants._TAG_MODULUS);
-         this.addBigIntegerElement(((RSAPublicKey) key).getPublicExponent(),
-                                   Constants._TAG_EXPONENT);
-      } else {
-         Object exArgs[] = { Constants._TAG_RSAKEYVALUE,
-                             key.getClass().getName() };
+            throw new IllegalArgumentException(I18n.translate("KeyValue.IllegalArgument", exArgs));
+        }
+    }
 
-         throw new IllegalArgumentException(I18n
-            .translate("KeyValue.IllegalArgument", exArgs));
-      }
-   }
-
-   /** @inheritDoc */
-   public PublicKey getPublicKey() throws XMLSecurityException {
+    /** @inheritDoc */
+    public PublicKey getPublicKey() throws XMLSecurityException {
+        try {
+            KeyFactory rsaFactory = KeyFactory.getInstance("RSA");
 
-      try {
-         KeyFactory rsaFactory = KeyFactory.getInstance("RSA");
-
-         // KeyFactory rsaFactory = KeyFactory.getInstance(JCE_RSA);
-         RSAPublicKeySpec rsaKeyspec =
-            new RSAPublicKeySpec(this
-               .getBigIntegerFromChildElement(Constants._TAG_MODULUS, Constants
-               .SignatureSpecNS), this
-                  .getBigIntegerFromChildElement(Constants
-                     ._TAG_EXPONENT, Constants.SignatureSpecNS));
-         PublicKey pk = rsaFactory.generatePublic(rsaKeyspec);
+            RSAPublicKeySpec rsaKeyspec =
+                new RSAPublicKeySpec(
+                    this.getBigIntegerFromChildElement(
+                        Constants._TAG_MODULUS, Constants.SignatureSpecNS
+                    ),
+                    this.getBigIntegerFromChildElement(
+                        Constants._TAG_EXPONENT, Constants.SignatureSpecNS
+                    )
+                );
+            PublicKey pk = rsaFactory.generatePublic(rsaKeyspec);
 
-         return pk;
-      } catch (NoSuchAlgorithmException ex) {
-         throw new XMLSecurityException("empty", ex);
-      } catch (InvalidKeySpecException ex) {
-         throw new XMLSecurityException("empty", ex);
-      }
-   }
+            return pk;
+        } catch (NoSuchAlgorithmException ex) {
+            throw new XMLSecurityException("empty", ex);
+        } catch (InvalidKeySpecException ex) {
+            throw new XMLSecurityException("empty", ex);
+        }
+    }
 
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_RSAKEYVALUE;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_RSAKEYVALUE;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.content.x509;
 
@@ -26,51 +28,43 @@
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-/**
- *
- * @author $Author: mullan $
- *
- */
-public class XMLX509CRL extends SignatureElementProxy
-        implements XMLX509DataContent {
+public class XMLX509CRL extends SignatureElementProxy implements XMLX509DataContent {
 
-   /**
-    * Constructor XMLX509CRL
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public XMLX509CRL(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
-   }
+    /**
+     * Constructor XMLX509CRL
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public XMLX509CRL(Element element, String BaseURI) throws XMLSecurityException {
+        super(element, BaseURI);
+    }
 
-   /**
-    * Constructor X509CRL
-    *
-    * @param doc
-    * @param crlBytes
-    */
-   public XMLX509CRL(Document doc, byte[] crlBytes) {
+    /**
+     * Constructor X509CRL
+     *
+     * @param doc
+     * @param crlBytes
+     */
+    public XMLX509CRL(Document doc, byte[] crlBytes) {
+        super(doc);
 
-      super(doc);
-
-      this.addBase64Text(crlBytes);
-   }
+        this.addBase64Text(crlBytes);
+    }
 
-   /**
-    * Method getCRLBytes
-    *
-    * @return the CRL bytes
-    * @throws XMLSecurityException
-    */
-   public byte[] getCRLBytes() throws XMLSecurityException {
-      return this.getBytesFromTextChild();
-   }
+    /**
+     * Method getCRLBytes
+     *
+     * @return the CRL bytes
+     * @throws XMLSecurityException
+     */
+    public byte[] getCRLBytes() throws XMLSecurityException {
+        return this.getBytesFromTextChild();
+    }
 
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_X509CRL;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_X509CRL;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.content.x509;
 
@@ -25,6 +27,7 @@
 import java.security.cert.CertificateException;
 import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
+import java.util.Arrays;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
@@ -32,135 +35,134 @@
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-/**
- *
- * @author $Author: mullan $
- */
-public class XMLX509Certificate extends SignatureElementProxy
-        implements XMLX509DataContent {
+public class XMLX509Certificate extends SignatureElementProxy implements XMLX509DataContent {
 
-   /** Field JCA_CERT_ID */
-   public static final String JCA_CERT_ID = "X.509";
+    /** Field JCA_CERT_ID */
+    public static final String JCA_CERT_ID = "X.509";
 
-   /**
-    * Constructor X509Certificate
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public XMLX509Certificate(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
-   }
+    /**
+     * Constructor X509Certificate
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public XMLX509Certificate(Element element, String BaseURI) throws XMLSecurityException {
+        super(element, BaseURI);
+    }
 
-   /**
-    * Constructor X509Certificate
-    *
-    * @param doc
-    * @param certificateBytes
-    */
-   public XMLX509Certificate(Document doc, byte[] certificateBytes) {
+    /**
+     * Constructor X509Certificate
+     *
+     * @param doc
+     * @param certificateBytes
+     */
+    public XMLX509Certificate(Document doc, byte[] certificateBytes) {
+        super(doc);
 
-      super(doc);
+        this.addBase64Text(certificateBytes);
+    }
 
-      this.addBase64Text(certificateBytes);
-   }
+    /**
+     * Constructor XMLX509Certificate
+     *
+     * @param doc
+     * @param x509certificate
+     * @throws XMLSecurityException
+     */
+    public XMLX509Certificate(Document doc, X509Certificate x509certificate)
+        throws XMLSecurityException {
+        super(doc);
 
-   /**
-    * Constructor XMLX509Certificate
-    *
-    * @param doc
-    * @param x509certificate
-    * @throws XMLSecurityException
-    */
-   public XMLX509Certificate(Document doc, X509Certificate x509certificate)
-           throws XMLSecurityException {
-
-      super(doc);
+        try {
+            this.addBase64Text(x509certificate.getEncoded());
+        } catch (java.security.cert.CertificateEncodingException ex) {
+            throw new XMLSecurityException("empty", ex);
+        }
+    }
 
-      try {
-         this.addBase64Text(x509certificate.getEncoded());
-      } catch (java.security.cert.CertificateEncodingException ex) {
-         throw new XMLSecurityException("empty", ex);
-      }
-   }
+    /**
+     * Method getCertificateBytes
+     *
+     * @return the certificate bytes
+     * @throws XMLSecurityException
+     */
+    public byte[] getCertificateBytes() throws XMLSecurityException {
+        return this.getBytesFromTextChild();
+    }
 
-   /**
-    * Method getCertificateBytes
-    *
-    * @return the certificate bytes
-    * @throws XMLSecurityException
-    */
-   public byte[] getCertificateBytes() throws XMLSecurityException {
-      return this.getBytesFromTextChild();
-   }
-
-   /**
-    * Method getX509Certificate
-    *
-    * @return the x509 certificate
-    * @throws XMLSecurityException
-    */
-   public X509Certificate getX509Certificate() throws XMLSecurityException {
+    /**
+     * Method getX509Certificate
+     *
+     * @return the x509 certificate
+     * @throws XMLSecurityException
+     */
+    public X509Certificate getX509Certificate() throws XMLSecurityException {
+        try {
+            byte certbytes[] = this.getCertificateBytes();
+            CertificateFactory certFact =
+                CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID);
+            X509Certificate cert =
+                (X509Certificate) certFact.generateCertificate(
+                    new ByteArrayInputStream(certbytes)
+                );
 
-      try {
-         byte certbytes[] = this.getCertificateBytes();
-         CertificateFactory certFact =
-            CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID);
-         X509Certificate cert =
-            (X509Certificate) certFact
-               .generateCertificate(new ByteArrayInputStream(certbytes));
+            if (cert != null) {
+                return cert;
+            }
 
-         if (cert != null) {
-            return cert;
-         }
+            return null;
+        } catch (CertificateException ex) {
+            throw new XMLSecurityException("empty", ex);
+        }
+    }
 
-         return null;
-      } catch (CertificateException ex) {
-         throw new XMLSecurityException("empty", ex);
-      }
-   }
+    /**
+     * Method getPublicKey
+     *
+     * @return the publickey
+     * @throws XMLSecurityException
+     */
+    public PublicKey getPublicKey() throws XMLSecurityException {
+        X509Certificate cert = this.getX509Certificate();
 
-   /**
-    * Method getPublicKey
-    *
-    * @return teh publickey
-    * @throws XMLSecurityException
-    */
-   public PublicKey getPublicKey() throws XMLSecurityException {
+        if (cert != null) {
+            return cert.getPublicKey();
+        }
 
-      X509Certificate cert = this.getX509Certificate();
-
-      if (cert != null) {
-         return cert.getPublicKey();
-      }
-
-      return null;
-   }
+        return null;
+    }
 
     /** @inheritDoc */
     public boolean equals(Object obj) {
-
-        if (obj == null) {
-            return false;
-        }
-        if (!this.getClass().getName().equals(obj.getClass().getName())) {
+        if (!(obj instanceof XMLX509Certificate)) {
             return false;
         }
         XMLX509Certificate other = (XMLX509Certificate) obj;
         try {
-
-            /** $todo$ or should be create X509Certificates and use the equals() from the Certs */
-            return java.security.MessageDigest.isEqual
-                (other.getCertificateBytes(), this.getCertificateBytes());
+            return Arrays.equals(other.getCertificateBytes(), this.getCertificateBytes());
         } catch (XMLSecurityException ex) {
             return false;
         }
     }
 
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_X509CERTIFICATE;
-   }
+    public int hashCode() {
+        int result = 17;
+        try {
+            byte[] bytes = getCertificateBytes();
+            for (int i = 0; i < bytes.length; i++) {
+                result = 31 * result + bytes[i];
+            }
+        } catch (XMLSecurityException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+            }
+        }
+        return result;
+    }
+
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_X509CERTIFICATE;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,32 +2,30 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.content.x509;
 
-
-
-
-
 /**
  * Just used for tagging contents that are allowed inside a ds:X509Data Element.
  *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  */
 public interface XMLX509DataContent {
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,139 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.keys.content.x509;
+
+import java.security.MessageDigest;
+import java.security.cert.X509Certificate;
+
+import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
+import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+import com.sun.org.apache.xml.internal.security.utils.Constants;
+import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * Provides content model support for the <code>dsig11:X509Digest</code> element.
+ *
+ * @author Brent Putman (putmanb@georgetown.edu)
+ */
+public class XMLX509Digest extends Signature11ElementProxy implements XMLX509DataContent {
+
+    /**
+     * Constructor XMLX509Digest
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public XMLX509Digest(Element element, String BaseURI) throws XMLSecurityException {
+        super(element, BaseURI);
+    }
+
+    /**
+     * Constructor XMLX509Digest
+     *
+     * @param doc
+     * @param digestBytes
+     * @param algorithmURI
+     */
+    public XMLX509Digest(Document doc, byte[] digestBytes, String algorithmURI) {
+        super(doc);
+        this.addBase64Text(digestBytes);
+        this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI);
+    }
+
+    /**
+     * Constructor XMLX509Digest
+     *
+     * @param doc
+     * @param x509certificate
+     * @param algorithmURI
+     * @throws XMLSecurityException
+     */
+    public XMLX509Digest(Document doc, X509Certificate x509certificate, String algorithmURI) throws XMLSecurityException {
+        super(doc);
+        this.addBase64Text(getDigestBytesFromCert(x509certificate, algorithmURI));
+        this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI);
+    }
+
+    /**
+     * Method getAlgorithmAttr
+     *
+     * @return the Algorithm attribute
+     */
+    public Attr getAlgorithmAttr() {
+        return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_ALGORITHM);
+    }
+
+    /**
+     * Method getAlgorithm
+     *
+     * @return Algorithm string
+     */
+    public String getAlgorithm() {
+        return this.getAlgorithmAttr().getNodeValue();
+    }
+
+    /**
+     * Method getDigestBytes
+     *
+     * @return the digestbytes
+     * @throws XMLSecurityException
+     */
+    public byte[] getDigestBytes() throws XMLSecurityException {
+        return this.getBytesFromTextChild();
+    }
+
+    /**
+     * Method getDigestBytesFromCert
+     *
+     * @param cert
+     * @param algorithmURI
+     * @return digest bytes from the given certificate
+     *
+     * @throws XMLSecurityException
+     */
+    public static byte[] getDigestBytesFromCert(X509Certificate cert, String algorithmURI) throws XMLSecurityException {
+        String jcaDigestAlgorithm = JCEMapper.translateURItoJCEID(algorithmURI);
+        if (jcaDigestAlgorithm == null) {
+            Object exArgs[] = { algorithmURI };
+            throw new XMLSecurityException("XMLX509Digest.UnknownDigestAlgorithm", exArgs);
+        }
+
+        try {
+            MessageDigest md = MessageDigest.getInstance(jcaDigestAlgorithm);
+            return md.digest(cert.getEncoded());
+        } catch (Exception e) {
+            Object exArgs[] = { jcaDigestAlgorithm };
+            throw new XMLSecurityException("XMLX509Digest.FailedDigest", exArgs);
+        }
+
+    }
+
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_X509DIGEST;
+    }
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.content.x509;
 
@@ -31,17 +33,11 @@
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-/**
- *
- * @author $Author: mullan $
- */
-public class XMLX509IssuerSerial extends SignatureElementProxy
-        implements XMLX509DataContent {
+public class XMLX509IssuerSerial extends SignatureElementProxy implements XMLX509DataContent {
 
-    /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(
-                    XMLX509IssuerSerial.class.getName());
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(XMLX509IssuerSerial.class.getName());
 
     /**
      * Constructor XMLX509IssuerSerial
@@ -50,8 +46,7 @@
      * @param baseURI
      * @throws XMLSecurityException
      */
-    public XMLX509IssuerSerial(Element element, String baseURI)
-           throws XMLSecurityException {
+    public XMLX509IssuerSerial(Element element, String baseURI) throws XMLSecurityException {
         super(element, baseURI);
     }
 
@@ -62,11 +57,9 @@
      * @param x509IssuerName
      * @param x509SerialNumber
      */
-    public XMLX509IssuerSerial(Document doc, String x509IssuerName,
-                               BigInteger x509SerialNumber) {
-
+    public XMLX509IssuerSerial(Document doc, String x509IssuerName, BigInteger x509SerialNumber) {
         super(doc);
-        XMLUtils.addReturnToElement(this._constructionElement);
+        XMLUtils.addReturnToElement(this.constructionElement);
         addTextElement(x509IssuerName, Constants._TAG_X509ISSUERNAME);
         addTextElement(x509SerialNumber.toString(), Constants._TAG_X509SERIALNUMBER);
     }
@@ -78,8 +71,7 @@
      * @param x509IssuerName
      * @param x509SerialNumber
      */
-    public XMLX509IssuerSerial(Document doc, String x509IssuerName,
-                               String x509SerialNumber) {
+    public XMLX509IssuerSerial(Document doc, String x509IssuerName, String x509SerialNumber) {
         this(doc, x509IssuerName, new BigInteger(x509SerialNumber));
     }
 
@@ -90,10 +82,8 @@
      * @param x509IssuerName
      * @param x509SerialNumber
      */
-    public XMLX509IssuerSerial(Document doc, String x509IssuerName,
-                               int x509SerialNumber) {
-        this(doc, x509IssuerName,
-             new BigInteger(Integer.toString(x509SerialNumber)));
+    public XMLX509IssuerSerial(Document doc, String x509IssuerName, int x509SerialNumber) {
+        this(doc, x509IssuerName, new BigInteger(Integer.toString(x509SerialNumber)));
     }
 
     /**
@@ -103,10 +93,11 @@
      * @param x509certificate
      */
     public XMLX509IssuerSerial(Document doc, X509Certificate x509certificate) {
-
-        this(doc,
-             RFC2253Parser.normalize(x509certificate.getIssuerDN().getName()),
-             x509certificate.getSerialNumber());
+        this(
+            doc,
+            x509certificate.getIssuerX500Principal().getName(),
+            x509certificate.getSerialNumber()
+        );
     }
 
     /**
@@ -115,11 +106,11 @@
      * @return the serial number
      */
     public BigInteger getSerialNumber() {
-
-        String text = this.getTextFromChildElement
-            (Constants._TAG_X509SERIALNUMBER, Constants.SignatureSpecNS);
-        if (log.isLoggable(java.util.logging.Level.FINE))
+        String text =
+            this.getTextFromChildElement(Constants._TAG_X509SERIALNUMBER, Constants.SignatureSpecNS);
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
             log.log(java.util.logging.Level.FINE, "X509SerialNumber text: " + text);
+        }
 
         return new BigInteger(text);
     }
@@ -139,27 +130,28 @@
      * @return the issuer name
      */
     public String getIssuerName()  {
-
-        return RFC2253Parser
-           .normalize(this
-              .getTextFromChildElement(Constants._TAG_X509ISSUERNAME,
-                                       Constants.SignatureSpecNS));
+        return RFC2253Parser.normalize(
+            this.getTextFromChildElement(Constants._TAG_X509ISSUERNAME, Constants.SignatureSpecNS)
+        );
     }
 
     /** @inheritDoc */
     public boolean equals(Object obj) {
-
-        if (obj == null) {
-            return false;
-        }
-        if (!this.getClass().getName().equals(obj.getClass().getName())) {
+        if (!(obj instanceof XMLX509IssuerSerial)) {
             return false;
         }
 
         XMLX509IssuerSerial other = (XMLX509IssuerSerial) obj;
 
         return this.getSerialNumber().equals(other.getSerialNumber())
-               && this.getIssuerName().equals(other.getIssuerName());
+            && this.getIssuerName().equals(other.getIssuerName());
+    }
+
+    public int hashCode() {
+        int result = 17;
+        result = 31 * result + getSerialNumber().hashCode();
+        result = 31 * result + getIssuerName().hashCode();
+        return result;
     }
 
     /** @inheritDoc */
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,30 +2,28 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.content.x509;
 
-import java.io.IOException;
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
 import java.security.cert.X509Certificate;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Method;
+import java.util.Arrays;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.utils.Base64;
@@ -37,14 +35,13 @@
 /**
  * Handles SubjectKeyIdentifier (SKI) for X.509v3.
  *
- * @author $Author: mullan $
- * @see <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/security/cert/X509Extension.html">Interface X509Extension</A>
+ * @see <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/security/cert/X509Extension.html">
+ * Interface X509Extension</A>
  */
-public class XMLX509SKI extends SignatureElementProxy
-        implements XMLX509DataContent {
+public class XMLX509SKI extends SignatureElementProxy implements XMLX509DataContent {
 
-    /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(XMLX509SKI.class.getName());
 
     /**
@@ -53,7 +50,7 @@
      * distinct keys used by the same subject to be differentiated
      * (e.g., as key updating occurs).
      * <BR />
-     * A key identifer shall be unique with respect to all key identifiers
+     * A key identifier shall be unique with respect to all key identifiers
      * for the subject with which it is used. This extension is always non-critical.
      */
     public static final String SKI_OID = "2.5.29.14";
@@ -77,7 +74,7 @@
      * @throws XMLSecurityException
      */
     public XMLX509SKI(Document doc, X509Certificate x509certificate)
-           throws XMLSecurityException {
+        throws XMLSecurityException {
         super(doc);
         this.addBase64Text(XMLX509SKI.getSKIBytesFromCert(x509certificate));
     }
@@ -89,8 +86,7 @@
      * @param BaseURI
      * @throws XMLSecurityException
      */
-    public XMLX509SKI(Element element, String BaseURI)
-           throws XMLSecurityException {
+    public XMLX509SKI(Element element, String BaseURI) throws XMLSecurityException {
         super(element, BaseURI);
     }
 
@@ -117,9 +113,8 @@
         throws XMLSecurityException {
 
         if (cert.getVersion() < 3) {
-            Object exArgs[] = { new Integer(cert.getVersion()) };
-            throw new XMLSecurityException("certificate.noSki.lowVersion",
-                                           exArgs);
+            Object exArgs[] = { Integer.valueOf(cert.getVersion()) };
+            throw new XMLSecurityException("certificate.noSki.lowVersion", exArgs);
         }
 
         /*
@@ -137,7 +132,7 @@
          * Strip away first four bytes from the extensionValue
          * The first two bytes are the tag and length of the extensionValue
          * OCTET STRING, and the next two bytes are the tag and length of
-         * the skid OCTET STRING.
+         * the ski OCTET STRING.
          */
         byte skidValue[] = new byte[extensionValue.length - 4];
 
@@ -152,23 +147,35 @@
 
     /** @inheritDoc */
     public boolean equals(Object obj) {
-        if (obj == null) {
-            return false;
-        }
-        if (!this.getClass().getName().equals(obj.getClass().getName())) {
+        if (!(obj instanceof XMLX509SKI)) {
             return false;
         }
 
         XMLX509SKI other = (XMLX509SKI) obj;
 
         try {
-            return java.security.MessageDigest.isEqual(other.getSKIBytes(),
-                                        this.getSKIBytes());
+            return Arrays.equals(other.getSKIBytes(), this.getSKIBytes());
         } catch (XMLSecurityException ex) {
             return false;
         }
     }
 
+    public int hashCode() {
+        int result = 17;
+        try {
+            byte[] bytes = getSKIBytes();
+            for (int i = 0; i < bytes.length; i++) {
+                result = 31 * result + bytes[i];
+            }
+        } catch (XMLSecurityException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+            }
+        }
+        return result;
+
+    }
+
     /** @inheritDoc */
     public String getBaseLocalName() {
         return Constants._TAG_X509SKI;
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.content.x509;
 
@@ -30,65 +32,57 @@
 import org.w3c.dom.Element;
 
 /**
- *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  */
-public class XMLX509SubjectName extends SignatureElementProxy
-        implements XMLX509DataContent {
+public class XMLX509SubjectName extends SignatureElementProxy implements XMLX509DataContent {
 
-   /**
-    * Constructor X509SubjectName
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public XMLX509SubjectName(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
-   }
-
-   /**
-    * Constructor X509SubjectName
-    *
-    * @param doc
-    * @param X509SubjectNameString
-    */
-   public XMLX509SubjectName(Document doc, String X509SubjectNameString) {
+    /**
+     * Constructor X509SubjectName
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public XMLX509SubjectName(Element element, String BaseURI)
+        throws XMLSecurityException {
+        super(element, BaseURI);
+    }
 
-      super(doc);
+    /**
+     * Constructor X509SubjectName
+     *
+     * @param doc
+     * @param X509SubjectNameString
+     */
+    public XMLX509SubjectName(Document doc, String X509SubjectNameString) {
+        super(doc);
 
-      this.addText(X509SubjectNameString);
-   }
+        this.addText(X509SubjectNameString);
+    }
 
-   /**
-    * Constructor XMLX509SubjectName
-    *
-    * @param doc
-    * @param x509certificate
-    */
-   public XMLX509SubjectName(Document doc, X509Certificate x509certificate) {
-      this(doc,
-           RFC2253Parser.normalize(x509certificate.getSubjectDN().getName()));
-   }
+    /**
+     * Constructor XMLX509SubjectName
+     *
+     * @param doc
+     * @param x509certificate
+     */
+    public XMLX509SubjectName(Document doc, X509Certificate x509certificate) {
+        this(doc, x509certificate.getSubjectX500Principal().getName());
+    }
 
-   /**
-    * Method getSubjectName
-    *
-    *
-    * @return the subject name
-    */
-   public String getSubjectName() {
-      return RFC2253Parser.normalize(this.getTextFromTextChild());
-   }
+    /**
+     * Method getSubjectName
+     *
+     *
+     * @return the subject name
+     */
+    public String getSubjectName() {
+        return RFC2253Parser.normalize(this.getTextFromTextChild());
+    }
 
     /** @inheritDoc */
     public boolean equals(Object obj) {
-        if (obj == null) {
-            return false;
-        }
-
-        if (!this.getClass().getName().equals(obj.getClass().getName())) {
+        if (!(obj instanceof XMLX509SubjectName)) {
             return false;
         }
 
@@ -97,10 +91,16 @@
         String thisSubject = this.getSubjectName();
 
         return thisSubject.equals(otherSubject);
-   }
+    }
 
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_X509SUBJECTNAME;
-   }
+    public int hashCode() {
+        int result = 17;
+        result = 31 * result + this.getSubjectName().hashCode();
+        return result;
+    }
+
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_X509SUBJECTNAME;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,88 +2,80 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver;
 
-
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 
-
-/**
- *
- *
- * @author $Author: mullan $
- */
 public class InvalidKeyResolverException extends XMLSecurityException {
 
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
 
-   /**
-    * Constructor InvalidKeyResolverException
-    *
-    */
-   public InvalidKeyResolverException() {
-      super();
-   }
+    /**
+     * Constructor InvalidKeyResolverException
+     *
+     */
+    public InvalidKeyResolverException() {
+        super();
+    }
 
-   /**
-    * Constructor InvalidKeyResolverException
-    *
-    * @param _msgID
-    */
-   public InvalidKeyResolverException(String _msgID) {
-      super(_msgID);
-   }
+    /**
+     * Constructor InvalidKeyResolverException
+     *
+     * @param msgID
+     */
+    public InvalidKeyResolverException(String msgID) {
+        super(msgID);
+    }
 
-   /**
-    * Constructor InvalidKeyResolverException
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public InvalidKeyResolverException(String _msgID, Object exArgs[]) {
-      super(_msgID, exArgs);
-   }
+    /**
+     * Constructor InvalidKeyResolverException
+     *
+     * @param msgID
+     * @param exArgs
+     */
+    public InvalidKeyResolverException(String msgID, Object exArgs[]) {
+        super(msgID, exArgs);
+    }
 
-   /**
-    * Constructor InvalidKeyResolverException
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public InvalidKeyResolverException(String _msgID,
-                                      Exception _originalException) {
-      super(_msgID, _originalException);
-   }
+    /**
+     * Constructor InvalidKeyResolverException
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public InvalidKeyResolverException(String msgID, Exception originalException) {
+        super(msgID, originalException);
+    }
 
-   /**
-    * Constructor InvalidKeyResolverException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public InvalidKeyResolverException(String _msgID, Object exArgs[],
-                                      Exception _originalException) {
-      super(_msgID, exArgs, _originalException);
-   }
+    /**
+     * Constructor InvalidKeyResolverException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public InvalidKeyResolverException(String msgID, Object exArgs[], Exception originalException) {
+        super(msgID, exArgs, originalException);
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -31,10 +31,13 @@
 
 import javax.crypto.SecretKey;
 
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.DEREncodedKeyValueResolver;
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.DSAKeyValueResolver;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.KeyInfoReferenceResolver;
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RSAKeyValueResolver;
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RetrievalMethodResolver;
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509CertificateResolver;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509DigestResolver;
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509IssuerSerialResolver;
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SKIResolver;
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SubjectNameResolver;
@@ -277,6 +280,9 @@
         keyResolverList.add(new KeyResolver(new RetrievalMethodResolver()));
         keyResolverList.add(new KeyResolver(new X509SubjectNameResolver()));
         keyResolverList.add(new KeyResolver(new X509IssuerSerialResolver()));
+        keyResolverList.add(new KeyResolver(new DEREncodedKeyValueResolver()));
+        keyResolverList.add(new KeyResolver(new KeyInfoReferenceResolver()));
+        keyResolverList.add(new KeyResolver(new X509DigestResolver()));
 
         resolverVector.addAll(keyResolverList);
     }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,90 +2,80 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver;
 
-
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 
-
-/**
- *
- *
- *
- *
- * @author $Author: mullan $
- *
- */
 public class KeyResolverException extends XMLSecurityException {
 
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
 
-   /**
-    * Constructor KeyResolverException
-    *
-    */
-   public KeyResolverException() {
-      super();
-   }
+    /**
+     * Constructor KeyResolverException
+     *
+     */
+    public KeyResolverException() {
+        super();
+    }
 
-   /**
-    * Constructor KeyResolverException
-    *
-    * @param _msgID
-    */
-   public KeyResolverException(String _msgID) {
-      super(_msgID);
-   }
+    /**
+     * Constructor KeyResolverException
+     *
+     * @param msgID
+     */
+    public KeyResolverException(String msgID) {
+        super(msgID);
+    }
 
-   /**
-    * Constructor KeyResolverException
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public KeyResolverException(String _msgID, Object exArgs[]) {
-      super(_msgID, exArgs);
-   }
+    /**
+     * Constructor KeyResolverException
+     *
+     * @param msgID
+     * @param exArgs
+     */
+    public KeyResolverException(String msgID, Object exArgs[]) {
+        super(msgID, exArgs);
+    }
 
-   /**
-    * Constructor KeyResolverException
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public KeyResolverException(String _msgID, Exception _originalException) {
-      super(_msgID, _originalException);
-   }
+    /**
+     * Constructor KeyResolverException
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public KeyResolverException(String msgID, Exception originalException) {
+        super(msgID, originalException);
+    }
 
-   /**
-    * Constructor KeyResolverException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public KeyResolverException(String _msgID, Object exArgs[],
-                               Exception _originalException) {
-      super(_msgID, exArgs, _originalException);
-   }
+    /**
+     * Constructor KeyResolverException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public KeyResolverException(String msgID, Object exArgs[], Exception originalException) {
+        super(msgID, exArgs, originalException);
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,24 +2,27 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver;
 
+import java.security.PrivateKey;
 import java.security.PublicKey;
 import java.security.cert.X509Certificate;
 import java.util.HashMap;
@@ -30,78 +33,89 @@
 import org.w3c.dom.Element;
 
 /**
- * This class is abstract class for a child KeyInfo Elemnet.
+ * This class is an abstract class for a child KeyInfo Element.
  *
- * If you want your KeyResolver, at first you must extend this class, and register
+ * If you want the your KeyResolver, at firstly you must extend this class, and register
  * as following in config.xml
  * <PRE>
  *  &lt;KeyResolver URI="http://www.w3.org/2000/09/xmldsig#KeyValue"
  *   JAVACLASS="MyPackage.MyKeyValueImpl"//gt;
  * </PRE>
- *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
  */
 public abstract class KeyResolverSpi {
-   /**
-    * This method helps the {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver} to decide whether a
-    * {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi} is able to perform the requested action.
-    *
-    * @param element
-    * @param BaseURI
-    * @param storage
-    * @return
-    */
-   public boolean engineCanResolve(Element element, String BaseURI,
-                                                    StorageResolver storage) {
-           throw new UnsupportedOperationException();
-   }
+
+    /** Field properties */
+    protected java.util.Map<String, String> properties = null;
+
+    protected boolean globalResolver = false;
+
+    protected boolean secureValidation;
+
+    /**
+     * Set whether secure validation is enabled or not. The default is false.
+     */
+    public void setSecureValidation(boolean secureValidation) {
+        this.secureValidation = secureValidation;
+    }
 
-   /**
-    * Method engineResolvePublicKey
-    *
-    * @param element
-    * @param BaseURI
-    * @param storage
-    * @return resolved public key from the registered from the element.
-    *
-    * @throws KeyResolverException
-    */
-   public PublicKey engineResolvePublicKey(
-      Element element, String BaseURI, StorageResolver storage)
-         throws KeyResolverException {
-           throw new UnsupportedOperationException();
+    /**
+     * This method returns whether the KeyResolverSpi is able to perform the requested action.
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return whether the KeyResolverSpi is able to perform the requested action.
+     */
+    public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
+     * Method engineResolvePublicKey
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return resolved public key from the registered from the element.
+     *
+     * @throws KeyResolverException
+     */
+    public PublicKey engineResolvePublicKey(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        throw new UnsupportedOperationException();
     };
 
-   /**
-    * Method engineResolvePublicKey
-    *
-    * @param element
-    * @param BaseURI
-    * @param storage
-    * @return resolved public key from the registered from the element.
-    *
-    * @throws KeyResolverException
-    */
+    /**
+     * Method engineLookupAndResolvePublicKey
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return resolved public key from the registered from the element.
+     *
+     * @throws KeyResolverException
+     */
     public PublicKey engineLookupAndResolvePublicKey(
-      Element element, String BaseURI, StorageResolver storage)
-         throws KeyResolverException {
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
         KeyResolverSpi tmp = cloneIfNeeded();
-        if (!tmp.engineCanResolve(element, BaseURI, storage))
-                return null;
-            return tmp.engineResolvePublicKey(element, BaseURI, storage);
+        if (!tmp.engineCanResolve(element, baseURI, storage)) {
+            return null;
+        }
+        return tmp.engineResolvePublicKey(element, baseURI, storage);
     }
 
     private KeyResolverSpi cloneIfNeeded() throws KeyResolverException {
-        KeyResolverSpi tmp=this;
+        KeyResolverSpi tmp = this;
         if (globalResolver) {
-                try {
-                        tmp = (KeyResolverSpi) getClass().newInstance();
-                } catch (InstantiationException e) {
-                        throw new KeyResolverException("",e);
-                } catch (IllegalAccessException e) {
-                        throw new KeyResolverException("",e);
-                }
+            try {
+                tmp = getClass().newInstance();
+            } catch (InstantiationException e) {
+                throw new KeyResolverException("", e);
+            } catch (IllegalAccessException e) {
+                throw new KeyResolverException("", e);
+            }
         }
         return tmp;
     }
@@ -110,116 +124,138 @@
      * Method engineResolveCertificate
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @param storage
      * @return resolved X509Certificate key from the registered from the elements
      *
      * @throws KeyResolverException
      */
     public X509Certificate engineResolveX509Certificate(
-       Element element, String BaseURI, StorageResolver storage)
-          throws KeyResolverException{
-                   throw new UnsupportedOperationException();
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException{
+        throw new UnsupportedOperationException();
     };
 
-   /**
-    * Method engineResolveCertificate
-    *
-    * @param element
-    * @param BaseURI
-    * @param storage
-    * @return resolved X509Certificate key from the registered from the elements
-    *
-    * @throws KeyResolverException
-    */
+    /**
+     * Method engineLookupResolveX509Certificate
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return resolved X509Certificate key from the registered from the elements
+     *
+     * @throws KeyResolverException
+     */
     public X509Certificate engineLookupResolveX509Certificate(
-      Element element, String BaseURI, StorageResolver storage)
-         throws KeyResolverException {
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
         KeyResolverSpi tmp = cloneIfNeeded();
-        if (!tmp.engineCanResolve(element, BaseURI, storage))
-                return null;
-        return tmp.engineResolveX509Certificate(element, BaseURI, storage);
+        if (!tmp.engineCanResolve(element, baseURI, storage)) {
+            return null;
+        }
+        return tmp.engineResolveX509Certificate(element, baseURI, storage);
 
     }
     /**
      * Method engineResolveSecretKey
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @param storage
      * @return resolved SecretKey key from the registered from the elements
      *
      * @throws KeyResolverException
      */
     public SecretKey engineResolveSecretKey(
-       Element element, String BaseURI, StorageResolver storage)
-          throws KeyResolverException{
-                   throw new UnsupportedOperationException();
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException{
+        throw new UnsupportedOperationException();
     };
 
-   /**
-    * Method engineResolveSecretKey
-    *
-    * @param element
-    * @param BaseURI
-    * @param storage
-    * @return resolved SecretKey key from the registered from the elements
-    *
-    * @throws KeyResolverException
-    */
-   public SecretKey engineLookupAndResolveSecretKey(
-      Element element, String BaseURI, StorageResolver storage)
-         throws KeyResolverException {
-           KeyResolverSpi tmp = cloneIfNeeded();
-           if (!tmp.engineCanResolve(element, BaseURI, storage))
-                   return null;
-                return tmp.engineResolveSecretKey(element, BaseURI, storage);
-   }
+    /**
+     * Method engineLookupAndResolveSecretKey
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return resolved SecretKey key from the registered from the elements
+     *
+     * @throws KeyResolverException
+     */
+    public SecretKey engineLookupAndResolveSecretKey(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        KeyResolverSpi tmp = cloneIfNeeded();
+        if (!tmp.engineCanResolve(element, baseURI, storage)) {
+            return null;
+        }
+        return tmp.engineResolveSecretKey(element, baseURI, storage);
+    }
 
-   /** Field _properties */
-   protected java.util.Map<String,String> _properties = null;
-
-   protected boolean globalResolver=false;
+    /**
+     * Method engineLookupAndResolvePrivateKey
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return resolved PrivateKey key from the registered from the elements
+     *
+     * @throws KeyResolverException
+     */
+    public PrivateKey engineLookupAndResolvePrivateKey(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        // This method was added later, it has no equivalent
+        // engineResolvePrivateKey() in the old API.
+        // We cannot throw UnsupportedOperationException because
+        // KeyResolverSpi implementations who don't know about
+        // this method would stop the search too early.
+        return null;
+    }
 
-   /**
-    * Method engineSetProperty
-    *
-    * @param key
-    * @param value
-    */
-   public void engineSetProperty(String key, String value) {
-           if (_properties==null)
-                   _properties=new HashMap<String,String>();
-      this._properties.put(key, value);
-   }
+    /**
+     * Method engineSetProperty
+     *
+     * @param key
+     * @param value
+     */
+    public void engineSetProperty(String key, String value) {
+        if (properties == null) {
+            properties = new HashMap<String, String>();
+        }
+        properties.put(key, value);
+    }
 
-   /**
-    * Method engineGetProperty
-    *
-    * @param key
-    * @return obtain the property appointed by key
-    */
-   public String engineGetProperty(String key) {
-           if (_properties==null)
-                   return null;
+    /**
+     * Method engineGetProperty
+     *
+     * @param key
+     * @return obtain the property appointed by key
+     */
+    public String engineGetProperty(String key) {
+        if (properties == null) {
+            return null;
+        }
 
-      return this._properties.get(key);
-   }
+        return properties.get(key);
+    }
 
-   /**
-    * Method understandsProperty
-    *
-    * @param propertyToTest
-    * @return true if understood the property
-    */
-   public boolean understandsProperty(String propertyToTest) {
-           if (_properties==null)
-                   return false;
+    /**
+     * Method understandsProperty
+     *
+     * @param propertyToTest
+     * @return true if understood the property
+     */
+    public boolean understandsProperty(String propertyToTest) {
+        if (properties == null) {
+            return false;
+        }
 
-      return  this._properties.get(propertyToTest)!=null;
-   }
-   public void setGlobalResolver(boolean globalResolver) {
+        return properties.get(propertyToTest) != null;
+    }
+
+    public void setGlobalResolver(boolean globalResolver) {
         this.globalResolver = globalResolver;
-   }
+    }
 
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,83 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
+
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.cert.X509Certificate;
+
+import javax.crypto.SecretKey;
+
+import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+import com.sun.org.apache.xml.internal.security.keys.content.DEREncodedKeyValue;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
+import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
+import com.sun.org.apache.xml.internal.security.utils.Constants;
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
+import org.w3c.dom.Element;
+
+/**
+ * KeyResolverSpi implementation which resolves public keys from a
+ * <code>dsig11:DEREncodedKeyValue</code> element.
+ *
+ * @author Brent Putman (putmanb@georgetown.edu)
+ */
+public class DEREncodedKeyValueResolver extends KeyResolverSpi {
+
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(DEREncodedKeyValueResolver.class.getName());
+
+    /** {@inheritDoc}. */
+    public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
+        return XMLUtils.elementIsInSignature11Space(element, Constants._TAG_DERENCODEDKEYVALUE);
+    }
+
+    /** {@inheritDoc}. */
+    public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage)
+        throws KeyResolverException {
+
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
+        }
+
+        if (!engineCanResolve(element, baseURI, storage)) {
+            return null;
+        }
+
+        try {
+            DEREncodedKeyValue derKeyValue = new DEREncodedKeyValue(element, baseURI);
+            return derKeyValue.getPublicKey();
+        } catch (XMLSecurityException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
+            }
+        }
+
+        return null;
+    }
+
+    /** {@inheritDoc}. */
+    public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage)
+        throws KeyResolverException {
+        return null;
+    }
+
+    /** {@inheritDoc}. */
+    public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage)
+        throws KeyResolverException {
+        return null;
+    }
+
+    /** {@inheritDoc}. */
+    public PrivateKey engineLookupAndResolvePrivateKey(Element element, String baseURI, StorageResolver storage)
+        throws KeyResolverException {
+        return null;
+    }
+
+
+
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,30 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
 
-
-
 import java.security.PublicKey;
 import java.security.cert.X509Certificate;
 
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.keys.content.keyvalues.DSAKeyValue;
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
@@ -34,66 +33,70 @@
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Element;
 
-
-/**
- *
- * @author $Author: mullan $
- */
 public class DSAKeyValueResolver extends KeyResolverSpi {
 
-   /**
-    * Method engineResolvePublicKey
-    *
-    * @param element
-    * @param BaseURI
-    * @param storage
-    * @return null if no {@link PublicKey} could be obtained
-    */
-   public PublicKey engineLookupAndResolvePublicKey(
-           Element element, String BaseURI, StorageResolver storage) {
-            if (element == null) {
-                 return null;
-            }
-            Element dsaKeyElement=null;
-            boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element,
-                                      Constants._TAG_KEYVALUE);
-            if (isKeyValue) {
-                dsaKeyElement =
-                        XMLUtils.selectDsNode(element.getFirstChild(),Constants._TAG_DSAKEYVALUE,0);
-       } else if (XMLUtils.elementIsInSignatureSpace(element,
-               Constants._TAG_DSAKEYVALUE)) {
-                 // this trick is needed to allow the RetrievalMethodResolver to eat a
-                 // ds:DSAKeyValue directly (without KeyValue)
-                 dsaKeyElement = element;
-            }
-
-      if (dsaKeyElement == null) {
-                    return null;
-      }
-
-      try {
-         DSAKeyValue dsaKeyValue = new DSAKeyValue(dsaKeyElement,
-                                                   BaseURI);
-         PublicKey pk = dsaKeyValue.getPublicKey();
-
-         return pk;
-      } catch (XMLSecurityException ex) {
-                //do nothing
-      }
-
-      return null;
-   }
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(DSAKeyValueResolver.class.getName());
 
 
-   /** @inheritDoc */
-   public X509Certificate engineLookupResolveX509Certificate(
-           Element element, String BaseURI, StorageResolver storage) {
-      return null;
-   }
+    /**
+     * Method engineResolvePublicKey
+     *
+     * @param element
+     * @param BaseURI
+     * @param storage
+     * @return null if no {@link PublicKey} could be obtained
+     */
+    public PublicKey engineLookupAndResolvePublicKey(
+        Element element, String BaseURI, StorageResolver storage
+    ) {
+        if (element == null) {
+            return null;
+        }
+        Element dsaKeyElement = null;
+        boolean isKeyValue =
+            XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE);
+        if (isKeyValue) {
+            dsaKeyElement =
+                XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_DSAKEYVALUE, 0);
+        } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_DSAKEYVALUE)) {
+            // this trick is needed to allow the RetrievalMethodResolver to eat a
+            // ds:DSAKeyValue directly (without KeyValue)
+            dsaKeyElement = element;
+        }
+
+        if (dsaKeyElement == null) {
+            return null;
+        }
 
-   /** @inheritDoc */
-   public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
-           Element element, String BaseURI, StorageResolver storage){
-      return null;
-   }
+        try {
+            DSAKeyValue dsaKeyValue = new DSAKeyValue(dsaKeyElement, BaseURI);
+            PublicKey pk = dsaKeyValue.getPublicKey();
+
+            return pk;
+        } catch (XMLSecurityException ex) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
+            }
+            //do nothing
+        }
+
+        return null;
+    }
+
+
+    /** @inheritDoc */
+    public X509Certificate engineLookupResolveX509Certificate(
+        Element element, String BaseURI, StorageResolver storage
+    ) {
+        return null;
+    }
+
+    /** @inheritDoc */
+    public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
+        Element element, String BaseURI, StorageResolver storage
+    ) {
+        return null;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,39 +2,43 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
 
 import java.security.Key;
 import java.security.PublicKey;
 import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.List;
 
 import javax.crypto.SecretKey;
 
 import com.sun.org.apache.xml.internal.security.encryption.EncryptedKey;
 import com.sun.org.apache.xml.internal.security.encryption.XMLCipher;
+import com.sun.org.apache.xml.internal.security.encryption.XMLEncryptionException;
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
 import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
 import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Element;
 
-
 /**
  * The <code>EncryptedKeyResolver</code> is not a generic resolver.  It can
  * only be for specific instantiations, as the key being unwrapped will
@@ -47,78 +51,100 @@
  *
  * @author Berin Lautenbach
  */
-
 public class EncryptedKeyResolver extends KeyResolverSpi {
 
-        /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(
-                        RSAKeyValueResolver.class.getName());
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(EncryptedKeyResolver.class.getName());
+
+    private Key kek;
+    private String algorithm;
+    private List<KeyResolverSpi> internalKeyResolvers;
 
-
-        Key _kek;
-        String _algorithm;
+    /**
+     * Constructor for use when a KEK needs to be derived from a KeyInfo
+     * list
+     * @param algorithm
+     */
+    public EncryptedKeyResolver(String algorithm) {
+        kek = null;
+        this.algorithm = algorithm;
+    }
 
-        /**
-         * Constructor for use when a KEK needs to be derived from a KeyInfo
-         * list
-         * @param algorithm
-         */
-        public EncryptedKeyResolver(String algorithm) {
-                _kek = null;
-        _algorithm=algorithm;
-        }
+    /**
+     * Constructor used for when a KEK has been set
+     * @param algorithm
+     * @param kek
+     */
+    public EncryptedKeyResolver(String algorithm, Key kek) {
+        this.algorithm = algorithm;
+        this.kek = kek;
+    }
 
-        /**
-         * Constructor used for when a KEK has been set
-         * @param algorithm
-         * @param kek
-         */
-
-        public EncryptedKeyResolver(String algorithm, Key kek) {
-                _algorithm = algorithm;
-                _kek = kek;
-
+    /**
+     * This method is used to add a custom {@link KeyResolverSpi} to help
+     * resolve the KEK.
+     *
+     * @param realKeyResolver
+     */
+    public void registerInternalKeyResolver(KeyResolverSpi realKeyResolver) {
+        if (internalKeyResolvers == null) {
+            internalKeyResolvers = new ArrayList<KeyResolverSpi>();
         }
+        internalKeyResolvers.add(realKeyResolver);
+    }
 
     /** @inheritDoc */
-   public PublicKey engineLookupAndResolvePublicKey(
-           Element element, String BaseURI, StorageResolver storage) {
-
-           return null;
-   }
+    public PublicKey engineLookupAndResolvePublicKey(
+        Element element, String BaseURI, StorageResolver storage
+    ) {
+        return null;
+    }
 
-   /** @inheritDoc */
-   public X509Certificate engineLookupResolveX509Certificate(
-           Element element, String BaseURI, StorageResolver storage) {
-      return null;
-   }
+    /** @inheritDoc */
+    public X509Certificate engineLookupResolveX509Certificate(
+        Element element, String BaseURI, StorageResolver storage
+    ) {
+        return null;
+    }
 
-   /** @inheritDoc */
-   public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
-           Element element, String BaseURI, StorageResolver storage) {
-           SecretKey key=null;
-           if (log.isLoggable(java.util.logging.Level.FINE))
-                        log.log(java.util.logging.Level.FINE, "EncryptedKeyResolver - Can I resolve " + element.getTagName());
+    /** @inheritDoc */
+    public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
+        Element element, String BaseURI, StorageResolver storage
+    ) {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "EncryptedKeyResolver - Can I resolve " + element.getTagName());
+        }
+
+        if (element == null) {
+            return null;
+        }
 
-              if (element == null) {
-                 return null;
-              }
-
-              boolean isEncryptedKey = XMLUtils.elementIsInEncryptionSpace(element,
-                                      EncryptionConstants._TAG_ENCRYPTEDKEY);
+        SecretKey key = null;
+        boolean isEncryptedKey =
+            XMLUtils.elementIsInEncryptionSpace(element, EncryptionConstants._TAG_ENCRYPTEDKEY);
+        if (isEncryptedKey) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "Passed an Encrypted Key");
+            }
+            try {
+                XMLCipher cipher = XMLCipher.getInstance();
+                cipher.init(XMLCipher.UNWRAP_MODE, kek);
+                if (internalKeyResolvers != null) {
+                    int size = internalKeyResolvers.size();
+                    for (int i = 0; i < size; i++) {
+                        cipher.registerInternalKeyResolver(internalKeyResolvers.get(i));
+                    }
+                }
+                EncryptedKey ek = cipher.loadEncryptedKey(element);
+                key = (SecretKey) cipher.decryptKey(ek, algorithm);
+            } catch (XMLEncryptionException e) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+                }
+            }
+        }
 
-              if (isEncryptedKey) {
-                          log.log(java.util.logging.Level.FINE, "Passed an Encrypted Key");
-                          try {
-                                  XMLCipher cipher = XMLCipher.getInstance();
-                                  cipher.init(XMLCipher.UNWRAP_MODE, _kek);
-                                  EncryptedKey ek = cipher.loadEncryptedKey(element);
-                                  key = (SecretKey) cipher.decryptKey(ek, _algorithm);
-                          }
-                          catch (Exception e) {}
-              }
-
-      return key;
-   }
+        return key;
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,290 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.cert.X509Certificate;
+
+import javax.crypto.SecretKey;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
+import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+import com.sun.org.apache.xml.internal.security.keys.KeyInfo;
+import com.sun.org.apache.xml.internal.security.keys.content.KeyInfoReference;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
+import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
+import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
+import com.sun.org.apache.xml.internal.security.utils.Constants;
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
+import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.xml.sax.SAXException;
+
+/**
+ * KeyResolverSpi implementation which resolves public keys, private keys, secret keys, and X.509 certificates from a
+ * <code>dsig11:KeyInfoReference</code> element.
+ *
+ * @author Brent Putman (putmanb@georgetown.edu)
+ */
+public class KeyInfoReferenceResolver extends KeyResolverSpi {
+
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(KeyInfoReferenceResolver.class.getName());
+
+    /** {@inheritDoc}. */
+    public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
+        return XMLUtils.elementIsInSignature11Space(element, Constants._TAG_KEYINFOREFERENCE);
+    }
+
+    /** {@inheritDoc}. */
+    public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage)
+        throws KeyResolverException {
+
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
+        }
+
+        if (!engineCanResolve(element, baseURI, storage)) {
+            return null;
+        }
+
+        try {
+            KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage);
+            if (referent != null) {
+                return referent.getPublicKey();
+            }
+        } catch (XMLSecurityException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
+            }
+        }
+
+        return null;
+    }
+
+    /** {@inheritDoc}. */
+    public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage)
+        throws KeyResolverException {
+
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
+        }
+
+        if (!engineCanResolve(element, baseURI, storage)) {
+            return null;
+        }
+
+        try {
+            KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage);
+            if (referent != null) {
+                return referent.getX509Certificate();
+            }
+        } catch (XMLSecurityException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
+            }
+        }
+
+        return null;
+    }
+
+    /** {@inheritDoc}. */
+    public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage)
+        throws KeyResolverException {
+
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
+        }
+
+        if (!engineCanResolve(element, baseURI, storage)) {
+            return null;
+        }
+
+        try {
+            KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage);
+            if (referent != null) {
+                return referent.getSecretKey();
+            }
+        } catch (XMLSecurityException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
+            }
+        }
+
+        return null;
+    }
+
+    /** {@inheritDoc}. */
+    public PrivateKey engineLookupAndResolvePrivateKey(Element element, String baseURI, StorageResolver storage)
+        throws KeyResolverException {
+
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
+        }
+
+        if (!engineCanResolve(element, baseURI, storage)) {
+            return null;
+        }
+
+        try {
+            KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage);
+            if (referent != null) {
+                return referent.getPrivateKey();
+            }
+        } catch (XMLSecurityException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * Resolve the KeyInfoReference Element's URI attribute into a KeyInfo instance.
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return the KeyInfo which is referred to by this KeyInfoReference, or null if can not be resolved
+     * @throws XMLSecurityException
+     */
+    private KeyInfo resolveReferentKeyInfo(Element element, String baseURI, StorageResolver storage) throws XMLSecurityException {
+        KeyInfoReference reference = new KeyInfoReference(element, baseURI);
+        Attr uriAttr = reference.getURIAttr();
+
+        XMLSignatureInput resource = resolveInput(uriAttr, baseURI, secureValidation);
+
+        Element referentElement = null;
+        try {
+            referentElement = obtainReferenceElement(resource);
+        } catch (Exception e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
+            }
+            return null;
+        }
+
+        if (referentElement == null) {
+            log.log(java.util.logging.Level.FINE, "De-reference of KeyInfoReference URI returned null: " + uriAttr.getValue());
+            return null;
+        }
+
+        validateReference(referentElement);
+
+        KeyInfo referent = new KeyInfo(referentElement, baseURI);
+        referent.addStorageResolver(storage);
+        return referent;
+    }
+
+    /**
+     * Validate the Element referred to by the KeyInfoReference.
+     *
+     * @param referentElement
+     *
+     * @throws XMLSecurityException
+     */
+    private void validateReference(Element referentElement) throws XMLSecurityException {
+        if (!XMLUtils.elementIsInSignatureSpace(referentElement, Constants._TAG_KEYINFO)) {
+            Object exArgs[] = { new QName(referentElement.getNamespaceURI(), referentElement.getLocalName()) };
+            throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.WrongType", exArgs);
+        }
+
+        KeyInfo referent = new KeyInfo(referentElement, "");
+        if (referent.containsKeyInfoReference()) {
+            if (secureValidation) {
+                throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.ReferenceWithSecure");
+            } else {
+                // Don't support chains of references at this time. If do support in the future, this is where the code
+                // would go to validate that don't have a cycle, resulting in an infinite loop. This may be unrealistic
+                // to implement, and/or very expensive given remote URI references.
+                throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.ReferenceWithoutSecure");
+            }
+        }
+
+    }
+
+    /**
+     * Resolve the XML signature input represented by the specified URI.
+     *
+     * @param uri
+     * @param baseURI
+     * @param secureValidation
+     * @return
+     * @throws XMLSecurityException
+     */
+    private XMLSignatureInput resolveInput(Attr uri, String baseURI, boolean secureValidation)
+        throws XMLSecurityException {
+        ResourceResolver resRes = ResourceResolver.getInstance(uri, baseURI, secureValidation);
+        XMLSignatureInput resource = resRes.resolve(uri, baseURI, secureValidation);
+        return resource;
+    }
+
+    /**
+     * Resolve the Element effectively represented by the XML signature input source.
+     *
+     * @param resource
+     * @return
+     * @throws CanonicalizationException
+     * @throws ParserConfigurationException
+     * @throws IOException
+     * @throws SAXException
+     * @throws KeyResolverException
+     */
+    private Element obtainReferenceElement(XMLSignatureInput resource)
+        throws CanonicalizationException, ParserConfigurationException,
+        IOException, SAXException, KeyResolverException {
+
+        Element e;
+        if (resource.isElement()){
+            e = (Element) resource.getSubNode();
+        } else if (resource.isNodeSet()) {
+            log.log(java.util.logging.Level.FINE, "De-reference of KeyInfoReference returned an unsupported NodeSet");
+            return null;
+        } else {
+            // Retrieved resource is a byte stream
+            byte inputBytes[] = resource.getBytes();
+            e = getDocFromBytes(inputBytes);
+        }
+        return e;
+    }
+
+    /**
+     * Parses a byte array and returns the parsed Element.
+     *
+     * @param bytes
+     * @return the Document Element after parsing bytes
+     * @throws KeyResolverException if something goes wrong
+     */
+    private Element getDocFromBytes(byte[] bytes) throws KeyResolverException {
+        try {
+            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+            dbf.setNamespaceAware(true);
+            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
+            DocumentBuilder db = dbf.newDocumentBuilder();
+            Document doc = db.parse(new ByteArrayInputStream(bytes));
+            return doc.getDocumentElement();
+        } catch (SAXException ex) {
+            throw new KeyResolverException("empty", ex);
+        } catch (IOException ex) {
+            throw new KeyResolverException("empty", ex);
+        } catch (ParserConfigurationException ex) {
+            throw new KeyResolverException("empty", ex);
+        }
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,353 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
+
+import java.security.Key;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.X509Certificate;
+import java.util.Arrays;
+import java.util.Enumeration;
+import javax.crypto.SecretKey;
+import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+import com.sun.org.apache.xml.internal.security.keys.content.X509Data;
+import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate;
+import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509IssuerSerial;
+import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI;
+import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SubjectName;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
+import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
+import com.sun.org.apache.xml.internal.security.utils.Constants;
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
+import org.w3c.dom.Element;
+
+/**
+ * Resolves a PrivateKey within a KeyStore based on the KeyInfo hints.
+ * For X509Data hints, the certificate associated with the private key entry must match.
+ * For a KeyName hint, the KeyName must match the alias of a PrivateKey entry within the KeyStore.
+ */
+public class PrivateKeyResolver extends KeyResolverSpi {
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(PrivateKeyResolver.class.getName());
+
+    private KeyStore keyStore;
+    private char[] password;
+
+    /**
+     * Constructor.
+     */
+    public PrivateKeyResolver(KeyStore keyStore, char[] password) {
+        this.keyStore = keyStore;
+        this.password = password;
+    }
+
+    /**
+     * This method returns whether the KeyResolverSpi is able to perform the requested action.
+     *
+     * @param element
+     * @param BaseURI
+     * @param storage
+     * @return whether the KeyResolverSpi is able to perform the requested action.
+     */
+    public boolean engineCanResolve(Element element, String BaseURI, StorageResolver storage) {
+        if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)
+            || XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
+            return true;
+        }
+
+        return false;
+    }
+
+    /**
+     * Method engineLookupAndResolvePublicKey
+     *
+     * @param element
+     * @param BaseURI
+     * @param storage
+     * @return null if no {@link PublicKey} could be obtained
+     * @throws KeyResolverException
+     */
+    public PublicKey engineLookupAndResolvePublicKey(
+        Element element, String BaseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        return null;
+    }
+
+    /**
+     * Method engineResolveX509Certificate
+     * @inheritDoc
+     * @param element
+     * @param BaseURI
+     * @param storage
+     * @throws KeyResolverException
+     */
+    public X509Certificate engineLookupResolveX509Certificate(
+        Element element, String BaseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        return null;
+    }
+
+    /**
+     * Method engineResolveSecretKey
+     *
+     * @param element
+     * @param BaseURI
+     * @param storage
+     * @return resolved SecretKey key or null if no {@link SecretKey} could be obtained
+     *
+     * @throws KeyResolverException
+     */
+    public SecretKey engineResolveSecretKey(
+        Element element, String BaseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        return null;
+    }
+
+    /**
+     * Method engineResolvePrivateKey
+     * @inheritDoc
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return resolved PrivateKey key or null if no {@link PrivateKey} could be obtained
+     * @throws KeyResolverException
+     */
+    public PrivateKey engineLookupAndResolvePrivateKey(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
+        }
+
+        if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
+            PrivateKey privKey = resolveX509Data(element, baseURI);
+            if (privKey != null) {
+                return privKey;
+            }
+        } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
+            log.log(java.util.logging.Level.FINE, "Can I resolve KeyName?");
+            String keyName = element.getFirstChild().getNodeValue();
+
+            try {
+                Key key = keyStore.getKey(keyName, password);
+                if (key instanceof PrivateKey) {
+                    return (PrivateKey) key;
+                }
+            } catch (Exception e) {
+                log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
+            }
+        }
+
+        log.log(java.util.logging.Level.FINE, "I can't");
+        return null;
+    }
+
+    private PrivateKey resolveX509Data(Element element, String baseURI) {
+        log.log(java.util.logging.Level.FINE, "Can I resolve X509Data?");
+
+        try {
+            X509Data x509Data = new X509Data(element, baseURI);
+
+            int len = x509Data.lengthSKI();
+            for (int i = 0; i < len; i++) {
+                XMLX509SKI x509SKI = x509Data.itemSKI(i);
+                PrivateKey privKey = resolveX509SKI(x509SKI);
+                if (privKey != null) {
+                    return privKey;
+                }
+            }
+
+            len = x509Data.lengthIssuerSerial();
+            for (int i = 0; i < len; i++) {
+                XMLX509IssuerSerial x509Serial = x509Data.itemIssuerSerial(i);
+                PrivateKey privKey = resolveX509IssuerSerial(x509Serial);
+                if (privKey != null) {
+                    return privKey;
+                }
+            }
+
+            len = x509Data.lengthSubjectName();
+            for (int i = 0; i < len; i++) {
+                XMLX509SubjectName x509SubjectName = x509Data.itemSubjectName(i);
+                PrivateKey privKey = resolveX509SubjectName(x509SubjectName);
+                if (privKey != null) {
+                    return privKey;
+                }
+            }
+
+            len = x509Data.lengthCertificate();
+            for (int i = 0; i < len; i++) {
+                XMLX509Certificate x509Cert = x509Data.itemCertificate(i);
+                PrivateKey privKey = resolveX509Certificate(x509Cert);
+                if (privKey != null) {
+                    return privKey;
+                }
+            }
+        } catch (XMLSecurityException e) {
+            log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
+        } catch (KeyStoreException e) {
+            log.log(java.util.logging.Level.FINE, "KeyStoreException", e);
+        }
+
+        return null;
+    }
+
+    /*
+     * Search for a private key entry in the KeyStore with the same Subject Key Identifier
+     */
+    private PrivateKey resolveX509SKI(XMLX509SKI x509SKI) throws XMLSecurityException, KeyStoreException {
+        log.log(java.util.logging.Level.FINE, "Can I resolve X509SKI?");
+
+        Enumeration<String> aliases = keyStore.aliases();
+        while (aliases.hasMoreElements()) {
+            String alias = aliases.nextElement();
+            if (keyStore.isKeyEntry(alias)) {
+
+                Certificate cert = keyStore.getCertificate(alias);
+                if (cert instanceof X509Certificate) {
+                    XMLX509SKI certSKI = new XMLX509SKI(x509SKI.getDocument(), (X509Certificate) cert);
+
+                    if (certSKI.equals(x509SKI)) {
+                        log.log(java.util.logging.Level.FINE, "match !!! ");
+
+                        try {
+                            Key key = keyStore.getKey(alias, password);
+                            if (key instanceof PrivateKey) {
+                                return (PrivateKey) key;
+                            }
+                        } catch (Exception e) {
+                            log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
+                            // Keep searching
+                        }
+                    }
+                }
+            }
+        }
+
+        return null;
+    }
+
+    /*
+     * Search for a private key entry in the KeyStore with the same Issuer/Serial Number pair.
+     */
+    private PrivateKey resolveX509IssuerSerial(XMLX509IssuerSerial x509Serial) throws KeyStoreException {
+        log.log(java.util.logging.Level.FINE, "Can I resolve X509IssuerSerial?");
+
+        Enumeration<String> aliases = keyStore.aliases();
+        while (aliases.hasMoreElements()) {
+            String alias = aliases.nextElement();
+            if (keyStore.isKeyEntry(alias)) {
+
+                Certificate cert = keyStore.getCertificate(alias);
+                if (cert instanceof X509Certificate) {
+                    XMLX509IssuerSerial certSerial =
+                        new XMLX509IssuerSerial(x509Serial.getDocument(), (X509Certificate) cert);
+
+                    if (certSerial.equals(x509Serial)) {
+                        log.log(java.util.logging.Level.FINE, "match !!! ");
+
+                        try {
+                            Key key = keyStore.getKey(alias, password);
+                            if (key instanceof PrivateKey) {
+                                return (PrivateKey) key;
+                            }
+                        } catch (Exception e) {
+                            log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
+                            // Keep searching
+                        }
+                    }
+                }
+            }
+        }
+
+        return null;
+    }
+
+    /*
+     * Search for a private key entry in the KeyStore with the same Subject Name.
+     */
+    private PrivateKey resolveX509SubjectName(XMLX509SubjectName x509SubjectName) throws KeyStoreException {
+        log.log(java.util.logging.Level.FINE, "Can I resolve X509SubjectName?");
+
+        Enumeration<String> aliases = keyStore.aliases();
+        while (aliases.hasMoreElements()) {
+            String alias = aliases.nextElement();
+            if (keyStore.isKeyEntry(alias)) {
+
+                Certificate cert = keyStore.getCertificate(alias);
+                if (cert instanceof X509Certificate) {
+                    XMLX509SubjectName certSN =
+                        new XMLX509SubjectName(x509SubjectName.getDocument(), (X509Certificate) cert);
+
+                    if (certSN.equals(x509SubjectName)) {
+                        log.log(java.util.logging.Level.FINE, "match !!! ");
+
+                        try {
+                            Key key = keyStore.getKey(alias, password);
+                            if (key instanceof PrivateKey) {
+                                return (PrivateKey) key;
+                            }
+                        } catch (Exception e) {
+                            log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
+                            // Keep searching
+                        }
+                    }
+                }
+            }
+        }
+
+        return null;
+    }
+
+    /*
+     * Search for a private key entry in the KeyStore with the same Certificate.
+     */
+    private PrivateKey resolveX509Certificate(
+        XMLX509Certificate x509Cert
+    ) throws XMLSecurityException, KeyStoreException {
+        log.log(java.util.logging.Level.FINE, "Can I resolve X509Certificate?");
+        byte[] x509CertBytes = x509Cert.getCertificateBytes();
+
+        Enumeration<String> aliases = keyStore.aliases();
+        while (aliases.hasMoreElements()) {
+            String alias = aliases.nextElement();
+            if (keyStore.isKeyEntry(alias)) {
+
+                Certificate cert = keyStore.getCertificate(alias);
+                if (cert instanceof X509Certificate) {
+                    byte[] certBytes = null;
+
+                    try {
+                        certBytes = cert.getEncoded();
+                    } catch (CertificateEncodingException e1) {
+                    }
+
+                    if (certBytes != null && Arrays.equals(certBytes, x509CertBytes)) {
+                        log.log(java.util.logging.Level.FINE, "match !!! ");
+
+                        try {
+                            Key key = keyStore.getKey(alias, password);
+                            if (key instanceof PrivateKey) {
+                                return (PrivateKey) key;
+                            }
+                        }
+                        catch (Exception e) {
+                            log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
+                            // Keep searching
+                        }
+                    }
+                }
+            }
+        }
+
+        return null;
+    }
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
 
-
-
 import java.security.PublicKey;
 import java.security.cert.X509Certificate;
 
@@ -34,69 +34,63 @@
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Element;
 
-
-/**
- *
- * @author $Author: mullan $
- */
 public class RSAKeyValueResolver extends KeyResolverSpi {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(
-                        RSAKeyValueResolver.class.getName());
-
-   /** Field _rsaKeyElement */
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(RSAKeyValueResolver.class.getName());
 
 
-   /** @inheritDoc */
-   public PublicKey engineLookupAndResolvePublicKey(
-           Element element, String BaseURI, StorageResolver storage) {
-           if (log.isLoggable(java.util.logging.Level.FINE))
-                        log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
-      if (element == null) {
-         return null;
-      }
+    /** @inheritDoc */
+    public PublicKey engineLookupAndResolvePublicKey(
+        Element element, String BaseURI, StorageResolver storage
+    ) {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
+        }
+        if (element == null) {
+            return null;
+        }
 
-          boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element,
-                                              Constants._TAG_KEYVALUE);
-          Element rsaKeyElement=null;
-          if (isKeyValue) {
-                   rsaKeyElement = XMLUtils.selectDsNode(element.getFirstChild(),
-                                    Constants._TAG_RSAKEYVALUE, 0);
-          } else if (XMLUtils.elementIsInSignatureSpace(element,
-              Constants._TAG_RSAKEYVALUE)) {
-         // this trick is needed to allow the RetrievalMethodResolver to eat a
-         // ds:RSAKeyValue directly (without KeyValue)
-         rsaKeyElement = element;
-          }
+        boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE);
+        Element rsaKeyElement = null;
+        if (isKeyValue) {
+            rsaKeyElement =
+                XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_RSAKEYVALUE, 0);
+        } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RSAKEYVALUE)) {
+            // this trick is needed to allow the RetrievalMethodResolver to eat a
+            // ds:RSAKeyValue directly (without KeyValue)
+            rsaKeyElement = element;
+        }
 
+        if (rsaKeyElement == null) {
+            return null;
+        }
 
-      if (rsaKeyElement == null) {
-         return null;
-      }
+        try {
+            RSAKeyValue rsaKeyValue = new RSAKeyValue(rsaKeyElement, BaseURI);
 
-      try {
-         RSAKeyValue rsaKeyValue = new RSAKeyValue(rsaKeyElement,
-                                                   BaseURI);
+            return rsaKeyValue.getPublicKey();
+        } catch (XMLSecurityException ex) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
+            }
+        }
 
-         return rsaKeyValue.getPublicKey();
-      } catch (XMLSecurityException ex) {
-         log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
-      }
+        return null;
+    }
 
-      return null;
-   }
+    /** @inheritDoc */
+    public X509Certificate engineLookupResolveX509Certificate(
+        Element element, String BaseURI, StorageResolver storage
+    ) {
+        return null;
+    }
 
-   /** @inheritDoc */
-   public X509Certificate engineLookupResolveX509Certificate(
-           Element element, String BaseURI, StorageResolver storage) {
-      return null;
-   }
-
-   /** @inheritDoc */
-   public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
-           Element element, String BaseURI, StorageResolver storage) {
-      return null;
-   }
+    /** @inheritDoc */
+    public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
+        Element element, String BaseURI, StorageResolver storage
+    ) {
+        return null;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
 
-
-
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.security.PublicKey;
@@ -35,6 +35,8 @@
 import java.util.Set;
 
 import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
 
 import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
@@ -51,11 +53,11 @@
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
 import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 import org.xml.sax.SAXException;
 
-
 /**
  * The RetrievalMethodResolver can retrieve public keys and certificates from
  * other locations. The location is specified using the ds:RetrievalMethod
@@ -65,252 +67,325 @@
  * RetrievalMethodResolver cannot handle itself, resolving of the extracted
  * element is delegated back to the KeyResolver mechanism.
  *
- * @author $Author: mullan $ modified by Dave Garcia
+ * @author $Author: raul $ modified by Dave Garcia
  */
 public class RetrievalMethodResolver extends KeyResolverSpi {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(
-                        RetrievalMethodResolver.class.getName());
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(RetrievalMethodResolver.class.getName());
 
-   /**
-    * Method engineResolvePublicKey
-    * @inheritDoc
-    * @param element
-    * @param BaseURI
-    * @param storage
-    *
-    */
-   public PublicKey engineLookupAndResolvePublicKey(
-           Element element, String BaseURI, StorageResolver storage)
-              {
-           if  (!XMLUtils.elementIsInSignatureSpace(element,
-               Constants._TAG_RETRIEVALMETHOD)) {
-                   return null;
-           }
+    /**
+     * Method engineResolvePublicKey
+     * @inheritDoc
+     * @param element
+     * @param baseURI
+     * @param storage
+     */
+    public PublicKey engineLookupAndResolvePublicKey(
+           Element element, String baseURI, StorageResolver storage
+    ) {
+        if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RETRIEVALMETHOD)) {
+            return null;
+        }
 
-      try {
-                   //Create a retrieval method over the given element
-                   RetrievalMethod rm = new RetrievalMethod(element, BaseURI);
-               String type = rm.getType();
-                   XMLSignatureInput resource=resolveInput(rm,BaseURI);
-           if (RetrievalMethod.TYPE_RAWX509.equals(type)) {
-                //a raw certificate, direct parsing is done!
-                X509Certificate cert=getRawCertificate(resource);
-                                if (cert != null) {
-                                 return cert.getPublicKey();
-                            }
-                                return null;
-            };
-                        Element e = obtainRefrenceElement(resource);
-                        return resolveKey(e,BaseURI,storage);
-          } catch (XMLSecurityException ex) {
-         log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
-      } catch (CertificateException ex) {
-         log.log(java.util.logging.Level.FINE, "CertificateException", ex);
-      } catch (IOException ex) {
-         log.log(java.util.logging.Level.FINE, "IOException", ex);
-      } catch (ParserConfigurationException e) {
-                  log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e);
-          } catch (SAXException e) {
-                 log.log(java.util.logging.Level.FINE, "SAXException", e);
-          }
-      return null;
-   }
+        try {
+            // Create a retrieval method over the given element
+            RetrievalMethod rm = new RetrievalMethod(element, baseURI);
+            String type = rm.getType();
+            XMLSignatureInput resource = resolveInput(rm, baseURI, secureValidation);
+            if (RetrievalMethod.TYPE_RAWX509.equals(type)) {
+                // a raw certificate, direct parsing is done!
+                X509Certificate cert = getRawCertificate(resource);
+                if (cert != null) {
+                    return cert.getPublicKey();
+                }
+                return null;
+             }
+             Element e = obtainReferenceElement(resource);
+
+             // Check to make sure that the reference is not to another RetrievalMethod
+             // which points to this element
+             if (XMLUtils.elementIsInSignatureSpace(e, Constants._TAG_RETRIEVALMETHOD)) {
+                 if (secureValidation) {
+                     String error = "Error: It is forbidden to have one RetrievalMethod "
+                         + "point to another with secure validation";
+                     if (log.isLoggable(java.util.logging.Level.FINE)) {
+                         log.log(java.util.logging.Level.FINE, error);
+                     }
+                     return null;
+                 }
+                 RetrievalMethod rm2 = new RetrievalMethod(e, baseURI);
+                 XMLSignatureInput resource2 = resolveInput(rm2, baseURI, secureValidation);
+                 Element e2 = obtainReferenceElement(resource2);
+                 if (e2 == element) {
+                     if (log.isLoggable(java.util.logging.Level.FINE)) {
+                         log.log(java.util.logging.Level.FINE, "Error: Can't have RetrievalMethods pointing to each other");
+                     }
+                     return null;
+                 }
+             }
 
-   static private Element obtainRefrenceElement(XMLSignatureInput resource) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException, KeyResolverException {
-           Element e;
-           if (resource.isElement()){
-                   e=(Element) resource.getSubNode();
-           } else if (resource.isNodeSet()) {
-                   //Retrieved resource is a nodeSet
-                   e=getDocumentElement(resource.getNodeSet());
-           } else {
-                   //Retrieved resource is an inputStream
-                   byte inputBytes[] = resource.getBytes();
-                   e = getDocFromBytes(inputBytes);
-                   //otherwise, we parse the resource, create an Element and delegate
-                   if (log.isLoggable(java.util.logging.Level.FINE))
-                           log.log(java.util.logging.Level.FINE, "we have to parse " + inputBytes.length + " bytes");
-           }
-           return e;
-   }
+             return resolveKey(e, baseURI, storage);
+         } catch (XMLSecurityException ex) {
+             if (log.isLoggable(java.util.logging.Level.FINE)) {
+                 log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
+             }
+         } catch (CertificateException ex) {
+             if (log.isLoggable(java.util.logging.Level.FINE)) {
+                 log.log(java.util.logging.Level.FINE, "CertificateException", ex);
+             }
+         } catch (IOException ex) {
+             if (log.isLoggable(java.util.logging.Level.FINE)) {
+                 log.log(java.util.logging.Level.FINE, "IOException", ex);
+             }
+         } catch (ParserConfigurationException e) {
+             if (log.isLoggable(java.util.logging.Level.FINE)) {
+                 log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e);
+             }
+         } catch (SAXException e) {
+             if (log.isLoggable(java.util.logging.Level.FINE)) {
+                 log.log(java.util.logging.Level.FINE, "SAXException", e);
+             }
+         }
+         return null;
+    }
+
+    /**
+     * Method engineResolveX509Certificate
+     * @inheritDoc
+     * @param element
+     * @param baseURI
+     * @param storage
+     */
+    public X509Certificate engineLookupResolveX509Certificate(
+        Element element, String baseURI, StorageResolver storage) {
+        if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RETRIEVALMETHOD)) {
+             return null;
+        }
+
+        try {
+            RetrievalMethod rm = new RetrievalMethod(element, baseURI);
+            String type = rm.getType();
+            XMLSignatureInput resource = resolveInput(rm, baseURI, secureValidation);
+            if (RetrievalMethod.TYPE_RAWX509.equals(type)) {
+                return getRawCertificate(resource);
+            }
 
-   /**
-    * Method engineResolveX509Certificate
-    * @inheritDoc
-    * @param element
-    * @param BaseURI
-    * @param storage
-    *
-    */
-   public X509Certificate engineLookupResolveX509Certificate(
-           Element element, String BaseURI, StorageResolver storage)
-              {
-           if  (!XMLUtils.elementIsInSignatureSpace(element,
-               Constants._TAG_RETRIEVALMETHOD)) {
-                   return null;
-           }
+            Element e = obtainReferenceElement(resource);
+
+            // Check to make sure that the reference is not to another RetrievalMethod
+            // which points to this element
+            if (XMLUtils.elementIsInSignatureSpace(e, Constants._TAG_RETRIEVALMETHOD)) {
+                if (secureValidation) {
+                    String error = "Error: It is forbidden to have one RetrievalMethod "
+                        + "point to another with secure validation";
+                    if (log.isLoggable(java.util.logging.Level.FINE)) {
+                        log.log(java.util.logging.Level.FINE, error);
+                    }
+                    return null;
+                }
+                RetrievalMethod rm2 = new RetrievalMethod(e, baseURI);
+                XMLSignatureInput resource2 = resolveInput(rm2, baseURI, secureValidation);
+                Element e2 = obtainReferenceElement(resource2);
+                if (e2 == element) {
+                    if (log.isLoggable(java.util.logging.Level.FINE)) {
+                        log.log(java.util.logging.Level.FINE, "Error: Can't have RetrievalMethods pointing to each other");
+                    }
+                    return null;
+                }
+            }
 
-           try {
-         RetrievalMethod rm = new RetrievalMethod(element, BaseURI);
-                 String type = rm.getType();
-                 XMLSignatureInput resource=resolveInput(rm,BaseURI);
-                 if (RetrievalMethod.TYPE_RAWX509.equals(type)) {
-                X509Certificate cert=getRawCertificate(resource);
-            return cert;
-                 }
-                 Element e = obtainRefrenceElement(resource);
-                 return resolveCertificate(e,BaseURI,storage);
-      } catch (XMLSecurityException ex) {
-         log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
-      } catch (CertificateException ex) {
-         log.log(java.util.logging.Level.FINE, "CertificateException", ex);
-      } catch (IOException ex) {
-         log.log(java.util.logging.Level.FINE, "IOException", ex);
-          } catch (ParserConfigurationException e) {
-                  log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e);
-          } catch (SAXException e) {
-                 log.log(java.util.logging.Level.FINE, "SAXException", e);
-          }
-      return null;
-   }
+            return resolveCertificate(e, baseURI, storage);
+        } catch (XMLSecurityException ex) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
+            }
+        } catch (CertificateException ex) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "CertificateException", ex);
+            }
+        } catch (IOException ex) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "IOException", ex);
+            }
+        } catch (ParserConfigurationException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e);
+            }
+        } catch (SAXException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "SAXException", e);
+            }
+        }
+        return null;
+    }
 
-   /**
-    * Retrieves a x509Certificate from the given information
-    * @param e
-    * @param BaseURI
-    * @param storage
-    * @return
-    * @throws KeyResolverException
-    */
-   static private X509Certificate resolveCertificate(Element e,String BaseURI,StorageResolver storage) throws KeyResolverException{
-                  if (log.isLoggable(java.util.logging.Level.FINE))
-                          log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"+ e.getLocalName() + " Element");
-                  //An element has been provided
-          if (e != null) {
-                          return KeyResolver.getX509Certificate(e,BaseURI, storage);
-                  }
-                  return null;
-   }
+    /**
+     * Retrieves a x509Certificate from the given information
+     * @param e
+     * @param baseURI
+     * @param storage
+     * @return
+     * @throws KeyResolverException
+     */
+    private static X509Certificate resolveCertificate(
+        Element e, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"
+                + e.getLocalName() + " Element");
+        }
+        // An element has been provided
+        if (e != null) {
+            return KeyResolver.getX509Certificate(e, baseURI, storage);
+        }
+        return null;
+    }
 
-   /**
-    * Retrieves a x509Certificate from the given information
-    * @param e
-    * @param BaseURI
-    * @param storage
-    * @return
-    * @throws KeyResolverException
-    */
-   static private PublicKey resolveKey(Element e,String BaseURI,StorageResolver storage) throws KeyResolverException{
-                  if (log.isLoggable(java.util.logging.Level.FINE))
-                          log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"+ e.getLocalName() + " Element");
-                  //An element has been provided
-          if (e != null) {
-                          return KeyResolver.getPublicKey(e,BaseURI, storage);
-                  }
-                  return null;
-   }
+    /**
+     * Retrieves a PublicKey from the given information
+     * @param e
+     * @param baseURI
+     * @param storage
+     * @return
+     * @throws KeyResolverException
+     */
+    private static PublicKey resolveKey(
+        Element e, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"
+                + e.getLocalName() + " Element");
+        }
+        // An element has been provided
+        if (e != null) {
+            return KeyResolver.getPublicKey(e, baseURI, storage);
+        }
+        return null;
+    }
 
-   static private X509Certificate getRawCertificate(XMLSignatureInput resource) throws CanonicalizationException, IOException, CertificateException{
-           byte inputBytes[] = resource.getBytes();
-       // if the resource stores a raw certificate, we have to handle it
-       CertificateFactory certFact =CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID);
-       X509Certificate cert =(X509Certificate) certFact.generateCertificate(new ByteArrayInputStream(inputBytes));
-       return cert;
-   }
-   /**
-    * Resolves the input from the given retrieval method
-    * @return
-    * @throws XMLSecurityException
-    */
-   static private XMLSignatureInput resolveInput(RetrievalMethod rm,String BaseURI) throws XMLSecurityException{
-       Attr uri = rm.getURIAttr();
-           //Apply the trnasforms
-       Transforms transforms = rm.getTransforms();
-       ResourceResolver resRes = ResourceResolver.getInstance(uri, BaseURI);
-       if (resRes != null) {
-          XMLSignatureInput resource = resRes.resolve(uri, BaseURI);
-          if (transforms != null) {
-                  log.log(java.util.logging.Level.FINE, "We have Transforms");
-                          resource = transforms.performTransforms(resource);
-          }
-                  return resource;
-       }
-           return null;
-   }
+    private static Element obtainReferenceElement(XMLSignatureInput resource)
+        throws CanonicalizationException, ParserConfigurationException,
+        IOException, SAXException, KeyResolverException {
+        Element e;
+        if (resource.isElement()){
+            e = (Element) resource.getSubNode();
+        } else if (resource.isNodeSet()) {
+            // Retrieved resource is a nodeSet
+            e = getDocumentElement(resource.getNodeSet());
+        } else {
+            // Retrieved resource is an inputStream
+            byte inputBytes[] = resource.getBytes();
+            e = getDocFromBytes(inputBytes);
+            // otherwise, we parse the resource, create an Element and delegate
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "we have to parse " + inputBytes.length + " bytes");
+            }
+        }
+        return e;
+    }
+
+    private static X509Certificate getRawCertificate(XMLSignatureInput resource)
+        throws CanonicalizationException, IOException, CertificateException {
+        byte inputBytes[] = resource.getBytes();
+        // if the resource stores a raw certificate, we have to handle it
+        CertificateFactory certFact =
+            CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID);
+        X509Certificate cert = (X509Certificate)
+            certFact.generateCertificate(new ByteArrayInputStream(inputBytes));
+        return cert;
+    }
 
-   /**
-    * Parses a byte array and returns the parsed Element.
-    *
-    * @param bytes
-    * @return the Document Element after parsing bytes
-    * @throws KeyResolverException if something goes wrong
-    */
-   static Element getDocFromBytes(byte[] bytes) throws KeyResolverException {
-      try {
-         javax.xml.parsers.DocumentBuilderFactory dbf =javax.xml.parsers.DocumentBuilderFactory.newInstance();
-         dbf.setNamespaceAware(true);
-         dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
-         javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
-         org.w3c.dom.Document doc =
-            db.parse(new java.io.ByteArrayInputStream(bytes));
-         return doc.getDocumentElement();
-      } catch (org.xml.sax.SAXException ex) {
-         throw new KeyResolverException("empty", ex);
-      } catch (java.io.IOException ex) {
-         throw new KeyResolverException("empty", ex);
-      } catch (javax.xml.parsers.ParserConfigurationException ex) {
-         throw new KeyResolverException("empty", ex);
-      }
-   }
+    /**
+     * Resolves the input from the given retrieval method
+     * @return
+     * @throws XMLSecurityException
+     */
+    private static XMLSignatureInput resolveInput(
+        RetrievalMethod rm, String baseURI, boolean secureValidation
+    ) throws XMLSecurityException {
+        Attr uri = rm.getURIAttr();
+        // Apply the transforms
+        Transforms transforms = rm.getTransforms();
+        ResourceResolver resRes = ResourceResolver.getInstance(uri, baseURI, secureValidation);
+        XMLSignatureInput resource = resRes.resolve(uri, baseURI, secureValidation);
+        if (transforms != null) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "We have Transforms");
+            }
+            resource = transforms.performTransforms(resource);
+        }
+        return resource;
+    }
+
+    /**
+     * Parses a byte array and returns the parsed Element.
+     *
+     * @param bytes
+     * @return the Document Element after parsing bytes
+     * @throws KeyResolverException if something goes wrong
+     */
+    private static Element getDocFromBytes(byte[] bytes) throws KeyResolverException {
+        try {
+            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+            dbf.setNamespaceAware(true);
+            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
+            DocumentBuilder db = dbf.newDocumentBuilder();
+            Document doc = db.parse(new ByteArrayInputStream(bytes));
+            return doc.getDocumentElement();
+        } catch (SAXException ex) {
+            throw new KeyResolverException("empty", ex);
+        } catch (IOException ex) {
+            throw new KeyResolverException("empty", ex);
+        } catch (ParserConfigurationException ex) {
+            throw new KeyResolverException("empty", ex);
+        }
+    }
 
-   /**
-    * Method engineResolveSecretKey
-    * @inheritDoc
-    * @param element
-    * @param BaseURI
-    * @param storage
-    *
-    */
-   public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
-           Element element, String BaseURI, StorageResolver storage)
-   {
-      return null;
-   }
-
-   static Element getDocumentElement(Set<Node> set) {
-           Iterator<Node> it=set.iterator();
-           Element e=null;
-           while (it.hasNext()) {
-                   Node currentNode=it.next();
-                   if (currentNode != null && currentNode.getNodeType() == Node.ELEMENT_NODE) {
-                           e=(Element)currentNode;
-                           break;
-                   }
+    /**
+     * Method engineResolveSecretKey
+     * @inheritDoc
+     * @param element
+     * @param baseURI
+     * @param storage
+     */
+    public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
+        Element element, String baseURI, StorageResolver storage
+    ) {
+        return null;
+    }
 
-           }
-           List<Element> parents=new ArrayList<Element>(10);
+    private static Element getDocumentElement(Set<Node> set) {
+        Iterator<Node> it = set.iterator();
+        Element e = null;
+        while (it.hasNext()) {
+            Node currentNode = it.next();
+            if (currentNode != null && Node.ELEMENT_NODE == currentNode.getNodeType()) {
+                e = (Element) currentNode;
+                break;
+            }
+        }
+        List<Node> parents = new ArrayList<Node>();
 
-                //Obtain all the parents of the elemnt
-                while (e != null) {
-                        parents.add(e);
-                        Node n=e.getParentNode();
-                        if (n == null || n.getNodeType() != Node.ELEMENT_NODE) {
-                                break;
-                        }
-                        e=(Element)n;
-                }
-                //Visit them in reverse order.
-                ListIterator<Element> it2=parents.listIterator(parents.size()-1);
-                Element ele=null;
-                while (it2.hasPrevious()) {
-                        ele=it2.previous();
-                        if (set.contains(ele)) {
-                                return ele;
-                        }
+        // Obtain all the parents of the elemnt
+        while (e != null) {
+            parents.add(e);
+            Node n = e.getParentNode();
+            if (n == null || Node.ELEMENT_NODE != n.getNodeType()) {
+                break;
+            }
+            e = (Element) n;
         }
-                return null;
-   }
+        // Visit them in reverse order.
+        ListIterator<Node> it2 = parents.listIterator(parents.size()-1);
+        Element ele = null;
+        while (it2.hasPrevious()) {
+            ele = (Element) it2.previous();
+            if (set.contains(ele)) {
+                return ele;
+            }
+        }
+        return null;
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,129 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
+
+import java.security.Key;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.cert.X509Certificate;
+import javax.crypto.SecretKey;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
+import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
+import com.sun.org.apache.xml.internal.security.utils.Constants;
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
+import org.w3c.dom.Element;
+
+/**
+ * Resolves a SecretKey within a KeyStore based on the KeyName.
+ * The KeyName is the key entry alias within the KeyStore.
+ */
+public class SecretKeyResolver extends KeyResolverSpi
+{
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(SecretKeyResolver.class.getName());
+
+    private KeyStore keyStore;
+    private char[] password;
+
+    /**
+     * Constructor.
+     */
+    public SecretKeyResolver(KeyStore keyStore, char[] password) {
+        this.keyStore = keyStore;
+        this.password = password;
+    }
+
+    /**
+     * This method returns whether the KeyResolverSpi is able to perform the requested action.
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return whether the KeyResolverSpi is able to perform the requested action.
+     */
+    public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
+        return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME);
+    }
+
+    /**
+     * Method engineLookupAndResolvePublicKey
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return null if no {@link PublicKey} could be obtained
+     * @throws KeyResolverException
+     */
+    public PublicKey engineLookupAndResolvePublicKey(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        return null;
+    }
+
+    /**
+     * Method engineResolveX509Certificate
+     * @inheritDoc
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @throws KeyResolverException
+     */
+    public X509Certificate engineLookupResolveX509Certificate(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        return null;
+    }
+
+    /**
+     * Method engineResolveSecretKey
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return resolved SecretKey key or null if no {@link SecretKey} could be obtained
+     *
+     * @throws KeyResolverException
+     */
+    public SecretKey engineResolveSecretKey(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
+        }
+
+        if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
+            String keyName = element.getFirstChild().getNodeValue();
+            try {
+                Key key = keyStore.getKey(keyName, password);
+                if (key instanceof SecretKey) {
+                    return (SecretKey) key;
+                }
+            } catch (Exception e) {
+                log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
+            }
+        }
+
+        log.log(java.util.logging.Level.FINE, "I can't");
+        return null;
+    }
+
+    /**
+     * Method engineResolvePrivateKey
+     * @inheritDoc
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return resolved PrivateKey key or null if no {@link PrivateKey} could be obtained
+     * @throws KeyResolverException
+     */
+    public PrivateKey engineLookupAndResolvePrivateKey(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        return null;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,172 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
+
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.cert.X509Certificate;
+import javax.crypto.SecretKey;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
+import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
+import com.sun.org.apache.xml.internal.security.utils.Constants;
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
+import org.w3c.dom.Element;
+
+/**
+ * Resolves a single Key based on the KeyName.
+ */
+public class SingleKeyResolver extends KeyResolverSpi
+{
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(SingleKeyResolver.class.getName());
+
+    private String keyName;
+    private PublicKey publicKey;
+    private PrivateKey privateKey;
+    private SecretKey secretKey;
+
+    /**
+     * Constructor.
+     * @param keyName
+     * @param publicKey
+     */
+    public SingleKeyResolver(String keyName, PublicKey publicKey) {
+        this.keyName = keyName;
+        this.publicKey = publicKey;
+    }
+
+    /**
+     * Constructor.
+     * @param keyName
+     * @param privateKey
+     */
+    public SingleKeyResolver(String keyName, PrivateKey privateKey) {
+        this.keyName = keyName;
+        this.privateKey = privateKey;
+    }
+
+    /**
+     * Constructor.
+     * @param keyName
+     * @param secretKey
+     */
+    public SingleKeyResolver(String keyName, SecretKey secretKey) {
+        this.keyName = keyName;
+        this.secretKey = secretKey;
+    }
+
+    /**
+     * This method returns whether the KeyResolverSpi is able to perform the requested action.
+     *
+     * @param element
+     * @param BaseURI
+     * @param storage
+     * @return whether the KeyResolverSpi is able to perform the requested action.
+     */
+    public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
+        return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME);
+    }
+
+    /**
+     * Method engineLookupAndResolvePublicKey
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return null if no {@link PublicKey} could be obtained
+     * @throws KeyResolverException
+     */
+    public PublicKey engineLookupAndResolvePublicKey(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
+        }
+
+        if (publicKey != null
+            && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
+            String name = element.getFirstChild().getNodeValue();
+            if (keyName.equals(name)) {
+                return publicKey;
+            }
+        }
+
+        log.log(java.util.logging.Level.FINE, "I can't");
+        return null;
+    }
+
+    /**
+     * Method engineResolveX509Certificate
+     * @inheritDoc
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @throws KeyResolverException
+     */
+    public X509Certificate engineLookupResolveX509Certificate(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        return null;
+    }
+
+    /**
+     * Method engineResolveSecretKey
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return resolved SecretKey key or null if no {@link SecretKey} could be obtained
+     *
+     * @throws KeyResolverException
+     */
+    public SecretKey engineResolveSecretKey(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
+        }
+
+        if (secretKey != null
+            && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
+            String name = element.getFirstChild().getNodeValue();
+            if (keyName.equals(name)) {
+                return secretKey;
+            }
+        }
+
+        log.log(java.util.logging.Level.FINE, "I can't");
+        return null;
+    }
+
+    /**
+     * Method engineResolvePrivateKey
+     * @inheritDoc
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return resolved PrivateKey key or null if no {@link PrivateKey} could be obtained
+     * @throws KeyResolverException
+     */
+    public PrivateKey engineLookupAndResolvePrivateKey(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
+        }
+
+        if (privateKey != null
+            && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
+            String name = element.getFirstChild().getNodeValue();
+            if (keyName.equals(name)) {
+                return privateKey;
+            }
+        }
+
+        log.log(java.util.logging.Level.FINE, "I can't");
+        return null;
+    }
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,30 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
 
-
-
 import java.security.PublicKey;
 import java.security.cert.X509Certificate;
 
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate;
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
@@ -35,96 +34,93 @@
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Element;
 
-
 /**
  * Resolves Certificates which are directly contained inside a
  * <CODE>ds:X509Certificate</CODE> Element.
  *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  */
 public class X509CertificateResolver extends KeyResolverSpi {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(X509CertificateResolver.class.getName());
 
-
+    /**
+     * Method engineResolvePublicKey
+     * @inheritDoc
+     * @param element
+     * @param BaseURI
+     * @param storage
+     *
+     * @throws KeyResolverException
+     */
+    public PublicKey engineLookupAndResolvePublicKey(
+        Element element, String BaseURI, StorageResolver storage
+    ) throws KeyResolverException {
 
-   /**
-    * Method engineResolvePublicKey
-    * @inheritDoc
-    * @param element
-    * @param BaseURI
-    * @param storage
-    *
-    * @throws KeyResolverException
-    */
-   public PublicKey engineLookupAndResolvePublicKey(
-           Element element, String BaseURI, StorageResolver storage)
-              throws KeyResolverException {
-
-      X509Certificate cert = this.engineLookupResolveX509Certificate(element,
-                                BaseURI, storage);
+        X509Certificate cert =
+            this.engineLookupResolveX509Certificate(element, BaseURI, storage);
 
-      if (cert != null) {
-         return cert.getPublicKey();
-      }
+        if (cert != null) {
+            return cert.getPublicKey();
+        }
 
-      return null;
-   }
+        return null;
+    }
 
-   /**
-    * Method engineResolveX509Certificate
-    * @inheritDoc
-    * @param element
-    * @param BaseURI
-    * @param storage
-    *
-    * @throws KeyResolverException
-    */
-   public X509Certificate engineLookupResolveX509Certificate(
-           Element element, String BaseURI, StorageResolver storage)
-              throws KeyResolverException {
+    /**
+     * Method engineResolveX509Certificate
+     * @inheritDoc
+     * @param element
+     * @param BaseURI
+     * @param storage
+     *
+     * @throws KeyResolverException
+     */
+    public X509Certificate engineLookupResolveX509Certificate(
+        Element element, String BaseURI, StorageResolver storage
+    ) throws KeyResolverException {
 
-      try {
-          Element[] els=XMLUtils.selectDsNodes(element.getFirstChild(),
-                  Constants._TAG_X509CERTIFICATE);
-         if ((els == null) || (els.length == 0)) {
-                 Element el=XMLUtils.selectDsNode(element.getFirstChild(),
-                     Constants._TAG_X509DATA,0);
-             if (el!=null) {
-                 return engineLookupResolveX509Certificate(el, BaseURI, storage);
-             }
-                 return null;
-         }
+        try {
+            Element[] els =
+                XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509CERTIFICATE);
+            if ((els == null) || (els.length == 0)) {
+                Element el =
+                    XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_X509DATA, 0);
+                if (el != null) {
+                    return engineLookupResolveX509Certificate(el, BaseURI, storage);
+                }
+                return null;
+            }
 
-         // populate Object array
-         for (int i = 0; i < els.length; i++) {
-                 XMLX509Certificate xmlCert=new XMLX509Certificate(els[i], BaseURI);
-                 X509Certificate cert = xmlCert.getX509Certificate();
-            if (cert!=null) {
-                return cert;
+            // populate Object array
+            for (int i = 0; i < els.length; i++) {
+                XMLX509Certificate xmlCert = new XMLX509Certificate(els[i], BaseURI);
+                X509Certificate cert = xmlCert.getX509Certificate();
+                if (cert != null) {
+                    return cert;
+                }
             }
-         }
-         return null;
-      } catch (XMLSecurityException ex) {
-         log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
-
-         throw new KeyResolverException("generic.EmptyMessage", ex);
-      }
-   }
+            return null;
+        } catch (XMLSecurityException ex) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
+            }
+            throw new KeyResolverException("generic.EmptyMessage", ex);
+        }
+    }
 
-   /**
-    * Method engineResolveSecretKey
-    * @inheritDoc
-    * @param element
-    * @param BaseURI
-    * @param storage
-    *
-    */
-   public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
-           Element element, String BaseURI, StorageResolver storage)
-   {
-      return null;
-   }
+    /**
+     * Method engineResolveSecretKey
+     * @inheritDoc
+     * @param element
+     * @param BaseURI
+     * @param storage
+     */
+    public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
+        Element element, String BaseURI, StorageResolver storage
+    ) {
+        return null;
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,164 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
+
+import java.security.PublicKey;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.util.Arrays;
+import java.util.Iterator;
+
+import javax.crypto.SecretKey;
+
+import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+import com.sun.org.apache.xml.internal.security.keys.content.X509Data;
+import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Digest;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
+import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
+import com.sun.org.apache.xml.internal.security.utils.Constants;
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
+import org.w3c.dom.Element;
+
+/**
+ * KeyResolverSpi implementation which resolves public keys and X.509 certificates from a
+ * <code>dsig11:X509Digest</code> element.
+ *
+ * @author Brent Putman (putmanb@georgetown.edu)
+ */
+public class X509DigestResolver extends KeyResolverSpi {
+
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(X509DigestResolver.class.getName());
+
+    /** {@inheritDoc}. */
+    public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
+        if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
+            try {
+                X509Data x509Data = new X509Data(element, baseURI);
+                return x509Data.containsDigest();
+            } catch (XMLSecurityException e) {
+                return false;
+            }
+        } else {
+            return false;
+        }
+    }
+
+    /** {@inheritDoc}. */
+    public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage)
+        throws KeyResolverException {
+
+        X509Certificate cert = this.engineLookupResolveX509Certificate(element, baseURI, storage);
+
+        if (cert != null) {
+            return cert.getPublicKey();
+        }
+
+        return null;
+    }
+
+    /** {@inheritDoc}. */
+    public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage)
+        throws KeyResolverException {
+
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
+        }
+
+        if (!engineCanResolve(element, baseURI, storage)) {
+            return null;
+        }
+
+        try {
+            return resolveCertificate(element, baseURI, storage);
+        } catch (XMLSecurityException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
+            }
+        }
+
+        return null;
+    }
+
+    /** {@inheritDoc}. */
+    public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage)
+        throws KeyResolverException {
+        return null;
+    }
+
+    /**
+     * Resolves from the storage resolver the actual certificate represented by the digest.
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return
+     * @throws XMLSecurityException
+     */
+    private X509Certificate resolveCertificate(Element element, String baseURI, StorageResolver storage)
+        throws XMLSecurityException {
+
+        XMLX509Digest x509Digests[] = null;
+
+        Element x509childNodes[] = XMLUtils.selectDs11Nodes(element.getFirstChild(), Constants._TAG_X509DIGEST);
+
+        if (x509childNodes == null || x509childNodes.length <= 0) {
+            return null;
+        }
+
+        try {
+            checkStorage(storage);
+
+            x509Digests = new XMLX509Digest[x509childNodes.length];
+
+            for (int i = 0; i < x509childNodes.length; i++) {
+                x509Digests[i] = new XMLX509Digest(x509childNodes[i], baseURI);
+            }
+
+            Iterator<Certificate> storageIterator = storage.getIterator();
+            while (storageIterator.hasNext()) {
+                X509Certificate cert = (X509Certificate) storageIterator.next();
+
+                for (int i = 0; i < x509Digests.length; i++) {
+                    XMLX509Digest keyInfoDigest = x509Digests[i];
+                    byte[] certDigestBytes = XMLX509Digest.getDigestBytesFromCert(cert, keyInfoDigest.getAlgorithm());
+
+                    if (Arrays.equals(keyInfoDigest.getDigestBytes(), certDigestBytes)) {
+                        if (log.isLoggable(java.util.logging.Level.FINE)) {
+                            log.log(java.util.logging.Level.FINE, "Found certificate with: " + cert.getSubjectX500Principal().getName());
+                        }
+                        return cert;
+                    }
+
+                }
+            }
+
+        } catch (XMLSecurityException ex) {
+            throw new KeyResolverException("empty", ex);
+        }
+
+        return null;
+    }
+
+    /**
+     * Method checkSrorage
+     *
+     * @param storage
+     * @throws KeyResolverException
+     */
+    private void checkStorage(StorageResolver storage) throws KeyResolverException {
+        if (storage == null) {
+            Object exArgs[] = { Constants._TAG_X509DIGEST };
+            KeyResolverException ex = new KeyResolverException("KeyResolver.needStorageResolver", exArgs);
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "", ex);
+            }
+            throw ex;
+        }
+    }
+
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,28 +2,30 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
 
-
-
 import java.security.PublicKey;
+import java.security.cert.Certificate;
 import java.security.cert.X509Certificate;
+import java.util.Iterator;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.keys.content.X509Data;
@@ -35,114 +37,114 @@
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import org.w3c.dom.Element;
 
-
-/**
- *
- * @author $Author: mullan $
- */
 public class X509IssuerSerialResolver extends KeyResolverSpi {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(
-                    X509IssuerSerialResolver.class.getName());
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(X509IssuerSerialResolver.class.getName());
 
 
-   /** @inheritDoc */
-   public PublicKey engineLookupAndResolvePublicKey(
-           Element element, String BaseURI, StorageResolver storage)
-              throws KeyResolverException {
+    /** @inheritDoc */
+    public PublicKey engineLookupAndResolvePublicKey(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
 
-      X509Certificate cert = this.engineLookupResolveX509Certificate(element,
-                                BaseURI, storage);
+        X509Certificate cert =
+            this.engineLookupResolveX509Certificate(element, baseURI, storage);
 
-      if (cert != null) {
-         return cert.getPublicKey();
-      }
+        if (cert != null) {
+            return cert.getPublicKey();
+        }
 
-      return null;
-   }
+        return null;
+    }
 
-   /** @inheritDoc */
-   public X509Certificate engineLookupResolveX509Certificate(
-           Element element, String BaseURI, StorageResolver storage)
-              throws KeyResolverException {
-         if (log.isLoggable(java.util.logging.Level.FINE))
-                log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
+    /** @inheritDoc */
+    public X509Certificate engineLookupResolveX509Certificate(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
+        }
 
-          X509Data x509data = null;
-          try {
-             x509data = new X509Data(element, BaseURI);
-           } catch (XMLSignatureException ex) {
-              log.log(java.util.logging.Level.FINE, "I can't");
-         return null;
-           } catch (XMLSecurityException ex) {
-              log.log(java.util.logging.Level.FINE, "I can't");
-          return null;
-           }
-
-           if (x509data == null) {
-              log.log(java.util.logging.Level.FINE, "I can't");
-              return null;
-           }
+        X509Data x509data = null;
+        try {
+            x509data = new X509Data(element, baseURI);
+        } catch (XMLSignatureException ex) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "I can't");
+            }
+            return null;
+        } catch (XMLSecurityException ex) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "I can't");
+            }
+            return null;
+        }
 
-           if (!x509data.containsIssuerSerial()) {
-                    return null;
-           }
-      try {
-         if (storage == null) {
-            Object exArgs[] = { Constants._TAG_X509ISSUERSERIAL };
-            KeyResolverException ex =
-               new KeyResolverException("KeyResolver.needStorageResolver",
-                                        exArgs);
+        if (!x509data.containsIssuerSerial()) {
+            return null;
+        }
+        try {
+            if (storage == null) {
+                Object exArgs[] = { Constants._TAG_X509ISSUERSERIAL };
+                KeyResolverException ex =
+                    new KeyResolverException("KeyResolver.needStorageResolver", exArgs);
 
-            log.log(java.util.logging.Level.INFO, "", ex);
-            throw ex;
-         }
-
-         int noOfISS = x509data.lengthIssuerSerial();
-
-         while (storage.hasNext()) {
-            X509Certificate cert = storage.next();
-            XMLX509IssuerSerial certSerial = new XMLX509IssuerSerial(element.getOwnerDocument(), cert);
-
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Found Certificate Issuer: "
-                      + certSerial.getIssuerName());
-                log.log(java.util.logging.Level.FINE, "Found Certificate Serial: "
-                      + certSerial.getSerialNumber().toString());
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "", ex);
+                }
+                throw ex;
             }
 
-            for (int i=0; i<noOfISS; i++) {
-               XMLX509IssuerSerial xmliss = x509data.itemIssuerSerial(i);
+            int noOfISS = x509data.lengthIssuerSerial();
+
+            Iterator<Certificate> storageIterator = storage.getIterator();
+            while (storageIterator.hasNext()) {
+                X509Certificate cert = (X509Certificate)storageIterator.next();
+                XMLX509IssuerSerial certSerial = new XMLX509IssuerSerial(element.getOwnerDocument(), cert);
+
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "Found Certificate Issuer: " + certSerial.getIssuerName());
+                    log.log(java.util.logging.Level.FINE, "Found Certificate Serial: " + certSerial.getSerialNumber().toString());
+                }
+
+                for (int i = 0; i < noOfISS; i++) {
+                    XMLX509IssuerSerial xmliss = x509data.itemIssuerSerial(i);
 
-               if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Found Element Issuer:     "
-                         + xmliss.getIssuerName());
-                    log.log(java.util.logging.Level.FINE, "Found Element Serial:     "
-                         + xmliss.getSerialNumber().toString());
-               }
+                    if (log.isLoggable(java.util.logging.Level.FINE)) {
+                        log.log(java.util.logging.Level.FINE, "Found Element Issuer:     "
+                                  + xmliss.getIssuerName());
+                        log.log(java.util.logging.Level.FINE, "Found Element Serial:     "
+                                  + xmliss.getSerialNumber().toString());
+                    }
 
-               if (certSerial.equals(xmliss)) {
-                  log.log(java.util.logging.Level.FINE, "match !!! ");
-
-                  return cert;
-               }
-                log.log(java.util.logging.Level.FINE, "no match...");
+                    if (certSerial.equals(xmliss)) {
+                        if (log.isLoggable(java.util.logging.Level.FINE)) {
+                            log.log(java.util.logging.Level.FINE, "match !!! ");
+                        }
+                        return cert;
+                    }
+                    if (log.isLoggable(java.util.logging.Level.FINE)) {
+                        log.log(java.util.logging.Level.FINE, "no match...");
+                    }
+                }
             }
-         }
 
-         return null;
-      } catch (XMLSecurityException ex) {
-         log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
+            return null;
+        } catch (XMLSecurityException ex) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
+            }
 
-         throw new KeyResolverException("generic.EmptyMessage", ex);
-      }
-   }
+            throw new KeyResolverException("generic.EmptyMessage", ex);
+        }
+    }
 
-   /** @inheritDoc */
-   public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
-           Element element, String BaseURI, StorageResolver storage) {
-      return null;
-   }
+    /** @inheritDoc */
+    public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
+        Element element, String baseURI, StorageResolver storage
+    ) {
+        return null;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,28 +2,30 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
 
-
-
 import java.security.PublicKey;
+import java.security.cert.Certificate;
 import java.security.cert.X509Certificate;
+import java.util.Iterator;
 
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
@@ -35,124 +37,121 @@
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Element;
 
-
-/**
- *
- *
- * @author $Author: mullan $
- */
 public class X509SKIResolver extends KeyResolverSpi {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(X509SKIResolver.class.getName());
 
 
-   /**
-    * Method engineResolvePublicKey
-    *
-    * @param element
-    * @param BaseURI
-    * @param storage
-    * @return null if no {@link PublicKey} could be obtained
-    * @throws KeyResolverException
-    */
-   public PublicKey engineLookupAndResolvePublicKey(
-           Element element, String BaseURI, StorageResolver storage)
-              throws KeyResolverException {
+    /**
+     * Method engineResolvePublicKey
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return null if no {@link PublicKey} could be obtained
+     * @throws KeyResolverException
+     */
+    public PublicKey engineLookupAndResolvePublicKey(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
 
-      X509Certificate cert = this.engineLookupResolveX509Certificate(element,
-                                BaseURI, storage);
+        X509Certificate cert =
+            this.engineLookupResolveX509Certificate(element, baseURI, storage);
 
-      if (cert != null) {
-         return cert.getPublicKey();
-      }
+        if (cert != null) {
+            return cert.getPublicKey();
+        }
 
-      return null;
-   }
+        return null;
+    }
 
-   /**
-    * Method engineResolveX509Certificate
-    * @inheritDoc
-    * @param element
-    * @param BaseURI
-    * @param storage
-    *
-    * @throws KeyResolverException
-    */
-   public X509Certificate engineLookupResolveX509Certificate(
-           Element element, String BaseURI, StorageResolver storage)
-              throws KeyResolverException {
-           if (log.isLoggable(java.util.logging.Level.FINE)) {
-             log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
-           }
-           if (!XMLUtils.elementIsInSignatureSpace(element,
-              Constants._TAG_X509DATA)) {
-                 log.log(java.util.logging.Level.FINE, "I can't");
-                 return null;
-           }
-           /** Field _x509childObject[] */
-           XMLX509SKI x509childObject[] = null;
+    /**
+     * Method engineResolveX509Certificate
+     * @inheritDoc
+     * @param element
+     * @param baseURI
+     * @param storage
+     *
+     * @throws KeyResolverException
+     */
+    public X509Certificate engineLookupResolveX509Certificate(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
+        }
+        if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "I can't");
+            }
+            return null;
+        }
+        /** Field _x509childObject[] */
+        XMLX509SKI x509childObject[] = null;
 
-           Element x509childNodes[] = null;
-           x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(),
-                          Constants._TAG_X509SKI);
+        Element x509childNodes[] = null;
+        x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SKI);
 
-           if (!((x509childNodes != null)
-                         && (x509childNodes.length > 0))) {
-                   log.log(java.util.logging.Level.FINE, "I can't");
-                return null;
-           }
-           try {
-         if (storage == null) {
-            Object exArgs[] = { Constants._TAG_X509SKI };
-            KeyResolverException ex =
-               new KeyResolverException("KeyResolver.needStorageResolver",
-                                        exArgs);
-
-            log.log(java.util.logging.Level.INFO, "", ex);
+        if (!((x509childNodes != null) && (x509childNodes.length > 0))) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "I can't");
+            }
+            return null;
+        }
+        try {
+            if (storage == null) {
+                Object exArgs[] = { Constants._TAG_X509SKI };
+                KeyResolverException ex =
+                    new KeyResolverException("KeyResolver.needStorageResolver", exArgs);
 
-            throw ex;
-         }
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "", ex);
+                }
 
-         x509childObject = new XMLX509SKI[x509childNodes.length];
+                throw ex;
+            }
+
+            x509childObject = new XMLX509SKI[x509childNodes.length];
 
-         for (int i = 0; i < x509childNodes.length; i++) {
-            x509childObject[i] =
-               new XMLX509SKI(x509childNodes[i], BaseURI);
-         }
+            for (int i = 0; i < x509childNodes.length; i++) {
+                x509childObject[i] = new XMLX509SKI(x509childNodes[i], baseURI);
+            }
 
-         while (storage.hasNext()) {
-            X509Certificate cert = storage.next();
-            XMLX509SKI certSKI = new XMLX509SKI(element.getOwnerDocument(), cert);
+            Iterator<Certificate> storageIterator = storage.getIterator();
+            while (storageIterator.hasNext()) {
+                X509Certificate cert = (X509Certificate)storageIterator.next();
+                XMLX509SKI certSKI = new XMLX509SKI(element.getOwnerDocument(), cert);
 
-            for (int i = 0; i < x509childObject.length; i++) {
-               if (certSKI.equals(x509childObject[i])) {
-                  log.log(java.util.logging.Level.FINE, "Return PublicKey from "
-                            + cert.getSubjectDN().getName());
+                for (int i = 0; i < x509childObject.length; i++) {
+                    if (certSKI.equals(x509childObject[i])) {
+                        if (log.isLoggable(java.util.logging.Level.FINE)) {
+                            log.log(java.util.logging.Level.FINE, "Return PublicKey from " + cert.getSubjectX500Principal().getName());
+                        }
 
-                  return cert;
-               }
+                        return cert;
+                    }
+                }
             }
-         }
-      } catch (XMLSecurityException ex) {
-         throw new KeyResolverException("empty", ex);
-      }
+        } catch (XMLSecurityException ex) {
+            throw new KeyResolverException("empty", ex);
+        }
 
-      return null;
-   }
+        return null;
+    }
 
-   /**
-    * Method engineResolveSecretKey
-    * @inheritDoc
-    * @param element
-    * @param BaseURI
-    * @param storage
-    *
-    */
-   public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
-           Element element, String BaseURI, StorageResolver storage)
-    {
-      return null;
-   }
+    /**
+     * Method engineResolveSecretKey
+     * @inheritDoc
+     * @param element
+     * @param baseURI
+     * @param storage
+     *
+     */
+    public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
+        Element element, String baseURI, StorageResolver storage
+    ) {
+        return null;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,28 +2,30 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
 
-
-
 import java.security.PublicKey;
+import java.security.cert.Certificate;
 import java.security.cert.X509Certificate;
+import java.util.Iterator;
 
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
@@ -35,133 +37,140 @@
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Element;
 
-
-/**
- *
- * @author $Author: mullan $
- */
 public class X509SubjectNameResolver extends KeyResolverSpi {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(
-                    X509SubjectNameResolver.class.getName());
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(X509SubjectNameResolver.class.getName());
 
 
-   /**
-    * Method engineResolvePublicKey
-    *
-    * @param element
-    * @param BaseURI
-    * @param storage
-    * @return null if no {@link PublicKey} could be obtained
-    * @throws KeyResolverException
-    */
-   public PublicKey engineLookupAndResolvePublicKey(
-           Element element, String BaseURI, StorageResolver storage)
-              throws KeyResolverException {
+    /**
+     * Method engineResolvePublicKey
+     *
+     * @param element
+     * @param BaseURI
+     * @param storage
+     * @return null if no {@link PublicKey} could be obtained
+     * @throws KeyResolverException
+     */
+    public PublicKey engineLookupAndResolvePublicKey(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
 
-      X509Certificate cert = this.engineLookupResolveX509Certificate(element,
-                                BaseURI, storage);
+        X509Certificate cert =
+            this.engineLookupResolveX509Certificate(element, baseURI, storage);
 
-      if (cert != null) {
-         return cert.getPublicKey();
-      }
+        if (cert != null) {
+            return cert.getPublicKey();
+        }
 
-      return null;
-   }
+        return null;
+    }
 
-   /**
-    * Method engineResolveX509Certificate
-    * @inheritDoc
-    * @param element
-    * @param BaseURI
-    * @param storage
-    *
-    * @throws KeyResolverException
-    */
-   public X509Certificate engineLookupResolveX509Certificate(
-           Element element, String BaseURI, StorageResolver storage)
-              throws KeyResolverException {
-           if (log.isLoggable(java.util.logging.Level.FINE))
-                log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
-           Element[] x509childNodes = null;
-           XMLX509SubjectName x509childObject[] = null;
+    /**
+     * Method engineResolveX509Certificate
+     * @inheritDoc
+     * @param element
+     * @param baseURI
+     * @param storage
+     *
+     * @throws KeyResolverException
+     */
+    public X509Certificate engineLookupResolveX509Certificate(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
+        }
+        Element[] x509childNodes = null;
+        XMLX509SubjectName x509childObject[] = null;
 
-           if (!XMLUtils.elementIsInSignatureSpace(element,
-                         Constants._TAG_X509DATA) ) {
-                        log.log(java.util.logging.Level.FINE, "I can't");
-                 return null;
-           }
-       x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(),
-                 Constants._TAG_X509SUBJECTNAME);
+        if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "I can't");
+            }
+            return null;
+        }
+        x509childNodes =
+            XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SUBJECTNAME);
 
         if (!((x509childNodes != null)
-                && (x509childNodes.length > 0))) {
-                    log.log(java.util.logging.Level.FINE, "I can't");
-                    return null;
+            && (x509childNodes.length > 0))) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "I can't");
+            }
+            return null;
+        }
+
+        try {
+            if (storage == null) {
+                Object exArgs[] = { Constants._TAG_X509SUBJECTNAME };
+                KeyResolverException ex =
+                    new KeyResolverException("KeyResolver.needStorageResolver", exArgs);
+
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "", ex);
+                }
+
+                throw ex;
+            }
+
+            x509childObject = new XMLX509SubjectName[x509childNodes.length];
+
+            for (int i = 0; i < x509childNodes.length; i++) {
+                x509childObject[i] = new XMLX509SubjectName(x509childNodes[i], baseURI);
             }
 
-      try {
-         if (storage == null) {
-            Object exArgs[] = { Constants._TAG_X509SUBJECTNAME };
-            KeyResolverException ex =
-               new KeyResolverException("KeyResolver.needStorageResolver",
-                                        exArgs);
+            Iterator<Certificate> storageIterator = storage.getIterator();
+            while (storageIterator.hasNext()) {
+                X509Certificate cert = (X509Certificate)storageIterator.next();
+                XMLX509SubjectName certSN =
+                    new XMLX509SubjectName(element.getOwnerDocument(), cert);
 
-            log.log(java.util.logging.Level.INFO, "", ex);
-
-            throw ex;
-         }
-
-         x509childObject =
-            new XMLX509SubjectName[x509childNodes.length];
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "Found Certificate SN: " + certSN.getSubjectName());
+                }
 
-         for (int i = 0; i < x509childNodes.length; i++) {
-            x509childObject[i] =
-               new XMLX509SubjectName(x509childNodes[i],
-                                      BaseURI);
-         }
+                for (int i = 0; i < x509childObject.length; i++) {
+                    if (log.isLoggable(java.util.logging.Level.FINE)) {
+                        log.log(java.util.logging.Level.FINE, "Found Element SN:     "
+                              + x509childObject[i].getSubjectName());
+                    }
 
-         while (storage.hasNext()) {
-            X509Certificate cert = storage.next();
-            XMLX509SubjectName certSN =
-               new XMLX509SubjectName(element.getOwnerDocument(), cert);
-
-            log.log(java.util.logging.Level.FINE, "Found Certificate SN: " + certSN.getSubjectName());
-
-            for (int i = 0; i < x509childObject.length; i++) {
-               log.log(java.util.logging.Level.FINE, "Found Element SN:     "
-                         + x509childObject[i].getSubjectName());
+                    if (certSN.equals(x509childObject[i])) {
+                        if (log.isLoggable(java.util.logging.Level.FINE)) {
+                            log.log(java.util.logging.Level.FINE, "match !!! ");
+                        }
 
-               if (certSN.equals(x509childObject[i])) {
-                  log.log(java.util.logging.Level.FINE, "match !!! ");
+                        return cert;
+                    }
+                    if (log.isLoggable(java.util.logging.Level.FINE)) {
+                        log.log(java.util.logging.Level.FINE, "no match...");
+                    }
+                }
+            }
 
-                  return cert;
-               }
-               log.log(java.util.logging.Level.FINE, "no match...");
+            return null;
+        } catch (XMLSecurityException ex) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
             }
-         }
-
-         return null;
-      } catch (XMLSecurityException ex) {
-         log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
 
-         throw new KeyResolverException("generic.EmptyMessage", ex);
-      }
-   }
+            throw new KeyResolverException("generic.EmptyMessage", ex);
+        }
+    }
 
-   /**
-    * Method engineResolveSecretKey
-    * @inheritDoc
-    * @param element
-    * @param BaseURI
-    * @param storage
-    *
-    */
-   public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
-           Element element, String BaseURI, StorageResolver storage)
-   {
-      return null;
-   }
+    /**
+     * Method engineResolveSecretKey
+     * @inheritDoc
+     * @param element
+     * @param baseURI
+     * @param storage
+     *
+     */
+    public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
+        Element element, String baseURI, StorageResolver storage
+    ) {
+        return null;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,197 +2,187 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.storage;
 
 import java.security.KeyStore;
+import java.security.cert.Certificate;
 import java.security.cert.X509Certificate;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
+import java.util.NoSuchElementException;
 
 import com.sun.org.apache.xml.internal.security.keys.storage.implementations.KeyStoreResolver;
 import com.sun.org.apache.xml.internal.security.keys.storage.implementations.SingleCertificateResolver;
 
-
 /**
  * This class collects customized resolvers for Certificates.
- *
- * @author $Author: mullan $
  */
 public class StorageResolver {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(StorageResolver.class.getName());
 
-   /** Field _storageResolvers */
-   List<Object> _storageResolvers = null;
-
-   /** Field _iterator */
-   Iterator<Object> _iterator = null;
+    /** Field storageResolvers */
+    private List<StorageResolverSpi> storageResolvers = null;
 
-   /**
-    * Constructor StorageResolver
-    *
-    */
-   public StorageResolver() {}
+    /**
+     * Constructor StorageResolver
+     *
+     */
+    public StorageResolver() {}
 
-   /**
-    * Constructor StorageResolver
-    *
-    * @param resolver
-    */
-   public StorageResolver(StorageResolverSpi resolver) {
-      this.add(resolver);
-   }
+    /**
+     * Constructor StorageResolver
+     *
+     * @param resolver
+     */
+    public StorageResolver(StorageResolverSpi resolver) {
+        this.add(resolver);
+    }
 
-   /**
-    * Method addResolver
-    *
-    * @param resolver
-    */
-   public void add(StorageResolverSpi resolver) {
-           if (_storageResolvers==null)
-                   _storageResolvers=new ArrayList<Object>();
-      this._storageResolvers.add(resolver);
-
-      this._iterator = null;
-   }
+    /**
+     * Method addResolver
+     *
+     * @param resolver
+     */
+    public void add(StorageResolverSpi resolver) {
+        if (storageResolvers == null) {
+            storageResolvers = new ArrayList<StorageResolverSpi>();
+        }
+        this.storageResolvers.add(resolver);
+    }
 
-   /**
-    * Constructor StorageResolver
-    *
-    * @param keyStore
-    */
-   public StorageResolver(KeyStore keyStore) {
-      this.add(keyStore);
-   }
-
-   /**
-    * Method addKeyStore
-    *
-    * @param keyStore
-    */
-   public void add(KeyStore keyStore) {
+    /**
+     * Constructor StorageResolver
+     *
+     * @param keyStore
+     */
+    public StorageResolver(KeyStore keyStore) {
+        this.add(keyStore);
+    }
 
-      try {
-         this.add(new KeyStoreResolver(keyStore));
-      } catch (StorageResolverException ex) {
-         log.log(java.util.logging.Level.SEVERE, "Could not add KeyStore because of: ", ex);
-      }
-   }
+    /**
+     * Method addKeyStore
+     *
+     * @param keyStore
+     */
+    public void add(KeyStore keyStore) {
+        try {
+            this.add(new KeyStoreResolver(keyStore));
+        } catch (StorageResolverException ex) {
+            log.log(java.util.logging.Level.SEVERE, "Could not add KeyStore because of: ", ex);
+        }
+    }
 
-   /**
-    * Constructor StorageResolver
-    *
-    * @param x509certificate
-    */
-   public StorageResolver(X509Certificate x509certificate) {
-      this.add(x509certificate);
-   }
+    /**
+     * Constructor StorageResolver
+     *
+     * @param x509certificate
+     */
+    public StorageResolver(X509Certificate x509certificate) {
+        this.add(x509certificate);
+    }
 
-   /**
-    * Method addCertificate
-    *
-    * @param x509certificate
-    */
-   public void add(X509Certificate x509certificate) {
-      this.add(new SingleCertificateResolver(x509certificate));
-   }
+    /**
+     * Method addCertificate
+     *
+     * @param x509certificate
+     */
+    public void add(X509Certificate x509certificate) {
+        this.add(new SingleCertificateResolver(x509certificate));
+    }
 
-   /**
-    * Method getIterator
-    * @return the iterator for the resolvers.
-    *
-    */
-   public Iterator<Object> getIterator() {
+    /**
+     * Method getIterator
+     * @return the iterator for the resolvers.
+     */
+    public Iterator<Certificate> getIterator() {
+        return new StorageResolverIterator(this.storageResolvers.iterator());
+    }
 
-      if (this._iterator == null) {
-         if (_storageResolvers==null)
-                   _storageResolvers=new ArrayList<Object>();
-         this._iterator = new StorageResolverIterator(this._storageResolvers.iterator());
-      }
+    /**
+     * Class StorageResolverIterator
+     * This iterates over all the Certificates found in all the resolvers.
+     */
+    static class StorageResolverIterator implements Iterator<Certificate> {
 
-      return this._iterator;
-   }
+        /** Field resolvers */
+        Iterator<StorageResolverSpi> resolvers = null;
 
-   /**
-    * Method hasNext
-    *
-    * @return true if there is more elements.
-    */
-   public boolean hasNext() {
+        /** Field currentResolver */
+        Iterator<Certificate> currentResolver = null;
 
-      if (this._iterator == null) {
-          if (_storageResolvers==null)
-                   _storageResolvers=new ArrayList<Object>();
-         this._iterator = new StorageResolverIterator(this._storageResolvers.iterator());
-      }
+        /**
+         * Constructor StorageResolverIterator
+         *
+         * @param resolvers
+         */
+        public StorageResolverIterator(Iterator<StorageResolverSpi> resolvers) {
+            this.resolvers = resolvers;
+            currentResolver = findNextResolver();
+        }
 
-      return this._iterator.hasNext();
-   }
+        /** @inheritDoc */
+        public boolean hasNext() {
+            if (currentResolver == null) {
+                return false;
+            }
 
-   /**
-    * Method next
-    *
-    * @return the next element
-    */
-   public X509Certificate next() {
-      return (X509Certificate) this._iterator.next();
-   }
+            if (currentResolver.hasNext()) {
+                return true;
+            }
+
+            currentResolver = findNextResolver();
+            return (currentResolver != null);
+        }
 
-   /**
-    * Class StorageResolverIterator
-    *
-    * @author $Author: mullan $
-    * @version $Revision: 1.5 $
-    */
-   static class StorageResolverIterator implements Iterator<Object> {
+        /** @inheritDoc */
+        public Certificate next() {
+            if (hasNext()) {
+                return currentResolver.next();
+            }
 
-      /** Field _resolvers */
-      Iterator<Object> _resolvers = null;
+            throw new NoSuchElementException();
+        }
 
-      /**
-       * Constructor FilesystemIterator
-       *
-       * @param resolvers
-       */
-      public StorageResolverIterator(Iterator<Object> resolvers) {
-         this._resolvers = resolvers;
-      }
-
-      /** @inheritDoc */
-      public boolean hasNext() {
-          return _resolvers.hasNext();
-      }
+        /**
+         * Method remove
+         */
+        public void remove() {
+            throw new UnsupportedOperationException("Can't remove keys from KeyStore");
+        }
 
-      /** @inheritDoc */
-      public Object next() {
-          return _resolvers.next();
-      }
+        // Find the next storage with at least one element and return its Iterator
+        private Iterator<Certificate> findNextResolver() {
+            while (resolvers.hasNext()) {
+                StorageResolverSpi resolverSpi = resolvers.next();
+                Iterator<Certificate> iter = resolverSpi.getIterator();
+                if (iter.hasNext()) {
+                    return iter;
+                }
+            }
 
-      /**
-       * Method remove
-       */
-      public void remove() {
-         throw new UnsupportedOperationException(
-            "Can't remove keys from KeyStore");
-      }
-   }
+            return null;
+        }
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,86 +2,82 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.storage;
 
-
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 
 
-/**
- *
- * @author $Author: mullan $
- */
 public class StorageResolverException extends XMLSecurityException {
 
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
 
-   /**
-    * Constructor StorageResolverException
-    *
-    */
-   public StorageResolverException() {
-      super();
-   }
+    /**
+     * Constructor StorageResolverException
+     *
+     */
+    public StorageResolverException() {
+        super();
+    }
 
-   /**
-    * Constructor StorageResolverException
-    *
-    * @param _msgID
-    */
-   public StorageResolverException(String _msgID) {
-      super(_msgID);
-   }
+    /**
+     * Constructor StorageResolverException
+     *
+     * @param msgID
+     */
+    public StorageResolverException(String msgID) {
+        super(msgID);
+    }
 
-   /**
-    * Constructor StorageResolverException
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public StorageResolverException(String _msgID, Object exArgs[]) {
-      super(_msgID, exArgs);
-   }
+    /**
+     * Constructor StorageResolverException
+     *
+     * @param msgID
+     * @param exArgs
+     */
+    public StorageResolverException(String msgID, Object exArgs[]) {
+        super(msgID, exArgs);
+    }
 
-   /**
-    * Constructor StorageResolverException
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public StorageResolverException(String _msgID, Exception _originalException) {
-      super(_msgID, _originalException);
-   }
+    /**
+     * Constructor StorageResolverException
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public StorageResolverException(String msgID, Exception originalException) {
+        super(msgID, originalException);
+    }
 
-   /**
-    * Constructor StorageResolverException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public StorageResolverException(String _msgID, Object exArgs[],
-                                   Exception _originalException) {
-      super(_msgID, exArgs, _originalException);
-   }
+    /**
+     * Constructor StorageResolverException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public StorageResolverException(String msgID, Object exArgs[],
+                                    Exception originalException) {
+        super(msgID, exArgs, originalException);
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,39 +2,35 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.storage;
 
-
-
+import java.security.cert.Certificate;
 import java.util.Iterator;
 
-
-/**
- *
- * @author $Author: mullan $
- */
 public abstract class StorageResolverSpi {
 
-   /**
-    * Method getIterator
-    *
-    * @return the iterator for the storage
-    */
-   public abstract Iterator<?> getIterator();
+    /**
+     * Method getIterator
+     *
+     * @return the iterator for the storage
+     */
+    public abstract Iterator<Certificate> getIterator();
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.storage.implementations;
 
@@ -24,6 +26,7 @@
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
+import java.security.cert.Certificate;
 import java.security.cert.CertificateException;
 import java.security.cert.CertificateExpiredException;
 import java.security.cert.CertificateFactory;
@@ -39,188 +42,188 @@
 
 /**
  * This {@link StorageResolverSpi} makes all raw (binary) {@link X509Certificate}s
- * which reside as files in a single directory available to the {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}.
- *
- * @author $Author: mullan $
+ * which reside as files in a single directory available to the
+ * {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}.
  */
 public class CertsInFilesystemDirectoryResolver extends StorageResolverSpi {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(
-                    CertsInFilesystemDirectoryResolver.class.getName());
+            CertsInFilesystemDirectoryResolver.class.getName()
+        );
 
-   /** Field _merlinsCertificatesDir */
-   String _merlinsCertificatesDir = null;
+    /** Field merlinsCertificatesDir */
+    private String merlinsCertificatesDir = null;
 
-   /** Field _certs */
-   private List<X509Certificate> _certs = new ArrayList<X509Certificate>();
-
-   /** Field _iterator */
-   Iterator<X509Certificate> _iterator = null;
+    /** Field certs */
+    private List<X509Certificate> certs = new ArrayList<X509Certificate>();
 
-   /**
-    *
-    *
-    * @param directoryName
-    * @throws StorageResolverException
-    */
-   public CertsInFilesystemDirectoryResolver(String directoryName)
-           throws StorageResolverException {
+    /**
+     * @param directoryName
+     * @throws StorageResolverException
+     */
+    public CertsInFilesystemDirectoryResolver(String directoryName)
+        throws StorageResolverException {
+        this.merlinsCertificatesDir = directoryName;
 
-      this._merlinsCertificatesDir = directoryName;
+        this.readCertsFromHarddrive();
+    }
 
-      this.readCertsFromHarddrive();
-
-      this._iterator = new FilesystemIterator(this._certs);
-   }
+    /**
+     * Method readCertsFromHarddrive
+     *
+     * @throws StorageResolverException
+     */
+    private void readCertsFromHarddrive() throws StorageResolverException {
 
-   /**
-    * Method readCertsFromHarddrive
-    *
-    * @throws StorageResolverException
-    */
-   private void readCertsFromHarddrive() throws StorageResolverException {
+        File certDir = new File(this.merlinsCertificatesDir);
+        List<String> al = new ArrayList<String>();
+        String[] names = certDir.list();
 
-      File certDir = new File(this._merlinsCertificatesDir);
-      ArrayList<String> al = new ArrayList<String>();
-      String[] names = certDir.list();
+        for (int i = 0; i < names.length; i++) {
+            String currentFileName = names[i];
 
-      for (int i = 0; i < names.length; i++) {
-         String currentFileName = names[i];
+            if (currentFileName.endsWith(".crt")) {
+                al.add(names[i]);
+            }
+        }
 
-         if (currentFileName.endsWith(".crt")) {
-            al.add(names[i]);
-         }
-      }
+        CertificateFactory cf = null;
 
-      CertificateFactory cf = null;
-
-      try {
-         cf = CertificateFactory.getInstance("X.509");
-      } catch (CertificateException ex) {
-         throw new StorageResolverException("empty", ex);
-      }
+        try {
+            cf = CertificateFactory.getInstance("X.509");
+        } catch (CertificateException ex) {
+            throw new StorageResolverException("empty", ex);
+        }
 
-      if (cf == null) {
-         throw new StorageResolverException("empty");
-      }
+        if (cf == null) {
+            throw new StorageResolverException("empty");
+        }
 
-      for (int i = 0; i < al.size(); i++) {
-         String filename = certDir.getAbsolutePath() + File.separator
-                           + al.get(i);
-         File file = new File(filename);
-         boolean added = false;
-         String dn = null;
+        for (int i = 0; i < al.size(); i++) {
+            String filename = certDir.getAbsolutePath() + File.separator + al.get(i);
+            File file = new File(filename);
+            boolean added = false;
+            String dn = null;
 
-         try {
-            FileInputStream fis = new FileInputStream(file);
-            X509Certificate cert =
-               (X509Certificate) cf.generateCertificate(fis);
+            FileInputStream fis = null;
+            try {
+                fis = new FileInputStream(file);
+                X509Certificate cert =
+                    (X509Certificate) cf.generateCertificate(fis);
 
-            fis.close();
-
-            //add to ArrayList
-            cert.checkValidity();
-            this._certs.add(cert);
+                //add to ArrayList
+                cert.checkValidity();
+                this.certs.add(cert);
 
-            dn = cert.getSubjectDN().getName();
-            added = true;
-         } catch (FileNotFoundException ex) {
-            log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex);
-         } catch (IOException ex) {
-            log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex);
-         } catch (CertificateNotYetValidException ex) {
-            log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex);
-         } catch (CertificateExpiredException ex) {
-            log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex);
-         } catch (CertificateException ex) {
-            log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex);
-         }
-
-         if (added) {
-            if (log.isLoggable(java.util.logging.Level.FINE))
-                log.log(java.util.logging.Level.FINE, "Added certificate: " + dn);
-         }
-      }
-   }
+                dn = cert.getSubjectX500Principal().getName();
+                added = true;
+            } catch (FileNotFoundException ex) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex);
+                }
+            } catch (CertificateNotYetValidException ex) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex);
+                }
+            } catch (CertificateExpiredException ex) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex);
+                }
+            } catch (CertificateException ex) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex);
+                }
+            } finally {
+                try {
+                    if (fis != null) {
+                        fis.close();
+                    }
+                } catch (IOException ex) {
+                    if (log.isLoggable(java.util.logging.Level.FINE)) {
+                        log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex);
+                    }
+                }
+            }
 
-   /** @inheritDoc */
-   public Iterator<X509Certificate> getIterator() {
-      return this._iterator;
-   }
+            if (added && log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "Added certificate: " + dn);
+            }
+        }
+    }
 
-   /**
-    * Class FilesystemIterator
-    *
-    * @author $Author: mullan $
-    * @version $Revision: 1.5 $
-    */
-   private static class FilesystemIterator implements Iterator<X509Certificate> {
+    /** @inheritDoc */
+    public Iterator<Certificate> getIterator() {
+        return new FilesystemIterator(this.certs);
+    }
 
-      /** Field _certs */
-      List<X509Certificate> _certs = null;
-
-      /** Field _i */
-      int _i;
+    /**
+     * Class FilesystemIterator
+     */
+    private static class FilesystemIterator implements Iterator<Certificate> {
 
-      /**
-       * Constructor FilesystemIterator
-       *
-       * @param certs
-       */
-      public FilesystemIterator(List<X509Certificate> certs) {
-         this._certs = certs;
-         this._i = 0;
-      }
+        /** Field certs */
+        List<X509Certificate> certs = null;
+
+        /** Field i */
+        int i;
 
-      /** @inheritDoc */
-      public boolean hasNext() {
-         return (this._i < this._certs.size());
-      }
-
-      /** @inheritDoc */
-      public X509Certificate next() {
-         return this._certs.get(this._i++);
-      }
+        /**
+         * Constructor FilesystemIterator
+         *
+         * @param certs
+         */
+        public FilesystemIterator(List<X509Certificate> certs) {
+            this.certs = certs;
+            this.i = 0;
+        }
 
-      /**
-       * Method remove
-       *
-       */
-      public void remove() {
-         throw new UnsupportedOperationException(
-            "Can't remove keys from KeyStore");
-      }
-   }
+        /** @inheritDoc */
+        public boolean hasNext() {
+            return (this.i < this.certs.size());
+        }
+
+        /** @inheritDoc */
+        public Certificate next() {
+            return this.certs.get(this.i++);
+        }
+
+        /**
+         * Method remove
+         *
+         */
+        public void remove() {
+            throw new UnsupportedOperationException("Can't remove keys from KeyStore");
+        }
+    }
 
-   /**
-    * Method main
-    *
-    * @param unused
-    * @throws Exception
-    */
-   public static void main(String unused[]) throws Exception {
+    /**
+     * Method main
+     *
+     * @param unused
+     * @throws Exception
+     */
+    public static void main(String unused[]) throws Exception {
 
-      CertsInFilesystemDirectoryResolver krs =
-         new CertsInFilesystemDirectoryResolver(
-            "data/ie/baltimore/merlin-examples/merlin-xmldsig-eighteen/certs");
+        CertsInFilesystemDirectoryResolver krs =
+            new CertsInFilesystemDirectoryResolver(
+                "data/ie/baltimore/merlin-examples/merlin-xmldsig-eighteen/certs");
 
-      for (Iterator<X509Certificate> i = krs.getIterator(); i.hasNext(); ) {
-         X509Certificate cert = i.next();
-         byte[] ski =
-            com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI
-               .getSKIBytesFromCert(cert);
+        for (Iterator<Certificate> i = krs.getIterator(); i.hasNext(); ) {
+            X509Certificate cert = (X509Certificate) i.next();
+            byte[] ski =
+                com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI.getSKIBytesFromCert(cert);
 
-         System.out.println();
-         System.out.println("Base64(SKI())=                 \""
-                            + Base64.encode(ski) + "\"");
-         System.out.println("cert.getSerialNumber()=        \""
-                            + cert.getSerialNumber().toString() + "\"");
-         System.out.println("cert.getSubjectDN().getName()= \""
-                            + cert.getSubjectDN().getName() + "\"");
-         System.out.println("cert.getIssuerDN().getName()=  \""
-                            + cert.getIssuerDN().getName() + "\"");
-      }
-   }
+            System.out.println();
+            System.out.println("Base64(SKI())=                 \""
+                               + Base64.encode(ski) + "\"");
+            System.out.println("cert.getSerialNumber()=        \""
+                               + cert.getSerialNumber().toString() + "\"");
+            System.out.println("cert.getSubjectX500Principal().getName()= \""
+                               + cert.getSubjectX500Principal().getName() + "\"");
+            System.out.println("cert.getIssuerX500Principal().getName()=  \""
+                               + cert.getIssuerX500Principal().getName() + "\"");
+        }
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,147 +2,152 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.storage.implementations;
 
 import java.security.KeyStore;
 import java.security.KeyStoreException;
-import java.security.cert.X509Certificate;
+import java.security.cert.Certificate;
 import java.util.Enumeration;
 import java.util.Iterator;
+import java.util.NoSuchElementException;
 
 import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverException;
 import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi;
 
-
 /**
  * Makes the Certificates from a JAVA {@link KeyStore} object available to the
  * {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}.
- *
- * @author $Author: mullan $
  */
 public class KeyStoreResolver extends StorageResolverSpi {
 
-   /** Field _keyStore */
-   KeyStore _keyStore = null;
-
-   /** Field _iterator */
-   Iterator<X509Certificate> _iterator = null;
+    /** Field keyStore */
+    private KeyStore keyStore = null;
 
-   /**
-    * Constructor KeyStoreResolver
-    *
-    * @param keyStore is the keystore which contains the Certificates
-    * @throws StorageResolverException
-    */
-   public KeyStoreResolver(KeyStore keyStore) throws StorageResolverException {
-      this._keyStore = keyStore;
-      this._iterator = new KeyStoreIterator(this._keyStore);
-   }
-
-   /** @inheritDoc */
-   public Iterator<X509Certificate> getIterator() {
-      return this._iterator;
-   }
+    /**
+     * Constructor KeyStoreResolver
+     *
+     * @param keyStore is the keystore which contains the Certificates
+     * @throws StorageResolverException
+     */
+    public KeyStoreResolver(KeyStore keyStore) throws StorageResolverException {
+        this.keyStore = keyStore;
+        // Do a quick check on the keystore
+        try {
+            keyStore.aliases();
+        } catch (KeyStoreException ex) {
+            throw new StorageResolverException("generic.EmptyMessage", ex);
+        }
+    }
 
-   /**
-    * Class KeyStoreIterator
-    *
-    * @author $Author: mullan $
-    * @version $Revision: 1.5 $
-    */
-   static class KeyStoreIterator implements Iterator<X509Certificate> {
-
-      /** Field _keyStore */
-      KeyStore _keyStore = null;
-
-      /** Field _aliases */
-      Enumeration<String> _aliases = null;
+    /** @inheritDoc */
+    public Iterator<Certificate> getIterator() {
+        return new KeyStoreIterator(this.keyStore);
+    }
 
-      /**
-       * Constructor KeyStoreIterator
-       *
-       * @param keyStore
-       * @throws StorageResolverException
-       */
-      public KeyStoreIterator(KeyStore keyStore)
-              throws StorageResolverException {
+    /**
+     * Class KeyStoreIterator
+     */
+    static class KeyStoreIterator implements Iterator<Certificate> {
 
-         try {
-            this._keyStore = keyStore;
-            this._aliases = this._keyStore.aliases();
-         } catch (KeyStoreException ex) {
-            throw new StorageResolverException("generic.EmptyMessage", ex);
-         }
-      }
+        /** Field keyStore */
+        KeyStore keyStore = null;
+
+        /** Field aliases */
+        Enumeration<String> aliases = null;
+
+        /** Field nextCert */
+        Certificate nextCert = null;
 
-      /** @inheritDoc */
-      public boolean hasNext() {
-         return this._aliases.hasMoreElements();
-      }
-
-      /** @inheritDoc */
-      @SuppressWarnings("unchecked")
-      public X509Certificate next() {
-
-         String alias = this._aliases.nextElement();
+        /**
+         * Constructor KeyStoreIterator
+         *
+         * @param keyStore
+         */
+        public KeyStoreIterator(KeyStore keyStore) {
+            try {
+                this.keyStore = keyStore;
+                this.aliases = this.keyStore.aliases();
+            } catch (KeyStoreException ex) {
+                // empty Enumeration
+                this.aliases = new Enumeration<String>() {
+                    public boolean hasMoreElements() {
+                        return false;
+                    }
+                    public String nextElement() {
+                        return null;
+                    }
+                };
+            }
+        }
 
-         try {
-            return (X509Certificate)this._keyStore.getCertificate(alias);
-         } catch (KeyStoreException ex) {
-            return null;
-         }
-      }
+        /** @inheritDoc */
+        public boolean hasNext() {
+            if (nextCert == null) {
+                nextCert = findNextCert();
+            }
 
-      /**
-       * Method remove
-       *
-       */
-      public void remove() {
-         throw new UnsupportedOperationException(
-            "Can't remove keys from KeyStore");
-      }
-   }
+            return (nextCert != null);
+        }
+
+        /** @inheritDoc */
+        public Certificate next() {
+            if (nextCert == null) {
+                // maybe caller did not call hasNext()
+                nextCert = findNextCert();
 
-   /**
-    * Method main
-    *
-    * @param unused
-    * @throws Exception
-    */
-   public static void main(String unused[]) throws Exception {
+                if (nextCert == null) {
+                    throw new NoSuchElementException();
+                }
+            }
 
-      KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
+            Certificate ret = nextCert;
+            nextCert = null;
+            return ret;
+        }
+
+        /**
+         * Method remove
+         */
+        public void remove() {
+            throw new UnsupportedOperationException("Can't remove keys from KeyStore");
+        }
 
-      ks.load(
-         new java.io.FileInputStream(
-         "data/com/sun/org/apache/xml/internal/security/samples/input/keystore.jks"),
-            "xmlsecurity".toCharArray());
-
-      KeyStoreResolver krs = new KeyStoreResolver(ks);
+        // Find the next entry that contains a certificate and return it.
+        // In particular, this skips over entries containing symmetric keys.
+        private Certificate findNextCert() {
+            while (this.aliases.hasMoreElements()) {
+                String alias = this.aliases.nextElement();
+                try {
+                    Certificate cert = this.keyStore.getCertificate(alias);
+                    if (cert != null) {
+                        return cert;
+                    }
+                } catch (KeyStoreException ex) {
+                    return null;
+                }
+            }
 
-      for (Iterator<X509Certificate> i = krs.getIterator(); i.hasNext(); ) {
-         X509Certificate cert = i.next();
-         byte[] ski =
-            com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI
-               .getSKIBytesFromCert(cert);
+            return null;
+        }
 
-         System.out.println(com.sun.org.apache.xml.internal.security.utils.Base64.encode(ski));
-      }
-   }
+    }
+
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,102 +2,93 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.storage.implementations;
 
+import java.security.cert.Certificate;
 import java.security.cert.X509Certificate;
 import java.util.Iterator;
+import java.util.NoSuchElementException;
 
 import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi;
 
-
 /**
  * This {@link StorageResolverSpi} makes a single {@link X509Certificate}
  * available to the {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}.
- *
- * @author $Author: mullan $
  */
 public class SingleCertificateResolver extends StorageResolverSpi {
 
-   /** Field _certificate */
-   X509Certificate _certificate = null;
-
-   /** Field _iterator */
-   Iterator<X509Certificate> _iterator = null;
+    /** Field certificate */
+    private X509Certificate certificate = null;
 
-   /**
-    *
-    *
-    * @param x509cert the single {@link X509Certificate}
-    */
-   public SingleCertificateResolver(X509Certificate x509cert) {
-      this._certificate = x509cert;
-      this._iterator = new InternalIterator(this._certificate);
-   }
+    /**
+     * @param x509cert the single {@link X509Certificate}
+     */
+    public SingleCertificateResolver(X509Certificate x509cert) {
+        this.certificate = x509cert;
+    }
 
-   /** @inheritDoc */
-   public Iterator<X509Certificate> getIterator() {
-      return this._iterator;
-   }
+    /** @inheritDoc */
+    public Iterator<Certificate> getIterator() {
+        return new InternalIterator(this.certificate);
+    }
 
-   /**
-    * Class InternalIterator
-    *
-    * @author $Author: mullan $
-    * @version $Revision: 1.5 $
-    */
-   static class InternalIterator implements Iterator<X509Certificate> {
+    /**
+     * Class InternalIterator
+     */
+    static class InternalIterator implements Iterator<Certificate> {
 
-      /** Field _alreadyReturned */
-      boolean _alreadyReturned = false;
+        /** Field alreadyReturned */
+        boolean alreadyReturned = false;
+
+        /** Field certificate */
+        X509Certificate certificate = null;
 
-      /** Field _certificate */
-      X509Certificate _certificate = null;
+        /**
+         * Constructor InternalIterator
+         *
+         * @param x509cert
+         */
+        public InternalIterator(X509Certificate x509cert) {
+            this.certificate = x509cert;
+        }
 
-      /**
-       * Constructor InternalIterator
-       *
-       * @param x509cert
-       */
-      public InternalIterator(X509Certificate x509cert) {
-         this._certificate = x509cert;
-      }
-
-      /** @inheritDoc */
-      public boolean hasNext() {
-         return (!this._alreadyReturned);
-      }
+        /** @inheritDoc */
+        public boolean hasNext() {
+            return !this.alreadyReturned;
+        }
 
-      /** @inheritDoc */
-      public X509Certificate next() {
-
-         this._alreadyReturned = true;
-
-         return this._certificate;
-      }
+        /** @inheritDoc */
+        public Certificate next() {
+            if (this.alreadyReturned) {
+                throw new NoSuchElementException();
+            }
+            this.alreadyReturned = true;
+            return this.certificate;
+        }
 
-      /**
-       * Method remove
-       *
-       */
-      public void remove() {
-         throw new UnsupportedOperationException(
-            "Can't remove keys from KeyStore");
-      }
-   }
+        /**
+         * Method remove
+         */
+        public void remove() {
+            throw new UnsupportedOperationException("Can't remove keys from KeyStore");
+        }
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml	Mon Jul 22 17:37:15 2013 -0700
@@ -52,9 +52,6 @@
       <TransformAlgorithm URI="http://www.w3.org/TR/1999/REC-xslt-19991116"
                           JAVACLASS="com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXSLT" />
       <!-- XPath version 2 -->
-      <TransformAlgorithm URI="http://www.w3.org/2002/04/xmldsig-filter2"
-                          JAVACLASS="com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXPath2Filter" />
-      <!-- XPath version 2b -->
       <TransformAlgorithm URI="http://www.w3.org/2002/06/xmldsig-filter2"
                           JAVACLASS="com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXPath2Filter" />
    </TransformAlgorithms>
@@ -78,6 +75,12 @@
                           JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA512" />
       <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"
                           JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA1" />
+      <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"
+                          JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA256" />
+      <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384"
+                          JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA384" />
+      <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"
+                          JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA512" />
 
       <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-md5"
                           JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.IntegrityHmac$IntegrityHmacMD5" />
@@ -97,7 +100,7 @@
                     Description="MD5 message digest from RFC 1321"
                     AlgorithmClass="MessageDigest"
                     RequirementLevel="NOT RECOMMENDED"
-                    SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
                     JCEName="MD5"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmlenc#ripemd160"
@@ -122,7 +125,7 @@
                     Description="SHA message digest with 384 bit"
                     AlgorithmClass="MessageDigest"
                     RequirementLevel="OPTIONAL"
-                    SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
                     JCEName="SHA-384"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmlenc#sha512"
@@ -142,14 +145,14 @@
                     Description="RSA Signature with MD5 message digest"
                     AlgorithmClass="Signature"
                     RequirementLevel="NOT RECOMMENDED"
-                    SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
                     JCEName="MD5withRSA"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-ripemd160"
                     Description="RSA Signature with RIPEMD-160 message digest"
                     AlgorithmClass="Signature"
                     RequirementLevel="OPTIONAL"
-                    SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
                     JCEName="RIPEMD160withRSA"/>
 
          <Algorithm URI="http://www.w3.org/2000/09/xmldsig#rsa-sha1"
@@ -162,43 +165,64 @@
                     Description="RSA Signature with SHA-256 message digest"
                     AlgorithmClass="Signature"
                     RequirementLevel="OPTIONAL"
-                    SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
                     JCEName="SHA256withRSA"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha384"
                     Description="RSA Signature with SHA-384 message digest"
                     AlgorithmClass="Signature"
                     RequirementLevel="OPTIONAL"
-                    SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
                     JCEName="SHA384withRSA"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"
                     Description="RSA Signature with SHA-512 message digest"
                     AlgorithmClass="Signature"
                     RequirementLevel="OPTIONAL"
-                    SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
                     JCEName="SHA512withRSA"/>
                     
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"
                     Description="ECDSA Signature with SHA-1 message digest"
                     AlgorithmClass="Signature"
                     RequirementLevel="OPTIONAL"
-                    SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
-                    JCEName="ECDSAwithSHA1"/>
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    JCEName="SHA1withECDSA"/>
+
+         <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"
+                    Description="ECDSA Signature with SHA-256 message digest"
+                    AlgorithmClass="Signature"
+                    RequirementLevel="OPTIONAL"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    JCEName="SHA256withECDSA"/>
+
+         <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384"
+                    Description="ECDSA Signature with SHA-384 message digest"
+                    AlgorithmClass="Signature"
+                    RequirementLevel="OPTIONAL"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    JCEName="SHA384withECDSA"/>
+
+         <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"
+                    Description="ECDSA Signature with SHA-512 message digest"
+                    AlgorithmClass="Signature"
+                    RequirementLevel="OPTIONAL"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    JCEName="SHA512withECDSA"/>
 
          <!-- MAC Algorithms -->
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-md5"
                     Description="Message Authentication code using MD5"
                     AlgorithmClass="Mac"
                     RequirementLevel="NOT RECOMMENDED"
-                    SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
                     JCEName="HmacMD5"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160"
                     Description="Message Authentication code using RIPEMD-160"
                     AlgorithmClass="Mac"
                     RequirementLevel="OPTIONAL"
-                    SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
                     JCEName="HMACRIPEMD160"/>
 
          <Algorithm URI="http://www.w3.org/2000/09/xmldsig#hmac-sha1"
@@ -211,21 +235,21 @@
                     Description="Message Authentication code using SHA-256"
                     AlgorithmClass="Mac"
                     RequirementLevel="OPTIONAL"
-                    SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
                     JCEName="HmacSHA256"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-sha384"
                     Description="Message Authentication code using SHA-384"
                     AlgorithmClass="Mac"
                     RequirementLevel="OPTIONAL"
-                    SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
                     JCEName="HmacSHA384"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-sha512"
                     Description="Message Authentication code using SHA-512"
                     AlgorithmClass="Mac"
                     RequirementLevel="OPTIONAL"
-                    SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
                     JCEName="HmacSHA512"/>
 
          <!-- Block encryption Algorithms -->
@@ -260,7 +284,31 @@
                     KeyLength="256"
                     RequiredKey="AES"
                     JCEName="AES/CBC/ISO10126Padding"/>
+                    
+         <Algorithm URI="http://www.w3.org/2009/xmlenc11#aes128-gcm"
+                   Description="Block encryption using AES with a key length of 128 bit in GCM"
+                   AlgorithmClass="BlockEncryption"
+                   RequirementLevel="OPTIONAL"
+                   KeyLength="128"
+                   RequiredKey="AES"
+                   JCEName="AES/GCM/NoPadding"/>
+                   
+         <Algorithm URI="http://www.w3.org/2009/xmlenc11#aes192-gcm"
+                   Description="Block encryption using AES with a key length of 192 bit in GCM"
+                   AlgorithmClass="BlockEncryption"
+                   RequirementLevel="OPTIONAL"
+                   KeyLength="192"
+                   RequiredKey="AES"
+                   JCEName="AES/GCM/NoPadding"/>
 
+         <Algorithm URI="http://www.w3.org/2009/xmlenc11#aes256-gcm"
+                   Description="Block encryption using AES with a key length of 256 bit in GCM"
+                   AlgorithmClass="BlockEncryption"
+                   RequirementLevel="OPTIONAL"
+                   KeyLength="256"
+                   RequiredKey="AES"
+                   JCEName="AES/GCM/NoPadding"/>
+         
          <Algorithm URI="http://www.w3.org/2001/04/xmlenc#rsa-1_5"
                     Description="Key Transport RSA-v1.5"
                     AlgorithmClass="KeyTransport"
@@ -273,7 +321,14 @@
                     AlgorithmClass="KeyTransport"
                     RequirementLevel="REQUIRED"
                     RequiredKey="RSA"
-                    JCEName="RSA/ECB/OAEPWithSHA1AndMGF1Padding"/>
+                    JCEName="RSA/ECB/OAEPPadding"/>
+                    
+         <Algorithm URI="http://www.w3.org/2009/xmlenc11#rsa-oaep"
+                    Description="Key Transport RSA-OAEP"
+                    AlgorithmClass="KeyTransport"
+                    RequirementLevel="OPTIONAL"
+                    RequiredKey="RSA"
+                    JCEName="RSA/ECB/OAEPPadding"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmlenc#dh"
                     Description="Key Agreement Diffie-Hellman"
@@ -314,14 +369,7 @@
 
       </Algorithms>
    </JCEAlgorithmMappings>
-   <ResourceBundles defaultLanguageCode="en" defaultCountryCode="US">
-      <ResourceBundle LanguageCode="en"
-                      CountryCode="US"
-                      LOCATION="com.sun.org.apache.xml.internal.security/resource/xmlsecurity_en.properties" />
-      <ResourceBundle LanguageCode="de"
-                      CountryCode="DE"
-                      LOCATION="com.sun.org.apache.xml.internal.security/resource/xmlsecurity_de.properties" />
-   </ResourceBundles>
+   <ResourceBundles defaultLanguageCode="en" defaultCountryCode="US"/>
    <ResourceResolvers>
       <Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverDirectHTTP"
                 DESCRIPTION="A simple resolver for requests to HTTP space" />
@@ -330,32 +378,8 @@
       <Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverFragment"
                 DESCRIPTION="A simple resolver for requests of same-document URIs" />
       <Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverXPointer"
-                DESCRIPTION="A simple resolver for requests of XPointer fragents" />
+                DESCRIPTION="A simple resolver for requests of XPointer fragments" />
    </ResourceResolvers>
-   <!-- <defaultLocale languageCode="en" countryCode="US" /> -->
-   <KeyInfo>
-      <ContentHandler LOCALNAME="KeyName"
-                      NAMESPACE="http://www.w3.org/2000/09/xmldsig#"
-                      JAVACLASS="com.sun.org.apache.xml.internal.security.keys.content.KeyName" />
-      <ContentHandler LOCALNAME="KeyValue"
-                      NAMESPACE="http://www.w3.org/2000/09/xmldsig#"
-                      JAVACLASS="com.sun.org.apache.xml.internal.security.keys.content.KeyValue" />
-      <ContentHandler LOCALNAME="RetrievalMethod"
-                      NAMESPACE="http://www.w3.org/2000/09/xmldsig#"
-                      JAVACLASS="com.sun.org.apache.xml.internal.security.keys.content.RetrievalMethod" />
-      <ContentHandler LOCALNAME="X509Data"
-                      NAMESPACE="http://www.w3.org/2000/09/xmldsig#"
-                      JAVACLASS="com.sun.org.apache.xml.internal.security.keys.content.X509Data" />
-      <ContentHandler LOCALNAME="PGPData"
-                      NAMESPACE="http://www.w3.org/2000/09/xmldsig#"
-                      JAVACLASS="com.sun.org.apache.xml.internal.security.keys.content.PGPData" />
-      <ContentHandler LOCALNAME="SPKIData"
-                      NAMESPACE="http://www.w3.org/2000/09/xmldsig#"
-                      JAVACLASS="com.sun.org.apache.xml.internal.security.keys.content.SPKIData" />
-      <ContentHandler LOCALNAME="MgmtData"
-                      NAMESPACE="http://www.w3.org/2000/09/xmldsig#"
-                      JAVACLASS="com.sun.org.apache.xml.internal.security.keys.content.MgmtData" />
-   </KeyInfo>
    <KeyResolver>
       <!-- This section contains a list of KeyResolvers that are available in
            every KeyInfo object -->
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties	Thu Jul 18 03:38:49 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,36 +0,0 @@
-# ------------------------------------------------------------------------
-#
-# Logging Configuration
-#
-# ------------------------------------------------------------------------
-#
-log4j.rootLogger=DEBUG, LOGTXT
-
-########################################################################
-#
-# Logging based on packages
-#
-########################################################################
-log4j.logger.com.sun.org.apache.xml.internal.security=DEBUG, LOGTXT
-log4j.logger.com.sun.org.apache.xml.internal.security.test.AllTests=DEBUG, LOGTXT
-
-########################################################################
-#
-# Logfile definitions 
-#
-########################################################################
-#Console Log
-log4j.appender.Console=org.apache.log4j.ConsoleAppender
-log4j.appender.Console.Threshold=DEBUG
-log4j.appender.Console.layout=org.apache.log4j.PatternLayout
-log4j.appender.Console.layout.ConversionPattern=%-5p %C{1}:%L - %m\n
-log4j.appender.Console.Target=System.err
-
-#LOGTXT Log
-log4j.appender.LOGTXT=org.apache.log4j.FileAppender
-log4j.appender.LOGTXT.File=log.txt
-log4j.appender.LOGTXT.Append=true
-log4j.appender.LOGTXT.Threshold=DEBUG
-log4j.appender.LOGTXT.layout=org.apache.log4j.PatternLayout
-log4j.appender.LOGTXT.layout.ConversionPattern=%-5p %C{1}:%L - %m\n
-
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties	Mon Jul 22 17:37:15 2013 -0700
@@ -5,6 +5,7 @@
 algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures.
 algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures.
 algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs.
+algorithms.HMACOutputLengthMin = HMACOutputLength must not be less than {0}
 algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms
 algorithms.NoSuchAlgorithm = Der Algorithmus {0} ist nicht verfügbar. Original Nachricht war: {1}
 algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm
@@ -88,8 +89,13 @@
 signature.Canonicalizer.UnknownCanonicalizer = Unbekannter Canonicalizer. Kein Handler installiert für URI {0}
 signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature
 signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first
+signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled
+signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled
 signature.signaturePropertyHasNoTarget = Das Target Attribut der SignatureProperty muss gesetzt sein
+signature.tooManyReferences = {0} references are contained in the Manifest, maximum {1} are allowed with secure validation
+signature.tooManyTransforms = {0} transforms are contained in the Reference, maximum {1} are allowed with secure validation
 signature.Transform.ErrorDuringTransform = Während der Transformation {0} trat eine {1} auf.
+signature.Transform.ForbiddenTransform = Transform {0} is forbidden when secure validation is enabled
 signature.Transform.NotYetImplemented = Transform {0} noch nicht implementiert
 signature.Transform.NullPointerTransform = Null pointer als URI übergeben. Programmierfehler?
 signature.Transform.UnknownTransform = Unbekannte Transformation. Kein Handler installiert für URI {0}
@@ -103,6 +109,7 @@
 signature.Verification.keyStore = Öffnen des KeyStore fehlgeschlagen
 signature.Verification.MissingID = Cannot resolve element with ID {0}
 signature.Verification.MissingResources = Kann die externe Resource {0} nicht auflösen
+signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected
 signature.Verification.NoSignatureElement = Input Dokument enthält kein {0} Element mit dem Namespace {1}
 signature.Verification.Reference.NoInput = Die Reference für den URI {0} hat keinen XMLSignatureInput erhalten.
 signature.Verification.SignatureError = Signatur Fehler
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties	Mon Jul 22 17:37:15 2013 -0700
@@ -1,126 +1,131 @@
-algorithm.alreadyRegistered = URI {0} already assigned to class {1}
-algorithm.classDoesNotExist = Cannot register URI {0} to class {1} because this class does not exist in CLASSPATH
-algorithm.ClassDoesNotExist = Class {0} does not exist
-algorithm.extendsWrongClass = Cannot register URI {0} to class {1} because it does not extend {2}
-algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures.
-algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures.
-algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs.
-algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms
-algorithms.NoSuchAlgorithm = The requested algorithm {0} does not exist. Original Message was: {1}
-algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm
-algorithms.NoSuchProvider = The specified Provider {0} does not exist. Original Message was: {1}
-algorithms.operationOnlyVerification = A public key can only used for verification of a signature.
-algorithms.WrongKeyForThisOperation = Sorry, you supplied the wrong key type for this operation! You supplied a {0} but a {1} is needed.
-attributeValueIllegal = The attribute {0} has value {1} but must be {2}
-c14n.Canonicalizer.Exception = Exception during Canonicalization:  Original Message was {0}
-c14n.Canonicalizer.IllegalNode = Illegal node type {0}, node name was {1}
-c14n.Canonicalizer.NoSuchCanonicalizer = No canonicalizer found with URI {0}
-c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException during Canonicalization:  Original Message was {0}
-c14n.Canonicalizer.RelativeNamespace = Element {0} has a relative namespace: {1}="{2}"
-c14n.Canonicalizer.SAXException = SAXException during Canonicalization:  Original Message was {0}
-c14n.Canonicalizer.TraversalNotSupported = This DOM document does not support Traversal {0}
-c14n.Canonicalizer.UnsupportedEncoding = Unsupported encoding {0}
-c14n.Canonicalizer.UnsupportedOperation = This canonicalizer does not support this operation
-c14n.XMLUtils.circumventBug2650forgotten = The tree has not been prepared for canonicalization using XMLUtils#circumventBug2650(Document)
-certificate.noSki.lowVersion = Certificate cannot contain a SubjectKeyIdentifier because it is only X509v{0}
-certificate.noSki.notOctetString = Certificates SubjectKeyIdentifier is not a OctetString
-certificate.noSki.null = Certificate does not contain a SubjectKeyIdentifier
-defaultNamespaceCannotBeSetHere = Default namespace cannot be set here
-ElementProxy.nullElement = Cannot create an ElementProxy from a null argument
-empty = {0}
-encryption.algorithmCannotBeUsedForEncryptedData = encryption.algorithmCannotBeUsedForEncryptedData {0}
-encryption.algorithmCannotEatInitParams = encryption.algorithmCannotEatInitParams
-encryption.algorithmCannotEncryptDecrypt = encryption.algorithmCannotEncryptDecrypt
-encryption.algorithmCannotWrapUnWrap = encryption.algorithmCannotWrapUnWrap
-encryption.ExplicitKeySizeMismatch = The xenc:KeySize element requests a key size of {0} bit but the algorithm implements {1} bit
-encryption.nonceLongerThanDecryptedPlaintext = The given nonce is longer than the available plaintext. I Cannot strip away this.
-encryption.RSAOAEP.dataHashWrong = data hash wrong
-encryption.RSAOAEP.dataStartWrong = data wrong start {0}
-encryption.RSAOAEP.dataTooShort = data too short
-encryption.RSAPKCS15.blockTruncated = block truncated
-encryption.RSAPKCS15.noDataInBlock = no data in block
-encryption.RSAPKCS15.unknownBlockType = unknown block type
-encryption.nokey = No Key Encryption Key loaded and cannot determine using key resolvers
-endorsed.jdk1.4.0 = Since it seems that nobody reads our installation notes, we must do it in the exception messages. Hope you read them. You did NOT use the endorsed mechanism from JDK 1.4 properly; look at <http://xml.apache.org/security/Java/installation.html> how to solve this problem.
-errorMessages.InvalidDigestValueException = INVALID signature -- check reference resolution.
-errorMessages.InvalidSignatureValueException = INVALID signature -- core validation failed.
-errorMessages.IOException = Other file I/O and similar exceptions.
-errorMessages.MissingKeyFailureException = Cannot verify because of missing public key. Provide it via addResource and try again.
-errorMessages.MissingResourceFailureException = Cannot verify because of unresolved references. Provide it via addResource and try again.
-errorMessages.NoSuchAlgorithmException = Unknown Algorithm {0}
-errorMessages.NotYetImplementedException = Functionality not yet there.
-errorMessages.XMLSignatureException = Verification failed for some other reason.
-decoding.divisible.four = It should be divisible by four
-decoding.general = Error while decoding
-FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented.
-FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0}
-FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1}
-FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0}
-generic.dontHaveConstructionElement = I do not have a construction Element
-generic.EmptyMessage = {0}
-generic.NotYetImplemented = {0} Not YET implemented ;-((
-java.security.InvalidKeyException = Invalid key
-java.security.NoSuchProviderException = Unknown or unsupported provider
-java.security.UnknownKeyType = Unknown or unsupported key type {0}
-KeyInfo.needKeyResolver = More than one keyResovler have to be registered
-KeyInfo.nokey = Cannot get key from {0}
-KeyInfo.noKey = Cannot get the public key
-KeyInfo.wrongNumberOfObject = Need {0} keyObjects
-KeyInfo.wrongUse = This object was made for getting {0}
-keyResolver.alreadyRegistered = {1} class has already been registered for {0}
-KeyResolver.needStorageResolver = Need a StorageResolver to retrieve a Certificate from a {0}
-KeyResoverSpiImpl.cannotGetCert = Cannot get the Certificate that include or in {1} in implement class {0}
-KeyResoverSpiImpl.elementGeneration = Cannot make {1} element in implement class {0}
-KeyResoverSpiImpl.getPoublicKey = Cannot get the public key from implement class {0}
-KeyResoverSpiImpl.InvalidElement = Cannot set (2) Element in implement class {0}
-KeyResoverSpiImpl.keyStore = KeyStorage error in implement class {0}
-KeyResoverSpiImpl.need.Element = {1} type of Element is needed in implement class {0}
-KeyResoverSpiImpl.wrongCRLElement = Cannot make CRL from {1} in implement class {0}
-KeyResoverSpiImpl.wrongKeyObject =  Need {1} type of KeyObject for generation Element in implement class{0}
-KeyResoverSpiImpl.wrongNumberOfObject = Need {1} keyObject in implement class {0}
-KeyStore.alreadyRegistered = {0} Class has already been registered for {1}
-KeyStore.register = {1} type class register error  in class {0}
-KeyStore.registerStore.register = Registeration error for type {0}
-KeyValue.IllegalArgument = Cannot create a {0} from {1}
-namespacePrefixAlreadyUsedByOtherURI = Namespace prefix {0} already used by other URI {1}
-notYetInitialized = The module {0} is not yet initialized
-prefix.AlreadyAssigned = You want to assign {0} as prefix for namespace {1} but it is already assigned for {2}
-signature.Canonicalizer.UnknownCanonicalizer = Unknown canonicalizer. No handler installed for URI {0}
-signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature
-signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first
-signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled
-signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled
-signature.signaturePropertyHasNoTarget = The Target attribute of the SignatureProperty must be set
-signature.Transform.ErrorDuringTransform = A {1} was thrown during the {0} transform
-signature.Transform.NotYetImplemented = Transform {0} not yet implemented
-signature.Transform.NullPointerTransform = Null pointer as URI. Programming bug?
-signature.Transform.UnknownTransform = Unknown transformation. No handler installed for URI {0}
-signature.Transform.node = Current Node: {0}
-signature.Transform.nodeAndType = Current Node: {0}, type: {1} 
-signature.Util.BignumNonPositive = bigInteger.signum() must be positive
-signature.Util.NonTextNode = Not a text node
-signature.Util.TooManyChilds = Too many childs of Type {0} in {1}
-signature.Verification.certificateError = Certificate error
-signature.Verification.IndexOutOfBounds = Index {0} illegal. We only have {1} References
-signature.Verification.internalError = Internal error
-signature.Verification.InvalidDigestOrReference = Invalid digest of reference {0}
-signature.Verification.keyStore = KeyStore error
-signature.Verification.MissingID = Cannot resolve element with ID {0}
-signature.Verification.MissingResources = Cannot resolve external resource {0}
-signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected
-signature.Verification.NoSignatureElement = Input document contains no {0} Element in namespace {1}
-signature.Verification.Reference.NoInput = The Reference for URI {0} has no XMLSignatureInput
-signature.Verification.SignatureError = Signature error
-signature.XMLSignatureInput.MissingConstuctor = Cannot construct a XMLSignatureInput from class {0}
-signature.XMLSignatureInput.SerializeDOM = Input initialized with DOM Element. Use Canonicalization to serialize it
-signature.XMLSignatureInput.nodesetReference = Unable to convert to nodeset the reference
-transform.Init.IllegalContextArgument = Invalid context argument of class {0}. Must be String, org.w3c.dom.NodeList or java.io.InputStream.
-transform.init.NotInitialized =
-transform.init.wrongURI = Initialized with wrong URI. How could this happen? We implement {0} but {1} was used during initialization
-utils.Base64.IllegalBitlength = Illegal byte length; Data to be decoded must be a multiple of 4
-Base64Decoding = Error while decoding
-utils.resolver.noClass = Could not find a resolver for URI {0} and Base {1}
-xml.WrongContent = Cannot find {0} in {1}
-xml.WrongElement = Cannot create a {0} from a {1} element
-xpath.funcHere.documentsDiffer = The XPath is not in the same document as the context node
-xpath.funcHere.noXPathContext = Try to evaluate an XPath which uses the here() function but XPath is not inside an ds:XPath Element. XPath was : {0}
+algorithm.alreadyRegistered = URI {0} already assigned to class {1}
+algorithm.classDoesNotExist = Cannot register URI {0} to class {1} because this class does not exist in CLASSPATH
+algorithm.ClassDoesNotExist = Class {0} does not exist
+algorithm.extendsWrongClass = Cannot register URI {0} to class {1} because it does not extend {2}
+algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures.
+algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures.
+algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs.
+algorithms.HMACOutputLengthMin = HMACOutputLength must not be less than {0}
+algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms
+algorithms.NoSuchAlgorithm = The requested algorithm {0} does not exist. Original Message was: {1}
+algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm
+algorithms.NoSuchProvider = The specified Provider {0} does not exist. Original Message was: {1}
+algorithms.operationOnlyVerification = A public key can only used for verification of a signature.
+algorithms.WrongKeyForThisOperation = Sorry, you supplied the wrong key type for this operation! You supplied a {0} but a {1} is needed.
+attributeValueIllegal = The attribute {0} has value {1} but must be {2}
+c14n.Canonicalizer.Exception = Exception during Canonicalization:  Original Message was {0}
+c14n.Canonicalizer.IllegalNode = Illegal node type {0}, node name was {1}
+c14n.Canonicalizer.NoSuchCanonicalizer = No canonicalizer found with URI {0}
+c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException during Canonicalization:  Original Message was {0}
+c14n.Canonicalizer.RelativeNamespace = Element {0} has a relative namespace: {1}="{2}"
+c14n.Canonicalizer.SAXException = SAXException during Canonicalization:  Original Message was {0}
+c14n.Canonicalizer.TraversalNotSupported = This DOM document does not support Traversal {0}
+c14n.Canonicalizer.UnsupportedEncoding = Unsupported encoding {0}
+c14n.Canonicalizer.UnsupportedOperation = This canonicalizer does not support this operation
+c14n.XMLUtils.circumventBug2650forgotten = The tree has not been prepared for canonicalization using XMLUtils#circumventBug2650(Document)
+certificate.noSki.lowVersion = Certificate cannot contain a SubjectKeyIdentifier because it is only X509v{0}
+certificate.noSki.notOctetString = Certificates SubjectKeyIdentifier is not a OctetString
+certificate.noSki.null = Certificate does not contain a SubjectKeyIdentifier
+defaultNamespaceCannotBeSetHere = Default namespace cannot be set here
+ElementProxy.nullElement = Cannot create an ElementProxy from a null argument
+empty = {0}
+encryption.algorithmCannotBeUsedForEncryptedData = encryption.algorithmCannotBeUsedForEncryptedData {0}
+encryption.algorithmCannotEatInitParams = encryption.algorithmCannotEatInitParams
+encryption.algorithmCannotEncryptDecrypt = encryption.algorithmCannotEncryptDecrypt
+encryption.algorithmCannotWrapUnWrap = encryption.algorithmCannotWrapUnWrap
+encryption.ExplicitKeySizeMismatch = The xenc:KeySize element requests a key size of {0} bit but the algorithm implements {1} bit
+encryption.nonceLongerThanDecryptedPlaintext = The given nonce is longer than the available plaintext. I Cannot strip away this.
+encryption.RSAOAEP.dataHashWrong = data hash wrong
+encryption.RSAOAEP.dataStartWrong = data wrong start {0}
+encryption.RSAOAEP.dataTooShort = data too short
+encryption.RSAPKCS15.blockTruncated = block truncated
+encryption.RSAPKCS15.noDataInBlock = no data in block
+encryption.RSAPKCS15.unknownBlockType = unknown block type
+encryption.nokey = No Key Encryption Key loaded and cannot determine using key resolvers
+endorsed.jdk1.4.0 = Since it seems that nobody reads our installation notes, we must do it in the exception messages. Hope you read them. You did NOT use the endorsed mechanism from JDK 1.4 properly; look at <http://xml.apache.org/security/Java/installation.html> how to solve this problem.
+errorMessages.InvalidDigestValueException = INVALID signature -- check reference resolution.
+errorMessages.InvalidSignatureValueException = INVALID signature -- core validation failed.
+errorMessages.IOException = Other file I/O and similar exceptions.
+errorMessages.MissingKeyFailureException = Cannot verify because of missing public key. Provide it via addResource and try again.
+errorMessages.MissingResourceFailureException = Cannot verify because of unresolved references. Provide it via addResource and try again.
+errorMessages.NoSuchAlgorithmException = Unknown Algorithm {0}
+errorMessages.NotYetImplementedException = Functionality not yet there.
+errorMessages.XMLSignatureException = Verification failed for some other reason.
+decoding.divisible.four = It should be divisible by four
+decoding.general = Error while decoding
+FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented.
+FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0}
+FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1}
+FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0}
+generic.dontHaveConstructionElement = I do not have a construction Element
+generic.EmptyMessage = {0}
+generic.NotYetImplemented = {0} Not YET implemented ;-((
+java.security.InvalidKeyException = Invalid key
+java.security.NoSuchProviderException = Unknown or unsupported provider
+java.security.UnknownKeyType = Unknown or unsupported key type {0}
+KeyInfo.needKeyResolver = More than one keyResovler have to be registered
+KeyInfo.nokey = Cannot get key from {0}
+KeyInfo.noKey = Cannot get the public key
+KeyInfo.wrongNumberOfObject = Need {0} keyObjects
+KeyInfo.wrongUse = This object was made for getting {0}
+keyResolver.alreadyRegistered = {1} class has already been registered for {0}
+KeyResolver.needStorageResolver = Need a StorageResolver to retrieve a Certificate from a {0}
+KeyResoverSpiImpl.cannotGetCert = Cannot get the Certificate that include or in {1} in implement class {0}
+KeyResoverSpiImpl.elementGeneration = Cannot make {1} element in implement class {0}
+KeyResoverSpiImpl.getPoublicKey = Cannot get the public key from implement class {0}
+KeyResoverSpiImpl.InvalidElement = Cannot set (2) Element in implement class {0}
+KeyResoverSpiImpl.keyStore = KeyStorage error in implement class {0}
+KeyResoverSpiImpl.need.Element = {1} type of Element is needed in implement class {0}
+KeyResoverSpiImpl.wrongCRLElement = Cannot make CRL from {1} in implement class {0}
+KeyResoverSpiImpl.wrongKeyObject =  Need {1} type of KeyObject for generation Element in implement class{0}
+KeyResoverSpiImpl.wrongNumberOfObject = Need {1} keyObject in implement class {0}
+KeyStore.alreadyRegistered = {0} Class has already been registered for {1}
+KeyStore.register = {1} type class register error  in class {0}
+KeyStore.registerStore.register = Registeration error for type {0}
+KeyValue.IllegalArgument = Cannot create a {0} from {1}
+namespacePrefixAlreadyUsedByOtherURI = Namespace prefix {0} already used by other URI {1}
+notYetInitialized = The module {0} is not yet initialized
+prefix.AlreadyAssigned = You want to assign {0} as prefix for namespace {1} but it is already assigned for {2}
+signature.Canonicalizer.UnknownCanonicalizer = Unknown canonicalizer. No handler installed for URI {0}
+signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature
+signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first
+signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled
+signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled
+signature.signaturePropertyHasNoTarget = The Target attribute of the SignatureProperty must be set
+signature.tooManyReferences = {0} references are contained in the Manifest, maximum {1} are allowed with secure validation
+signature.tooManyTransforms = {0} transforms are contained in the Reference, maximum {1} are allowed with secure validation
+signature.Transform.ErrorDuringTransform = A {1} was thrown during the {0} transform
+signature.Transform.ForbiddenTransform = Transform {0} is forbidden when secure validation is enabled
+signature.Transform.NotYetImplemented = Transform {0} not yet implemented
+signature.Transform.NullPointerTransform = Null pointer as URI. Programming bug?
+signature.Transform.UnknownTransform = Unknown transformation. No handler installed for URI {0}
+signature.Transform.node = Current Node: {0}
+signature.Transform.nodeAndType = Current Node: {0}, type: {1} 
+signature.Util.BignumNonPositive = bigInteger.signum() must be positive
+signature.Util.NonTextNode = Not a text node
+signature.Util.TooManyChilds = Too many childs of Type {0} in {1}
+signature.Verification.certificateError = Certificate error
+signature.Verification.IndexOutOfBounds = Index {0} illegal. We only have {1} References
+signature.Verification.internalError = Internal error
+signature.Verification.InvalidDigestOrReference = Invalid digest of reference {0}
+signature.Verification.keyStore = KeyStore error
+signature.Verification.MissingID = Cannot resolve element with ID {0}
+signature.Verification.MissingResources = Cannot resolve external resource {0}
+signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected
+signature.Verification.NoSignatureElement = Input document contains no {0} Element in namespace {1}
+signature.Verification.Reference.NoInput = The Reference for URI {0} has no XMLSignatureInput
+signature.Verification.SignatureError = Signature error
+signature.XMLSignatureInput.MissingConstuctor = Cannot construct a XMLSignatureInput from class {0}
+signature.XMLSignatureInput.SerializeDOM = Input initialized with DOM Element. Use Canonicalization to serialize it
+signature.XMLSignatureInput.nodesetReference = Unable to convert to nodeset the reference
+transform.Init.IllegalContextArgument = Invalid context argument of class {0}. Must be String, org.w3c.dom.NodeList or java.io.InputStream.
+transform.init.NotInitialized =
+transform.init.wrongURI = Initialized with wrong URI. How could this happen? We implement {0} but {1} was used during initialization
+transform.envelopedSignatureTransformNotInSignatureElement = Enveloped Transform cannot find Signature element
+utils.Base64.IllegalBitlength = Illegal byte length; Data to be decoded must be a multiple of 4
+Base64Decoding = Error while decoding
+utils.resolver.noClass = Could not find a resolver for URI {0} and Base {1}
+xml.WrongContent = Cannot find {0} in {1}
+xml.WrongElement = Cannot create a {0} from a {1} element
+xpath.funcHere.documentsDiffer = The XPath is not in the same document as the context node
+xpath.funcHere.noXPathContext = Try to evaluate an XPath which uses the here() function but XPath is not inside an ds:XPath Element. XPath was : {0}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,85 +2,85 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
-
-
 /**
- * Raised when the computed hash value doesn't match the given <i>DigestValue</i>.  Additional human readable info is passed to the constructor -- this being the benefit of raising an exception or returning a value.
+ * Raised when the computed hash value doesn't match the given <i>DigestValue</i>.
+ * Additional human readable info is passed to the constructor -- this being the benefit
+ * of raising an exception or returning a value.
  *
  * @author Christian Geuer-Pollmann
  */
 public class InvalidDigestValueException extends XMLSignatureException {
 
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
 
-   /**
-    * Constructor InvalidDigestValueException
-    *
-    */
-   public InvalidDigestValueException() {
-      super();
-   }
+    /**
+     * Constructor InvalidDigestValueException
+     *
+     */
+    public InvalidDigestValueException() {
+        super();
+    }
 
-   /**
-    * Constructor InvalidDigestValueException
-    *
-    * @param _msgID
-    */
-   public InvalidDigestValueException(String _msgID) {
-      super(_msgID);
-   }
+    /**
+     * Constructor InvalidDigestValueException
+     *
+     * @param msgID
+     */
+    public InvalidDigestValueException(String msgID) {
+        super(msgID);
+    }
 
-   /**
-    * Constructor InvalidDigestValueException
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public InvalidDigestValueException(String _msgID, Object exArgs[]) {
-      super(_msgID, exArgs);
-   }
+    /**
+     * Constructor InvalidDigestValueException
+     *
+     * @param msgID
+     * @param exArgs
+     */
+    public InvalidDigestValueException(String msgID, Object exArgs[]) {
+        super(msgID, exArgs);
+    }
 
-   /**
-    * Constructor InvalidDigestValueException
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public InvalidDigestValueException(String _msgID,
-                                      Exception _originalException) {
-      super(_msgID, _originalException);
-   }
+    /**
+     * Constructor InvalidDigestValueException
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public InvalidDigestValueException(String msgID, Exception originalException) {
+        super(msgID, originalException);
+    }
 
-   /**
-    * Constructor InvalidDigestValueException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public InvalidDigestValueException(String _msgID, Object exArgs[],
-                                      Exception _originalException) {
-      super(_msgID, exArgs, _originalException);
-   }
+    /**
+     * Constructor InvalidDigestValueException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public InvalidDigestValueException(String msgID, Object exArgs[], Exception originalException) {
+        super(msgID, exArgs, originalException);
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
-
-
 /**
  * Raised if testing the signature value over <i>DigestValue</i> fails because of invalid signature.
  *
@@ -30,58 +30,56 @@
  */
 public class InvalidSignatureValueException extends XMLSignatureException {
 
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
 
-   /**
-    * Constructor InvalidSignatureValueException
-    *
-    */
-   public InvalidSignatureValueException() {
-      super();
-   }
+    /**
+     * Constructor InvalidSignatureValueException
+     *
+     */
+    public InvalidSignatureValueException() {
+        super();
+    }
 
-   /**
-    * Constructor InvalidSignatureValueException
-    *
-    * @param _msgID
-    */
-   public InvalidSignatureValueException(String _msgID) {
-      super(_msgID);
-   }
+    /**
+     * Constructor InvalidSignatureValueException
+     *
+     * @param msgID
+     */
+    public InvalidSignatureValueException(String msgID) {
+        super(msgID);
+    }
 
-   /**
-    * Constructor InvalidSignatureValueException
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public InvalidSignatureValueException(String _msgID, Object exArgs[]) {
-      super(_msgID, exArgs);
-   }
+    /**
+     * Constructor InvalidSignatureValueException
+     *
+     * @param msgID
+     * @param exArgs
+     */
+    public InvalidSignatureValueException(String msgID, Object exArgs[]) {
+        super(msgID, exArgs);
+    }
 
-   /**
-    * Constructor InvalidSignatureValueException
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public InvalidSignatureValueException(String _msgID,
-                                         Exception _originalException) {
-      super(_msgID, _originalException);
-   }
+    /**
+     * Constructor InvalidSignatureValueException
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public InvalidSignatureValueException(String msgID, Exception originalException) {
+        super(msgID, originalException);
+    }
 
-   /**
-    * Constructor InvalidSignatureValueException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public InvalidSignatureValueException(String _msgID, Object exArgs[],
-                                         Exception _originalException) {
-      super(_msgID, exArgs, _originalException);
-   }
+    /**
+     * Constructor InvalidSignatureValueException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public InvalidSignatureValueException(String msgID, Object exArgs[], Exception originalException) {
+        super(msgID, exArgs, originalException);
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,33 +2,33 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
-
-
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
-import java.util.Map;
 
 import javax.xml.parsers.ParserConfigurationException;
 
@@ -38,7 +38,6 @@
 import com.sun.org.apache.xml.internal.security.transforms.Transforms;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.I18n;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
@@ -50,523 +49,561 @@
 import org.w3c.dom.Node;
 import org.xml.sax.SAXException;
 
-
-
 /**
  * Handles <code>&lt;ds:Manifest&gt;</code> elements.
  * <p> This element holds the <code>Reference</code> elements</p>
- * @author $author: $
  */
 public class Manifest extends SignatureElementProxy {
 
-  /** {@link java.util.logging} logging facility */
-  static java.util.logging.Logger log =
+    /**
+     * The maximum number of references per Manifest, if secure validation is enabled.
+     */
+    public static final int MAXIMUM_REFERENCE_COUNT = 30;
+
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(Manifest.class.getName());
 
-   /** Field _references */
-   List<Reference> _references;
-   Element[] _referencesEl;
+    /** Field references */
+    private List<Reference> references;
+    private Element[] referencesEl;
 
-   /** Field verificationResults[] */
-   private boolean verificationResults[] = null;
+    /** Field verificationResults[] */
+    private boolean verificationResults[] = null;
 
-   /** Field _resolverProperties */
-   Map<String,String> _resolverProperties = null;
+    /** Field resolverProperties */
+    private Map<String, String> resolverProperties = null;
 
-   /** Field _perManifestResolvers */
-   List<ResourceResolver> _perManifestResolvers = null;
+    /** Field perManifestResolvers */
+    private List<ResourceResolver> perManifestResolvers = null;
 
-   /**
-    * Consturts {@link Manifest}
-    *
-    * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
-    */
-   public Manifest(Document doc) {
+    private boolean secureValidation;
 
-      super(doc);
+    /**
+     * Constructs {@link Manifest}
+     *
+     * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
+     */
+    public Manifest(Document doc) {
+        super(doc);
 
-      XMLUtils.addReturnToElement(this._constructionElement);
+        XMLUtils.addReturnToElement(this.constructionElement);
 
-      this._references = new ArrayList<Reference>();
-   }
+        this.references = new ArrayList<Reference>();
+    }
 
-   /**
-    * Constructor Manifest
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public Manifest(Element element, String BaseURI)
-           throws XMLSecurityException {
-
-      super(element, BaseURI);
+    /**
+     * Constructor Manifest
+     *
+     * @param element
+     * @param baseURI
+     * @throws XMLSecurityException
+     */
+    public Manifest(Element element, String baseURI) throws XMLSecurityException {
+        this(element, baseURI, false);
 
-      Attr attr = element.getAttributeNodeNS(null, "Id");
-      if (attr != null) {
-          element.setIdAttributeNode(attr, true);
-      }
+    }
+    /**
+     * Constructor Manifest
+     *
+     * @param element
+     * @param baseURI
+     * @param secureValidation
+     * @throws XMLSecurityException
+     */
+    public Manifest(
+        Element element, String baseURI, boolean secureValidation
+    ) throws XMLSecurityException {
+        super(element, baseURI);
 
-      // check out Reference children
-      this._referencesEl = XMLUtils.selectDsNodes(this._constructionElement.getFirstChild(),
-         Constants._TAG_REFERENCE);
-      int le = this._referencesEl.length;
-      {
-         if (le == 0) {
+        Attr attr = element.getAttributeNodeNS(null, "Id");
+        if (attr != null) {
+            element.setIdAttributeNode(attr, true);
+        }
+        this.secureValidation = secureValidation;
 
+        // check out Reference children
+        this.referencesEl =
+            XMLUtils.selectDsNodes(
+                this.constructionElement.getFirstChild(), Constants._TAG_REFERENCE
+            );
+        int le = this.referencesEl.length;
+        if (le == 0) {
             // At least one Reference must be present. Bad.
-            Object exArgs[] = { Constants._TAG_REFERENCE,
-                                Constants._TAG_MANIFEST };
+            Object exArgs[] = { Constants._TAG_REFERENCE, Constants._TAG_MANIFEST };
 
             throw new DOMException(DOMException.WRONG_DOCUMENT_ERR,
                                    I18n.translate("xml.WrongContent", exArgs));
-         }
-      }
+        }
 
-      // create Vector
-      this._references = new ArrayList<Reference>(le);
+        if (secureValidation && le > MAXIMUM_REFERENCE_COUNT) {
+            Object exArgs[] = { le, MAXIMUM_REFERENCE_COUNT };
+
+            throw new XMLSecurityException("signature.tooManyReferences", exArgs);
+        }
 
-      for (int i = 0; i < le; i++) {
-         Element refElem = this._referencesEl[i];
-         Attr refAttr = refElem.getAttributeNodeNS(null, "Id");
-         if (refAttr != null) {
-             refElem.setIdAttributeNode(refAttr, true);
-         }
-         this._references.add(null);
-      }
-   }
+        // create List
+        this.references = new ArrayList<Reference>(le);
+
+        for (int i = 0; i < le; i++) {
+            Element refElem = referencesEl[i];
+            Attr refAttr = refElem.getAttributeNodeNS(null, "Id");
+            if (refAttr != null) {
+                refElem.setIdAttributeNode(refAttr, true);
+            }
+            this.references.add(null);
+        }
+    }
 
-   /**
-    * This <code>addDocument</code> method is used to add a new resource to the
-    * signed info. A {@link com.sun.org.apache.xml.internal.security.signature.Reference} is built
-    * from the supplied values.
-    *
-    * @param BaseURI the URI of the resource where the XML instance was stored
-    * @param referenceURI <code>URI</code> attribute in <code>Reference</code> for specifing where data is
-    * @param transforms com.sun.org.apache.xml.internal.security.signature.Transforms object with an ordered list of transformations to be performed.
-    * @param digestURI The digest algorthim URI to be used.
-    * @param ReferenceId
-    * @param ReferenceType
-    * @throws XMLSignatureException
-    */
-   public void addDocument(
-           String BaseURI, String referenceURI, Transforms transforms, String digestURI, String ReferenceId, String ReferenceType)
-              throws XMLSignatureException {
+    /**
+     * This <code>addDocument</code> method is used to add a new resource to the
+     * signed info. A {@link com.sun.org.apache.xml.internal.security.signature.Reference} is built
+     * from the supplied values.
+     *
+     * @param baseURI the URI of the resource where the XML instance was stored
+     * @param referenceURI <code>URI</code> attribute in <code>Reference</code> for specifying
+     * where data is
+     * @param transforms com.sun.org.apache.xml.internal.security.signature.Transforms object with an ordered
+     * list of transformations to be performed.
+     * @param digestURI The digest algorithm URI to be used.
+     * @param referenceId
+     * @param referenceType
+     * @throws XMLSignatureException
+     */
+    public void addDocument(
+        String baseURI, String referenceURI, Transforms transforms,
+        String digestURI, String referenceId, String referenceType
+    ) throws XMLSignatureException {
+        // the this.doc is handed implicitly by the this.getOwnerDocument()
+        Reference ref =
+            new Reference(this.doc, baseURI, referenceURI, this, transforms, digestURI);
 
-         // the this._doc is handed implicitly by the this.getOwnerDocument()
-         Reference ref = new Reference(this._doc, BaseURI, referenceURI, this,
-                                       transforms, digestURI);
+        if (referenceId != null) {
+            ref.setId(referenceId);
+        }
 
-         if (ReferenceId != null) {
-            ref.setId(ReferenceId);
-         }
-
-         if (ReferenceType != null) {
-            ref.setType(ReferenceType);
-         }
-
-         // add Reference object to our cache vector
-         this._references.add(ref);
+        if (referenceType != null) {
+            ref.setType(referenceType);
+        }
 
-         // add the Element of the Reference object to the Manifest/SignedInfo
-         this._constructionElement.appendChild(ref.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-   }
+        // add Reference object to our cache vector
+        this.references.add(ref);
+
+        // add the Element of the Reference object to the Manifest/SignedInfo
+        this.constructionElement.appendChild(ref.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-   /**
-    * The calculation of the DigestValues in the References must be after the
-    * References are already added to the document and during the signing
-    * process. This ensures that all neccesary data is in place.
-    *
-    * @throws ReferenceNotInitializedException
-    * @throws XMLSignatureException
-    */
-   public void generateDigestValues()
-           throws XMLSignatureException, ReferenceNotInitializedException {
-
-         for (int i = 0; i < this.getLength(); i++) {
-
+    /**
+     * The calculation of the DigestValues in the References must be after the
+     * References are already added to the document and during the signing
+     * process. This ensures that all necessary data is in place.
+     *
+     * @throws ReferenceNotInitializedException
+     * @throws XMLSignatureException
+     */
+    public void generateDigestValues()
+        throws XMLSignatureException, ReferenceNotInitializedException {
+        for (int i = 0; i < this.getLength(); i++) {
             // update the cached Reference object, the Element content is automatically updated
-            Reference currentRef = this._references.get(i);
-
+            Reference currentRef = this.references.get(i);
             currentRef.generateDigestValue();
-         }
-   }
+        }
+    }
 
-   /**
-    * Return the nonnegative number of added references.
-    *
-    * @return the number of references
-    */
-   public int getLength() {
-      return this._references.size();
-   }
+    /**
+     * Return the nonnegative number of added references.
+     *
+     * @return the number of references
+     */
+    public int getLength() {
+        return this.references.size();
+    }
 
-   /**
-    * Return the <it>i</it><sup>th</sup> reference.  Valid <code>i</code>
-    * values are 0 to <code>{link@ getSize}-1</code>.
-    *
-    * @param i Index of the requested {@link Reference}
-    * @return the <it>i</it><sup>th</sup> reference
-    * @throws XMLSecurityException
-    */
-   public Reference item(int i) throws XMLSecurityException {
+    /**
+     * Return the <it>i</it><sup>th</sup> reference. Valid <code>i</code>
+     * values are 0 to <code>{link@ getSize}-1</code>.
+     *
+     * @param i Index of the requested {@link Reference}
+     * @return the <it>i</it><sup>th</sup> reference
+     * @throws XMLSecurityException
+     */
+    public Reference item(int i) throws XMLSecurityException {
+        if (this.references.get(i) == null) {
+            // not yet constructed, so _we_ have to
+            Reference ref =
+                new Reference(referencesEl[i], this.baseURI, this, secureValidation);
 
-         if (this._references.get(i) == null) {
-
-            // not yet constructed, so _we_ have to
-            Reference ref = new Reference(_referencesEl[i], this._baseURI, this);
+            this.references.set(i, ref);
+        }
 
-            this._references.set(i, ref);
-         }
-
-         return this._references.get(i);
-
-   }
+        return this.references.get(i);
+    }
 
-   /**
-    * Sets the <code>Id</code> attribute
-    *
-    * @param Id the <code>Id</code> attribute in <code>ds:Manifest</code>
-    */
-   public void setId(String Id) {
+    /**
+     * Sets the <code>Id</code> attribute
+     *
+     * @param Id the <code>Id</code> attribute in <code>ds:Manifest</code>
+     */
+    public void setId(String Id) {
+        if (Id != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
+            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+        }
+    }
 
-      if (Id != null) {
-          setLocalIdAttribute(Constants._ATT_ID, Id);
-      }
-   }
-
-   /**
-    * Returns the <code>Id</code> attribute
-    *
-    * @return the <code>Id</code> attribute in <code>ds:Manifest</code>
-    */
-   public String getId() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
-   }
+    /**
+     * Returns the <code>Id</code> attribute
+     *
+     * @return the <code>Id</code> attribute in <code>ds:Manifest</code>
+     */
+    public String getId() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+    }
 
-   /**
-    * Used to do a <A HREF="http://www.w3.org/TR/xmldsig-core/#def-ValidationReference">reference
-    * validation</A> of all enclosed references using the {@link Reference#verify} method.
-    *
-    * <p>This step loops through all {@link Reference}s and does verify the hash
-    * values. If one or more verifications fail, the method returns
-    * <code>false</code>. If <i>all</i> verifications are successful,
-    * it returns <code>true</code>. The results of the individual reference
-    * validations are available by using the {@link #getVerificationResult(int)} method
-    *
-    * @return true if all References verify, false if one or more do not verify.
-    * @throws MissingResourceFailureException if a {@link Reference} does not verify (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException} because of an uninitialized {@link XMLSignatureInput}
-    * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify
-    * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify()
-    * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException
-    * @throws XMLSecurityException
-    */
-   public boolean verifyReferences()
-           throws MissingResourceFailureException, XMLSecurityException {
-      return this.verifyReferences(false);
-   }
+    /**
+     * Used to do a <A HREF="http://www.w3.org/TR/xmldsig-core/#def-ValidationReference">reference
+     * validation</A> of all enclosed references using the {@link Reference#verify} method.
+     *
+     * <p>This step loops through all {@link Reference}s and does verify the hash
+     * values. If one or more verifications fail, the method returns
+     * <code>false</code>. If <i>all</i> verifications are successful,
+     * it returns <code>true</code>. The results of the individual reference
+     * validations are available by using the {@link #getVerificationResult(int)} method
+     *
+     * @return true if all References verify, false if one or more do not verify.
+     * @throws MissingResourceFailureException if a {@link Reference} does not verify
+     * (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException}
+     * because of an uninitialized {@link XMLSignatureInput}
+     * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify
+     * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify()
+     * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException
+     * @throws XMLSecurityException
+     */
+    public boolean verifyReferences()
+        throws MissingResourceFailureException, XMLSecurityException {
+        return this.verifyReferences(false);
+    }
 
-   /**
-    * Used to do a <A HREF="http://www.w3.org/TR/xmldsig-core/#def-ValidationReference">reference
-    * validation</A> of all enclosed references using the {@link Reference#verify} method.
-    *
-    * <p>This step loops through all {@link Reference}s and does verify the hash
-    * values. If one or more verifications fail, the method returns
-    * <code>false</code>. If <i>all</i> verifications are successful,
-    * it returns <code>true</code>. The results of the individual reference
-    * validations are available by using the {@link #getVerificationResult(int)} method
-    *
-    * @param followManifests
-    * @return true if all References verify, false if one or more do not verify.
-    * @throws MissingResourceFailureException if a {@link Reference} does not verify (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException} because of an uninitialized {@link XMLSignatureInput}
-    * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify
-    * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify(boolean)
-    * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException
-    * @throws XMLSecurityException
-    */
-   public boolean verifyReferences(boolean followManifests)
-           throws MissingResourceFailureException, XMLSecurityException {
-      if (_referencesEl==null) {
-        this._referencesEl =
-            XMLUtils.selectDsNodes(this._constructionElement.getFirstChild(),
-                         Constants._TAG_REFERENCE);
-      }
-          if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "verify " +_referencesEl.length + " References");
-        log.log(java.util.logging.Level.FINE, "I am " + (followManifests
-                           ? ""
-                           : "not") + " requested to follow nested Manifests");
-      }
-      boolean verify = true;
-
-      if (_referencesEl.length==0) {
-         throw new XMLSecurityException("empty");
-      }
+    /**
+     * Used to do a <A HREF="http://www.w3.org/TR/xmldsig-core/#def-ValidationReference">reference
+     * validation</A> of all enclosed references using the {@link Reference#verify} method.
+     *
+     * <p>This step loops through all {@link Reference}s and does verify the hash
+     * values. If one or more verifications fail, the method returns
+     * <code>false</code>. If <i>all</i> verifications are successful,
+     * it returns <code>true</code>. The results of the individual reference
+     * validations are available by using the {@link #getVerificationResult(int)} method
+     *
+     * @param followManifests
+     * @return true if all References verify, false if one or more do not verify.
+     * @throws MissingResourceFailureException if a {@link Reference} does not verify
+     * (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException}
+     * because of an uninitialized {@link XMLSignatureInput}
+     * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify
+     * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify(boolean)
+     * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException
+     * @throws XMLSecurityException
+     */
+    public boolean verifyReferences(boolean followManifests)
+        throws MissingResourceFailureException, XMLSecurityException {
+        if (referencesEl == null) {
+            this.referencesEl =
+                XMLUtils.selectDsNodes(
+                    this.constructionElement.getFirstChild(), Constants._TAG_REFERENCE
+                );
+        }
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "verify " + referencesEl.length + " References");
+            log.log(java.util.logging.Level.FINE, "I am " + (followManifests
+                ? "" : "not") + " requested to follow nested Manifests");
+        }
+        if (referencesEl.length == 0) {
+            throw new XMLSecurityException("empty");
+        }
+        if (secureValidation && referencesEl.length > MAXIMUM_REFERENCE_COUNT) {
+            Object exArgs[] = { referencesEl.length, MAXIMUM_REFERENCE_COUNT };
 
-      this.verificationResults =
-         new boolean[_referencesEl.length];
-
-      for (int i =
-              0; i < this._referencesEl.length; i++) {
-         Reference currentRef =
-            new Reference(_referencesEl[i], this._baseURI, this);
+            throw new XMLSecurityException("signature.tooManyReferences", exArgs);
+        }
 
-         this._references.set(i, currentRef);
+        this.verificationResults = new boolean[referencesEl.length];
+        boolean verify = true;
+        for (int i = 0; i < this.referencesEl.length; i++) {
+            Reference currentRef =
+                new Reference(referencesEl[i], this.baseURI, this, secureValidation);
 
-         /* if only one item does not verify, the whole verification fails */
-         try {
-            boolean currentRefVerified = currentRef.verify();
+            this.references.set(i, currentRef);
 
-            this.setVerificationResult(i, currentRefVerified);
+            // if only one item does not verify, the whole verification fails
+            try {
+                boolean currentRefVerified = currentRef.verify();
+
+                this.setVerificationResult(i, currentRefVerified);
 
-            if (!currentRefVerified) {
-               verify = false;
-            }
-            if (log.isLoggable(java.util.logging.Level.FINE))
-                log.log(java.util.logging.Level.FINE, "The Reference has Type " + currentRef.getType());
+                if (!currentRefVerified) {
+                    verify = false;
+                }
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "The Reference has Type " + currentRef.getType());
+                }
 
-            // was verification successful till now and do we want to verify the Manifest?
-            if (verify && followManifests
-                    && currentRef.typeIsReferenceToManifest()) {
-               log.log(java.util.logging.Level.FINE, "We have to follow a nested Manifest");
+                // was verification successful till now and do we want to verify the Manifest?
+                if (verify && followManifests && currentRef.typeIsReferenceToManifest()) {
+                    if (log.isLoggable(java.util.logging.Level.FINE)) {
+                        log.log(java.util.logging.Level.FINE, "We have to follow a nested Manifest");
+                    }
 
-                try {
-                  XMLSignatureInput signedManifestNodes =
-                    currentRef.dereferenceURIandPerformTransforms(null);
-                  Set<Node> nl = signedManifestNodes.getNodeSet();
-                  Manifest referencedManifest = null;
-                  Iterator<Node> nlIterator = nl.iterator();
+                    try {
+                        XMLSignatureInput signedManifestNodes =
+                            currentRef.dereferenceURIandPerformTransforms(null);
+                        Set<Node> nl = signedManifestNodes.getNodeSet();
+                        Manifest referencedManifest = null;
+                        Iterator<Node> nlIterator = nl.iterator();
 
-                  findManifest: while (nlIterator.hasNext()) {
-                     Node n =  nlIterator.next();
+                        findManifest: while (nlIterator.hasNext()) {
+                            Node n = nlIterator.next();
 
-                     if ((n.getNodeType() == Node.ELEMENT_NODE) && ((Element) n)
-                             .getNamespaceURI()
-                             .equals(Constants.SignatureSpecNS) && ((Element) n)
-                             .getLocalName().equals(Constants._TAG_MANIFEST)) {
-                        try {
-                           referencedManifest =
-                              new Manifest((Element) n,
-                                           signedManifestNodes.getSourceURI());
-
-                           break findManifest;
-                        } catch (XMLSecurityException ex) {
+                            if ((n.getNodeType() == Node.ELEMENT_NODE)
+                                && ((Element) n).getNamespaceURI().equals(Constants.SignatureSpecNS)
+                                && ((Element) n).getLocalName().equals(Constants._TAG_MANIFEST)
+                            ) {
+                                try {
+                                    referencedManifest =
+                                        new Manifest(
+                                             (Element)n, signedManifestNodes.getSourceURI(), secureValidation
+                                        );
+                                    break findManifest;
+                                } catch (XMLSecurityException ex) {
+                                    if (log.isLoggable(java.util.logging.Level.FINE)) {
+                                        log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
+                                    }
+                                    // Hm, seems not to be a ds:Manifest
+                                }
+                            }
+                        }
 
-                           // Hm, seems not to be a ds:Manifest
+                        if (referencedManifest == null) {
+                            // The Reference stated that it points to a ds:Manifest
+                            // but we did not find a ds:Manifest in the signed area
+                            throw new MissingResourceFailureException("empty", currentRef);
                         }
-                     }
-                  }
 
-                  if (referencedManifest == null) {
-
-                     // The Reference stated that it points to a ds:Manifest
-                     // but we did not find a ds:Manifest in the signed area
-                     throw new MissingResourceFailureException("empty",
-                                                               currentRef);
-                  }
+                        referencedManifest.perManifestResolvers = this.perManifestResolvers;
+                        referencedManifest.resolverProperties = this.resolverProperties;
 
-                  referencedManifest._perManifestResolvers =
-                     this._perManifestResolvers;
-                  referencedManifest._resolverProperties =
-                     this._resolverProperties;
+                        boolean referencedManifestValid =
+                            referencedManifest.verifyReferences(followManifests);
 
-                  boolean referencedManifestValid =
-                     referencedManifest.verifyReferences(followManifests);
-
-                  if (!referencedManifestValid) {
-                     verify = false;
+                        if (!referencedManifestValid) {
+                            verify = false;
 
-                     log.log(java.util.logging.Level.WARNING, "The nested Manifest was invalid (bad)");
-                  } else {
-                     log.log(java.util.logging.Level.FINE, "The nested Manifest was valid (good)");
-                  }
-               } catch (IOException ex) {
-                  throw new ReferenceNotInitializedException("empty", ex);
-               } catch (ParserConfigurationException ex) {
-                  throw new ReferenceNotInitializedException("empty", ex);
-               } catch (SAXException ex) {
-                  throw new ReferenceNotInitializedException("empty", ex);
-               }
+                            log.log(java.util.logging.Level.WARNING, "The nested Manifest was invalid (bad)");
+                        } else {
+                            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                                log.log(java.util.logging.Level.FINE, "The nested Manifest was valid (good)");
+                            }
+                        }
+                    } catch (IOException ex) {
+                        throw new ReferenceNotInitializedException("empty", ex);
+                    } catch (ParserConfigurationException ex) {
+                        throw new ReferenceNotInitializedException("empty", ex);
+                    } catch (SAXException ex) {
+                        throw new ReferenceNotInitializedException("empty", ex);
+                    }
+                }
+            } catch (ReferenceNotInitializedException ex) {
+                Object exArgs[] = { currentRef.getURI() };
+
+                throw new MissingResourceFailureException(
+                    "signature.Verification.Reference.NoInput", exArgs, ex, currentRef
+                );
             }
-         } catch (ReferenceNotInitializedException ex) {
-            Object exArgs[] = { currentRef.getURI() };
+        }
 
-            throw new MissingResourceFailureException(
-               "signature.Verification.Reference.NoInput", exArgs, ex,
-               currentRef);
-         }
-      }
+        return verify;
+    }
 
-      return verify;
-   }
+    /**
+     * Method setVerificationResult
+     *
+     * @param index
+     * @param verify
+     */
+    private void setVerificationResult(int index, boolean verify) {
+        if (this.verificationResults == null) {
+            this.verificationResults = new boolean[this.getLength()];
+        }
+
+        this.verificationResults[index] = verify;
+    }
 
-   /**
-    * Method setVerificationResult
-    *
-    * @param index
-    * @param verify
-    */
-   private void setVerificationResult(int index, boolean verify)
-   {
-
-      if (this.verificationResults == null) {
-         this.verificationResults = new boolean[this.getLength()];
-      }
-
-      this.verificationResults[index] = verify;
-   }
+    /**
+     * After verifying a {@link Manifest} or a {@link SignedInfo} using the
+     * {@link Manifest#verifyReferences()} or {@link SignedInfo#verify()} methods,
+     * the individual results can be retrieved with this method.
+     *
+     * @param index an index of into a {@link Manifest} or a {@link SignedInfo}
+     * @return the results of reference validation at the specified index
+     * @throws XMLSecurityException
+     */
+    public boolean getVerificationResult(int index) throws XMLSecurityException {
+        if ((index < 0) || (index > this.getLength() - 1)) {
+            Object exArgs[] = { Integer.toString(index), Integer.toString(this.getLength()) };
+            Exception e =
+                new IndexOutOfBoundsException(
+                    I18n.translate("signature.Verification.IndexOutOfBounds", exArgs)
+                );
 
-   /**
-    * After verifying a {@link Manifest} or a {@link SignedInfo} using the
-    * {@link Manifest#verifyReferences()} or {@link SignedInfo#verify()} methods,
-    * the individual results can be retrieved with this method.
-    *
-    * @param index an index of into a {@link Manifest} or a {@link SignedInfo}
-    * @return the results of reference validation at the specified index
-    * @throws XMLSecurityException
-    */
-   public boolean getVerificationResult(int index) throws XMLSecurityException {
+            throw new XMLSecurityException("generic.EmptyMessage", e);
+        }
 
-      if ((index < 0) || (index > this.getLength() - 1)) {
-         Object exArgs[] = { Integer.toString(index),
-                             Integer.toString(this.getLength()) };
-         Exception e =
-            new IndexOutOfBoundsException(I18n
-               .translate("signature.Verification.IndexOutOfBounds", exArgs));
+        if (this.verificationResults == null) {
+            try {
+                this.verifyReferences();
+            } catch (Exception ex) {
+                throw new XMLSecurityException("generic.EmptyMessage", ex);
+            }
+        }
+
+        return this.verificationResults[index];
+    }
 
-         throw new XMLSecurityException("generic.EmptyMessage", e);
-      }
-
-      if (this.verificationResults == null) {
-         try {
-            this.verifyReferences();
-         } catch (Exception ex) {
-            throw new XMLSecurityException("generic.EmptyMessage", ex);
-         }
-      }
-
-      return this.verificationResults[index];
-   }
-
-   /**
-    * Adds Resource Resolver for retrieving resources at specified <code>URI</code> attribute in <code>reference</code> element
-    *
-    * @param resolver {@link ResourceResolver} can provide the implemenatin subclass of {@link ResourceResolverSpi} for retrieving resource.
-    */
-   public void addResourceResolver(ResourceResolver resolver) {
+    /**
+     * Adds Resource Resolver for retrieving resources at specified <code>URI</code> attribute
+     * in <code>reference</code> element
+     *
+     * @param resolver {@link ResourceResolver} can provide the implemenatin subclass of
+     * {@link ResourceResolverSpi} for retrieving resource.
+     */
+    public void addResourceResolver(ResourceResolver resolver) {
+        if (resolver == null) {
+            return;
+        }
+        if (perManifestResolvers == null) {
+            perManifestResolvers = new ArrayList<ResourceResolver>();
+        }
+        this.perManifestResolvers.add(resolver);
+    }
 
-      if (resolver == null) {
-          return;
-      }
-      if (_perManifestResolvers==null)
-          _perManifestResolvers = new ArrayList<ResourceResolver>();
-      this._perManifestResolvers.add(resolver);
-
-   }
+    /**
+     * Adds Resource Resolver for retrieving resources at specified <code>URI</code> attribute
+     * in <code>reference</code> element
+     *
+     * @param resolverSpi the implementation subclass of {@link ResourceResolverSpi} for
+     * retrieving the resource.
+     */
+    public void addResourceResolver(ResourceResolverSpi resolverSpi) {
+        if (resolverSpi == null) {
+            return;
+        }
+        if (perManifestResolvers == null) {
+            perManifestResolvers = new ArrayList<ResourceResolver>();
+        }
+        perManifestResolvers.add(new ResourceResolver(resolverSpi));
+    }
 
-   /**
-    * Adds Resource Resolver for retrieving resources at specified <code>URI</code> attribute in <code>reference</code> element
-    *
-    * @param resolverSpi the implemenatin subclass of {@link ResourceResolverSpi} for retrieving resource.
-    */
-   public void addResourceResolver(ResourceResolverSpi resolverSpi) {
-
-      if (resolverSpi == null) {
-          return;
-      }
-      if (_perManifestResolvers==null)
-                  _perManifestResolvers = new ArrayList<ResourceResolver>();
-      this._perManifestResolvers.add(new ResourceResolver(resolverSpi));
+    /**
+     * Get the Per-Manifest Resolver List
+     * @return the per-manifest Resolver List
+     */
+    public List<ResourceResolver> getPerManifestResolvers() {
+        return perManifestResolvers;
+    }
 
-   }
+    /**
+     * Get the resolver property map
+     * @return the resolver property map
+     */
+    public Map<String, String> getResolverProperties() {
+        return resolverProperties;
+    }
 
-   /**
-    * Used to pass parameters like proxy servers etc to the ResourceResolver
-    * implementation.
-    *
-    * @param key the key
-    * @param value the value
-    */
-   public void setResolverProperty(String key, String value) {
-           if (_resolverProperties==null) {
-                   _resolverProperties=new HashMap<String, String>(10);
-           }
-      this._resolverProperties.put(key, value);
-   }
+    /**
+     * Used to pass parameters like proxy servers etc to the ResourceResolver
+     * implementation.
+     *
+     * @param key the key
+     * @param value the value
+     */
+    public void setResolverProperty(String key, String value) {
+        if (resolverProperties == null) {
+            resolverProperties = new HashMap<String, String>(10);
+        }
+        this.resolverProperties.put(key, value);
+    }
 
-   /**
-    * Returns the value at specified key
-    *
-    * @param key the key
-    * @return the value
-    */
-   public String getResolverProperty(String key) {
-      return this._resolverProperties.get(key);
-   }
+    /**
+     * Returns the value at specified key
+     *
+     * @param key the key
+     * @return the value
+     */
+    public String getResolverProperty(String key) {
+        return this.resolverProperties.get(key);
+    }
 
-   /**
-    * Method getSignedContentItem
-    *
-    * @param i
-    * @return The signed content of the i reference.
-    *
-    * @throws XMLSignatureException
-    */
-   public byte[] getSignedContentItem(int i) throws XMLSignatureException {
-
-      try {
-         return this.getReferencedContentAfterTransformsItem(i).getBytes();
-      } catch (IOException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (CanonicalizationException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (InvalidCanonicalizerException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (XMLSecurityException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /**
+     * Method getSignedContentItem
+     *
+     * @param i
+     * @return The signed content of the i reference.
+     *
+     * @throws XMLSignatureException
+     */
+    public byte[] getSignedContentItem(int i) throws XMLSignatureException {
+        try {
+            return this.getReferencedContentAfterTransformsItem(i).getBytes();
+        } catch (IOException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (CanonicalizationException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (InvalidCanonicalizerException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (XMLSecurityException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /**
-    * Method getReferencedContentPriorTransformsItem
-    *
-    * @param i
-    * @return The contents before transformation of the reference i.
-    * @throws XMLSecurityException
-    */
-   public XMLSignatureInput getReferencedContentBeforeTransformsItem(int i)
-           throws XMLSecurityException {
-      return this.item(i).getContentsBeforeTransformation();
-   }
+    /**
+     * Method getReferencedContentPriorTransformsItem
+     *
+     * @param i
+     * @return The contents before transformation of the reference i.
+     * @throws XMLSecurityException
+     */
+    public XMLSignatureInput getReferencedContentBeforeTransformsItem(int i)
+        throws XMLSecurityException {
+        return this.item(i).getContentsBeforeTransformation();
+    }
 
-   /**
-    * Method getReferencedContentAfterTransformsItem
-    *
-    * @param i
-    * @return The contents after transformation of the reference i.
-    * @throws XMLSecurityException
-    */
-   public XMLSignatureInput getReferencedContentAfterTransformsItem(int i)
-           throws XMLSecurityException {
-      return this.item(i).getContentsAfterTransformation();
-   }
+    /**
+     * Method getReferencedContentAfterTransformsItem
+     *
+     * @param i
+     * @return The contents after transformation of the reference i.
+     * @throws XMLSecurityException
+     */
+    public XMLSignatureInput getReferencedContentAfterTransformsItem(int i)
+        throws XMLSecurityException {
+        return this.item(i).getContentsAfterTransformation();
+    }
 
-   /**
-    * Method getSignedContentLength
-    *
-    * @return The nu,ber of references contained in this reference.
-    */
-   public int getSignedContentLength() {
-      return this.getLength();
-   }
+    /**
+     * Method getSignedContentLength
+     *
+     * @return The number of references contained in this reference.
+     */
+    public int getSignedContentLength() {
+        return this.getLength();
+    }
 
-   /**
-    * Method getBaseLocalName
-    *
-    * @inheritDoc
-    */
-   public String getBaseLocalName() {
-      return Constants._TAG_MANIFEST;
-   }
+    /**
+     * Method getBaseLocalName
+     *
+     * @inheritDoc
+     */
+    public String getBaseLocalName() {
+        return Constants._TAG_MANIFEST;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,28 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
-
-
-
-
 /**
  * Thrown by {@link com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify()} when
  * testing the signature fails because of uninitialized
@@ -34,97 +32,93 @@
  */
 public class MissingResourceFailureException extends XMLSignatureException {
 
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
-   /** Field uninitializedReference */
-   Reference uninitializedReference = null;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
+
+    /** Field uninitializedReference */
+    private Reference uninitializedReference = null;
 
-   /**
-    * MissingKeyResourceFailureException constructor.
-    * @param _msgID
-    * @param reference
-    * @see #getReference
-    */
-   public MissingResourceFailureException(String _msgID, Reference reference) {
-
-      super(_msgID);
+    /**
+     * MissingKeyResourceFailureException constructor.
+     * @param msgID
+     * @param reference
+     * @see #getReference
+     */
+    public MissingResourceFailureException(String msgID, Reference reference) {
+        super(msgID);
 
-      this.uninitializedReference = reference;
-   }
+        this.uninitializedReference = reference;
+    }
 
-   /**
-    * Constructor MissingResourceFailureException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param reference
-    * @see #getReference
-    */
-   public MissingResourceFailureException(String _msgID, Object exArgs[],
-                                          Reference reference) {
+    /**
+     * Constructor MissingResourceFailureException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param reference
+     * @see #getReference
+     */
+    public MissingResourceFailureException(String msgID, Object exArgs[], Reference reference) {
+        super(msgID, exArgs);
 
-      super(_msgID, exArgs);
-
-      this.uninitializedReference = reference;
-   }
+        this.uninitializedReference = reference;
+    }
 
-   /**
-    * Constructor MissingResourceFailureException
-    *
-    * @param _msgID
-    * @param _originalException
-    * @param reference
-    * @see #getReference
-    */
-   public MissingResourceFailureException(String _msgID,
-                                          Exception _originalException,
-                                          Reference reference) {
+    /**
+     * Constructor MissingResourceFailureException
+     *
+     * @param msgID
+     * @param originalException
+     * @param reference
+     * @see #getReference
+     */
+    public MissingResourceFailureException(
+        String msgID, Exception originalException, Reference reference
+    ) {
+        super(msgID, originalException);
 
-      super(_msgID, _originalException);
-
-      this.uninitializedReference = reference;
-   }
+        this.uninitializedReference = reference;
+    }
 
-   /**
-    * Constructor MissingResourceFailureException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    * @param reference
-    * @see #getReference
-    */
-   public MissingResourceFailureException(String _msgID, Object exArgs[],
-                                          Exception _originalException,
-                                          Reference reference) {
+    /**
+     * Constructor MissingResourceFailureException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     * @param reference
+     * @see #getReference
+     */
+    public MissingResourceFailureException(
+        String msgID, Object exArgs[], Exception originalException, Reference reference
+    ) {
+        super(msgID, exArgs, originalException);
 
-      super(_msgID, exArgs, _originalException);
-
-      this.uninitializedReference = reference;
-   }
+        this.uninitializedReference = reference;
+    }
 
-   /**
-    * used to set the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference}
-    *
-    * @param reference the Reference object
-    * @see #getReference
-    */
-   public void setReference(Reference reference) {
-      this.uninitializedReference = reference;
-   }
+    /**
+     * used to set the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference}
+     *
+     * @param reference the Reference object
+     * @see #getReference
+     */
+    public void setReference(Reference reference) {
+        this.uninitializedReference = reference;
+    }
 
-   /**
-    * used to get the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference}
-    *
-    * This allows to supply the correct {@link com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput}
-    * to the {@link com.sun.org.apache.xml.internal.security.signature.Reference} to try again verification.
-    *
-    * @return the Reference object
-    * @see #setReference
-    */
-   public Reference getReference() {
-      return this.uninitializedReference;
-   }
+    /**
+     * used to get the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference}
+     *
+     * This allows to supply the correct {@link com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput}
+     * to the {@link com.sun.org.apache.xml.internal.security.signature.Reference} to try again verification.
+     *
+     * @return the Reference object
+     * @see #setReference
+     */
+    public Reference getReference() {
+        return this.uninitializedReference;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
@@ -24,30 +26,30 @@
 
 /**
  * An interface to tell to the c14n if a node is included or not in the output
- * @author raul
- *
  */
 public interface NodeFilter {
-        /**
-         * Tells if a node must be outputed in c14n.
-         * @param n
-         * @return 1 if the node should be outputed.
-         *                 0 if node must not be outputed,
-         *                -1 if the node and all it's child must not be output.
-         *
-         */
-        public int isNodeInclude(Node n);
-        /**
-         * Tells if a node must be outputed in a c14n.
-         * The caller must assured that this method is always call
-         * in document order. The implementations can use this
-         * restriction to optimize the transformation.
-         * @param n
-         * @param level the relative level in the tree
-         * @return 1 if the node should be outputed.
-         *                 0 if node must not be outputed,
-         *                -1 if the node and all it's child must not be output.
-         */
-        public int isNodeIncludeDO(Node n, int level);
+
+    /**
+     * Tells if a node must be output in c14n.
+     * @param n
+     * @return 1 if the node should be output.
+     *         0 if node must not be output,
+     *         -1 if the node and all it's child must not be output.
+     *
+     */
+    int isNodeInclude(Node n);
+
+    /**
+     * Tells if a node must be output in a c14n.
+     * The caller must assured that this method is always call
+     * in document order. The implementations can use this
+     * restriction to optimize the transformation.
+     * @param n
+     * @param level the relative level in the tree
+     * @return 1 if the node should be output.
+     *         0 if node must not be output,
+     *         -1 if the node and all it's child must not be output.
+     */
+    int isNodeIncludeDO(Node n, int level);
 
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,28 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -38,111 +39,99 @@
  */
 public class ObjectContainer extends SignatureElementProxy {
 
-   /**
-    * Constructs {@link ObjectContainer}
-    *
-    * @param doc the {@link Document} in which <code>Object</code> element is placed
-    */
-   public ObjectContainer(Document doc) {
-
-      super(doc);
-   }
+    /**
+     * Constructs {@link ObjectContainer}
+     *
+     * @param doc the {@link Document} in which <code>Object</code> element is placed
+     */
+    public ObjectContainer(Document doc) {
+        super(doc);
+    }
 
-   /**
-    * Constructs {@link ObjectContainer} from {@link Element}
-    *
-    * @param element is <code>Object</code> element
-    * @param BaseURI the URI of the resource where the XML instance was stored
-    * @throws XMLSecurityException
-    */
-   public ObjectContainer(Element element, String BaseURI)
-           throws XMLSecurityException {
-
-      super(element, BaseURI);
-   }
+    /**
+     * Constructs {@link ObjectContainer} from {@link Element}
+     *
+     * @param element is <code>Object</code> element
+     * @param baseURI the URI of the resource where the XML instance was stored
+     * @throws XMLSecurityException
+     */
+    public ObjectContainer(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
+    }
 
-   /**
-    * Sets the <code>Id</code> attribute
-    *
-    * @param Id <code>Id</code> attribute
-    */
-   public void setId(String Id) {
-
-      if (Id != null) {
-          setLocalIdAttribute(Constants._ATT_ID, Id);
-      }
-   }
+    /**
+     * Sets the <code>Id</code> attribute
+     *
+     * @param Id <code>Id</code> attribute
+     */
+    public void setId(String Id) {
+        if (Id != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
+            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+        }
+    }
 
-   /**
-    * Returns the <code>Id</code> attribute
-    *
-    * @return the <code>Id</code> attribute
-    */
-   public String getId() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
-   }
-
-   /**
-    * Sets the <code>MimeType</code> attribute
-    *
-    * @param MimeType the <code>MimeType</code> attribute
-    */
-   public void setMimeType(String MimeType) {
+    /**
+     * Returns the <code>Id</code> attribute
+     *
+     * @return the <code>Id</code> attribute
+     */
+    public String getId() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+    }
 
-      if ( (MimeType != null)) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_MIMETYPE,
-                                                MimeType);
-      }
-   }
+    /**
+     * Sets the <code>MimeType</code> attribute
+     *
+     * @param MimeType the <code>MimeType</code> attribute
+     */
+    public void setMimeType(String MimeType) {
+        if (MimeType != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_MIMETYPE, MimeType);
+        }
+    }
 
-   /**
-    * Returns the <code>MimeType</code> attribute
-    *
-    * @return the <code>MimeType</code> attribute
-    */
-   public String getMimeType() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_MIMETYPE);
-   }
-
-   /**
-    * Sets the <code>Encoding</code> attribute
-    *
-    * @param Encoding the <code>Encoding</code> attribute
-    */
-   public void setEncoding(String Encoding) {
-
-      if ((Encoding != null)) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_ENCODING,
-                                                Encoding);
-      }
-   }
+    /**
+     * Returns the <code>MimeType</code> attribute
+     *
+     * @return the <code>MimeType</code> attribute
+     */
+    public String getMimeType() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_MIMETYPE);
+    }
 
-   /**
-    * Returns the <code>Encoding</code> attribute
-    *
-    * @return the <code>Encoding</code> attribute
-    */
-   public String getEncoding() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_ENCODING);
-   }
+    /**
+     * Sets the <code>Encoding</code> attribute
+     *
+     * @param Encoding the <code>Encoding</code> attribute
+     */
+    public void setEncoding(String Encoding) {
+        if (Encoding != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_ENCODING, Encoding);
+        }
+    }
 
-   /**
-    * Adds child Node
-    *
-    * @param node child Node
-    * @return the new node in the tree.
-    */
-   public Node appendChild(Node node) {
-
-      Node result = null;
+    /**
+     * Returns the <code>Encoding</code> attribute
+     *
+     * @return the <code>Encoding</code> attribute
+     */
+    public String getEncoding() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ENCODING);
+    }
 
-      result = this._constructionElement.appendChild(node);
-
-      return result;
-   }
+    /**
+     * Adds child Node
+     *
+     * @param node child Node
+     * @return the new node in the tree.
+     */
+    public Node appendChild(Node node) {
+        return this.constructionElement.appendChild(node);
+    }
 
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_OBJECT;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_OBJECT;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,31 +2,32 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
-
-
 import java.io.IOException;
 import java.io.OutputStream;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 import java.util.HashSet;
+import java.util.Iterator;
 import java.util.Set;
 
 import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
@@ -34,6 +35,10 @@
 import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException;
 import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceData;
+import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceNodeSetData;
+import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceOctetStreamData;
+import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceSubTreeData;
 import com.sun.org.apache.xml.internal.security.transforms.InvalidTransformException;
 import com.sun.org.apache.xml.internal.security.transforms.Transform;
 import com.sun.org.apache.xml.internal.security.transforms.TransformationException;
@@ -42,7 +47,6 @@
 import com.sun.org.apache.xml.internal.security.utils.Base64;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.DigesterOutputStream;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
@@ -54,7 +58,6 @@
 import org.w3c.dom.Node;
 import org.w3c.dom.Text;
 
-
 /**
  * Handles <code>&lt;ds:Reference&gt;</code> elements.
  *
@@ -64,17 +67,17 @@
  *
  * <p>Create a new reference</p>
  * <pre>
- * Document _doc;
+ * Document doc;
  * MessageDigestAlgorithm sha1 = MessageDigestAlgorithm.getInstance("http://#sha1");
  * Reference ref = new Reference(new XMLSignatureInput(new FileInputStream("1.gif"),
  *                               "http://localhost/1.gif",
  *                               (Transforms) null, sha1);
- * Element refElem = ref.toElement(_doc);
+ * Element refElem = ref.toElement(doc);
  * </pre>
  *
  * <p>Verify a reference</p>
  * <pre>
- * Element refElem = _doc.getElement("Reference"); // PSEUDO
+ * Element refElem = doc.getElement("Reference"); // PSEUDO
  * Reference ref = new Reference(refElem);
  * String url = ref.getURI();
  * ref.setData(new XMLSignatureInput(new FileInputStream(url)));
@@ -103,689 +106,697 @@
  */
 public class Reference extends SignatureElementProxy {
 
-   /**
-    * Look up useC14N11 system property. If true, an explicit C14N11 transform
-    * will be added if necessary when generating the signature. See section
-    * 3.1.1 of http://www.w3.org/2007/xmlsec/Drafts/xmldsig-core/ for more info.
-    */
-   private static boolean useC14N11 =
-      AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
-         public Boolean run() {
-            return Boolean.getBoolean
-               ("com.sun.org.apache.xml.internal.security.useC14N11");
-         }
-      });
+    /** Field OBJECT_URI */
+    public static final String OBJECT_URI = Constants.SignatureSpecNS + Constants._TAG_OBJECT;
+
+    /** Field MANIFEST_URI */
+    public static final String MANIFEST_URI = Constants.SignatureSpecNS + Constants._TAG_MANIFEST;
+
+    /**
+     * The maximum number of transforms per reference, if secure validation is enabled.
+     */
+    public static final int MAXIMUM_TRANSFORM_COUNT = 5;
+
+    private boolean secureValidation;
 
-/*
-   static {
-      try {
-         useC14N11 = Boolean.getBoolean("com.sun.org.apache.xml.internal.security.useC14N11");
-      } catch (Exception e) {
-         // ignore exceptions
-      }
-   }
-*/
+    /**
+     * Look up useC14N11 system property. If true, an explicit C14N11 transform
+     * will be added if necessary when generating the signature. See section
+     * 3.1.1 of http://www.w3.org/2007/xmlsec/Drafts/xmldsig-core/ for more info.
+     */
+    private static boolean useC14N11 = (
+        AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
+            public Boolean run() {
+                return Boolean.valueOf(Boolean.getBoolean("com.sun.org.apache.xml.internal.security.useC14N11"));
+            }
+        })).booleanValue();
 
-   /** Field CacheSignedNodes */
-   public final static boolean CacheSignedNodes = false;
-
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    /** {@link org.apache.commons.logging} logging facility */
+    private static final java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(Reference.class.getName());
 
-   /** Field OBJECT_URI */
-   public static final String OBJECT_URI = Constants.SignatureSpecNS
-                                           + Constants._TAG_OBJECT;
+    private Manifest manifest;
+    private XMLSignatureInput transformsOutput;
+
+    private Transforms transforms;
 
-   /** Field MANIFEST_URI */
-   public static final String MANIFEST_URI = Constants.SignatureSpecNS
-                                             + Constants._TAG_MANIFEST;
-   //J-
-   Manifest _manifest = null;
-   XMLSignatureInput _transformsOutput;
-   //J+
+    private Element digestMethodElem;
 
-private Transforms transforms;
+    private Element digestValueElement;
 
-private Element digestMethodElem;
+    private ReferenceData referenceData;
 
-private Element digestValueElement;
-
-   /**
-    * Constructor Reference
-    *
-    * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
-    * @param BaseURI the URI of the resource where the XML instance will be stored
-    * @param ReferenceURI URI indicate where is data which will digested
-    * @param manifest
-    * @param transforms {@link Transforms} applied to data
-    * @param messageDigestAlgorithm {@link MessageDigestAlgorithm Digest algorithm} which is applied to the data
-    * TODO should we throw XMLSignatureException if MessageDigestAlgoURI is wrong?
-    * @throws XMLSignatureException
-    */
-   protected Reference(Document doc, String BaseURI, String ReferenceURI, Manifest manifest, Transforms transforms, String messageDigestAlgorithm)
-           throws XMLSignatureException {
-
-      super(doc);
+    /**
+     * Constructor Reference
+     *
+     * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
+     * @param baseURI the URI of the resource where the XML instance will be stored
+     * @param referenceURI URI indicate where is data which will digested
+     * @param manifest
+     * @param transforms {@link Transforms} applied to data
+     * @param messageDigestAlgorithm {@link MessageDigestAlgorithm Digest algorithm} which is
+     * applied to the data
+     * TODO should we throw XMLSignatureException if MessageDigestAlgoURI is wrong?
+     * @throws XMLSignatureException
+     */
+    protected Reference(
+        Document doc, String baseURI, String referenceURI, Manifest manifest,
+        Transforms transforms, String messageDigestAlgorithm
+    ) throws XMLSignatureException {
+        super(doc);
 
-      XMLUtils.addReturnToElement(this._constructionElement);
+        XMLUtils.addReturnToElement(this.constructionElement);
 
-      this._baseURI = BaseURI;
-      this._manifest = manifest;
+        this.baseURI = baseURI;
+        this.manifest = manifest;
 
-      this.setURI(ReferenceURI);
+        this.setURI(referenceURI);
 
-      // important: The ds:Reference must be added to the associated ds:Manifest
-      //            or ds:SignedInfo _before_ the this.resolverResult() is called.
-      // this._manifest.appendChild(this._constructionElement);
-      // this._manifest.appendChild(this._doc.createTextNode("\n"));
+        // important: The ds:Reference must be added to the associated ds:Manifest
+        //            or ds:SignedInfo _before_ the this.resolverResult() is called.
+        // this.manifest.appendChild(this.constructionElement);
+        // this.manifest.appendChild(this.doc.createTextNode("\n"));
 
-      if (transforms != null) {
-          this.transforms=transforms;
-         this._constructionElement.appendChild(transforms.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-      }
-      {
-         MessageDigestAlgorithm mda =
-            MessageDigestAlgorithm.getInstance(this._doc,
-                                               messageDigestAlgorithm);
+        if (transforms != null) {
+            this.transforms=transforms;
+            this.constructionElement.appendChild(transforms.getElement());
+            XMLUtils.addReturnToElement(this.constructionElement);
+        }
+        MessageDigestAlgorithm mda =
+            MessageDigestAlgorithm.getInstance(this.doc, messageDigestAlgorithm);
 
-         digestMethodElem=mda.getElement();
-         this._constructionElement.appendChild(digestMethodElem);
-         XMLUtils.addReturnToElement(this._constructionElement);
-      }
-      {
-         digestValueElement =
-            XMLUtils.createElementInSignatureSpace(this._doc,
-                                                   Constants._TAG_DIGESTVALUE);
+        digestMethodElem = mda.getElement();
+        this.constructionElement.appendChild(digestMethodElem);
+        XMLUtils.addReturnToElement(this.constructionElement);
 
-         this._constructionElement.appendChild(digestValueElement);
-         XMLUtils.addReturnToElement(this._constructionElement);
-      }
-   }
+        digestValueElement =
+            XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_DIGESTVALUE);
+
+        this.constructionElement.appendChild(digestValueElement);
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
 
-   /**
-    * Build a {@link Reference} from an {@link Element}
-    *
-    * @param element <code>Reference</code> element
-    * @param BaseURI the URI of the resource where the XML instance was stored
-    * @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs. We need this because the Manifest has the individual {@link ResourceResolver}s whcih have been set by the user
-    * @throws XMLSecurityException
-    */
-   protected Reference(Element element, String BaseURI, Manifest manifest)
-           throws XMLSecurityException {
-
-      super(element, BaseURI);
-      this._baseURI=BaseURI;
-      Element el=XMLUtils.getNextElement(element.getFirstChild());
-      if (Constants._TAG_TRANSFORMS.equals(el.getLocalName()) &&
-                  Constants.SignatureSpecNS.equals(el.getNamespaceURI())) {
-          transforms = new Transforms(el,this._baseURI);
-          el=XMLUtils.getNextElement(el.getNextSibling());
-      }
-      digestMethodElem = el;
-      digestValueElement =XMLUtils.getNextElement(digestMethodElem.getNextSibling());;
-      this._manifest = manifest;
-   }
-
-   /**
-    * Returns {@link MessageDigestAlgorithm}
-    *
-    *
-    * @return {@link MessageDigestAlgorithm}
-    *
-    * @throws XMLSignatureException
-    */
-   public MessageDigestAlgorithm getMessageDigestAlgorithm()
-           throws XMLSignatureException {
-
-      if (digestMethodElem == null) {
-         return null;
-      }
+    /**
+     * Build a {@link Reference} from an {@link Element}
+     *
+     * @param element <code>Reference</code> element
+     * @param baseURI the URI of the resource where the XML instance was stored
+     * @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs.
+     * We need this because the Manifest has the individual {@link ResourceResolver}s which have
+     * been set by the user
+     * @throws XMLSecurityException
+     */
+    protected Reference(Element element, String baseURI, Manifest manifest) throws XMLSecurityException {
+        this(element, baseURI, manifest, false);
+    }
 
-      String uri = digestMethodElem.getAttributeNS(null,
-         Constants._ATT_ALGORITHM);
-
-          if (uri == null) {
-                  return null;
-          }
-
-      return MessageDigestAlgorithm.getInstance(this._doc, uri);
-   }
-
-   /**
-    * Sets the <code>URI</code> of this <code>Reference</code> element
-    *
-    * @param URI the <code>URI</code> of this <code>Reference</code> element
-    */
-   public void setURI(String URI) {
+    /**
+     * Build a {@link Reference} from an {@link Element}
+     *
+     * @param element <code>Reference</code> element
+     * @param baseURI the URI of the resource where the XML instance was stored
+     * @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs.
+     * @param secureValidation whether secure validation is enabled or not
+     * We need this because the Manifest has the individual {@link ResourceResolver}s which have
+     * been set by the user
+     * @throws XMLSecurityException
+     */
+    protected Reference(Element element, String baseURI, Manifest manifest, boolean secureValidation)
+        throws XMLSecurityException {
+        super(element, baseURI);
+        this.secureValidation = secureValidation;
+        this.baseURI = baseURI;
+        Element el = XMLUtils.getNextElement(element.getFirstChild());
+        if (Constants._TAG_TRANSFORMS.equals(el.getLocalName())
+            && Constants.SignatureSpecNS.equals(el.getNamespaceURI())) {
+            transforms = new Transforms(el, this.baseURI);
+            transforms.setSecureValidation(secureValidation);
+            if (secureValidation && transforms.getLength() > MAXIMUM_TRANSFORM_COUNT) {
+                Object exArgs[] = { transforms.getLength(), MAXIMUM_TRANSFORM_COUNT };
 
-      if ( URI != null) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_URI,
-                                                  URI);
-      }
-   }
-
-   /**
-    * Returns the <code>URI</code> of this <code>Reference</code> element
-    *
-    * @return URI the <code>URI</code> of this <code>Reference</code> element
-    */
-   public String getURI() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_URI);
-   }
-
-   /**
-    * Sets the <code>Id</code> attribute of this <code>Reference</code> element
-    *
-    * @param Id the <code>Id</code> attribute of this <code>Reference</code> element
-    */
-   public void setId(String Id) {
+                throw new XMLSecurityException("signature.tooManyTransforms", exArgs);
+            }
+            el = XMLUtils.getNextElement(el.getNextSibling());
+        }
+        digestMethodElem = el;
+        digestValueElement = XMLUtils.getNextElement(digestMethodElem.getNextSibling());
+        this.manifest = manifest;
+    }
 
-      if ( Id != null ) {
-          setLocalIdAttribute(Constants._ATT_ID, Id);
-      }
-   }
-
-   /**
-    * Returns the <code>Id</code> attribute of this <code>Reference</code> element
-    *
-    * @return Id the <code>Id</code> attribute of this <code>Reference</code> element
-    */
-   public String getId() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
-   }
+    /**
+     * Returns {@link MessageDigestAlgorithm}
+     *
+     *
+     * @return {@link MessageDigestAlgorithm}
+     *
+     * @throws XMLSignatureException
+     */
+    public MessageDigestAlgorithm getMessageDigestAlgorithm() throws XMLSignatureException {
+        if (digestMethodElem == null) {
+            return null;
+        }
 
-   /**
-    * Sets the <code>type</code> atttibute of the Reference indicate whether an <code>ds:Object</code>, <code>ds:SignatureProperty</code>, or <code>ds:Manifest</code> element
-    *
-    * @param Type the <code>type</code> attribute of the Reference
-    */
-   public void setType(String Type) {
+        String uri = digestMethodElem.getAttributeNS(null, Constants._ATT_ALGORITHM);
+
+        if (uri == null) {
+            return null;
+        }
 
-      if (Type != null) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_TYPE,
-                                                  Type);
-      }
-   }
+        if (secureValidation && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(uri)) {
+            Object exArgs[] = { uri };
 
-   /**
-    * Return the <code>type</code> atttibute of the Reference indicate whether an <code>ds:Object</code>, <code>ds:SignatureProperty</code>, or <code>ds:Manifest</code> element
-    *
-    * @return the <code>type</code> attribute of the Reference
-    */
-   public String getType() {
-      return this._constructionElement.getAttributeNS(null,
-              Constants._ATT_TYPE);
-   }
+            throw new XMLSignatureException("signature.signatureAlgorithm", exArgs);
+        }
+
+        return MessageDigestAlgorithm.getInstance(this.doc, uri);
+    }
 
-   /**
-    * Method isReferenceToObject
-    *
-    * This returns true if the <CODE>Type</CODE> attribute of the
-    * <CODE>Refernce</CODE> element points to a <CODE>#Object</CODE> element
-    *
-    * @return true if the Reference type indicates that this Reference points to an <code>Object</code>
-    */
-   public boolean typeIsReferenceToObject() {
+    /**
+     * Sets the <code>URI</code> of this <code>Reference</code> element
+     *
+     * @param uri the <code>URI</code> of this <code>Reference</code> element
+     */
+    public void setURI(String uri) {
+        if (uri != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_URI, uri);
+        }
+    }
 
-      if (Reference.OBJECT_URI.equals(this.getType())) {
-         return true;
-      }
-
-      return false;
-   }
+    /**
+     * Returns the <code>URI</code> of this <code>Reference</code> element
+     *
+     * @return URI the <code>URI</code> of this <code>Reference</code> element
+     */
+    public String getURI() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_URI);
+    }
 
-   /**
-    * Method isReferenceToManifest
-    *
-    * This returns true if the <CODE>Type</CODE> attribute of the
-    * <CODE>Refernce</CODE> element points to a <CODE>#Manifest</CODE> element
-    *
-    * @return true if the Reference type indicates that this Reference points to a {@link Manifest}
-    */
-   public boolean typeIsReferenceToManifest() {
-
-      if (Reference.MANIFEST_URI.equals(this.getType())) {
-         return true;
-      }
+    /**
+     * Sets the <code>Id</code> attribute of this <code>Reference</code> element
+     *
+     * @param id the <code>Id</code> attribute of this <code>Reference</code> element
+     */
+    public void setId(String id) {
+        if (id != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
+            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+        }
+    }
 
-      return false;
-   }
-
-   /**
-    * Method setDigestValueElement
-    *
-    * @param digestValue
-    */
-   private void setDigestValueElement(byte[] digestValue)
-   {
-         Node n=digestValueElement.getFirstChild();
-         while (n!=null) {
-               digestValueElement.removeChild(n);
-               n = n.getNextSibling();
-         }
+    /**
+     * Returns the <code>Id</code> attribute of this <code>Reference</code> element
+     *
+     * @return Id the <code>Id</code> attribute of this <code>Reference</code> element
+     */
+    public String getId() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+    }
 
-         String base64codedValue = Base64.encode(digestValue);
-         Text t = this._doc.createTextNode(base64codedValue);
-
-         digestValueElement.appendChild(t);
-   }
+    /**
+     * Sets the <code>type</code> atttibute of the Reference indicate whether an
+     * <code>ds:Object</code>, <code>ds:SignatureProperty</code>, or <code>ds:Manifest</code>
+     * element.
+     *
+     * @param type the <code>type</code> attribute of the Reference
+     */
+    public void setType(String type) {
+        if (type != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_TYPE, type);
+        }
+    }
 
-   /**
-    * Method generateDigestValue
-    *
-    * @throws ReferenceNotInitializedException
-    * @throws XMLSignatureException
-    */
-   public void generateDigestValue()
-           throws XMLSignatureException, ReferenceNotInitializedException {
-      this.setDigestValueElement(this.calculateDigest(false));
-   }
-
-   /**
-    * Returns the XMLSignatureInput which is created by de-referencing the URI attribute.
-    * @return the XMLSignatureInput of the source of this reference
-    * @throws ReferenceNotInitializedException If the resolver found any
-    *  problem resolving the reference
-    */
-   public XMLSignatureInput getContentsBeforeTransformation()
-           throws ReferenceNotInitializedException {
+    /**
+     * Return the <code>type</code> atttibute of the Reference indicate whether an
+     * <code>ds:Object</code>, <code>ds:SignatureProperty</code>, or <code>ds:Manifest</code>
+     * element
+     *
+     * @return the <code>type</code> attribute of the Reference
+     */
+    public String getType() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_TYPE);
+    }
 
-      try {
-         Attr URIAttr = this._constructionElement.getAttributeNodeNS(null,
-            Constants._ATT_URI);
-         String URI;
+    /**
+     * Method isReferenceToObject
+     *
+     * This returns true if the <CODE>Type</CODE> attribute of the
+     * <CODE>Reference</CODE> element points to a <CODE>#Object</CODE> element
+     *
+     * @return true if the Reference type indicates that this Reference points to an
+     * <code>Object</code>
+     */
+    public boolean typeIsReferenceToObject() {
+        if (Reference.OBJECT_URI.equals(this.getType())) {
+            return true;
+        }
 
-         if (URIAttr == null) {
-            URI = null;
-         } else {
-            URI = URIAttr.getNodeValue();
-         }
-
-         ResourceResolver resolver = ResourceResolver.getInstance(URIAttr,
-            this._baseURI, this._manifest._perManifestResolvers);
-
-         if (resolver == null) {
-            Object exArgs[] = { URI };
+        return false;
+    }
 
-            throw new ReferenceNotInitializedException(
-               "signature.Verification.Reference.NoInput", exArgs);
-         }
-
-         resolver.addProperties(this._manifest._resolverProperties);
-
-         XMLSignatureInput input = resolver.resolve(URIAttr, this._baseURI);
+    /**
+     * Method isReferenceToManifest
+     *
+     * This returns true if the <CODE>Type</CODE> attribute of the
+     * <CODE>Reference</CODE> element points to a <CODE>#Manifest</CODE> element
+     *
+     * @return true if the Reference type indicates that this Reference points to a
+     * {@link Manifest}
+     */
+    public boolean typeIsReferenceToManifest() {
+        if (Reference.MANIFEST_URI.equals(this.getType())) {
+            return true;
+        }
 
-
-         return input;
-      }  catch (ResourceResolverException ex) {
-         throw new ReferenceNotInitializedException("empty", ex);
-      } catch (XMLSecurityException ex) {
-         throw new ReferenceNotInitializedException("empty", ex);
-      }
-   }
+        return false;
+    }
 
-   /**
-    * Returns the data which is referenced by the URI attribute. This method
-    * only works works after a call to verify.
-    * @return a XMLSignature with a byte array.
-    * @throws ReferenceNotInitializedException
-    *
-    * @deprecated use getContentsBeforeTransformation
-    */
-   @Deprecated
-   public XMLSignatureInput getTransformsInput() throws ReferenceNotInitializedException
-        {
-                XMLSignatureInput input=getContentsBeforeTransformation();
-                XMLSignatureInput result;
-                try {
-                        result = new XMLSignatureInput(input.getBytes());
-                } catch (CanonicalizationException ex) {
-                         throw new ReferenceNotInitializedException("empty", ex);
-                } catch (IOException ex) {
-                         throw new ReferenceNotInitializedException("empty", ex);
-                }
-                result.setSourceURI(input.getSourceURI());
-                return result;
+    /**
+     * Method setDigestValueElement
+     *
+     * @param digestValue
+     */
+    private void setDigestValueElement(byte[] digestValue) {
+        Node n = digestValueElement.getFirstChild();
+        while (n != null) {
+            digestValueElement.removeChild(n);
+            n = n.getNextSibling();
+        }
 
-   }
+        String base64codedValue = Base64.encode(digestValue);
+        Text t = this.doc.createTextNode(base64codedValue);
 
-   private XMLSignatureInput getContentsAfterTransformation(XMLSignatureInput input, OutputStream os)
-           throws XMLSignatureException {
-
-      try {
-         Transforms transforms = this.getTransforms();
-         XMLSignatureInput output = null;
+        digestValueElement.appendChild(t);
+    }
 
-         if (transforms != null) {
-            output = transforms.performTransforms(input,os);
-            this._transformsOutput = output;//new XMLSignatureInput(output.getBytes());
-
-            //this._transformsOutput.setSourceURI(output.getSourceURI());
-         } else {
-            output = input;
-         }
+    /**
+     * Method generateDigestValue
+     *
+     * @throws ReferenceNotInitializedException
+     * @throws XMLSignatureException
+     */
+    public void generateDigestValue()
+        throws XMLSignatureException, ReferenceNotInitializedException {
+        this.setDigestValueElement(this.calculateDigest(false));
+    }
 
-         return output;
-      } catch (ResourceResolverException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (CanonicalizationException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (InvalidCanonicalizerException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (TransformationException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (XMLSecurityException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /**
+     * Returns the XMLSignatureInput which is created by de-referencing the URI attribute.
+     * @return the XMLSignatureInput of the source of this reference
+     * @throws ReferenceNotInitializedException If the resolver found any
+     * problem resolving the reference
+     */
+    public XMLSignatureInput getContentsBeforeTransformation()
+        throws ReferenceNotInitializedException {
+        try {
+            Attr uriAttr =
+                this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI);
 
-   /**
-    * Returns the XMLSignatureInput which is the result of the Transforms.
-    * @return a XMLSignatureInput with all transformations applied.
-    * @throws XMLSignatureException
-    */
-   public XMLSignatureInput getContentsAfterTransformation()
-           throws XMLSignatureException {
-
-      XMLSignatureInput input = this.getContentsBeforeTransformation();
-
-      return this.getContentsAfterTransformation(input, null);
-   }
+            ResourceResolver resolver =
+                ResourceResolver.getInstance(
+                    uriAttr, this.baseURI, this.manifest.getPerManifestResolvers(), secureValidation
+                );
+            resolver.addProperties(this.manifest.getResolverProperties());
 
-   /**
-    * This method returns the XMLSignatureInput which represents the node set before
-    * some kind of canonicalization is applied for the first time.
-    * @return Gets a the node doing everything till the first c14n is needed
-    *
-    * @throws XMLSignatureException
-    */
-   public XMLSignatureInput getNodesetBeforeFirstCanonicalization()
-           throws XMLSignatureException {
-
-      try {
-         XMLSignatureInput input = this.getContentsBeforeTransformation();
-         XMLSignatureInput output = input;
-         Transforms transforms = this.getTransforms();
+            return resolver.resolve(uriAttr, this.baseURI, secureValidation);
+        }  catch (ResourceResolverException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        }
+    }
 
-         if (transforms != null) {
-            doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
-               Transform t = transforms.item(i);
-               String URI = t.getURI();
+    private XMLSignatureInput getContentsAfterTransformation(
+        XMLSignatureInput input, OutputStream os
+    ) throws XMLSignatureException {
+        try {
+            Transforms transforms = this.getTransforms();
+            XMLSignatureInput output = null;
 
-               if (URI.equals(Transforms
-                       .TRANSFORM_C14N_EXCL_OMIT_COMMENTS) || URI
-                          .equals(Transforms
-                             .TRANSFORM_C14N_EXCL_WITH_COMMENTS) || URI
-                                .equals(Transforms
-                                   .TRANSFORM_C14N_OMIT_COMMENTS) || URI
-                                      .equals(Transforms
-                                         .TRANSFORM_C14N_WITH_COMMENTS)) {
+            if (transforms != null) {
+                output = transforms.performTransforms(input, os);
+                this.transformsOutput = output;//new XMLSignatureInput(output.getBytes());
 
-                  break doTransforms;
-               }
-
-               output = t.performTransform(output, null);
+                //this.transformsOutput.setSourceURI(output.getSourceURI());
+            } else {
+                output = input;
             }
 
+            return output;
+        } catch (ResourceResolverException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (CanonicalizationException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (InvalidCanonicalizerException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (TransformationException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (XMLSecurityException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
+
+    /**
+     * Returns the XMLSignatureInput which is the result of the Transforms.
+     * @return a XMLSignatureInput with all transformations applied.
+     * @throws XMLSignatureException
+     */
+    public XMLSignatureInput getContentsAfterTransformation()
+        throws XMLSignatureException {
+        XMLSignatureInput input = this.getContentsBeforeTransformation();
+        cacheDereferencedElement(input);
+
+        return this.getContentsAfterTransformation(input, null);
+    }
+
+    /**
+     * This method returns the XMLSignatureInput which represents the node set before
+     * some kind of canonicalization is applied for the first time.
+     * @return Gets a the node doing everything till the first c14n is needed
+     *
+     * @throws XMLSignatureException
+     */
+    public XMLSignatureInput getNodesetBeforeFirstCanonicalization()
+        throws XMLSignatureException {
+        try {
+            XMLSignatureInput input = this.getContentsBeforeTransformation();
+            cacheDereferencedElement(input);
+            XMLSignatureInput output = input;
+            Transforms transforms = this.getTransforms();
+
+            if (transforms != null) {
+                doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
+                    Transform t = transforms.item(i);
+                    String uri = t.getURI();
+
+                    if (uri.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)
+                        || uri.equals(Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS)
+                        || uri.equals(Transforms.TRANSFORM_C14N_OMIT_COMMENTS)
+                        || uri.equals(Transforms.TRANSFORM_C14N_WITH_COMMENTS)) {
+                        break doTransforms;
+                    }
+
+                    output = t.performTransform(output, null);
+                }
+
             output.setSourceURI(input.getSourceURI());
-         }
-         return output;
-      } catch (IOException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (ResourceResolverException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (CanonicalizationException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (InvalidCanonicalizerException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (TransformationException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (XMLSecurityException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+            }
+            return output;
+        } catch (IOException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (ResourceResolverException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (CanonicalizationException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (InvalidCanonicalizerException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (TransformationException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (XMLSecurityException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /**
-    * Method getHTMLRepresentation
-    * @return The HTML of the transformation
-    * @throws XMLSignatureException
-    */
-   public String getHTMLRepresentation() throws XMLSignatureException {
+    /**
+     * Method getHTMLRepresentation
+     * @return The HTML of the transformation
+     * @throws XMLSignatureException
+     */
+    public String getHTMLRepresentation() throws XMLSignatureException {
+        try {
+            XMLSignatureInput nodes = this.getNodesetBeforeFirstCanonicalization();
 
-      try {
-         XMLSignatureInput nodes = this.getNodesetBeforeFirstCanonicalization();
-         Set<String> inclusiveNamespaces = new HashSet<String>();
-
-         {
             Transforms transforms = this.getTransforms();
             Transform c14nTransform = null;
 
             if (transforms != null) {
-               doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
-                  Transform t = transforms.item(i);
-                  String URI = t.getURI();
+                doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
+                    Transform t = transforms.item(i);
+                    String uri = t.getURI();
+
+                    if (uri.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)
+                        || uri.equals(Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS)) {
+                        c14nTransform = t;
+                        break doTransforms;
+                    }
+                }
+            }
 
-                  if (URI.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)
-                          || URI.equals(
-                             Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS)) {
-                     c14nTransform = t;
+            Set<String> inclusiveNamespaces = new HashSet<String>();
+            if (c14nTransform != null
+                && (c14nTransform.length(
+                    InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
+                    InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1)) {
 
-                     break doTransforms;
-                  }
-               }
+                // there is one InclusiveNamespaces element
+                InclusiveNamespaces in =
+                    new InclusiveNamespaces(
+                        XMLUtils.selectNode(
+                            c14nTransform.getElement().getFirstChild(),
+                            InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
+                            InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,
+                            0
+                        ), this.getBaseURI());
+
+                inclusiveNamespaces =
+                    InclusiveNamespaces.prefixStr2Set(in.getInclusiveNamespaces());
             }
 
-            if (c14nTransform != null) {
-
-               if (c14nTransform
-                       .length(InclusiveNamespaces
-                          .ExclusiveCanonicalizationNamespace, InclusiveNamespaces
-                          ._TAG_EC_INCLUSIVENAMESPACES) == 1) {
+            return nodes.getHTMLRepresentation(inclusiveNamespaces);
+        } catch (TransformationException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (InvalidTransformException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (XMLSecurityException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-                  // there is one InclusiveNamespaces element
-                  InclusiveNamespaces in = new InclusiveNamespaces(
-                        XMLUtils.selectNode(
-                        c14nTransform.getElement().getFirstChild(),
-                                                InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
-                        InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0), this.getBaseURI());
+    /**
+     * This method only works works after a call to verify.
+     * @return the transformed output(i.e. what is going to be digested).
+     */
+    public XMLSignatureInput getTransformsOutput() {
+        return this.transformsOutput;
+    }
 
-                  inclusiveNamespaces = InclusiveNamespaces.prefixStr2Set(
-                     in.getInclusiveNamespaces());
-               }
-            }
-         }
+    /**
+     * Get the ReferenceData that corresponds to the cached representation of the dereferenced
+     * object before transformation.
+     */
+    public ReferenceData getReferenceData() {
+        return referenceData;
+    }
 
-         return nodes.getHTMLRepresentation(inclusiveNamespaces);
-      } catch (TransformationException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (InvalidTransformException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (XMLSecurityException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /**
+     * This method returns the {@link XMLSignatureInput} which is referenced by the
+     * <CODE>URI</CODE> Attribute.
+     * @param os where to write the transformation can be null.
+     * @return the element to digest
+     *
+     * @throws XMLSignatureException
+     * @see Manifest#verifyReferences()
+     */
+    protected XMLSignatureInput dereferenceURIandPerformTransforms(OutputStream os)
+        throws XMLSignatureException {
+        try {
+            XMLSignatureInput input = this.getContentsBeforeTransformation();
+            cacheDereferencedElement(input);
 
-   /**
-    * This method only works works after a call to verify.
-    * @return the transformed output(i.e. what is going to be digested).
-    */
-   public XMLSignatureInput getTransformsOutput() {
-      return this._transformsOutput;
-   }
+            XMLSignatureInput output = this.getContentsAfterTransformation(input, os);
+            this.transformsOutput = output;
+            return output;
+        } catch (XMLSecurityException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        }
+    }
 
-   /**
-    * This method returns the {@link XMLSignatureInput} which is referenced by the
-    * <CODE>URI</CODE> Attribute.
-    * @param os where to write the transformation can be null.
-    * @return the element to digest
-    *
-    * @throws XMLSignatureException
-    * @see Manifest#verifyReferences()
-    */
-   protected XMLSignatureInput dereferenceURIandPerformTransforms(OutputStream os)
-           throws XMLSignatureException {
+    /**
+     * Store the dereferenced Element(s) so that it/they can be retrieved later.
+     */
+    private void cacheDereferencedElement(XMLSignatureInput input) {
+        if (input.isNodeSet()) {
+            try {
+                final Set<Node> s = input.getNodeSet();
+                referenceData = new ReferenceNodeSetData() {
+                    public Iterator<Node> iterator() {
+                        return new Iterator<Node>() {
 
-      try {
-         XMLSignatureInput input = this.getContentsBeforeTransformation();
-         XMLSignatureInput output = this.getContentsAfterTransformation(input, os);
+                            Iterator<Node> sIterator = s.iterator();
 
-         /* at this stage, this._transformsInput and this._transformsOutput
-          * contain a huge amount of nodes. When we do not cache these nodes
-          * but only preserve the octets, the memory footprint is dramatically
-          * reduced.
-          */
-         if (!Reference.CacheSignedNodes) {
+                            public boolean hasNext() {
+                                return sIterator.hasNext();
+                            }
+
+                            public Node next() {
+                                return sIterator.next();
+                            }
 
-            this._transformsOutput = output;//new XMLSignatureInput(output.getBytes());
-
-            //this._transformsOutput.setSourceURI(output.getSourceURI());
-         }
-         return output;
-      } catch (XMLSecurityException ex) {
-         throw new ReferenceNotInitializedException("empty", ex);
-      }
-   }
+                            public void remove() {
+                                throw new UnsupportedOperationException();
+                            }
+                        };
+                    }
+                };
+            } catch (Exception e) {
+                // log a warning
+                log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + e);
+            }
+        } else if (input.isElement()) {
+            referenceData = new ReferenceSubTreeData
+                (input.getSubNode(), input.isExcludeComments());
+        } else if (input.isOctetStream() || input.isByteArray()) {
+            try {
+                referenceData = new ReferenceOctetStreamData
+                    (input.getOctetStream(), input.getSourceURI(),
+                        input.getMIMEType());
+            } catch (IOException ioe) {
+                // log a warning
+                log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + ioe);
+            }
+        }
+    }
 
-   /**
-    * Method getTransforms
-    *
-    * @return The transforms that applied this reference.
-    * @throws InvalidTransformException
-    * @throws TransformationException
-    * @throws XMLSecurityException
-    * @throws XMLSignatureException
-    */
-   public Transforms getTransforms()
-           throws XMLSignatureException, InvalidTransformException,
-                  TransformationException, XMLSecurityException {
-
-      return transforms;
-   }
+    /**
+     * Method getTransforms
+     *
+     * @return The transforms that applied this reference.
+     * @throws InvalidTransformException
+     * @throws TransformationException
+     * @throws XMLSecurityException
+     * @throws XMLSignatureException
+     */
+    public Transforms getTransforms()
+        throws XMLSignatureException, InvalidTransformException,
+        TransformationException, XMLSecurityException {
+        return transforms;
+    }
 
-   /**
-    * Method getReferencedBytes
-    *
-    * @return the bytes that will be used to generated digest.
-    * @throws ReferenceNotInitializedException
-    * @throws XMLSignatureException
-    */
-   public byte[] getReferencedBytes()
-           throws ReferenceNotInitializedException, XMLSignatureException {
-    try {
-        XMLSignatureInput output=this.dereferenceURIandPerformTransforms(null);
-
-        byte[] signedBytes = output.getBytes();
-
-        return signedBytes;
-     } catch (IOException ex) {
-        throw new ReferenceNotInitializedException("empty", ex);
-     } catch (CanonicalizationException ex) {
-        throw new ReferenceNotInitializedException("empty", ex);
-     }
-
-   }
+    /**
+     * Method getReferencedBytes
+     *
+     * @return the bytes that will be used to generated digest.
+     * @throws ReferenceNotInitializedException
+     * @throws XMLSignatureException
+     */
+    public byte[] getReferencedBytes()
+        throws ReferenceNotInitializedException, XMLSignatureException {
+        try {
+            XMLSignatureInput output = this.dereferenceURIandPerformTransforms(null);
+            return output.getBytes();
+        } catch (IOException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        } catch (CanonicalizationException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        }
+    }
 
 
-   /**
-    * Method calculateDigest
-    *
-    * @param validating true if validating the reference
-    * @return reference Calculate the digest of this reference.
-    * @throws ReferenceNotInitializedException
-    * @throws XMLSignatureException
-    */
-   private byte[] calculateDigest(boolean validating)
-           throws ReferenceNotInitializedException, XMLSignatureException {
+    /**
+     * Method calculateDigest
+     *
+     * @param validating true if validating the reference
+     * @return reference Calculate the digest of this reference.
+     * @throws ReferenceNotInitializedException
+     * @throws XMLSignatureException
+     */
+    private byte[] calculateDigest(boolean validating)
+        throws ReferenceNotInitializedException, XMLSignatureException {
+        OutputStream os = null;
+        try {
+            MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
 
-      try {
-
-         MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
+            mda.reset();
+            DigesterOutputStream diOs = new DigesterOutputStream(mda);
+            os = new UnsyncBufferedOutputStream(diOs);
+            XMLSignatureInput output = this.dereferenceURIandPerformTransforms(os);
+            // if signing and c14n11 property == true explicitly add
+            // C14N11 transform if needed
+            if (Reference.useC14N11 && !validating && !output.isOutputStreamSet()
+                && !output.isOctetStream()) {
+                if (transforms == null) {
+                    transforms = new Transforms(this.doc);
+                    transforms.setSecureValidation(secureValidation);
+                    this.constructionElement.insertBefore(transforms.getElement(), digestMethodElem);
+                }
+                transforms.addTransform(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS);
+                output.updateOutputStream(os, true);
+            } else {
+                output.updateOutputStream(os);
+            }
+            os.flush();
 
-         mda.reset();
-         DigesterOutputStream diOs=new DigesterOutputStream(mda);
-         OutputStream os=new UnsyncBufferedOutputStream(diOs);
-         XMLSignatureInput output=this.dereferenceURIandPerformTransforms(os);
-         // if signing and c14n11 property == true explicitly add
-         // C14N11 transform if needed
-         if (Reference.useC14N11 && !validating &&
-             !output.isOutputStreamSet() && !output.isOctetStream()) {
-             if (transforms == null) {
-                 transforms = new Transforms(this._doc);
-                 this._constructionElement.insertBefore
-                     (transforms.getElement(), digestMethodElem);
-             }
-             transforms.addTransform(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS);
-             output.updateOutputStream(os, true);
-         } else {
-             output.updateOutputStream(os);
-         }
-         os.flush();
-         //this.getReferencedBytes(diOs);
-         //mda.update(data);
+            if (output.getOctetStreamReal() != null) {
+                output.getOctetStreamReal().close();
+            }
+
+            //this.getReferencedBytes(diOs);
+            //mda.update(data);
 
-         return diOs.getDigestValue();
-      } catch (XMLSecurityException ex) {
-         throw new ReferenceNotInitializedException("empty", ex);
-      } catch (IOException ex) {
-         throw new ReferenceNotInitializedException("empty", ex);
-      }
-   }
+            return diOs.getDigestValue();
+        } catch (XMLSecurityException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        } catch (IOException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        } finally {
+            if (os != null) {
+                try {
+                    os.close();
+                } catch (IOException ex) {
+                    throw new ReferenceNotInitializedException("empty", ex);
+                }
+            }
+        }
+    }
 
-   /**
-    * Returns the digest value.
-    *
-    * @return the digest value.
-    * @throws Base64DecodingException if Reference contains no proper base64 encoded data.
-    * @throws XMLSecurityException if the Reference does not contain a DigestValue element
-    */
-   public byte[] getDigestValue() throws Base64DecodingException, XMLSecurityException {
-      if (digestValueElement == null) {
-                  // The required element is not in the XML!
-                  Object[] exArgs ={ Constants._TAG_DIGESTVALUE,
-                                                         Constants.SignatureSpecNS };
-                  throw new XMLSecurityException(
-                                        "signature.Verification.NoSignatureElement",
-                                        exArgs);
-          }
-      byte[] elemDig = Base64.decode(digestValueElement);
-      return elemDig;
-   }
+    /**
+     * Returns the digest value.
+     *
+     * @return the digest value.
+     * @throws Base64DecodingException if Reference contains no proper base64 encoded data.
+     * @throws XMLSecurityException if the Reference does not contain a DigestValue element
+     */
+    public byte[] getDigestValue() throws Base64DecodingException, XMLSecurityException {
+        if (digestValueElement == null) {
+            // The required element is not in the XML!
+            Object[] exArgs ={ Constants._TAG_DIGESTVALUE, Constants.SignatureSpecNS };
+            throw new XMLSecurityException(
+                "signature.Verification.NoSignatureElement", exArgs
+            );
+        }
+        return Base64.decode(digestValueElement);
+    }
 
 
-   /**
-    * Tests reference valdiation is success or false
-    *
-    * @return true if reference valdiation is success, otherwise false
-    * @throws ReferenceNotInitializedException
-    * @throws XMLSecurityException
-    */
-   public boolean verify()
-           throws ReferenceNotInitializedException, XMLSecurityException {
-
-      byte[] elemDig = this.getDigestValue();
-      byte[] calcDig = this.calculateDigest(true);
-      boolean equal = MessageDigestAlgorithm.isEqual(elemDig, calcDig);
+    /**
+     * Tests reference validation is success or false
+     *
+     * @return true if reference validation is success, otherwise false
+     * @throws ReferenceNotInitializedException
+     * @throws XMLSecurityException
+     */
+    public boolean verify()
+        throws ReferenceNotInitializedException, XMLSecurityException {
+        byte[] elemDig = this.getDigestValue();
+        byte[] calcDig = this.calculateDigest(true);
+        boolean equal = MessageDigestAlgorithm.isEqual(elemDig, calcDig);
 
-      if (!equal) {
-         log.log(java.util.logging.Level.WARNING, "Verification failed for URI \"" + this.getURI() + "\"");
-         log.log(java.util.logging.Level.WARNING, "Expected Digest: " + Base64.encode(elemDig));
-         log.log(java.util.logging.Level.WARNING, "Actual Digest: " + Base64.encode(calcDig));
-      } else {
-         log.log(java.util.logging.Level.INFO, "Verification successful for URI \"" + this.getURI() + "\"");
-      }
+        if (!equal) {
+            log.log(java.util.logging.Level.WARNING, "Verification failed for URI \"" + this.getURI() + "\"");
+            log.log(java.util.logging.Level.WARNING, "Expected Digest: " + Base64.encode(elemDig));
+            log.log(java.util.logging.Level.WARNING, "Actual Digest: " + Base64.encode(calcDig));
+        } else {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "Verification successful for URI \"" + this.getURI() + "\"");
+            }
+        }
 
-      return equal;
-   }
+        return equal;
+    }
 
-   /**
-    * Method getBaseLocalName
-    * @inheritDoc
-    *
-    */
-   public String getBaseLocalName() {
-      return Constants._TAG_REFERENCE;
-   }
+    /**
+     * Method getBaseLocalName
+     * @inheritDoc
+     */
+    public String getBaseLocalName() {
+        return Constants._TAG_REFERENCE;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,28 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
-
-
-
-
 /**
  * Raised if verifying a {@link com.sun.org.apache.xml.internal.security.signature.Reference} fails
  * because of an uninitialized {@link com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput}
@@ -32,58 +30,56 @@
  */
 public class ReferenceNotInitializedException extends XMLSignatureException {
 
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
 
-   /**
-    * Constructor ReferenceNotInitializedException
-    *
-    */
-   public ReferenceNotInitializedException() {
-      super();
-   }
+    /**
+     * Constructor ReferenceNotInitializedException
+     *
+     */
+    public ReferenceNotInitializedException() {
+        super();
+    }
 
-   /**
-    * Constructor ReferenceNotInitializedException
-    *
-    * @param _msgID
-    */
-   public ReferenceNotInitializedException(String _msgID) {
-      super(_msgID);
-   }
+    /**
+     * Constructor ReferenceNotInitializedException
+     *
+     * @param msgID
+     */
+    public ReferenceNotInitializedException(String msgID) {
+        super(msgID);
+    }
 
-   /**
-    * Constructor ReferenceNotInitializedException
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public ReferenceNotInitializedException(String _msgID, Object exArgs[]) {
-      super(_msgID, exArgs);
-   }
+    /**
+     * Constructor ReferenceNotInitializedException
+     *
+     * @param msgID
+     * @param exArgs
+     */
+    public ReferenceNotInitializedException(String msgID, Object exArgs[]) {
+        super(msgID, exArgs);
+    }
 
-   /**
-    * Constructor ReferenceNotInitializedException
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public ReferenceNotInitializedException(String _msgID,
-                                           Exception _originalException) {
-      super(_msgID, _originalException);
-   }
+    /**
+     * Constructor ReferenceNotInitializedException
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public ReferenceNotInitializedException(String msgID, Exception originalException) {
+        super(msgID, originalException);
+    }
 
-   /**
-    * Constructor ReferenceNotInitializedException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public ReferenceNotInitializedException(String _msgID, Object exArgs[],
-                                           Exception _originalException) {
-      super(_msgID, exArgs, _originalException);
-   }
+    /**
+     * Constructor ReferenceNotInitializedException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public ReferenceNotInitializedException(String msgID, Object exArgs[], Exception originalException) {
+        super(msgID, exArgs, originalException);
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,34 +2,34 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-
 /**
  * Handles <code>&lt;ds:SignatureProperties&gt;</code> elements
  * This Element holds {@link SignatureProperty} that contian additional information items
@@ -37,120 +37,112 @@
  * for example, data-time stamp, serial number of cryptographic hardware.
  *
  * @author Christian Geuer-Pollmann
- *
  */
 public class SignatureProperties extends SignatureElementProxy {
 
-   /**
-    * Constructor SignatureProperties
-    *
-    * @param doc
-    */
-   public SignatureProperties(Document doc) {
-
-      super(doc);
+    /**
+     * Constructor SignatureProperties
+     *
+     * @param doc
+     */
+    public SignatureProperties(Document doc) {
+        super(doc);
 
-      XMLUtils.addReturnToElement(this._constructionElement);
-   }
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-   /**
-    * Constructs {@link SignatureProperties} from {@link Element}
-    * @param element <code>SignatureProperties</code> elementt
-    * @param BaseURI the URI of the resource where the XML instance was stored
-    * @throws XMLSecurityException
-    */
-   public SignatureProperties(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
+    /**
+     * Constructs {@link SignatureProperties} from {@link Element}
+     * @param element <code>SignatureProperties</code> element
+     * @param BaseURI the URI of the resource where the XML instance was stored
+     * @throws XMLSecurityException
+     */
+    public SignatureProperties(Element element, String BaseURI) throws XMLSecurityException {
+        super(element, BaseURI);
 
-      Attr attr = element.getAttributeNodeNS(null, "Id");
-      if (attr != null) {
-          element.setIdAttributeNode(attr, true);
-      }
+        Attr attr = element.getAttributeNodeNS(null, "Id");
+        if (attr != null) {
+            element.setIdAttributeNode(attr, true);
+        }
 
-      int length = getLength();
-      for (int i = 0; i < length; i++) {
-          Element propertyElem =
-              XMLUtils.selectDsNode(getElement(), Constants._TAG_SIGNATUREPROPERTY, i);
-          Attr propertyAttr = propertyElem.getAttributeNodeNS(null, "Id");
-          if (propertyAttr != null) {
-              propertyElem.setIdAttributeNode(propertyAttr, true);
-          }
-      }
-   }
+        int length = getLength();
+        for (int i = 0; i < length; i++) {
+            Element propertyElem =
+                XMLUtils.selectDsNode(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY, i);
+            Attr propertyAttr = propertyElem.getAttributeNodeNS(null, "Id");
+            if (propertyAttr != null) {
+                propertyElem.setIdAttributeNode(propertyAttr, true);
+            }
+        }
+    }
 
-   /**
-    * Return the nonnegative number of added SignatureProperty elements.
-    *
-    * @return the number of SignatureProperty elements
-    */
-   public int getLength() {
+    /**
+     * Return the nonnegative number of added SignatureProperty elements.
+     *
+     * @return the number of SignatureProperty elements
+     */
+    public int getLength() {
+        Element[] propertyElems =
+            XMLUtils.selectDsNodes(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY);
 
-         Element[] propertyElems =
-            XMLUtils.selectDsNodes(this._constructionElement,
-                                     Constants._TAG_SIGNATUREPROPERTY
-                                    );
-
-         return propertyElems.length;
-   }
+        return propertyElems.length;
+    }
 
-   /**
-    * Return the <it>i</it><sup>th</sup> SignatureProperty.  Valid <code>i</code>
-    * values are 0 to <code>{link@ getSize}-1</code>.
-    *
-    * @param i Index of the requested {@link SignatureProperty}
-    * @return the <it>i</it><sup>th</sup> SignatureProperty
-    * @throws XMLSignatureException
-    */
-   public SignatureProperty item(int i) throws XMLSignatureException {
-          try {
-         Element propertyElem =
-            XMLUtils.selectDsNode(this._constructionElement,
-                                 Constants._TAG_SIGNATUREPROPERTY,
-                                 i );
+    /**
+     * Return the <it>i</it><sup>th</sup> SignatureProperty. Valid <code>i</code>
+     * values are 0 to <code>{link@ getSize}-1</code>.
+     *
+     * @param i Index of the requested {@link SignatureProperty}
+     * @return the <it>i</it><sup>th</sup> SignatureProperty
+     * @throws XMLSignatureException
+     */
+    public SignatureProperty item(int i) throws XMLSignatureException {
+        try {
+            Element propertyElem =
+                XMLUtils.selectDsNode(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY, i);
 
-         if (propertyElem == null) {
-            return null;
-         }
-         return new SignatureProperty(propertyElem, this._baseURI);
-      } catch (XMLSecurityException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+            if (propertyElem == null) {
+                return null;
+            }
+            return new SignatureProperty(propertyElem, this.baseURI);
+        } catch (XMLSecurityException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /**
-    * Sets the <code>Id</code> attribute
-    *
-    * @param Id the <code>Id</code> attribute
-    */
-   public void setId(String Id) {
-
-      if (Id != null) {
-          setLocalIdAttribute(Constants._ATT_ID, Id);
-      }
-   }
+    /**
+     * Sets the <code>Id</code> attribute
+     *
+     * @param Id the <code>Id</code> attribute
+     */
+    public void setId(String Id) {
+        if (Id != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
+            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+        }
+    }
 
-   /**
-    * Returns the <code>Id</code> attribute
-    *
-    * @return the <code>Id</code> attribute
-    */
-   public String getId() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
-   }
+    /**
+     * Returns the <code>Id</code> attribute
+     *
+     * @return the <code>Id</code> attribute
+     */
+    public String getId() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+    }
 
-   /**
-    * Method addSignatureProperty
-    *
-    * @param sp
-    */
-   public void addSignatureProperty(SignatureProperty sp) {
-      this._constructionElement.appendChild(sp.getElement());
-      XMLUtils.addReturnToElement(this._constructionElement);
-   }
+    /**
+     * Method addSignatureProperty
+     *
+     * @param sp
+     */
+    public void addSignatureProperty(SignatureProperty sp) {
+        this.constructionElement.appendChild(sp.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_SIGNATUREPROPERTIES;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_SIGNATUREPROPERTIES;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,28 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -37,96 +38,96 @@
  */
 public class SignatureProperty extends SignatureElementProxy {
 
-   /**
-    * Constructs{@link SignatureProperty} using specified <code>Target</code> attribute
-    *
-    * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
-    * @param Target the <code>Target</code> attribute references the <code>Signature</code> element to which the property applies SignatureProperty
-    */
-   public SignatureProperty(Document doc, String Target) {
-      this(doc, Target, null);
-   }
-
-   /**
-    * Constructs {@link SignatureProperty} using sepcified <code>Target</code> attribute and <code>Id</code> attribute
-    *
-    * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
-    * @param Target the <code>Target</code> attribute references the <code>Signature</code> element to which the property applies
-    * @param Id the <code>Id</code> will be specified by {@link Reference#getURI} in validation
-    */
-   public SignatureProperty(Document doc, String Target, String Id) {
-
-      super(doc);
+    /**
+     * Constructs{@link SignatureProperty} using specified <code>target</code> attribute
+     *
+     * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
+     * @param target the <code>target</code> attribute references the <code>Signature</code>
+     * element to which the property applies SignatureProperty
+     */
+    public SignatureProperty(Document doc, String target) {
+        this(doc, target, null);
+    }
 
-      this.setTarget(Target);
-      this.setId(Id);
-   }
+    /**
+     * Constructs {@link SignatureProperty} using sepcified <code>target</code> attribute and
+     * <code>id</code> attribute
+     *
+     * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
+     * @param target the <code>target</code> attribute references the <code>Signature</code>
+     *  element to which the property applies
+     * @param id the <code>id</code> will be specified by {@link Reference#getURI} in validation
+     */
+    public SignatureProperty(Document doc, String target, String id) {
+        super(doc);
 
-   /**
-    * Constructs a {@link SignatureProperty} from an {@link Element}
-    * @param element <code>SignatureProperty</code> element
-    * @param BaseURI the URI of the resource where the XML instance was stored
-    * @throws XMLSecurityException
-    */
-   public SignatureProperty(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
-   }
+        this.setTarget(target);
+        this.setId(id);
+    }
 
-   /**
-    *   Sets the <code>Id</code> attribute
-    *
-    *   @param Id the <code>Id</code> attribute
-    */
-   public void setId(String Id) {
+    /**
+     * Constructs a {@link SignatureProperty} from an {@link Element}
+     * @param element <code>SignatureProperty</code> element
+     * @param BaseURI the URI of the resource where the XML instance was stored
+     * @throws XMLSecurityException
+     */
+    public SignatureProperty(Element element, String BaseURI) throws XMLSecurityException {
+        super(element, BaseURI);
+    }
 
-      if (Id != null) {
-          setLocalIdAttribute(Constants._ATT_ID, Id);
-      }
-   }
+    /**
+     *   Sets the <code>id</code> attribute
+     *
+     *   @param id the <code>id</code> attribute
+     */
+    public void setId(String id) {
+        if (id != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
+            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+        }
+    }
 
-   /**
-    * Returns the <code>Id</code> attribute
-    *
-    * @return the <code>Id</code> attribute
-    */
-   public String getId() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
-   }
-
-   /**
-    * Sets the <code>Target</code> attribute
-    *
-    * @param Target the <code>Target</code> attribute
-    */
-   public void setTarget(String Target) {
+    /**
+     * Returns the <code>id</code> attribute
+     *
+     * @return the <code>id</code> attribute
+     */
+    public String getId() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+    }
 
-      if ((Target != null)) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_TARGET, Target);
-      }
-   }
-
-   /**
-    * Returns the <code>Target</code> attribute
-    *
-    * @return the <code>Target</code> attribute
-    */
-   public String getTarget() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_TARGET);
-   }
+    /**
+     * Sets the <code>target</code> attribute
+     *
+     * @param target the <code>target</code> attribute
+     */
+    public void setTarget(String target) {
+        if (target != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_TARGET, target);
+        }
+    }
 
-   /**
-    * Method appendChild
-    *
-    * @param node
-    * @return the node in this element.
-    */
-   public Node appendChild(Node node) {
-      return this._constructionElement.appendChild(node);
-   }
+    /**
+     * Returns the <code>target</code> attribute
+     *
+     * @return the <code>target</code> attribute
+     */
+    public String getTarget() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_TARGET);
+    }
 
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_SIGNATUREPROPERTY;
-   }
+    /**
+     * Method appendChild
+     *
+     * @param node
+     * @return the node in this element.
+     */
+    public Node appendChild(Node node) {
+        return this.constructionElement.appendChild(node);
+    }
+
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_SIGNATUREPROPERTY;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
@@ -50,11 +52,11 @@
  */
 public class SignedInfo extends Manifest {
 
-    /** Field _signatureAlgorithm */
-    private SignatureAlgorithm _signatureAlgorithm = null;
+    /** Field signatureAlgorithm */
+    private SignatureAlgorithm signatureAlgorithm = null;
 
-    /** Field _c14nizedBytes           */
-    private byte[] _c14nizedBytes = null;
+    /** Field c14nizedBytes           */
+    private byte[] c14nizedBytes = null;
 
     private Element c14nMethod;
     private Element signatureMethod;
@@ -83,9 +85,9 @@
      *    Canonicalization method
      * @throws XMLSecurityException
      */
-    public SignedInfo(Document doc, String signatureMethodURI,
-        String canonicalizationMethodURI)
-              throws XMLSecurityException {
+    public SignedInfo(
+        Document doc, String signatureMethodURI, String canonicalizationMethodURI
+    ) throws XMLSecurityException {
         this(doc, signatureMethodURI, 0, canonicalizationMethodURI);
     }
 
@@ -100,31 +102,29 @@
      *    Canonicalization method
      * @throws XMLSecurityException
      */
-    public SignedInfo(Document doc, String signatureMethodURI,
-        int hMACOutputLength, String canonicalizationMethodURI)
-              throws XMLSecurityException {
-
+    public SignedInfo(
+        Document doc, String signatureMethodURI,
+        int hMACOutputLength, String canonicalizationMethodURI
+    ) throws XMLSecurityException {
         super(doc);
 
-        c14nMethod = XMLUtils.createElementInSignatureSpace(this._doc,
-                                Constants._TAG_CANONICALIZATIONMETHOD);
+        c14nMethod =
+            XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_CANONICALIZATIONMETHOD);
 
-        c14nMethod.setAttributeNS(null, Constants._ATT_ALGORITHM,
-                                  canonicalizationMethodURI);
-        this._constructionElement.appendChild(c14nMethod);
-        XMLUtils.addReturnToElement(this._constructionElement);
+        c14nMethod.setAttributeNS(null, Constants._ATT_ALGORITHM, canonicalizationMethodURI);
+        this.constructionElement.appendChild(c14nMethod);
+        XMLUtils.addReturnToElement(this.constructionElement);
 
         if (hMACOutputLength > 0) {
-            this._signatureAlgorithm = new SignatureAlgorithm(this._doc,
-                    signatureMethodURI, hMACOutputLength);
+            this.signatureAlgorithm =
+                new SignatureAlgorithm(this.doc, signatureMethodURI, hMACOutputLength);
         } else {
-            this._signatureAlgorithm = new SignatureAlgorithm(this._doc,
-                    signatureMethodURI);
+            this.signatureAlgorithm = new SignatureAlgorithm(this.doc, signatureMethodURI);
         }
 
-        signatureMethod = this._signatureAlgorithm.getElement();
-        this._constructionElement.appendChild(signatureMethod);
-        XMLUtils.addReturnToElement(this._constructionElement);
+        signatureMethod = this.signatureAlgorithm.getElement();
+        this.constructionElement.appendChild(signatureMethod);
+        XMLUtils.addReturnToElement(this.constructionElement);
     }
 
     /**
@@ -133,22 +133,22 @@
      * @param canonicalizationMethodElem
      * @throws XMLSecurityException
      */
-    public SignedInfo(Document doc, Element signatureMethodElem,
-        Element canonicalizationMethodElem) throws XMLSecurityException {
-
+    public SignedInfo(
+        Document doc, Element signatureMethodElem, Element canonicalizationMethodElem
+    ) throws XMLSecurityException {
         super(doc);
         // Check this?
         this.c14nMethod = canonicalizationMethodElem;
-        this._constructionElement.appendChild(c14nMethod);
-        XMLUtils.addReturnToElement(this._constructionElement);
+        this.constructionElement.appendChild(c14nMethod);
+        XMLUtils.addReturnToElement(this.constructionElement);
 
-        this._signatureAlgorithm =
+        this.signatureAlgorithm =
             new SignatureAlgorithm(signatureMethodElem, null);
 
-        signatureMethod = this._signatureAlgorithm.getElement();
-        this._constructionElement.appendChild(signatureMethod);
+        signatureMethod = this.signatureAlgorithm.getElement();
+        this.constructionElement.appendChild(signatureMethod);
 
-        XMLUtils.addReturnToElement(this._constructionElement);
+        XMLUtils.addReturnToElement(this.constructionElement);
     }
 
     /**
@@ -157,48 +157,76 @@
      * @param element <code>SignedInfo</code>
      * @param baseURI the URI of the resource where the XML instance was stored
      * @throws XMLSecurityException
-     * @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0033.html">Question</A>
-     * @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0054.html">Answer</A>
+     * @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0033.html">
+     * Question</A>
+     * @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0054.html">
+     * Answer</A>
      */
-    public SignedInfo(Element element, String baseURI)
-           throws XMLSecurityException {
+    public SignedInfo(Element element, String baseURI) throws XMLSecurityException {
+        this(element, baseURI, false);
+    }
 
+    /**
+     * Build a {@link SignedInfo} from an {@link Element}
+     *
+     * @param element <code>SignedInfo</code>
+     * @param baseURI the URI of the resource where the XML instance was stored
+     * @param secureValidation whether secure validation is enabled or not
+     * @throws XMLSecurityException
+     * @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0033.html">
+     * Question</A>
+     * @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0054.html">
+     * Answer</A>
+     */
+    public SignedInfo(
+        Element element, String baseURI, boolean secureValidation
+    ) throws XMLSecurityException {
         // Parse the Reference children and Id attribute in the Manifest
-        super(element, baseURI);
+        super(reparseSignedInfoElem(element), baseURI, secureValidation);
 
-        /* canonicalize ds:SignedInfo, reparse it into a new document
+        c14nMethod = XMLUtils.getNextElement(element.getFirstChild());
+        signatureMethod = XMLUtils.getNextElement(c14nMethod.getNextSibling());
+        this.signatureAlgorithm =
+            new SignatureAlgorithm(signatureMethod, this.getBaseURI(), secureValidation);
+    }
+
+    private static Element reparseSignedInfoElem(Element element)
+        throws XMLSecurityException {
+        /*
+         * If a custom canonicalizationMethod is used, canonicalize
+         * ds:SignedInfo, reparse it into a new document
          * and replace the original not-canonicalized ds:SignedInfo by
          * the re-parsed canonicalized one.
          */
-        c14nMethod = XMLUtils.getNextElement(element.getFirstChild());
-        String c14nMethodURI = this.getCanonicalizationMethodURI();
+        Element c14nMethod = XMLUtils.getNextElement(element.getFirstChild());
+        String c14nMethodURI =
+            c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
         if (!(c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS) ||
-              c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS) ||
-              c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS) ||
-              c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS))) {
+            c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS) ||
+            c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS) ||
+            c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS) ||
+            c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS) ||
+            c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS))) {
             // the c14n is not a secure one and can rewrite the URIs or like
-            // that reparse the SignedInfo to be sure
+            // so reparse the SignedInfo to be sure
             try {
                 Canonicalizer c14nizer =
-                Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
+                    Canonicalizer.getInstance(c14nMethodURI);
 
-                this._c14nizedBytes =
-                    c14nizer.canonicalizeSubtree(this._constructionElement);
+                byte[] c14nizedBytes = c14nizer.canonicalizeSubtree(element);
                 javax.xml.parsers.DocumentBuilderFactory dbf =
                     javax.xml.parsers.DocumentBuilderFactory.newInstance();
                 dbf.setNamespaceAware(true);
-                dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
-                               Boolean.TRUE);
+                dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
                 javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
                 Document newdoc =
-                    db.parse(new ByteArrayInputStream(this._c14nizedBytes));
+                    db.parse(new ByteArrayInputStream(c14nizedBytes));
                 Node imported =
-                    this._doc.importNode(newdoc.getDocumentElement(), true);
+                    element.getOwnerDocument().importNode(newdoc.getDocumentElement(), true);
 
-                this._constructionElement.getParentNode().replaceChild(imported,
-                    this._constructionElement);
+                element.getParentNode().replaceChild(imported, element);
 
-                this._constructionElement = (Element) imported;
+                return (Element) imported;
             } catch (ParserConfigurationException ex) {
                 throw new XMLSecurityException("empty", ex);
             } catch (IOException ex) {
@@ -207,184 +235,163 @@
                 throw new XMLSecurityException("empty", ex);
             }
         }
-        signatureMethod = XMLUtils.getNextElement(c14nMethod.getNextSibling());
-        this._signatureAlgorithm =
-            new SignatureAlgorithm(signatureMethod, this.getBaseURI());
+        return element;
+    }
+
+    /**
+     * Tests core validation process
+     *
+     * @return true if verification was successful
+     * @throws MissingResourceFailureException
+     * @throws XMLSecurityException
+     */
+    public boolean verify()
+        throws MissingResourceFailureException, XMLSecurityException {
+        return super.verifyReferences(false);
+    }
+
+    /**
+     * Tests core validation process
+     *
+     * @param followManifests defines whether the verification process has to verify referenced <CODE>ds:Manifest</CODE>s, too
+     * @return true if verification was successful
+     * @throws MissingResourceFailureException
+     * @throws XMLSecurityException
+     */
+    public boolean verify(boolean followManifests)
+        throws MissingResourceFailureException, XMLSecurityException {
+        return super.verifyReferences(followManifests);
+    }
+
+    /**
+     * Returns getCanonicalizedOctetStream
+     *
+     * @return the canonicalization result octet stream of <code>SignedInfo</code> element
+     * @throws CanonicalizationException
+     * @throws InvalidCanonicalizerException
+     * @throws XMLSecurityException
+     */
+    public byte[] getCanonicalizedOctetStream()
+        throws CanonicalizationException, InvalidCanonicalizerException, XMLSecurityException {
+        if (this.c14nizedBytes == null) {
+            Canonicalizer c14nizer =
+                Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
+
+            this.c14nizedBytes =
+                c14nizer.canonicalizeSubtree(this.constructionElement);
+        }
+
+        // make defensive copy
+        return this.c14nizedBytes.clone();
+    }
+
+    /**
+     * Output the C14n stream to the given OutputStream.
+     * @param os
+     * @throws CanonicalizationException
+     * @throws InvalidCanonicalizerException
+     * @throws XMLSecurityException
+     */
+    public void signInOctetStream(OutputStream os)
+        throws CanonicalizationException, InvalidCanonicalizerException, XMLSecurityException {
+        if (this.c14nizedBytes == null) {
+            Canonicalizer c14nizer =
+                Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
+            c14nizer.setWriter(os);
+            String inclusiveNamespaces = this.getInclusiveNamespaces();
+
+            if (inclusiveNamespaces == null) {
+                c14nizer.canonicalizeSubtree(this.constructionElement);
+            } else {
+                c14nizer.canonicalizeSubtree(this.constructionElement, inclusiveNamespaces);
+            }
+        } else {
+            try {
+                os.write(this.c14nizedBytes);
+            } catch (IOException e) {
+                throw new RuntimeException(e);
+            }
+        }
     }
 
-   /**
-    * Tests core validation process
-    *
-    * @return true if verification was successful
-    * @throws MissingResourceFailureException
-    * @throws XMLSecurityException
-    */
-   public boolean verify()
-           throws MissingResourceFailureException, XMLSecurityException {
-      return super.verifyReferences(false);
-   }
-
-   /**
-    * Tests core validation process
-    *
-    * @param followManifests defines whether the verification process has to verify referenced <CODE>ds:Manifest</CODE>s, too
-    * @return true if verification was successful
-    * @throws MissingResourceFailureException
-    * @throws XMLSecurityException
-    */
-   public boolean verify(boolean followManifests)
-           throws MissingResourceFailureException, XMLSecurityException {
-      return super.verifyReferences(followManifests);
-   }
+    /**
+     * Returns the Canonicalization method URI
+     *
+     * @return the Canonicalization method URI
+     */
+    public String getCanonicalizationMethodURI() {
+        return c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
+    }
 
-   /**
-    * Returns getCanonicalizedOctetStream
-    *
-    * @return the canonicalization result octedt stream of <code>SignedInfo</code> element
-    * @throws CanonicalizationException
-    * @throws InvalidCanonicalizerException
-    * @throws XMLSecurityException
-    */
-   public byte[] getCanonicalizedOctetStream()
-           throws CanonicalizationException, InvalidCanonicalizerException,
-                 XMLSecurityException {
+    /**
+     * Returns the Signature method URI
+     *
+     * @return the Signature method URI
+     */
+    public String getSignatureMethodURI() {
+        Element signatureElement = this.getSignatureMethodElement();
 
-      if ((this._c14nizedBytes == null)
-              /*&& (this._state == ElementProxy.MODE_SIGN)*/) {
-         Canonicalizer c14nizer =
-            Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
-
-         this._c14nizedBytes =
-            c14nizer.canonicalizeSubtree(this._constructionElement);
-      }
+        if (signatureElement != null) {
+            return signatureElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
+        }
 
-      // make defensive copy
-      byte[] output = new byte[this._c14nizedBytes.length];
-
-      System.arraycopy(this._c14nizedBytes, 0, output, 0, output.length);
-
-      return output;
-   }
+        return null;
+    }
 
-   /**
-    *  Output the C14n stream to the give outputstream.
-    * @param os
-    * @throws CanonicalizationException
-    * @throws InvalidCanonicalizerException
-    * @throws XMLSecurityException
-    */
-   public void signInOctectStream(OutputStream os)
-       throws CanonicalizationException, InvalidCanonicalizerException,
-           XMLSecurityException {
-
-        if ((this._c14nizedBytes == null)) {
-       Canonicalizer c14nizer =
-          Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
-       c14nizer.setWriter(os);
-       String inclusiveNamespaces = this.getInclusiveNamespaces();
+    /**
+     * Method getSignatureMethodElement
+     * @return returns the SignatureMethod Element
+     *
+     */
+    public Element getSignatureMethodElement() {
+        return signatureMethod;
+    }
 
-       if(inclusiveNamespaces == null)
-        c14nizer.canonicalizeSubtree(this._constructionElement);
-       else
-        c14nizer.canonicalizeSubtree(this._constructionElement, inclusiveNamespaces);
-    } else {
-        try {
-                        os.write(this._c14nizedBytes);
-                } catch (IOException e) {
-                        throw new RuntimeException(""+e);
-                }
+    /**
+     * Creates a SecretKey for the appropriate Mac algorithm based on a
+     * byte[] array password.
+     *
+     * @param secretKeyBytes
+     * @return the secret key for the SignedInfo element.
+     */
+    public SecretKey createSecretKey(byte[] secretKeyBytes) {
+        return new SecretKeySpec(secretKeyBytes, this.signatureAlgorithm.getJCEAlgorithmString());
     }
-   }
-
-   /**
-    * Returns the Canonicalization method URI
-    *
-    * @return the Canonicalization method URI
-    */
-   public String getCanonicalizationMethodURI() {
 
-
-     return c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
-   }
-
-   /**
-    * Returns the Signature method URI
-    *
-    * @return the Signature method URI
-    */
-   public String getSignatureMethodURI() {
-
-      Element signatureElement = this.getSignatureMethodElement();
-
-      if (signatureElement != null) {
-         return signatureElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
-      }
-
-      return null;
-   }
+    protected SignatureAlgorithm getSignatureAlgorithm() {
+        return signatureAlgorithm;
+    }
 
-   /**
-    * Method getSignatureMethodElement
-    * @return gets The SignatureMethod Node.
-    *
-    */
-   public Element getSignatureMethodElement() {
-           return signatureMethod;
-   }
-
-   /**
-    * Creates a SecretKey for the appropriate Mac algorithm based on a
-    * byte[] array password.
-    *
-    * @param secretKeyBytes
-    * @return the secret key for the SignedInfo element.
-    */
-   public SecretKey createSecretKey(byte[] secretKeyBytes)
-   {
+    /**
+     * Method getBaseLocalName
+     * @inheritDoc
+     *
+     */
+    public String getBaseLocalName() {
+        return Constants._TAG_SIGNEDINFO;
+    }
 
-      return new SecretKeySpec(secretKeyBytes,
-                               this._signatureAlgorithm
-                                  .getJCEAlgorithmString());
-   }
+    public String getInclusiveNamespaces() {
+        String c14nMethodURI = c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
+        if (!(c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#") ||
+            c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#WithComments"))) {
+            return null;
+        }
+
+        Element inclusiveElement = XMLUtils.getNextElement(c14nMethod.getFirstChild());
 
-   protected SignatureAlgorithm getSignatureAlgorithm() {
-           return _signatureAlgorithm;
-   }
-   /**
-    * Method getBaseLocalName
-    * @inheritDoc
-    *
-    */
-   public String getBaseLocalName() {
-      return Constants._TAG_SIGNEDINFO;
-   }
-
-   public String getInclusiveNamespaces() {
-
-
-
-     String c14nMethodURI = c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
-     if(!(c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#") ||
-                        c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#WithComments"))) {
+        if (inclusiveElement != null) {
+            try {
+                String inclusiveNamespaces =
+                    new InclusiveNamespaces(
+                        inclusiveElement,
+                        InclusiveNamespaces.ExclusiveCanonicalizationNamespace
+                    ).getInclusiveNamespaces();
+                return inclusiveNamespaces;
+            } catch (XMLSecurityException e) {
                 return null;
             }
-
-     Element inclusiveElement = XMLUtils.getNextElement(
-                 c14nMethod.getFirstChild());
-
-     if(inclusiveElement != null)
-     {
-         try
-         {
-             String inclusiveNamespaces = new InclusiveNamespaces(inclusiveElement,
-                         InclusiveNamespaces.ExclusiveCanonicalizationNamespace).getInclusiveNamespaces();
-             return inclusiveNamespaces;
-         }
-         catch (XMLSecurityException e)
-         {
-             return null;
-         }
-     }
-     return null;
+        }
+        return null;
     }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
-
-
 import java.io.IOException;
 import java.io.OutputStream;
 import java.security.Key;
@@ -42,7 +42,6 @@
 import com.sun.org.apache.xml.internal.security.utils.Base64;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.I18n;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import com.sun.org.apache.xml.internal.security.utils.SignerOutputStream;
 import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream;
@@ -56,7 +55,6 @@
 import org.w3c.dom.NodeList;
 import org.w3c.dom.Text;
 
-
 /**
  * Handles <code>&lt;ds:Signature&gt;</code> elements.
  * This is the main class that deals with creating and verifying signatures.
@@ -64,7 +62,7 @@
  * <p>There are 2 types of constructors for this class. The ones that take a
  * document, baseURI and 1 or more Java Objects. This is mostly used for
  * signing purposes.
- * The other constructor is the one that takes a DOM Element and a BaseURI.
+ * The other constructor is the one that takes a DOM Element and a baseURI.
  * This is used mostly with for verifying, when you have a SignatureElement.
  *
  * There are a few different types of methods:
@@ -76,329 +74,391 @@
  * ObjectContainer during signing.</li>
  * <li>sign and checkSignatureValue methods are used to sign and validate the
  * signature. </li></ul>
- *
- * @author $Author: mullan $
  */
 public final class XMLSignature extends SignatureElementProxy {
 
-   /** {@link java.util.logging} logging facility */
-   static java.util.logging.Logger log =
+    /** MAC - Required HMAC-SHA1 */
+    public static final String ALGO_ID_MAC_HMAC_SHA1 =
+        Constants.SignatureSpecNS + "hmac-sha1";
+
+    /** Signature - Required DSAwithSHA1 (DSS) */
+    public static final String ALGO_ID_SIGNATURE_DSA =
+        Constants.SignatureSpecNS + "dsa-sha1";
+
+    /** Signature - Recommended RSAwithSHA1 */
+    public static final String ALGO_ID_SIGNATURE_RSA =
+        Constants.SignatureSpecNS + "rsa-sha1";
+
+    /** Signature - Recommended RSAwithSHA1 */
+    public static final String ALGO_ID_SIGNATURE_RSA_SHA1 =
+        Constants.SignatureSpecNS + "rsa-sha1";
+
+    /** Signature - NOT Recommended RSAwithMD5 */
+    public static final String ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5 =
+        Constants.MoreAlgorithmsSpecNS + "rsa-md5";
+
+    /** Signature - Optional RSAwithRIPEMD160 */
+    public static final String ALGO_ID_SIGNATURE_RSA_RIPEMD160 =
+        Constants.MoreAlgorithmsSpecNS + "rsa-ripemd160";
+
+    /** Signature - Optional RSAwithSHA256 */
+    public static final String ALGO_ID_SIGNATURE_RSA_SHA256 =
+        Constants.MoreAlgorithmsSpecNS + "rsa-sha256";
+
+    /** Signature - Optional RSAwithSHA384 */
+    public static final String ALGO_ID_SIGNATURE_RSA_SHA384 =
+        Constants.MoreAlgorithmsSpecNS + "rsa-sha384";
+
+    /** Signature - Optional RSAwithSHA512 */
+    public static final String ALGO_ID_SIGNATURE_RSA_SHA512 =
+        Constants.MoreAlgorithmsSpecNS + "rsa-sha512";
+
+    /** HMAC - NOT Recommended HMAC-MD5 */
+    public static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 =
+        Constants.MoreAlgorithmsSpecNS + "hmac-md5";
+
+    /** HMAC - Optional HMAC-RIPEMD160 */
+    public static final String ALGO_ID_MAC_HMAC_RIPEMD160 =
+        Constants.MoreAlgorithmsSpecNS + "hmac-ripemd160";
+
+    /** HMAC - Optional HMAC-SHA256 */
+    public static final String ALGO_ID_MAC_HMAC_SHA256 =
+        Constants.MoreAlgorithmsSpecNS + "hmac-sha256";
+
+    /** HMAC - Optional HMAC-SHA284 */
+    public static final String ALGO_ID_MAC_HMAC_SHA384 =
+        Constants.MoreAlgorithmsSpecNS + "hmac-sha384";
+
+    /** HMAC - Optional HMAC-SHA512 */
+    public static final String ALGO_ID_MAC_HMAC_SHA512 =
+        Constants.MoreAlgorithmsSpecNS + "hmac-sha512";
+
+    /**Signature - Optional ECDSAwithSHA1 */
+    public static final String ALGO_ID_SIGNATURE_ECDSA_SHA1 =
+        "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1";
+
+    /**Signature - Optional ECDSAwithSHA256 */
+    public static final String ALGO_ID_SIGNATURE_ECDSA_SHA256 =
+        "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256";
+
+    /**Signature - Optional ECDSAwithSHA384 */
+    public static final String ALGO_ID_SIGNATURE_ECDSA_SHA384 =
+        "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384";
+
+    /**Signature - Optional ECDSAwithSHA512 */
+    public static final String ALGO_ID_SIGNATURE_ECDSA_SHA512 =
+        "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512";
+
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(XMLSignature.class.getName());
 
-   //J-
-   /** MAC - Required HMAC-SHA1 */
-   public static final String ALGO_ID_MAC_HMAC_SHA1 = Constants.SignatureSpecNS + "hmac-sha1";
+    /** ds:Signature.ds:SignedInfo element */
+    private SignedInfo signedInfo;
+
+    /** ds:Signature.ds:KeyInfo */
+    private KeyInfo keyInfo;
 
-   /** Signature - Required DSAwithSHA1 (DSS) */
-   public static final String ALGO_ID_SIGNATURE_DSA = Constants.SignatureSpecNS + "dsa-sha1";
+    /**
+     * Checking the digests in References in a Signature are mandatory, but for
+     * References inside a Manifest it is application specific. This boolean is
+     * to indicate that the References inside Manifests should be validated.
+     */
+    private boolean followManifestsDuringValidation = false;
+
+    private Element signatureValueElement;
 
-   /** Signature - Recommended RSAwithSHA1 */
-   public static final String ALGO_ID_SIGNATURE_RSA = Constants.SignatureSpecNS + "rsa-sha1";
-   /** Signature - Recommended RSAwithSHA1 */
-   public static final String ALGO_ID_SIGNATURE_RSA_SHA1 = Constants.SignatureSpecNS + "rsa-sha1";
-   /** Signature - NOT Recommended RSAwithMD5 */
-   public static final String ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5 = Constants.MoreAlgorithmsSpecNS + "rsa-md5";
-   /** Signature - Optional RSAwithRIPEMD160 */
-   public static final String ALGO_ID_SIGNATURE_RSA_RIPEMD160 = Constants.MoreAlgorithmsSpecNS + "rsa-ripemd160";
-   /** Signature - Optional RSAwithSHA256 */
-   public static final String ALGO_ID_SIGNATURE_RSA_SHA256 = Constants.MoreAlgorithmsSpecNS + "rsa-sha256";
-   /** Signature - Optional RSAwithSHA384 */
-   public static final String ALGO_ID_SIGNATURE_RSA_SHA384 = Constants.MoreAlgorithmsSpecNS + "rsa-sha384";
-   /** Signature - Optional RSAwithSHA512 */
-   public static final String ALGO_ID_SIGNATURE_RSA_SHA512 = Constants.MoreAlgorithmsSpecNS + "rsa-sha512";
+    private static final int MODE_SIGN = 0;
+    private static final int MODE_VERIFY = 1;
+    private int state = MODE_SIGN;
 
-   /** HMAC - NOT Recommended HMAC-MD5 */
-   public static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 = Constants.MoreAlgorithmsSpecNS + "hmac-md5";
-   /** HMAC - Optional HMAC-RIPEMD160 */
-   public static final String ALGO_ID_MAC_HMAC_RIPEMD160 = Constants.MoreAlgorithmsSpecNS + "hmac-ripemd160";
-   /** HMAC - Optional HMAC-SHA256 */
-   public static final String ALGO_ID_MAC_HMAC_SHA256 = Constants.MoreAlgorithmsSpecNS + "hmac-sha256";
-   /** HMAC - Optional HMAC-SHA284 */
-   public static final String ALGO_ID_MAC_HMAC_SHA384 = Constants.MoreAlgorithmsSpecNS + "hmac-sha384";
-   /** HMAC - Optional HMAC-SHA512 */
-   public static final String ALGO_ID_MAC_HMAC_SHA512 = Constants.MoreAlgorithmsSpecNS + "hmac-sha512";
-   /**Signature - Optional ECDSAwithSHA1 */
-   public static final String ALGO_ID_SIGNATURE_ECDSA_SHA1 = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1";
+    /**
+     * This creates a new <CODE>ds:Signature</CODE> Element and adds an empty
+     * <CODE>ds:SignedInfo</CODE>.
+     * The <code>ds:SignedInfo</code> is initialized with the specified Signature
+     * algorithm and Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS which is REQUIRED
+     * by the spec. This method's main use is for creating a new signature.
+     *
+     * @param doc Document in which the signature will be appended after creation.
+     * @param baseURI URI to be used as context for all relative URIs.
+     * @param signatureMethodURI signature algorithm to use.
+     * @throws XMLSecurityException
+     */
+    public XMLSignature(Document doc, String baseURI, String signatureMethodURI)
+        throws XMLSecurityException {
+        this(doc, baseURI, signatureMethodURI, 0, Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
+    }
 
-
-   //J+
-
-   /** ds:Signature.ds:SignedInfo element */
-   private SignedInfo _signedInfo = null;
-
-   /** ds:Signature.ds:KeyInfo */
-   private KeyInfo _keyInfo = null;
-
-   /**
-    * Checking the digests in References in a Signature are mandatory, but for
-    * References inside a Manifest it is application specific. This boolean is
-    * to indicate that the References inside Manifests should be validated.
-    */
-   private boolean _followManifestsDuringValidation = false;
-
-private Element signatureValueElement;
+    /**
+     * Constructor XMLSignature
+     *
+     * @param doc
+     * @param baseURI
+     * @param signatureMethodURI the Signature method to be used.
+     * @param hmacOutputLength
+     * @throws XMLSecurityException
+     */
+    public XMLSignature(Document doc, String baseURI, String signatureMethodURI,
+                        int hmacOutputLength) throws XMLSecurityException {
+        this(
+            doc, baseURI, signatureMethodURI, hmacOutputLength,
+            Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS
+        );
+    }
 
-  /**
-    * This creates a new <CODE>ds:Signature</CODE> Element and adds an empty
-    * <CODE>ds:SignedInfo</CODE>.
-    * The <code>ds:SignedInfo</code> is initialized with the specified Signature
-    * algorithm and Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS which is REQUIRED
-    * by the spec. This method's main use is for creating a new signature.
-    *
-    * @param doc Document in which the signature will be appended after creation.
-    * @param BaseURI URI to be used as context for all relative URIs.
-    * @param SignatureMethodURI signature algorithm to use.
-    * @throws XMLSecurityException
-    */
-   public XMLSignature(Document doc, String BaseURI, String SignatureMethodURI)
-           throws XMLSecurityException {
-      this(doc, BaseURI, SignatureMethodURI, 0,
-           Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
-   }
+    /**
+     * Constructor XMLSignature
+     *
+     * @param doc
+     * @param baseURI
+     * @param signatureMethodURI the Signature method to be used.
+     * @param canonicalizationMethodURI the canonicalization algorithm to be
+     * used to c14nize the SignedInfo element.
+     * @throws XMLSecurityException
+     */
+    public XMLSignature(
+        Document doc,
+        String baseURI,
+        String signatureMethodURI,
+        String canonicalizationMethodURI
+    ) throws XMLSecurityException {
+        this(doc, baseURI, signatureMethodURI, 0, canonicalizationMethodURI);
+    }
 
-   /**
-    * Constructor XMLSignature
-    *
-    * @param doc
-    * @param BaseURI
-    * @param SignatureMethodURI the Signature method to be used.
-    * @param HMACOutputLength
-    * @throws XMLSecurityException
-    */
-   public XMLSignature(
-           Document doc, String BaseURI, String SignatureMethodURI, int HMACOutputLength)
-              throws XMLSecurityException {
-      this(doc, BaseURI, SignatureMethodURI, HMACOutputLength,
-           Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
-   }
+    /**
+     * Constructor XMLSignature
+     *
+     * @param doc
+     * @param baseURI
+     * @param signatureMethodURI
+     * @param hmacOutputLength
+     * @param canonicalizationMethodURI
+     * @throws XMLSecurityException
+     */
+    public XMLSignature(
+        Document doc,
+        String baseURI,
+        String signatureMethodURI,
+        int hmacOutputLength,
+        String canonicalizationMethodURI
+    ) throws XMLSecurityException {
+        super(doc);
 
-   /**
-    * Constructor XMLSignature
-    *
-    * @param doc
-    * @param BaseURI
-    * @param SignatureMethodURI the Signature method to be used.
-    * @param CanonicalizationMethodURI the canonicalization algorithm to be used to c14nize the SignedInfo element.
-    * @throws XMLSecurityException
-    */
-   public XMLSignature(
-           Document doc, String BaseURI, String SignatureMethodURI, String CanonicalizationMethodURI)
-              throws XMLSecurityException {
-      this(doc, BaseURI, SignatureMethodURI, 0, CanonicalizationMethodURI);
-   }
+        String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS);
+        if (xmlnsDsPrefix == null || xmlnsDsPrefix.length() == 0) {
+            this.constructionElement.setAttributeNS(
+                Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS
+            );
+        } else {
+            this.constructionElement.setAttributeNS(
+                Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS
+            );
+        }
+        XMLUtils.addReturnToElement(this.constructionElement);
+
+        this.baseURI = baseURI;
+        this.signedInfo =
+            new SignedInfo(
+                this.doc, signatureMethodURI, hmacOutputLength, canonicalizationMethodURI
+            );
+
+        this.constructionElement.appendChild(this.signedInfo.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
 
-   /**
-    * Constructor XMLSignature
-    *
-    * @param doc
-    * @param BaseURI
-    * @param SignatureMethodURI
-    * @param HMACOutputLength
-    * @param CanonicalizationMethodURI
-    * @throws XMLSecurityException
-    */
-   public XMLSignature(
-           Document doc, String BaseURI, String SignatureMethodURI, int HMACOutputLength, String CanonicalizationMethodURI)
-              throws XMLSecurityException {
+        // create an empty SignatureValue; this is filled by setSignatureValueElement
+        signatureValueElement =
+            XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_SIGNATUREVALUE);
 
-      super(doc);
-
-      String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS);
-      if (xmlnsDsPrefix == null) {
-         this._constructionElement.setAttributeNS
-            (Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS);
-      } else {
-         this._constructionElement.setAttributeNS
-            (Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS);
-      }
-      XMLUtils.addReturnToElement(this._constructionElement);
+        this.constructionElement.appendChild(signatureValueElement);
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-      this._baseURI = BaseURI;
-      this._signedInfo = new SignedInfo(this._doc, SignatureMethodURI,
-                                        HMACOutputLength,
-                                        CanonicalizationMethodURI);
-
-      this._constructionElement.appendChild(this._signedInfo.getElement());
-      XMLUtils.addReturnToElement(this._constructionElement);
-
-      // create an empty SignatureValue; this is filled by setSignatureValueElement
-      signatureValueElement =
-         XMLUtils.createElementInSignatureSpace(this._doc,
-                                                Constants._TAG_SIGNATUREVALUE);
+    /**
+     *  Creates a XMLSignature in a Document
+     * @param doc
+     * @param baseURI
+     * @param SignatureMethodElem
+     * @param CanonicalizationMethodElem
+     * @throws XMLSecurityException
+     */
+    public XMLSignature(
+        Document doc,
+        String baseURI,
+        Element SignatureMethodElem,
+        Element CanonicalizationMethodElem
+    ) throws XMLSecurityException {
+        super(doc);
 
-      this._constructionElement.appendChild(signatureValueElement);
-      XMLUtils.addReturnToElement(this._constructionElement);
-   }
-   /**
-    *  Creates a XMLSignature in a Document
-    * @param doc
-    * @param BaseURI
-    * @param SignatureMethodElem
-    * @param CanonicalizationMethodElem
-    * @throws XMLSecurityException
-    */
-   public XMLSignature(
-           Document doc, String BaseURI, Element SignatureMethodElem, Element CanonicalizationMethodElem)
-              throws XMLSecurityException {
+        String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS);
+        if (xmlnsDsPrefix == null || xmlnsDsPrefix.length() == 0) {
+            this.constructionElement.setAttributeNS(
+                Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS
+            );
+        } else {
+            this.constructionElement.setAttributeNS(
+                Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS
+            );
+        }
+        XMLUtils.addReturnToElement(this.constructionElement);
+
+        this.baseURI = baseURI;
+        this.signedInfo =
+            new SignedInfo(this.doc, SignatureMethodElem, CanonicalizationMethodElem);
 
-      super(doc);
+        this.constructionElement.appendChild(this.signedInfo.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
 
-      String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS);
-      if (xmlnsDsPrefix == null) {
-         this._constructionElement.setAttributeNS
-            (Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS);
-      } else {
-         this._constructionElement.setAttributeNS
-            (Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS);
-      }
-      XMLUtils.addReturnToElement(this._constructionElement);
+        // create an empty SignatureValue; this is filled by setSignatureValueElement
+        signatureValueElement =
+            XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_SIGNATUREVALUE);
+
+        this.constructionElement.appendChild(signatureValueElement);
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-      this._baseURI = BaseURI;
-      this._signedInfo = new SignedInfo(this._doc, SignatureMethodElem, CanonicalizationMethodElem);
-
-      this._constructionElement.appendChild(this._signedInfo.getElement());
-      XMLUtils.addReturnToElement(this._constructionElement);
-
-      // create an empty SignatureValue; this is filled by setSignatureValueElement
-      signatureValueElement =
-         XMLUtils.createElementInSignatureSpace(this._doc,
-                                                Constants._TAG_SIGNATUREVALUE);
-
-      this._constructionElement.appendChild(signatureValueElement);
-      XMLUtils.addReturnToElement(this._constructionElement);
-   }
+    /**
+     * This will parse the element and construct the Java Objects.
+     * That will allow a user to validate the signature.
+     *
+     * @param element ds:Signature element that contains the whole signature
+     * @param baseURI URI to be prepended to all relative URIs
+     * @throws XMLSecurityException
+     * @throws XMLSignatureException if the signature is badly formatted
+     */
+    public XMLSignature(Element element, String baseURI)
+        throws XMLSignatureException, XMLSecurityException {
+        this(element, baseURI, false);
+    }
 
-   /**
-    * This will parse the element and construct the Java Objects.
-    * That will allow a user to validate the signature.
-    *
-    * @param element ds:Signature element that contains the whole signature
-    * @param BaseURI URI to be prepended to all relative URIs
-    * @throws XMLSecurityException
-    * @throws XMLSignatureException if the signature is badly formatted
-    */
-   public XMLSignature(Element element, String BaseURI)
-           throws XMLSignatureException, XMLSecurityException {
+    /**
+     * This will parse the element and construct the Java Objects.
+     * That will allow a user to validate the signature.
+     *
+     * @param element ds:Signature element that contains the whole signature
+     * @param baseURI URI to be prepended to all relative URIs
+     * @param secureValidation whether secure secureValidation is enabled or not
+     * @throws XMLSecurityException
+     * @throws XMLSignatureException if the signature is badly formatted
+     */
+    public XMLSignature(Element element, String baseURI, boolean secureValidation)
+        throws XMLSignatureException, XMLSecurityException {
+        super(element, baseURI);
 
-      super(element, BaseURI);
+        // check out SignedInfo child
+        Element signedInfoElem = XMLUtils.getNextElement(element.getFirstChild());
 
-      // check out SignedInfo child
-      Element signedInfoElem = XMLUtils.getNextElement(element.getFirstChild());// XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
-                                  //Constants._TAG_SIGNEDINFO,0);
-
-      // check to see if it is there
-      if (signedInfoElem == null) {
-         Object exArgs[] = { Constants._TAG_SIGNEDINFO,
-                             Constants._TAG_SIGNATURE };
+        // check to see if it is there
+        if (signedInfoElem == null) {
+            Object exArgs[] = { Constants._TAG_SIGNEDINFO, Constants._TAG_SIGNATURE };
+            throw new XMLSignatureException("xml.WrongContent", exArgs);
+        }
 
-         throw new XMLSignatureException("xml.WrongContent", exArgs);
-      }
+        // create a SignedInfo object from that element
+        this.signedInfo = new SignedInfo(signedInfoElem, baseURI, secureValidation);
+        // get signedInfoElem again in case it has changed
+        signedInfoElem = XMLUtils.getNextElement(element.getFirstChild());
 
-      // create a SignedInfo object from that element
-      this._signedInfo = new SignedInfo(signedInfoElem, BaseURI);
-
-      // check out SignatureValue child
-      this.signatureValueElement =XMLUtils.getNextElement(signedInfoElem.getNextSibling()); //XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
-                                       //  Constants._TAG_SIGNATUREVALUE,0);
+        // check out SignatureValue child
+        this.signatureValueElement =
+            XMLUtils.getNextElement(signedInfoElem.getNextSibling());
 
-      // check to see if it exists
-      if (signatureValueElement == null) {
-         Object exArgs[] = { Constants._TAG_SIGNATUREVALUE,
-                             Constants._TAG_SIGNATURE };
+        // check to see if it exists
+        if (signatureValueElement == null) {
+            Object exArgs[] = { Constants._TAG_SIGNATUREVALUE, Constants._TAG_SIGNATURE };
+            throw new XMLSignatureException("xml.WrongContent", exArgs);
+        }
+        Attr signatureValueAttr = signatureValueElement.getAttributeNodeNS(null, "Id");
+        if (signatureValueAttr != null) {
+            signatureValueElement.setIdAttributeNode(signatureValueAttr, true);
+        }
 
-         throw new XMLSignatureException("xml.WrongContent", exArgs);
-      }
-      Attr signatureValueAttr = signatureValueElement.getAttributeNodeNS(null, "Id");
-      if (signatureValueAttr != null) {
-          signatureValueElement.setIdAttributeNode(signatureValueAttr, true);
-      }
-
-      // <element ref="ds:KeyInfo" minOccurs="0"/>
-      Element keyInfoElem = XMLUtils.getNextElement(signatureValueElement.getNextSibling());//XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
-                              // Constants._TAG_KEYINFO,0);
+        // <element ref="ds:KeyInfo" minOccurs="0"/>
+        Element keyInfoElem =
+            XMLUtils.getNextElement(signatureValueElement.getNextSibling());
 
-      // If it exists use it, but it's not mandatory
-      if ((keyInfoElem != null) && (keyInfoElem.getNamespaceURI().equals(Constants.SignatureSpecNS) &&
-                  keyInfoElem.getLocalName().equals(Constants._TAG_KEYINFO)) ) {
-         this._keyInfo = new KeyInfo(keyInfoElem, BaseURI);
-      }
+        // If it exists use it, but it's not mandatory
+        if (keyInfoElem != null
+            && keyInfoElem.getNamespaceURI().equals(Constants.SignatureSpecNS)
+            && keyInfoElem.getLocalName().equals(Constants._TAG_KEYINFO)) {
+            this.keyInfo = new KeyInfo(keyInfoElem, baseURI);
+            this.keyInfo.setSecureValidation(secureValidation);
+        }
 
-      // <element ref="ds:Object" minOccurs="0" maxOccurs="unbounded"/>
-      Element objectElem =
-          XMLUtils.getNextElement(signatureValueElement.getNextSibling());
-      while (objectElem != null) {
-          Attr objectAttr = objectElem.getAttributeNodeNS(null, "Id");
-          if (objectAttr != null) {
-              objectElem.setIdAttributeNode(objectAttr, true);
-          }
+        // <element ref="ds:Object" minOccurs="0" maxOccurs="unbounded"/>
+        Element objectElem =
+            XMLUtils.getNextElement(signatureValueElement.getNextSibling());
+        while (objectElem != null) {
+            Attr objectAttr = objectElem.getAttributeNodeNS(null, "Id");
+            if (objectAttr != null) {
+                objectElem.setIdAttributeNode(objectAttr, true);
+            }
 
-          NodeList nodes = objectElem.getChildNodes();
-          int length = nodes.getLength();
-          // Register Ids of the Object child elements
-          for (int i = 0; i < length; i++) {
-              Node child = nodes.item(i);
-              if (child.getNodeType() == Node.ELEMENT_NODE) {
-                  Element childElem = (Element)child;
-                  String tag = childElem.getLocalName();
-                  if (tag.equals("Manifest")) {
-                      new Manifest(childElem, BaseURI);
-                  } else if (tag.equals("SignatureProperties")) {
-                      new SignatureProperties(childElem, BaseURI);
-                  }
-              }
-          }
+            NodeList nodes = objectElem.getChildNodes();
+            int length = nodes.getLength();
+            // Register Ids of the Object child elements
+            for (int i = 0; i < length; i++) {
+                Node child = nodes.item(i);
+                if (child.getNodeType() == Node.ELEMENT_NODE) {
+                    Element childElem = (Element)child;
+                    String tag = childElem.getLocalName();
+                    if (tag.equals("Manifest")) {
+                        new Manifest(childElem, baseURI);
+                    } else if (tag.equals("SignatureProperties")) {
+                        new SignatureProperties(childElem, baseURI);
+                    }
+                }
+            }
 
-          objectElem = XMLUtils.getNextElement(objectElem.getNextSibling());
-      }
-   }
+            objectElem = XMLUtils.getNextElement(objectElem.getNextSibling());
+        }
+
+        this.state = MODE_VERIFY;
+    }
 
-   /**
-    * Sets the <code>Id</code> attribute
-    *
-    * @param Id Id value to be used by the id attribute on the Signature Element
-    */
-   public void setId(String Id) {
+    /**
+     * Sets the <code>Id</code> attribute
+     *
+     * @param id Id value for the id attribute on the Signature Element
+     */
+    public void setId(String id) {
+        if (id != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
+            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+        }
+    }
 
-      if (Id != null) {
-          setLocalIdAttribute(Constants._ATT_ID, Id);
-      }
-   }
-
-   /**
-    * Returns the <code>Id</code> attribute
-    *
-    * @return the <code>Id</code> attribute
-    */
-   public String getId() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
-   }
+    /**
+     * Returns the <code>Id</code> attribute
+     *
+     * @return the <code>Id</code> attribute
+     */
+    public String getId() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+    }
 
-   /**
-    * Returns the completely parsed <code>SignedInfo</code> object.
-    *
-    * @return the completely parsed <code>SignedInfo</code> object.
-    */
-   public SignedInfo getSignedInfo() {
-      return this._signedInfo;
-   }
+    /**
+     * Returns the completely parsed <code>SignedInfo</code> object.
+     *
+     * @return the completely parsed <code>SignedInfo</code> object.
+     */
+    public SignedInfo getSignedInfo() {
+        return this.signedInfo;
+    }
 
-   /**
-    * Returns the octet value of the SignatureValue element.
-    * Throws an XMLSignatureException if it has no or wrong content.
-    *
-    * @return the value of the SignatureValue element.
-    * @throws XMLSignatureException If there is no content
-    */
-   public byte[] getSignatureValue() throws XMLSignatureException {
-
-      try {
-          byte[] signatureValue = Base64.decode(signatureValueElement);
-
-         return signatureValue;
-      } catch (Base64DecodingException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /**
+     * Returns the octet value of the SignatureValue element.
+     * Throws an XMLSignatureException if it has no or wrong content.
+     *
+     * @return the value of the SignatureValue element.
+     * @throws XMLSignatureException If there is no content
+     */
+    public byte[] getSignatureValue() throws XMLSignatureException {
+        try {
+            return Base64.decode(signatureValueElement);
+        } catch (Base64DecodingException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
     /**
      * Base64 encodes and sets the bytes as the content of the SignatureValue
@@ -409,8 +469,7 @@
     private void setSignatureValueElement(byte[] bytes) {
 
         while (signatureValueElement.hasChildNodes()) {
-            signatureValueElement.removeChild
-                (signatureValueElement.getFirstChild());
+            signatureValueElement.removeChild(signatureValueElement.getFirstChild());
         }
 
         String base64codedValue = Base64.encode(bytes);
@@ -419,373 +478,393 @@
             base64codedValue = "\n" + base64codedValue + "\n";
         }
 
-        Text t = this._doc.createTextNode(base64codedValue);
+        Text t = this.doc.createTextNode(base64codedValue);
         signatureValueElement.appendChild(t);
     }
 
-   /**
-    * Returns the KeyInfo child. If we are in signing mode and the KeyInfo
-    * does not exist yet, it is created on demand and added to the Signature.
-    * <br>
-    * This allows to add arbitrary content to the KeyInfo during signing.
-    *
-    * @return the KeyInfo object
-    */
-   public KeyInfo getKeyInfo() {
+    /**
+     * Returns the KeyInfo child. If we are in signing mode and the KeyInfo
+     * does not exist yet, it is created on demand and added to the Signature.
+     * <br>
+     * This allows to add arbitrary content to the KeyInfo during signing.
+     *
+     * @return the KeyInfo object
+     */
+    public KeyInfo getKeyInfo() {
+        // check to see if we are signing and if we have to create a keyinfo
+        if (this.state == MODE_SIGN && this.keyInfo == null) {
 
-      // check to see if we are signing and if we have to create a keyinfo
-      if ( (this._keyInfo == null)) {
-
-         // create the KeyInfo
-         this._keyInfo = new KeyInfo(this._doc);
+            // create the KeyInfo
+            this.keyInfo = new KeyInfo(this.doc);
 
-         // get the Element from KeyInfo
-         Element keyInfoElement = this._keyInfo.getElement();
-         Element firstObject=null;
-         Node sibling= this._constructionElement.getFirstChild();
-         firstObject = XMLUtils.selectDsNode(sibling,Constants._TAG_OBJECT,0);
+            // get the Element from KeyInfo
+            Element keyInfoElement = this.keyInfo.getElement();
+            Element firstObject =
+                XMLUtils.selectDsNode(
+                    this.constructionElement.getFirstChild(), Constants._TAG_OBJECT, 0
+                );
 
             if (firstObject != null) {
-
-               // add it before the object
-               this._constructionElement.insertBefore(keyInfoElement,
-                                                      firstObject);
-               XMLUtils.addReturnBeforeChild(this._constructionElement, firstObject);
+                // add it before the object
+                this.constructionElement.insertBefore(keyInfoElement, firstObject);
+                XMLUtils.addReturnBeforeChild(this.constructionElement, firstObject);
             } else {
+                // add it as the last element to the signature
+                this.constructionElement.appendChild(keyInfoElement);
+                XMLUtils.addReturnToElement(this.constructionElement);
+            }
+        }
 
-               // add it as the last element to the signature
-               this._constructionElement.appendChild(keyInfoElement);
-               XMLUtils.addReturnToElement(this._constructionElement);
-            }
-      }
-
-      return this._keyInfo;
-   }
+        return this.keyInfo;
+    }
 
-   /**
-    * Appends an Object (not a <code>java.lang.Object</code> but an Object
-    * element) to the Signature. Please note that this is only possible
-    * when signing.
-    *
-    * @param object ds:Object to be appended.
-    * @throws XMLSignatureException When this object is used to verify.
-    */
-   public void appendObject(ObjectContainer object)
-           throws XMLSignatureException {
+    /**
+     * Appends an Object (not a <code>java.lang.Object</code> but an Object
+     * element) to the Signature. Please note that this is only possible
+     * when signing.
+     *
+     * @param object ds:Object to be appended.
+     * @throws XMLSignatureException When this object is used to verify.
+     */
+    public void appendObject(ObjectContainer object) throws XMLSignatureException {
+        //try {
+        //if (this.state != MODE_SIGN) {
+        // throw new XMLSignatureException(
+        //  "signature.operationOnlyBeforeSign");
+        //}
 
-      //try {
-         //if (this._state != MODE_SIGN) {
-           // throw new XMLSignatureException(
-             //  "signature.operationOnlyBeforeSign");
-         //}
-
-         this._constructionElement.appendChild(object.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-      //} catch (XMLSecurityException ex) {
+        this.constructionElement.appendChild(object.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+        //} catch (XMLSecurityException ex) {
         // throw new XMLSignatureException("empty", ex);
-      //}
-   }
+        //}
+    }
 
-   /**
-    * Returns the <code>i<code>th <code>ds:Object</code> child of the signature
-    * or null if no such <code>ds:Object</code> element exists.
-    *
-    * @param i
-    * @return the <code>i<code>th <code>ds:Object</code> child of the signature or null if no such <code>ds:Object</code> element exists.
-    */
-   public ObjectContainer getObjectItem(int i) {
+    /**
+     * Returns the <code>i<code>th <code>ds:Object</code> child of the signature
+     * or null if no such <code>ds:Object</code> element exists.
+     *
+     * @param i
+     * @return the <code>i<code>th <code>ds:Object</code> child of the signature
+     * or null if no such <code>ds:Object</code> element exists.
+     */
+    public ObjectContainer getObjectItem(int i) {
+        Element objElem =
+            XMLUtils.selectDsNode(
+                this.constructionElement.getFirstChild(), Constants._TAG_OBJECT, i
+            );
 
-      Element objElem = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
-            Constants._TAG_OBJECT,i);
-
-      try {
-         return new ObjectContainer(objElem, this._baseURI);
-      } catch (XMLSecurityException ex) {
-         return null;
-      }
-   }
+        try {
+            return new ObjectContainer(objElem, this.baseURI);
+        } catch (XMLSecurityException ex) {
+            return null;
+        }
+    }
 
-   /**
-    * Returns the number of all <code>ds:Object</code> elements.
-    *
-    * @return the number of all <code>ds:Object</code> elements.
-    */
-   public int getObjectLength() {
-      return this.length(Constants.SignatureSpecNS, Constants._TAG_OBJECT);
-   }
+    /**
+     * Returns the number of all <code>ds:Object</code> elements.
+     *
+     * @return the number of all <code>ds:Object</code> elements.
+     */
+    public int getObjectLength() {
+        return this.length(Constants.SignatureSpecNS, Constants._TAG_OBJECT);
+    }
 
-   /**
-    * Digests all References in the SignedInfo, calculates the signature value and
-    * sets it in the SignatureValue Element.
-    *
-    * @param signingKey the {@link java.security.PrivateKey} or {@link javax.crypto.SecretKey} that is used to sign.
-    * @throws XMLSignatureException
-    */
-   public void sign(Key signingKey) throws XMLSignatureException {
+    /**
+     * Digests all References in the SignedInfo, calculates the signature value
+     * and sets it in the SignatureValue Element.
+     *
+     * @param signingKey the {@link java.security.PrivateKey} or
+     * {@link javax.crypto.SecretKey} that is used to sign.
+     * @throws XMLSignatureException
+     */
+    public void sign(Key signingKey) throws XMLSignatureException {
 
-      if (signingKey instanceof PublicKey) {
-         throw new IllegalArgumentException(I18n
-            .translate("algorithms.operationOnlyVerification"));
-      }
+        if (signingKey instanceof PublicKey) {
+            throw new IllegalArgumentException(
+                I18n.translate("algorithms.operationOnlyVerification")
+            );
+        }
 
-      try {
-        // if (this._state == MODE_SIGN) {
+        try {
             //Create a SignatureAlgorithm object
-                SignedInfo si = this.getSignedInfo();
+            SignedInfo si = this.getSignedInfo();
             SignatureAlgorithm sa = si.getSignatureAlgorithm();
-            // initialize SignatureAlgorithm for signing
-            sa.initSign(signingKey);
-
-            // generate digest values for all References in this SignedInfo
-            si.generateDigestValues();
-            OutputStream so=new UnsyncBufferedOutputStream(new SignerOutputStream(sa));
+            OutputStream so = null;
             try {
-                so.close();
-            } catch (IOException e) {
-                //Imposible
+                // initialize SignatureAlgorithm for signing
+                sa.initSign(signingKey);
+
+                // generate digest values for all References in this SignedInfo
+                si.generateDigestValues();
+                so = new UnsyncBufferedOutputStream(new SignerOutputStream(sa));
+                // get the canonicalized bytes from SignedInfo
+                si.signInOctetStream(so);
+            } catch (XMLSecurityException ex) {
+                throw ex;
+            } finally {
+                if (so != null) {
+                    try {
+                        so.close();
+                    } catch (IOException ex) {
+                        if (log.isLoggable(java.util.logging.Level.FINE)) {
+                            log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
+                        }
+                    }
+                }
             }
-            // get the canonicalized bytes from SignedInfo
-            si.signInOctectStream(so);
-
-            byte jcebytes[] = sa.sign();
 
-            // set them on the SignateValue element
-            this.setSignatureValueElement(jcebytes);
-         //}
-      } catch (CanonicalizationException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (InvalidCanonicalizerException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (XMLSecurityException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+            // set them on the SignatureValue element
+            this.setSignatureValueElement(sa.sign());
+        } catch (XMLSignatureException ex) {
+            throw ex;
+        } catch (CanonicalizationException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (InvalidCanonicalizerException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (XMLSecurityException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /**
-    * Adds a {@link ResourceResolver} to enable the retrieval of resources.
-    *
-    * @param resolver
-    */
-   public void addResourceResolver(ResourceResolver resolver) {
-      this.getSignedInfo().addResourceResolver(resolver);
-   }
+    /**
+     * Adds a {@link ResourceResolver} to enable the retrieval of resources.
+     *
+     * @param resolver
+     */
+    public void addResourceResolver(ResourceResolver resolver) {
+        this.getSignedInfo().addResourceResolver(resolver);
+    }
 
-   /**
-    * Adds a {@link ResourceResolverSpi} to enable the retrieval of resources.
-    *
-    * @param resolver
-    */
-   public void addResourceResolver(ResourceResolverSpi resolver) {
-      this.getSignedInfo().addResourceResolver(resolver);
-   }
+    /**
+     * Adds a {@link ResourceResolverSpi} to enable the retrieval of resources.
+     *
+     * @param resolver
+     */
+    public void addResourceResolver(ResourceResolverSpi resolver) {
+        this.getSignedInfo().addResourceResolver(resolver);
+    }
 
-   /**
-    * Extracts the public key from the certificate and verifies if the signature
-    * is valid by re-digesting all References, comparing those against the
-    * stored DigestValues and then checking to see if the Signatures match on
-    * the SignedInfo.
-    *
-    * @param cert Certificate that contains the public key part of the keypair that was used to sign.
-    * @return true if the signature is valid, false otherwise
-    * @throws XMLSignatureException
-    */
-   public boolean checkSignatureValue(X509Certificate cert)
-           throws XMLSignatureException {
+    /**
+     * Extracts the public key from the certificate and verifies if the signature
+     * is valid by re-digesting all References, comparing those against the
+     * stored DigestValues and then checking to see if the Signatures match on
+     * the SignedInfo.
+     *
+     * @param cert Certificate that contains the public key part of the keypair
+     * that was used to sign.
+     * @return true if the signature is valid, false otherwise
+     * @throws XMLSignatureException
+     */
+    public boolean checkSignatureValue(X509Certificate cert)
+        throws XMLSignatureException {
+        // see if cert is null
+        if (cert != null) {
+            // check the values with the public key from the cert
+            return this.checkSignatureValue(cert.getPublicKey());
+        }
 
-      // see if cert is null
-      if (cert != null) {
-
-         //check the values with the public key from the cert
-         return this.checkSignatureValue(cert.getPublicKey());
-      }
-
-      Object exArgs[] = { "Didn't get a certificate" };
-      throw new XMLSignatureException("empty", exArgs);
-
-   }
+        Object exArgs[] = { "Didn't get a certificate" };
+        throw new XMLSignatureException("empty", exArgs);
+    }
 
-   /**
-    * Verifies if the signature is valid by redigesting all References,
-    * comparing those against the stored DigestValues and then checking to see
-    * if the Signatures match on the SignedInfo.
-    *
-    * @param pk {@link java.security.PublicKey} part of the keypair or {@link javax.crypto.SecretKey} that was used to sign
-    * @return true if the signature is valid, false otherwise
-    * @throws XMLSignatureException
-    */
-   public boolean checkSignatureValue(Key pk) throws XMLSignatureException {
-
-      //COMMENT: pk suggests it can only be a public key?
-      //check to see if the key is not null
-      if (pk == null) {
-         Object exArgs[] = { "Didn't get a key" };
-
-         throw new XMLSignatureException("empty", exArgs);
-      }
-      // all references inside the signedinfo need to be dereferenced and
-      // digested again to see if the outcome matches the stored value in the
-      // SignedInfo.
-      // If _followManifestsDuringValidation is true it will do the same for
-      // References inside a Manifest.
-      try {
-         SignedInfo si=this.getSignedInfo();
-         //create a SignatureAlgorithms from the SignatureMethod inside
-         //SignedInfo. This is used to validate the signature.
-         SignatureAlgorithm sa =si.getSignatureAlgorithm();
-         if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "SignatureMethodURI = " + sa.getAlgorithmURI());
+    /**
+     * Verifies if the signature is valid by redigesting all References,
+     * comparing those against the stored DigestValues and then checking to see
+     * if the Signatures match on the SignedInfo.
+     *
+     * @param pk {@link java.security.PublicKey} part of the keypair or
+     * {@link javax.crypto.SecretKey} that was used to sign
+     * @return true if the signature is valid, false otherwise
+     * @throws XMLSignatureException
+     */
+    public boolean checkSignatureValue(Key pk) throws XMLSignatureException {
+        //COMMENT: pk suggests it can only be a public key?
+        //check to see if the key is not null
+        if (pk == null) {
+            Object exArgs[] = { "Didn't get a key" };
+            throw new XMLSignatureException("empty", exArgs);
+        }
+        // all references inside the signedinfo need to be dereferenced and
+        // digested again to see if the outcome matches the stored value in the
+        // SignedInfo.
+        // If followManifestsDuringValidation is true it will do the same for
+        // References inside a Manifest.
+        try {
+            SignedInfo si = this.getSignedInfo();
+            //create a SignatureAlgorithms from the SignatureMethod inside
+            //SignedInfo. This is used to validate the signature.
+            SignatureAlgorithm sa = si.getSignatureAlgorithm();
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "signatureMethodURI = " + sa.getAlgorithmURI());
                 log.log(java.util.logging.Level.FINE, "jceSigAlgorithm    = " + sa.getJCEAlgorithmString());
                 log.log(java.util.logging.Level.FINE, "jceSigProvider     = " + sa.getJCEProviderName());
                 log.log(java.util.logging.Level.FINE, "PublicKey = " + pk);
-         }
-         sa.initVerify(pk);
+            }
+            byte sigBytes[] = null;
+            try {
+                sa.initVerify(pk);
 
-         // Get the canonicalized (normalized) SignedInfo
-         SignerOutputStream so=new SignerOutputStream(sa);
-         OutputStream bos=new UnsyncBufferedOutputStream(so);
-         si.signInOctectStream(bos);
-         try {
-                bos.close();
-         } catch (IOException e) {
-                //Imposible
-         }
+                // Get the canonicalized (normalized) SignedInfo
+                SignerOutputStream so = new SignerOutputStream(sa);
+                OutputStream bos = new UnsyncBufferedOutputStream(so);
 
-         //retrieve the byte[] from the stored signature
-         byte sigBytes[] = this.getSignatureValue();
+                si.signInOctetStream(bos);
+                bos.close();
+                // retrieve the byte[] from the stored signature
+                sigBytes = this.getSignatureValue();
+            } catch (IOException ex) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
+                }
+                // Impossible...
+            } catch (XMLSecurityException ex) {
+                throw ex;
+            }
 
-         //Have SignatureAlgorithm sign the input bytes and compare them to the
-         //bytes that were stored in the signature.
-         if (!sa.verify(sigBytes)) {
-            log.log(java.util.logging.Level.WARNING, "Signature verification failed.");
-            return false;
-         }
+            // have SignatureAlgorithm sign the input bytes and compare them to
+            // the bytes that were stored in the signature.
+            if (!sa.verify(sigBytes)) {
+                log.log(java.util.logging.Level.WARNING, "Signature verification failed.");
+                return false;
+            }
 
-         return si.verify(this._followManifestsDuringValidation);
-      } catch (XMLSecurityException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+            return si.verify(this.followManifestsDuringValidation);
+        } catch (XMLSignatureException ex) {
+            throw ex;
+        } catch (XMLSecurityException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /**
-    * Add a Reference with full parameters to this Signature
-    *
-    * @param referenceURI URI of the resource to be signed. Can be null in which
-    * case the dereferencing is application specific. Can be "" in which it's
-    * the parent node (or parent document?). There can only be one "" in each
-    * signature.
-    * @param trans Optional list of transformations to be done before digesting
-    * @param digestURI Mandatory URI of the digesting algorithm to use.
-    * @param ReferenceId Optional id attribute for this Reference
-    * @param ReferenceType Optional mimetype for the URI
-    * @throws XMLSignatureException
-    */
-   public void addDocument(
-           String referenceURI, Transforms trans, String digestURI, String ReferenceId, String ReferenceType)
-              throws XMLSignatureException {
-      this._signedInfo.addDocument(this._baseURI, referenceURI, trans,
-                                   digestURI, ReferenceId, ReferenceType);
-   }
+    /**
+     * Add a Reference with full parameters to this Signature
+     *
+     * @param referenceURI URI of the resource to be signed. Can be null in
+     * which case the dereferencing is application specific. Can be "" in which
+     * it's the parent node (or parent document?). There can only be one "" in
+     * each signature.
+     * @param trans Optional list of transformations to be done before digesting
+     * @param digestURI Mandatory URI of the digesting algorithm to use.
+     * @param referenceId Optional id attribute for this Reference
+     * @param referenceType Optional mimetype for the URI
+     * @throws XMLSignatureException
+     */
+    public void addDocument(
+        String referenceURI,
+        Transforms trans,
+        String digestURI,
+        String referenceId,
+        String referenceType
+    ) throws XMLSignatureException {
+        this.signedInfo.addDocument(
+            this.baseURI, referenceURI, trans, digestURI, referenceId, referenceType
+        );
+    }
 
-   /**
-    * This method is a proxy method for the {@link Manifest#addDocument} method.
-    *
-    * @param referenceURI URI according to the XML Signature specification.
-    * @param trans List of transformations to be applied.
-    * @param digestURI URI of the digest algorithm to be used.
-    * @see Manifest#addDocument
-    * @throws XMLSignatureException
-    */
-   public void addDocument(
-           String referenceURI, Transforms trans, String digestURI)
-              throws XMLSignatureException {
-      this._signedInfo.addDocument(this._baseURI, referenceURI, trans,
-                                   digestURI, null, null);
-   }
+    /**
+     * This method is a proxy method for the {@link Manifest#addDocument} method.
+     *
+     * @param referenceURI URI according to the XML Signature specification.
+     * @param trans List of transformations to be applied.
+     * @param digestURI URI of the digest algorithm to be used.
+     * @see Manifest#addDocument
+     * @throws XMLSignatureException
+     */
+    public void addDocument(
+        String referenceURI,
+        Transforms trans,
+        String digestURI
+    ) throws XMLSignatureException {
+        this.signedInfo.addDocument(this.baseURI, referenceURI, trans, digestURI, null, null);
+    }
 
-   /**
-    * Adds a Reference with just the URI and the transforms. This used the
-    * SHA1 algorithm as a default digest algorithm.
-    *
-    * @param referenceURI URI according to the XML Signature specification.
-    * @param trans List of transformations to be applied.
-    * @throws XMLSignatureException
-    */
-   public void addDocument(String referenceURI, Transforms trans)
-           throws XMLSignatureException {
-      this._signedInfo.addDocument(this._baseURI, referenceURI, trans,
-                                   Constants.ALGO_ID_DIGEST_SHA1, null, null);
-   }
+    /**
+     * Adds a Reference with just the URI and the transforms. This used the
+     * SHA1 algorithm as a default digest algorithm.
+     *
+     * @param referenceURI URI according to the XML Signature specification.
+     * @param trans List of transformations to be applied.
+     * @throws XMLSignatureException
+     */
+    public void addDocument(String referenceURI, Transforms trans)
+        throws XMLSignatureException {
+        this.signedInfo.addDocument(
+            this.baseURI, referenceURI, trans, Constants.ALGO_ID_DIGEST_SHA1, null, null
+        );
+    }
 
-   /**
-    * Add a Reference with just this URI. It uses SHA1 by default as the digest
-    * algorithm
-    *
-    * @param referenceURI URI according to the XML Signature specification.
-    * @throws XMLSignatureException
-    */
-   public void addDocument(String referenceURI) throws XMLSignatureException {
-      this._signedInfo.addDocument(this._baseURI, referenceURI, null,
-                                   Constants.ALGO_ID_DIGEST_SHA1, null, null);
-   }
+    /**
+     * Add a Reference with just this URI. It uses SHA1 by default as the digest
+     * algorithm
+     *
+     * @param referenceURI URI according to the XML Signature specification.
+     * @throws XMLSignatureException
+     */
+    public void addDocument(String referenceURI) throws XMLSignatureException {
+        this.signedInfo.addDocument(
+            this.baseURI, referenceURI, null, Constants.ALGO_ID_DIGEST_SHA1, null, null
+        );
+    }
 
-   /**
-    * Add an X509 Certificate to the KeyInfo. This will include the whole cert
-    * inside X509Data/X509Certificate tags.
-    *
-    * @param cert Certificate to be included. This should be the certificate of the key that was used to sign.
-    * @throws XMLSecurityException
-    */
-   public void addKeyInfo(X509Certificate cert) throws XMLSecurityException {
+    /**
+     * Add an X509 Certificate to the KeyInfo. This will include the whole cert
+     * inside X509Data/X509Certificate tags.
+     *
+     * @param cert Certificate to be included. This should be the certificate of
+     * the key that was used to sign.
+     * @throws XMLSecurityException
+     */
+    public void addKeyInfo(X509Certificate cert) throws XMLSecurityException {
+        X509Data x509data = new X509Data(this.doc);
 
-      X509Data x509data = new X509Data(this._doc);
-
-      x509data.addCertificate(cert);
-      this.getKeyInfo().add(x509data);
-   }
+        x509data.addCertificate(cert);
+        this.getKeyInfo().add(x509data);
+    }
 
-   /**
-    * Add this public key to the KeyInfo. This will include the complete key in
-    * the KeyInfo structure.
-    *
-    * @param pk
-    */
-   public void addKeyInfo(PublicKey pk) {
-      this.getKeyInfo().add(pk);
-   }
+    /**
+     * Add this public key to the KeyInfo. This will include the complete key in
+     * the KeyInfo structure.
+     *
+     * @param pk
+     */
+    public void addKeyInfo(PublicKey pk) {
+        this.getKeyInfo().add(pk);
+    }
+
+    /**
+     * Proxy method for {@link SignedInfo#createSecretKey(byte[])}. If you want
+     * to create a MAC, this method helps you to obtain the
+     * {@link javax.crypto.SecretKey} from octets.
+     *
+     * @param secretKeyBytes
+     * @return the secret key created.
+     * @see SignedInfo#createSecretKey(byte[])
+     */
+    public SecretKey createSecretKey(byte[] secretKeyBytes) {
+        return this.getSignedInfo().createSecretKey(secretKeyBytes);
+    }
 
-   /**
-    * Proxy method for {@link SignedInfo#createSecretKey(byte[])}. If you want to
-    * create a MAC, this method helps you to obtain the {@link javax.crypto.SecretKey}
-    * from octets.
-    *
-    * @param secretKeyBytes
-    * @return the secret key created.
-    * @see SignedInfo#createSecretKey(byte[])
-    */
-   public SecretKey createSecretKey(byte[] secretKeyBytes)
-   {
-      return this.getSignedInfo().createSecretKey(secretKeyBytes);
-   }
+    /**
+     * Signal wether Manifest should be automatically validated.
+     * Checking the digests in References in a Signature are mandatory, but for
+     * References inside a Manifest it is application specific. This boolean is
+     * to indicate that the References inside Manifests should be validated.
+     *
+     * @param followManifests
+     * @see <a href="http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation">
+     * Core validation section in the XML Signature Rec.</a>
+     */
+    public void setFollowNestedManifests(boolean followManifests) {
+        this.followManifestsDuringValidation = followManifests;
+    }
 
-   /**
-    * Signal wether Manifest should be automatically validated.
-    * Checking the digests in References in a Signature are mandatory, but for
-    * References inside a Manifest it is application specific. This boolean is
-    * to indicate that the References inside Manifests should be validated.
-    *
-    * @param followManifests
-    * @see <a href="http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation">Core validation section in the XML Signature Rec.</a>
-    */
-   public void setFollowNestedManifests(boolean followManifests) {
-      this._followManifestsDuringValidation = followManifests;
-   }
-
-   /**
-    * Get the local name of this element
-    *
-    * @return Constant._TAG_SIGNATURE
-    */
-   public String getBaseLocalName() {
-      return Constants._TAG_SIGNATURE;
-   }
+    /**
+     * Get the local name of this element
+     *
+     * @return Constants._TAG_SIGNATURE
+     */
+    public String getBaseLocalName() {
+        return Constants._TAG_SIGNATURE;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,29 +2,28 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
-
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 
-
 /**
  * All XML Signature related exceptions inherit herefrom.
  *
@@ -33,57 +32,56 @@
  */
 public class XMLSignatureException extends XMLSecurityException {
 
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
 
-   /**
-    * Constructor XMLSignatureException
-    *
-    */
-   public XMLSignatureException() {
-      super();
-   }
+    /**
+     * Constructor XMLSignatureException
+     *
+     */
+    public XMLSignatureException() {
+        super();
+    }
 
-   /**
-    * Constructor XMLSignatureException
-    *
-    * @param _msgID
-    */
-   public XMLSignatureException(String _msgID) {
-      super(_msgID);
-   }
+    /**
+     * Constructor XMLSignatureException
+     *
+     * @param msgID
+     */
+    public XMLSignatureException(String msgID) {
+        super(msgID);
+    }
 
-   /**
-    * Constructor XMLSignatureException
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public XMLSignatureException(String _msgID, Object exArgs[]) {
-      super(_msgID, exArgs);
-   }
+    /**
+     * Constructor XMLSignatureException
+     *
+     * @param msgID
+     * @param exArgs
+     */
+    public XMLSignatureException(String msgID, Object exArgs[]) {
+        super(msgID, exArgs);
+    }
 
-   /**
-    * Constructor XMLSignatureException
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public XMLSignatureException(String _msgID, Exception _originalException) {
-      super(_msgID, _originalException);
-   }
+    /**
+     * Constructor XMLSignatureException
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public XMLSignatureException(String msgID, Exception originalException) {
+        super(msgID, originalException);
+    }
 
-   /**
-    * Constructor XMLSignatureException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public XMLSignatureException(String _msgID, Object exArgs[],
-                                Exception _originalException) {
-      super(_msgID, exArgs, _originalException);
-   }
+    /**
+     * Constructor XMLSignatureException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public XMLSignatureException(String msgID, Object exArgs[], Exception originalException) {
+        super(msgID, exArgs, originalException);
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2008 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
@@ -25,7 +27,6 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
-import java.io.UnsupportedEncodingException;
 import java.util.ArrayList;
 import java.util.LinkedHashSet;
 import java.util.List;
@@ -53,17 +54,13 @@
  * @author Christian Geuer-Pollmann
  * $todo$ check whether an XMLSignatureInput can be _both_, octet stream _and_ node set?
  */
-public class XMLSignatureInput implements Cloneable {
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger
-            (XMLSignatureInput.class.getName());
-
+public class XMLSignatureInput {
     /*
      * The XMLSignature Input can be either:
      *   A byteArray like with/or without InputStream.
      *   Or a nodeSet like defined either:
      *       * as a collection of nodes
-     *       * or as subnode excluding or not commets and excluding or
+     *       * or as subnode excluding or not comments and excluding or
      *         not other nodes.
      */
 
@@ -71,63 +68,55 @@
      * Some InputStreams do not support the {@link java.io.InputStream#reset}
      * method, so we read it in completely and work on our Proxy.
      */
-    InputStream _inputOctetStreamProxy = null;
+    private InputStream inputOctetStreamProxy = null;
     /**
      * The original NodeSet for this XMLSignatureInput
      */
-    Set<Node> _inputNodeSet = null;
+    private Set<Node> inputNodeSet = null;
     /**
      * The original Element
      */
-    Node _subNode=null;
+    private Node subNode = null;
     /**
      * Exclude Node *for enveloped transformations*
      */
-    Node excludeNode=null;
+    private Node excludeNode = null;
     /**
      *
      */
-    boolean excludeComments=false;
+    private boolean excludeComments = false;
 
-    boolean isNodeSet=false;
+    private boolean isNodeSet = false;
     /**
      * A cached bytes
      */
-    byte []bytes=null;
+    private byte[] bytes = null;
 
     /**
-     * Some Transforms may require explicit MIME type, charset (IANA registered "character set"), or other such information concerning the data they are receiving from an earlier Transform or the source data, although no Transform algorithm specified in this document needs such explicit information. Such data characteristics are provided as parameters to the Transform algorithm and should be described in the specification for the algorithm.
+     * Some Transforms may require explicit MIME type, charset (IANA registered
+     * "character set"), or other such information concerning the data they are
+     * receiving from an earlier Transform or the source data, although no
+     * Transform algorithm specified in this document needs such explicit
+     * information. Such data characteristics are provided as parameters to the
+     * Transform algorithm and should be described in the specification for the
+     * algorithm.
      */
-    private String _MIMEType = null;
+    private String mimeType = null;
 
     /**
-     * Field _SourceURI
+     * Field sourceURI
      */
-    private String _SourceURI = null;
+    private String sourceURI = null;
 
     /**
      * Node Filter list.
      */
-    List<NodeFilter> nodeFilters=new ArrayList<NodeFilter>();
-
-    boolean needsToBeExpanded=false;
-    OutputStream outputStream=null;
+    private List<NodeFilter> nodeFilters = new ArrayList<NodeFilter>();
 
-    /**
-     * Check if the structured is needed to be circumbented.
-     * @return true if so.
-     */
-    public boolean isNeedsToBeExpanded() {
-        return needsToBeExpanded;
-    }
+    private boolean needsToBeExpanded = false;
+    private OutputStream outputStream = null;
 
-    /**
-     * Set if the structured is needed to be circumbented.
-     * @param needsToBeExpanded true if so.
-     */
-    public void setNeedsToBeExpanded(boolean needsToBeExpanded) {
-        this.needsToBeExpanded = needsToBeExpanded;
-    }
+    private DocumentBuilderFactory dfactory;
 
     /**
      * Construct a XMLSignatureInput from an octet array.
@@ -138,11 +127,8 @@
      * @param inputOctets an octet array which including XML document or node
      */
     public XMLSignatureInput(byte[] inputOctets) {
-
-        // NO  defensive copy
-
-        //this._inputOctetStreamProxy = new ByteArrayInputStream(inputOctets);
-        this.bytes=inputOctets;
+        // NO defensive copy
+        this.bytes = inputOctets;
     }
 
     /**
@@ -152,39 +138,7 @@
      * @param inputOctetStream
      */
     public XMLSignatureInput(InputStream inputOctetStream)  {
-        this._inputOctetStreamProxy=inputOctetStream;
-
-        //this(JavaUtils.getBytesFromStream(inputOctetStream));
-    }
-
-    /**
-     * Construct a XMLSignatureInput from a String.
-     * <p>
-     * This is a comfort method, which internally converts the String into a byte
-     * [] array using the {@link java.lang.String#getBytes()} method.
-     * @deprecated
-     * @param inputStr the input String which including XML document or node
-     */
-    @Deprecated
-    public XMLSignatureInput(String inputStr) {
-        this(inputStr.getBytes());
-    }
-
-    /**
-     * Construct a XMLSignatureInput from a String with a given encoding.
-     * <p>
-     * This is a comfort method, which internally converts the String into a byte
-     * [] array using the {@link java.lang.String#getBytes()} method.
-     *
-     * @deprecated
-     * @param inputStr the input String with encoding <code>encoding</code>
-     * @param encoding the encoding of <code>inputStr</code>
-     * @throws UnsupportedEncodingException
-     */
-    @Deprecated
-    public XMLSignatureInput(String inputStr, String encoding)
-           throws UnsupportedEncodingException {
-        this(inputStr.getBytes(encoding));
+        this.inputOctetStreamProxy = inputOctetStream;
     }
 
     /**
@@ -193,19 +147,33 @@
      *
      * @param rootNode
      */
-    public XMLSignatureInput(Node rootNode)
-    {
-        this._subNode = rootNode;
+    public XMLSignatureInput(Node rootNode) {
+        this.subNode = rootNode;
     }
 
     /**
      * Constructor XMLSignatureInput
      *
      * @param inputNodeSet
-     * @param usedXPathAPI
      */
     public XMLSignatureInput(Set<Node> inputNodeSet) {
-        this._inputNodeSet = inputNodeSet;
+        this.inputNodeSet = inputNodeSet;
+    }
+
+    /**
+     * Check if the structure needs to be expanded.
+     * @return true if so.
+     */
+    public boolean isNeedsToBeExpanded() {
+        return needsToBeExpanded;
+    }
+
+    /**
+     * Set if the structure needs to be expanded.
+     * @param needsToBeExpanded true if so.
+     */
+    public void setNeedsToBeExpanded(boolean needsToBeExpanded) {
+        this.needsToBeExpanded = needsToBeExpanded;
     }
 
     /**
@@ -218,12 +186,20 @@
      * @throws ParserConfigurationException
      * @throws CanonicalizationException
      */
-    public Set<Node> getNodeSet() throws CanonicalizationException,
-        ParserConfigurationException, IOException, SAXException {
+    public Set<Node> getNodeSet() throws CanonicalizationException, ParserConfigurationException,
+        IOException, SAXException {
         return getNodeSet(false);
     }
 
     /**
+     * Get the Input NodeSet.
+     * @return the Input NodeSet.
+     */
+    public Set<Node> getInputNodeSet() {
+        return inputNodeSet;
+    }
+
+    /**
      * Returns the node set from input which was specified as the parameter of
      * {@link XMLSignatureInput} constructor
      * @param circumvent
@@ -234,51 +210,54 @@
      * @throws ParserConfigurationException
      * @throws CanonicalizationException
      */
-    public Set<Node> getNodeSet(boolean circumvent)
-           throws ParserConfigurationException, IOException, SAXException,
-                  CanonicalizationException {
-        if (this._inputNodeSet!=null) {
-            return this._inputNodeSet;
+    public Set<Node> getNodeSet(boolean circumvent) throws ParserConfigurationException,
+        IOException, SAXException, CanonicalizationException {
+        if (inputNodeSet != null) {
+            return inputNodeSet;
         }
-        if ((this._inputOctetStreamProxy==null)&& (this._subNode!=null) ) {
-
+        if (inputOctetStreamProxy == null && subNode != null) {
             if (circumvent) {
-                XMLUtils.circumventBug2650(XMLUtils.getOwnerDocument(_subNode));
+                XMLUtils.circumventBug2650(XMLUtils.getOwnerDocument(subNode));
             }
-            this._inputNodeSet = new LinkedHashSet<Node>();
-            XMLUtils.getSet(_subNode,this._inputNodeSet, excludeNode, this.excludeComments);
-
-            return this._inputNodeSet;
-        } else if (this.isOctetStream()) {
+            inputNodeSet = new LinkedHashSet<Node>();
+            XMLUtils.getSet(subNode, inputNodeSet, excludeNode, excludeComments);
+            return inputNodeSet;
+        } else if (isOctetStream()) {
             convertToNodes();
-            LinkedHashSet<Node> result = new LinkedHashSet<Node>();
-            XMLUtils.getSet(_subNode, result,null,false);
-            //this._inputNodeSet=result;
+            Set<Node> result = new LinkedHashSet<Node>();
+            XMLUtils.getSet(subNode, result, null, false);
             return result;
         }
 
-        throw new RuntimeException(
-            "getNodeSet() called but no input data present");
+        throw new RuntimeException("getNodeSet() called but no input data present");
     }
 
     /**
-     * Returns the Octect stream(byte Stream) from input which was specified as
+     * Returns the Octet stream(byte Stream) from input which was specified as
      * the parameter of {@link XMLSignatureInput} constructor
      *
-     * @return the Octect stream(byte Stream) from input which was specified as
+     * @return the Octet stream(byte Stream) from input which was specified as
      * the parameter of {@link XMLSignatureInput} constructor
      * @throws IOException
      */
     public InputStream getOctetStream() throws IOException  {
+        if (inputOctetStreamProxy != null) {
+            return inputOctetStreamProxy;
+        }
 
-        return getResetableInputStream();
+        if (bytes != null) {
+            inputOctetStreamProxy = new ByteArrayInputStream(bytes);
+            return inputOctetStreamProxy;
+        }
+
+        return null;
     }
 
     /**
-     * @return real octect stream
+     * @return real octet stream
      */
-    public InputStream getOctetStreamReal () {
-        return this._inputOctetStreamProxy;
+    public InputStream getOctetStreamReal() {
+        return inputOctetStreamProxy;
     }
 
     /**
@@ -292,21 +271,12 @@
      * @throws IOException
      */
     public byte[] getBytes() throws IOException, CanonicalizationException {
-        if (bytes!=null) {
-            return bytes;
+        byte[] inputBytes = getBytesFromInputStream();
+        if (inputBytes != null) {
+            return inputBytes;
         }
-        InputStream is = getResetableInputStream();
-        if (is!=null) {
-            //resetable can read again bytes.
-            if (bytes==null) {
-                is.reset();
-                bytes=JavaUtils.getBytesFromStream(is);
-            }
-            return bytes;
-        }
-        Canonicalizer20010315OmitComments c14nizer =
-                new Canonicalizer20010315OmitComments();
-        bytes=c14nizer.engineCanonicalize(this);
+        Canonicalizer20010315OmitComments c14nizer = new Canonicalizer20010315OmitComments();
+        bytes = c14nizer.engineCanonicalize(this);
         return bytes;
     }
 
@@ -316,18 +286,18 @@
      * @return true if the object has been set up with a Node set
      */
     public boolean isNodeSet() {
-        return (( (this._inputOctetStreamProxy == null)
-              && (this._inputNodeSet != null) ) || isNodeSet);
+        return ((inputOctetStreamProxy == null
+            && inputNodeSet != null) || isNodeSet);
     }
 
     /**
      * Determines if the object has been set up with an Element
      *
-     * @return true if the object has been set up with a Node set
+     * @return true if the object has been set up with an Element
      */
     public boolean isElement() {
-        return ((this._inputOctetStreamProxy==null)&& (this._subNode!=null)
-                && (this._inputNodeSet==null) && !isNodeSet);
+        return (inputOctetStreamProxy == null && subNode != null
+            && inputNodeSet == null && !isNodeSet);
     }
 
     /**
@@ -336,8 +306,8 @@
      * @return true if the object has been set up with an octet stream
      */
     public boolean isOctetStream() {
-        return ( ((this._inputOctetStreamProxy != null) || bytes!=null)
-              && ((this._inputNodeSet == null) && _subNode ==null));
+        return ((inputOctetStreamProxy != null || bytes != null)
+          && (inputNodeSet == null && subNode == null));
     }
 
     /**
@@ -357,8 +327,7 @@
      * @return true is the object has been set up with an octet stream
      */
     public boolean isByteArray() {
-        return ( (bytes!=null)
-              && ((this._inputNodeSet == null) && _subNode ==null));
+        return (bytes != null && (this.inputNodeSet == null && subNode == null));
     }
 
     /**
@@ -367,25 +336,25 @@
      * @return true if the object has been set up correctly
      */
     public boolean isInitialized() {
-        return (this.isOctetStream() || this.isNodeSet());
+        return isOctetStream() || isNodeSet();
     }
 
     /**
-     * Returns MIMEType
+     * Returns mimeType
      *
-     * @return MIMEType
+     * @return mimeType
      */
     public String getMIMEType() {
-        return this._MIMEType;
+        return mimeType;
     }
 
     /**
-     * Sets MIMEType
+     * Sets mimeType
      *
-     * @param MIMEType
+     * @param mimeType
      */
-    public void setMIMEType(String MIMEType) {
-        this._MIMEType = MIMEType;
+    public void setMIMEType(String mimeType) {
+        this.mimeType = mimeType;
     }
 
     /**
@@ -394,16 +363,16 @@
      * @return SourceURI
      */
     public String getSourceURI() {
-        return this._SourceURI;
+        return sourceURI;
     }
 
     /**
      * Sets SourceURI
      *
-     * @param SourceURI
+     * @param sourceURI
      */
-    public void setSourceURI(String SourceURI) {
-        this._SourceURI = SourceURI;
+    public void setSourceURI(String sourceURI) {
+        this.sourceURI = sourceURI;
     }
 
     /**
@@ -411,22 +380,22 @@
      * @inheritDoc
      */
     public String toString() {
-        if (this.isNodeSet()) {
-            return "XMLSignatureInput/NodeSet/" + this._inputNodeSet.size()
-                   + " nodes/" + this.getSourceURI();
+        if (isNodeSet()) {
+            return "XMLSignatureInput/NodeSet/" + inputNodeSet.size()
+                   + " nodes/" + getSourceURI();
         }
-        if (this.isElement()) {
-            return "XMLSignatureInput/Element/" + this._subNode
-                + " exclude "+ this.excludeNode + " comments:" +
-                this.excludeComments +"/" + this.getSourceURI();
+        if (isElement()) {
+            return "XMLSignatureInput/Element/" + subNode
+                + " exclude "+ excludeNode + " comments:"
+                + excludeComments +"/" + getSourceURI();
         }
         try {
-            return "XMLSignatureInput/OctetStream/" + this.getBytes().length
-                   + " octets/" + this.getSourceURI();
+            return "XMLSignatureInput/OctetStream/" + getBytes().length
+                   + " octets/" + getSourceURI();
         } catch (IOException iex) {
-            return "XMLSignatureInput/OctetStream//" + this.getSourceURI();
+            return "XMLSignatureInput/OctetStream//" + getSourceURI();
         } catch (CanonicalizationException cex) {
-            return "XMLSignatureInput/OctetStream//" + this.getSourceURI();
+            return "XMLSignatureInput/OctetStream//" + getSourceURI();
         }
     }
 
@@ -437,9 +406,7 @@
      * @return The HTML representation for this XMLSignature
      */
     public String getHTMLRepresentation() throws XMLSignatureException {
-
         XMLSignatureInputDebugger db = new XMLSignatureInputDebugger(this);
-
         return db.getHTMLRepresentation();
     }
 
@@ -451,11 +418,9 @@
      * @return The HTML representation for this XMLSignature
      */
     public String getHTMLRepresentation(Set<String> inclusiveNamespaces)
-           throws XMLSignatureException {
-
-        XMLSignatureInputDebugger db = new XMLSignatureInputDebugger( this,
-                                        inclusiveNamespaces);
-
+       throws XMLSignatureException {
+        XMLSignatureInputDebugger db =
+            new XMLSignatureInputDebugger(this, inclusiveNamespaces);
         return db.getHTMLRepresentation();
     }
 
@@ -480,7 +445,7 @@
      * @return The excludeNode set.
      */
     public Node getSubNode() {
-        return _subNode;
+        return subNode;
     }
 
     /**
@@ -503,19 +468,18 @@
      * @throws CanonicalizationException
      */
     public void updateOutputStream(OutputStream diOs)
-    throws CanonicalizationException, IOException {
+        throws CanonicalizationException, IOException {
         updateOutputStream(diOs, false);
     }
 
     public void updateOutputStream(OutputStream diOs, boolean c14n11)
-    throws CanonicalizationException, IOException {
-        if (diOs==outputStream) {
+        throws CanonicalizationException, IOException {
+        if (diOs == outputStream) {
             return;
         }
-        if (bytes!=null) {
+        if (bytes != null) {
             diOs.write(bytes);
-            return;
-        } else if (_inputOctetStreamProxy==null) {
+        } else if (inputOctetStreamProxy == null) {
             CanonicalizerBase c14nizer = null;
             if (c14n11) {
                 c14nizer = new Canonicalizer11_OmitComments();
@@ -524,19 +488,16 @@
             }
             c14nizer.setWriter(diOs);
             c14nizer.engineCanonicalize(this);
-            return;
         } else {
-            InputStream is = getResetableInputStream();
-            if (bytes!=null) {
-                //already read write it, can be rea.
-                diOs.write(bytes,0,bytes.length);
-                return;
-            }
-            is.reset();
-            int num;
-            byte[] bytesT = new byte[1024];
-            while ((num=is.read(bytesT))>0) {
-                diOs.write(bytesT,0,num);
+            byte[] buffer = new byte[4 * 1024];
+            int bytesread = 0;
+            try {
+                while ((bytesread = inputOctetStreamProxy.read(buffer)) != -1) {
+                    diOs.write(buffer, 0, bytesread);
+                }
+            } catch (IOException ex) {
+                inputOctetStreamProxy.close();
+                throw ex;
             }
         }
     }
@@ -545,29 +506,22 @@
      * @param os
      */
     public void setOutputStream(OutputStream os) {
-        outputStream=os;
+        outputStream = os;
     }
 
-    protected InputStream getResetableInputStream() throws IOException{
-        if ((_inputOctetStreamProxy instanceof ByteArrayInputStream) ) {
-            if (!_inputOctetStreamProxy.markSupported()) {
-                throw new RuntimeException("Accepted as Markable but not truly been"+_inputOctetStreamProxy);
-            }
-            return _inputOctetStreamProxy;
+    private byte[] getBytesFromInputStream() throws IOException {
+        if (bytes != null) {
+            return bytes;
+        }
+        if (inputOctetStreamProxy == null) {
+            return null;
         }
-        if (bytes!=null) {
-            _inputOctetStreamProxy=new ByteArrayInputStream(bytes);
-            return _inputOctetStreamProxy;
+        try {
+            bytes = JavaUtils.getBytesFromStream(inputOctetStreamProxy);
+        } finally {
+            inputOctetStreamProxy.close();
         }
-        if (_inputOctetStreamProxy ==null)
-            return null;
-        if (_inputOctetStreamProxy.markSupported()) {
-            log.log(java.util.logging.Level.INFO, "Mark Suported but not used as reset");
-        }
-        bytes=JavaUtils.getBytesFromStream(_inputOctetStreamProxy);
-        _inputOctetStreamProxy.close();
-        _inputOctetStreamProxy=new ByteArrayInputStream(bytes);
-        return _inputOctetStreamProxy;
+        return bytes;
     }
 
     /**
@@ -578,7 +532,9 @@
             try {
                 convertToNodes();
             } catch (Exception e) {
-                throw new XMLSecurityRuntimeException("signature.XMLSignatureInput.nodesetReference",e);
+                throw new XMLSecurityRuntimeException(
+                    "signature.XMLSignatureInput.nodesetReference", e
+                );
             }
         }
         nodeFilters.add(filter);
@@ -588,7 +544,6 @@
      * @return the node filters
      */
     public List<NodeFilter> getNodeFilters() {
-        // TODO Auto-generated method stub
         return nodeFilters;
     }
 
@@ -596,39 +551,42 @@
      * @param b
      */
     public void setNodeSet(boolean b) {
-        isNodeSet=b;
+        isNodeSet = b;
     }
 
     void convertToNodes() throws CanonicalizationException,
         ParserConfigurationException, IOException, SAXException {
-        DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
-        dfactory.setValidating(false);
-        dfactory.setNamespaceAware(true);
-        dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
-                            Boolean.TRUE);
+        if (dfactory == null) {
+            dfactory = DocumentBuilderFactory.newInstance();
+            dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
+            dfactory.setValidating(false);
+            dfactory.setNamespaceAware(true);
+        }
         DocumentBuilder db = dfactory.newDocumentBuilder();
         // select all nodes, also the comments.
         try {
-            db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils
-               .IgnoreAllErrorHandler());
+            db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());
 
             Document doc = db.parse(this.getOctetStream());
-
-            this._subNode=doc.getDocumentElement();
+            this.subNode = doc;
         } catch (SAXException ex) {
-
             // if a not-wellformed nodeset exists, put a container around it...
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
 
-            baos.write("<container>".getBytes());
+            baos.write("<container>".getBytes("UTF-8"));
             baos.write(this.getBytes());
-            baos.write("</container>".getBytes());
+            baos.write("</container>".getBytes("UTF-8"));
 
             byte result[] = baos.toByteArray();
             Document document = db.parse(new ByteArrayInputStream(result));
-            this._subNode=document.getDocumentElement().getFirstChild().getFirstChild();
+            this.subNode = document.getDocumentElement().getFirstChild().getFirstChild();
+        } finally {
+            if (this.inputOctetStreamProxy != null) {
+                this.inputOctetStreamProxy.close();
+            }
+            this.inputOctetStreamProxy = null;
+            this.bytes = null;
         }
-        this._inputOctetStreamProxy=null;
-        this.bytes=null;
     }
+
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
@@ -38,681 +40,591 @@
 
 /**
  * Class XMLSignatureInputDebugger
- *
- * @author $Author: mullan $
- * @version $Revision: 1.3 $
  */
 public class XMLSignatureInputDebugger {
 
-
+    /** Field _xmlSignatureInput */
+    private Set<Node> xpathNodeSet;
 
-        /** Field _xmlSignatureInput */
-        private Set<Node> _xpathNodeSet;
+    private Set<String> inclusiveNamespaces;
 
-        private Set<String> _inclusiveNamespaces;
+    /** Field doc */
+    private Document doc = null;
 
-        /** Field _doc */
-        private Document _doc = null;
-
-        /** Field _writer */
-        private Writer _writer = null;
+    /** Field writer */
+    private Writer writer = null;
 
-        // J-
-        // public static final String HTMLPrefix = "<!DOCTYPE HTML PUBLIC
-        // \"-//W3C//DTD HTML 4.01 Transitional//EN\"><html><head><style
-        // type=\"text/css\"><!-- .INCLUDED { color: #000000; background-color:
-        // #FFFFFF; font-weight: bold; } .EXCLUDED { color: #666666;
-        // background-color: #999999; } .INCLUDEDINCLUSIVENAMESPACE { color:
-        // #0000FF; background-color: #FFFFFF; font-weight: bold; font-style:
-        // italic; } .EXCLUDEDINCLUSIVENAMESPACE { color: #0000FF; background-color:
-        // #999999; font-style: italic; } --> </style> </head><body
-        // bgcolor=\"#999999\"><pre>";
-        /** The HTML Prefix* */
-        static final String HTMLPrefix = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"
-                        + "<html>\n"
-                        + "<head>\n"
-                        + "<title>Caninical XML node set</title>\n"
-                        + "<style type=\"text/css\">\n"
-                        + "<!-- \n"
-                        + ".INCLUDED { \n"
-                        + "   color: #000000; \n"
-                        + "   background-color: \n"
-                        + "   #FFFFFF; \n"
-                        + "   font-weight: bold; } \n"
-                        + ".EXCLUDED { \n"
-                        + "   color: #666666; \n"
-                        + "   background-color: \n"
-                        + "   #999999; } \n"
-                        + ".INCLUDEDINCLUSIVENAMESPACE { \n"
-                        + "   color: #0000FF; \n"
-                        + "   background-color: #FFFFFF; \n"
-                        + "   font-weight: bold; \n"
-                        + "   font-style: italic; } \n"
-                        + ".EXCLUDEDINCLUSIVENAMESPACE { \n"
-                        + "   color: #0000FF; \n"
-                        + "   background-color: #999999; \n"
-                        + "   font-style: italic; } \n"
-                        + "--> \n"
-                        + "</style> \n"
-                        + "</head>\n"
-                        + "<body bgcolor=\"#999999\">\n"
-                        + "<h1>Explanation of the output</h1>\n"
-                        + "<p>The following text contains the nodeset of the given Reference before it is canonicalized. There exist four different styles to indicate how a given node is treated.</p>\n"
-                        + "<ul>\n"
-                        + "<li class=\"INCLUDED\">A node which is in the node set is labeled using the INCLUDED style.</li>\n"
-                        + "<li class=\"EXCLUDED\">A node which is <em>NOT</em> in the node set is labeled EXCLUDED style.</li>\n"
-                        + "<li class=\"INCLUDEDINCLUSIVENAMESPACE\">A namespace which is in the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.</li>\n"
-                        + "<li class=\"EXCLUDEDINCLUSIVENAMESPACE\">A namespace which is in NOT the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.</li>\n"
-                        + "</ul>\n" + "<h1>Output</h1>\n" + "<pre>\n";
+    /** The HTML Prefix* */
+    static final String HTMLPrefix =
+        "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"
+        + "<html>\n"
+        + "<head>\n"
+        + "<title>Caninical XML node set</title>\n"
+        + "<style type=\"text/css\">\n"
+        + "<!-- \n"
+        + ".INCLUDED { \n"
+        + "   color: #000000; \n"
+        + "   background-color: \n"
+        + "   #FFFFFF; \n"
+        + "   font-weight: bold; } \n"
+        + ".EXCLUDED { \n"
+        + "   color: #666666; \n"
+        + "   background-color: \n"
+        + "   #999999; } \n"
+        + ".INCLUDEDINCLUSIVENAMESPACE { \n"
+        + "   color: #0000FF; \n"
+        + "   background-color: #FFFFFF; \n"
+        + "   font-weight: bold; \n"
+        + "   font-style: italic; } \n"
+        + ".EXCLUDEDINCLUSIVENAMESPACE { \n"
+        + "   color: #0000FF; \n"
+        + "   background-color: #999999; \n"
+        + "   font-style: italic; } \n"
+        + "--> \n"
+        + "</style> \n"
+        + "</head>\n"
+        + "<body bgcolor=\"#999999\">\n"
+        + "<h1>Explanation of the output</h1>\n"
+        + "<p>The following text contains the nodeset of the given Reference before it is canonicalized. There exist four different styles to indicate how a given node is treated.</p>\n"
+        + "<ul>\n"
+        + "<li class=\"INCLUDED\">A node which is in the node set is labeled using the INCLUDED style.</li>\n"
+        + "<li class=\"EXCLUDED\">A node which is <em>NOT</em> in the node set is labeled EXCLUDED style.</li>\n"
+        + "<li class=\"INCLUDEDINCLUSIVENAMESPACE\">A namespace which is in the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.</li>\n"
+        + "<li class=\"EXCLUDEDINCLUSIVENAMESPACE\">A namespace which is in NOT the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.</li>\n"
+        + "</ul>\n" + "<h1>Output</h1>\n" + "<pre>\n";
 
-        /** HTML Suffix * */
-        static final String HTMLSuffix = "</pre></body></html>";
-
-        static final String HTMLExcludePrefix = "<span class=\"EXCLUDED\">";
-
-        static final String HTMLExcludeSuffix = "</span>";
-
-        static final String HTMLIncludePrefix = "<span class=\"INCLUDED\">";
-
-        static final String HTMLIncludeSuffix = "</span>";
-
-        static final String HTMLIncludedInclusiveNamespacePrefix = "<span class=\"INCLUDEDINCLUSIVENAMESPACE\">";
-
-        static final String HTMLIncludedInclusiveNamespaceSuffix = "</span>";
-
-        static final String HTMLExcludedInclusiveNamespacePrefix = "<span class=\"EXCLUDEDINCLUSIVENAMESPACE\">";
+    /** HTML Suffix * */
+    static final String HTMLSuffix = "</pre></body></html>";
 
-        static final String HTMLExcludedInclusiveNamespaceSuffix = "</span>";
+    static final String HTMLExcludePrefix = "<span class=\"EXCLUDED\">";
 
-        private static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1;
-
-        private static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0;
+    static final String HTMLIncludePrefix = "<span class=\"INCLUDED\">";
 
-        private static final int NODE_AFTER_DOCUMENT_ELEMENT = 1;
-
-        static final AttrCompare ATTR_COMPARE = new AttrCompare();
+    static final String HTMLIncludeOrExcludeSuffix = "</span>";
 
-        // J+
-        private XMLSignatureInputDebugger() {
-                // do nothing
-        }
+    static final String HTMLIncludedInclusiveNamespacePrefix = "<span class=\"INCLUDEDINCLUSIVENAMESPACE\">";
 
-        /**
-         * Constructor XMLSignatureInputDebugger
-         *
-         * @param xmlSignatureInput the signatur to pretty print
-         */
-        public XMLSignatureInputDebugger(
-                        XMLSignatureInput xmlSignatureInput) {
+    static final String HTMLExcludedInclusiveNamespacePrefix = "<span class=\"EXCLUDEDINCLUSIVENAMESPACE\">";
+
+    private static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1;
 
-                if (!xmlSignatureInput.isNodeSet()) {
-                        this._xpathNodeSet = null;
-                } else {
-                        this._xpathNodeSet = xmlSignatureInput._inputNodeSet;
-                }
-        }
+    private static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0;
 
-        /**
-         * Constructor XMLSignatureInputDebugger
-         *
-         * @param xmlSignatureInput the signatur to pretty print
-         * @param inclusiveNamespace
-         */
-        public XMLSignatureInputDebugger(
-                        XMLSignatureInput xmlSignatureInput, Set<String> inclusiveNamespace) {
+    private static final int NODE_AFTER_DOCUMENT_ELEMENT = 1;
+
+    static final AttrCompare ATTR_COMPARE = new AttrCompare();
 
-                this(xmlSignatureInput);
-
-                this._inclusiveNamespaces = inclusiveNamespace;
+    /**
+     * Constructor XMLSignatureInputDebugger
+     *
+     * @param xmlSignatureInput the signature to pretty print
+     */
+    public XMLSignatureInputDebugger(XMLSignatureInput xmlSignatureInput) {
+        if (!xmlSignatureInput.isNodeSet()) {
+            this.xpathNodeSet = null;
+        } else {
+            this.xpathNodeSet = xmlSignatureInput.getInputNodeSet();
         }
-
-        /**
-         * Method getHTMLRepresentation
-         *
-         * @return The HTML Representation.
-         * @throws XMLSignatureException
-         */
-        public String getHTMLRepresentation() throws XMLSignatureException {
-
-                if ((this._xpathNodeSet == null) || (this._xpathNodeSet.size() == 0)) {
-                        return HTMLPrefix + "<blink>no node set, sorry</blink>"
-                                        + HTMLSuffix;
-                }
-
-                {
+    }
 
-                        // get only a single node as anchor to fetch the owner document
-                        Node n = this._xpathNodeSet.iterator().next();
-
-                        this._doc = XMLUtils.getOwnerDocument(n);
-                }
-
-                try {
-                        this._writer = new StringWriter();
+    /**
+     * Constructor XMLSignatureInputDebugger
+     *
+     * @param xmlSignatureInput the signatur to pretty print
+     * @param inclusiveNamespace
+     */
+    public XMLSignatureInputDebugger(
+        XMLSignatureInput xmlSignatureInput,
+        Set<String> inclusiveNamespace
+    ) {
+        this(xmlSignatureInput);
+        this.inclusiveNamespaces = inclusiveNamespace;
+    }
 
-                        this.canonicalizeXPathNodeSet(this._doc);
-                        this._writer.close();
-
-                        return this._writer.toString();
-                } catch (IOException ex) {
-                        throw new XMLSignatureException("empty", ex);
-                } finally {
-                        this._xpathNodeSet = null;
-                        this._doc = null;
-                        this._writer = null;
-                }
+    /**
+     * Method getHTMLRepresentation
+     *
+     * @return The HTML Representation.
+     * @throws XMLSignatureException
+     */
+    public String getHTMLRepresentation() throws XMLSignatureException {
+        if ((this.xpathNodeSet == null) || (this.xpathNodeSet.size() == 0)) {
+            return HTMLPrefix + "<blink>no node set, sorry</blink>" + HTMLSuffix;
         }
 
-        /**
-         * Method canonicalizeXPathNodeSet
-         *
-         * @param currentNode
-         * @throws XMLSignatureException
-         * @throws IOException
-         */
-        private void canonicalizeXPathNodeSet(Node currentNode)
-                        throws XMLSignatureException, IOException {
+        // get only a single node as anchor to fetch the owner document
+        Node n = this.xpathNodeSet.iterator().next();
 
-                int currentNodeType = currentNode.getNodeType();
-                switch (currentNodeType) {
-
-                case Node.DOCUMENT_TYPE_NODE:
-                default:
-                        break;
+        this.doc = XMLUtils.getOwnerDocument(n);
 
-                case Node.ENTITY_NODE:
-                case Node.NOTATION_NODE:
-                case Node.DOCUMENT_FRAGMENT_NODE:
-                case Node.ATTRIBUTE_NODE:
-                        throw new XMLSignatureException("empty");
-                case Node.DOCUMENT_NODE:
-                        this._writer.write(HTMLPrefix);
-
-                        for (Node currentChild = currentNode.getFirstChild(); currentChild != null; currentChild = currentChild
-                                        .getNextSibling()) {
-                                this.canonicalizeXPathNodeSet(currentChild);
-                        }
+        try {
+            this.writer = new StringWriter();
 
-                        this._writer.write(HTMLSuffix);
-                        break;
-
-                case Node.COMMENT_NODE:
-                        if (this._xpathNodeSet.contains(currentNode)) {
-                                this._writer.write(HTMLIncludePrefix);
-                        } else {
-                                this._writer.write(HTMLExcludePrefix);
-                        }
-
-                        int position = getPositionRelativeToDocumentElement(currentNode);
-
-                        if (position == NODE_AFTER_DOCUMENT_ELEMENT) {
-                                this._writer.write("\n");
-                        }
-
-                        this.outputCommentToWriter((Comment) currentNode);
+            this.canonicalizeXPathNodeSet(this.doc);
+            this.writer.close();
 
-                        if (position == NODE_BEFORE_DOCUMENT_ELEMENT) {
-                                this._writer.write("\n");
-                        }
-
-                        if (this._xpathNodeSet.contains(currentNode)) {
-                                this._writer.write(HTMLIncludeSuffix);
-                        } else {
-                                this._writer.write(HTMLExcludeSuffix);
-                        }
-                        break;
-
-                case Node.PROCESSING_INSTRUCTION_NODE:
-                        if (this._xpathNodeSet.contains(currentNode)) {
-                                this._writer.write(HTMLIncludePrefix);
-                        } else {
-                                this._writer.write(HTMLExcludePrefix);
-                        }
-
-                        position = getPositionRelativeToDocumentElement(currentNode);
-
-                        if (position == NODE_AFTER_DOCUMENT_ELEMENT) {
-                                this._writer.write("\n");
-                        }
-
-                        this.outputPItoWriter((ProcessingInstruction) currentNode);
+            return this.writer.toString();
+        } catch (IOException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } finally {
+            this.xpathNodeSet = null;
+            this.doc = null;
+            this.writer = null;
+        }
+    }
 
-                        if (position == NODE_BEFORE_DOCUMENT_ELEMENT) {
-                                this._writer.write("\n");
-                        }
-
-                        if (this._xpathNodeSet.contains(currentNode)) {
-                                this._writer.write(HTMLIncludeSuffix);
-                        } else {
-                                this._writer.write(HTMLExcludeSuffix);
-                        }
-                        break;
+    /**
+     * Method canonicalizeXPathNodeSet
+     *
+     * @param currentNode
+     * @throws XMLSignatureException
+     * @throws IOException
+     */
+    private void canonicalizeXPathNodeSet(Node currentNode)
+        throws XMLSignatureException, IOException {
 
-                case Node.TEXT_NODE:
-                case Node.CDATA_SECTION_NODE:
-                        if (this._xpathNodeSet.contains(currentNode)) {
-                                this._writer.write(HTMLIncludePrefix);
-                        } else {
-                                this._writer.write(HTMLExcludePrefix);
-                        }
+        int currentNodeType = currentNode.getNodeType();
+        switch (currentNodeType) {
 
-                        outputTextToWriter(currentNode.getNodeValue());
-
-                        for (Node nextSibling = currentNode.getNextSibling(); (nextSibling != null)
-                                        && ((nextSibling.getNodeType() == Node.TEXT_NODE) || (nextSibling
-                                                        .getNodeType() == Node.CDATA_SECTION_NODE)); nextSibling = nextSibling
-                                        .getNextSibling()) {
 
-                                /*
-                                 * The XPath data model allows to select only the first of a
-                                 * sequence of mixed text and CDATA nodes. But we must output
-                                 * them all, so we must search:
-                                 *
-                                 * @see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=6329
-                                 */
-                                this.outputTextToWriter(nextSibling.getNodeValue());
-                        }
-
-                        if (this._xpathNodeSet.contains(currentNode)) {
-                                this._writer.write(HTMLIncludeSuffix);
-                        } else {
-                                this._writer.write(HTMLExcludeSuffix);
-                        }
-                        break;
-
-                case Node.ELEMENT_NODE:
-                        Element currentElement = (Element) currentNode;
+        case Node.ENTITY_NODE:
+        case Node.NOTATION_NODE:
+        case Node.DOCUMENT_FRAGMENT_NODE:
+        case Node.ATTRIBUTE_NODE:
+            throw new XMLSignatureException("empty");
+        case Node.DOCUMENT_NODE:
+            this.writer.write(HTMLPrefix);
 
-                        if (this._xpathNodeSet.contains(currentNode)) {
-                                this._writer.write(HTMLIncludePrefix);
-                        } else {
-                                this._writer.write(HTMLExcludePrefix);
-                        }
-
-                        this._writer.write("&lt;");
-                        this._writer.write(currentElement.getTagName());
+            for (Node currentChild = currentNode.getFirstChild();
+                currentChild != null; currentChild = currentChild.getNextSibling()) {
+                this.canonicalizeXPathNodeSet(currentChild);
+            }
 
-                        if (this._xpathNodeSet.contains(currentNode)) {
-                                this._writer.write(HTMLIncludeSuffix);
-                        } else {
-                                this._writer.write(HTMLExcludeSuffix);
-                        }
+            this.writer.write(HTMLSuffix);
+            break;
 
-                        // we output all Attrs which are available
-                        NamedNodeMap attrs = currentElement.getAttributes();
-                        int attrsLength = attrs.getLength();
-                        Attr attrs2[] = new Attr[attrsLength];
-
-                        for (int i = 0; i < attrsLength; i++) {
-                                attrs2[i] = (Attr)attrs.item(i);
-                        }
-
-                        Arrays.sort(attrs2, ATTR_COMPARE);
-                        Object attrs3[] = attrs2;
+        case Node.COMMENT_NODE:
+            if (this.xpathNodeSet.contains(currentNode)) {
+                this.writer.write(HTMLIncludePrefix);
+            } else {
+                this.writer.write(HTMLExcludePrefix);
+            }
 
-                        for (int i = 0; i < attrsLength; i++) {
-                                Attr a = (Attr) attrs3[i];
-                                boolean included = this._xpathNodeSet.contains(a);
-                                boolean inclusive = this._inclusiveNamespaces.contains(a
-                                                .getName());
+            int position = getPositionRelativeToDocumentElement(currentNode);
 
-                                if (included) {
-                                        if (inclusive) {
+            if (position == NODE_AFTER_DOCUMENT_ELEMENT) {
+                this.writer.write("\n");
+            }
 
-                                                // included and inclusive
-                                                this._writer
-                                                                .write(HTMLIncludedInclusiveNamespacePrefix);
-                                        } else {
+            this.outputCommentToWriter((Comment) currentNode);
 
-                                                // included and not inclusive
-                                                this._writer.write(HTMLIncludePrefix);
-                                        }
-                                } else {
-                                        if (inclusive) {
-
-                                                // excluded and inclusive
-                                                this._writer
-                                                                .write(HTMLExcludedInclusiveNamespacePrefix);
-                                        } else {
+            if (position == NODE_BEFORE_DOCUMENT_ELEMENT) {
+                this.writer.write("\n");
+            }
 
-                                                // excluded and not inclusive
-                                                this._writer.write(HTMLExcludePrefix);
-                                        }
-                                }
-
-                                this.outputAttrToWriter(a.getNodeName(), a.getNodeValue());
-
-                                if (included) {
-                                        if (inclusive) {
-
-                                                // included and inclusive
-                                                this._writer
-                                                                .write(HTMLIncludedInclusiveNamespaceSuffix);
-                                        } else {
+            this.writer.write(HTMLIncludeOrExcludeSuffix);
+            break;
 
-                                                // included and not inclusive
-                                                this._writer.write(HTMLIncludeSuffix);
-                                        }
-                                } else {
-                                        if (inclusive) {
+        case Node.PROCESSING_INSTRUCTION_NODE:
+            if (this.xpathNodeSet.contains(currentNode)) {
+                this.writer.write(HTMLIncludePrefix);
+            } else {
+                this.writer.write(HTMLExcludePrefix);
+            }
 
-                                                // excluded and inclusive
-                                                this._writer
-                                                                .write(HTMLExcludedInclusiveNamespaceSuffix);
-                                        } else {
-
-                                                // excluded and not inclusive
-                                                this._writer.write(HTMLExcludeSuffix);
-                                        }
-                                }
-                        }
+            position = getPositionRelativeToDocumentElement(currentNode);
 
-                        if (this._xpathNodeSet.contains(currentNode)) {
-                                this._writer.write(HTMLIncludePrefix);
-                        } else {
-                                this._writer.write(HTMLExcludePrefix);
-                        }
+            if (position == NODE_AFTER_DOCUMENT_ELEMENT) {
+                this.writer.write("\n");
+            }
 
-                        this._writer.write("&gt;");
+            this.outputPItoWriter((ProcessingInstruction) currentNode);
 
-                        if (this._xpathNodeSet.contains(currentNode)) {
-                                this._writer.write(HTMLIncludeSuffix);
-                        } else {
-                                this._writer.write(HTMLExcludeSuffix);
-                        }
+            if (position == NODE_BEFORE_DOCUMENT_ELEMENT) {
+                this.writer.write("\n");
+            }
 
-                        // traversal
-                        for (Node currentChild = currentNode.getFirstChild(); currentChild != null; currentChild = currentChild
-                                        .getNextSibling()) {
-                                this.canonicalizeXPathNodeSet(currentChild);
-                        }
-
-                        if (this._xpathNodeSet.contains(currentNode)) {
-                                this._writer.write(HTMLIncludePrefix);
-                        } else {
-                                this._writer.write(HTMLExcludePrefix);
-                        }
+            this.writer.write(HTMLIncludeOrExcludeSuffix);
+            break;
 
-                        this._writer.write("&lt;/");
-                        this._writer.write(currentElement.getTagName());
-                        this._writer.write("&gt;");
-
-                        if (this._xpathNodeSet.contains(currentNode)) {
-                                this._writer.write(HTMLIncludeSuffix);
-                        } else {
-                                this._writer.write(HTMLExcludeSuffix);
-                        }
-                        break;
-                }
-        }
+        case Node.TEXT_NODE:
+        case Node.CDATA_SECTION_NODE:
+            if (this.xpathNodeSet.contains(currentNode)) {
+                this.writer.write(HTMLIncludePrefix);
+            } else {
+                this.writer.write(HTMLExcludePrefix);
+            }
 
-        /**
-         * Checks whether a Comment or ProcessingInstruction is before or after the
-         * document element. This is needed for prepending or appending "\n"s.
-         *
-         * @param currentNode
-         *            comment or pi to check
-         * @return NODE_BEFORE_DOCUMENT_ELEMENT,
-         *         NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT or
-         *         NODE_AFTER_DOCUMENT_ELEMENT
-         * @see #NODE_BEFORE_DOCUMENT_ELEMENT
-         * @see #NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT
-         * @see #NODE_AFTER_DOCUMENT_ELEMENT
-         */
-        private int getPositionRelativeToDocumentElement(Node currentNode) {
-
-                if (currentNode == null) {
-                        return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
-                }
-
-                Document doc = currentNode.getOwnerDocument();
-
-                if (currentNode.getParentNode() != doc) {
-                        return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
-                }
-
-                Element documentElement = doc.getDocumentElement();
-
-                if (documentElement == null) {
-                        return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
-                }
+            outputTextToWriter(currentNode.getNodeValue());
 
-                if (documentElement == currentNode) {
-                        return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
-                }
-
-                for (Node x = currentNode; x != null; x = x.getNextSibling()) {
-                        if (x == documentElement) {
-                                return NODE_BEFORE_DOCUMENT_ELEMENT;
-                        }
-                }
-
-                return NODE_AFTER_DOCUMENT_ELEMENT;
-        }
+            for (Node nextSibling = currentNode.getNextSibling();
+                (nextSibling != null)
+                && ((nextSibling.getNodeType() == Node.TEXT_NODE)
+                    || (nextSibling.getNodeType() == Node.CDATA_SECTION_NODE));
+                nextSibling = nextSibling.getNextSibling()) {
+                /*
+                 * The XPath data model allows to select only the first of a
+                 * sequence of mixed text and CDATA nodes. But we must output
+                 * them all, so we must search:
+                 *
+                 * @see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=6329
+                 */
+                this.outputTextToWriter(nextSibling.getNodeValue());
+            }
 
-        /**
-         * Normalizes an {@link Attr}ibute value
-         *
-         * The string value of the node is modified by replacing
-         * <UL>
-         * <LI>all ampersands (&) with <CODE>&amp;amp;</CODE></LI>
-         * <LI>all open angle brackets (<) with <CODE>&amp;lt;</CODE></LI>
-         * <LI>all quotation mark characters with <CODE>&amp;quot;</CODE></LI>
-         * <LI>and the whitespace characters <CODE>#x9</CODE>, #xA, and #xD,
-         * with character references. The character references are written in
-         * uppercase hexadecimal with no leading zeroes (for example, <CODE>#xD</CODE>
-         * is represented by the character reference <CODE>&amp;#xD;</CODE>)</LI>
-         * </UL>
-         *
-         * @param name
-         * @param value
-         * @throws IOException
-         */
-        private void outputAttrToWriter(String name, String value)
-                        throws IOException {
+            this.writer.write(HTMLIncludeOrExcludeSuffix);
+            break;
+
+        case Node.ELEMENT_NODE:
+            Element currentElement = (Element) currentNode;
 
-                this._writer.write(" ");
-                this._writer.write(name);
-                this._writer.write("=\"");
-
-                int length = value.length();
-
-                for (int i = 0; i < length; i++) {
-                        char c = value.charAt(i);
-
-                        switch (c) {
+            if (this.xpathNodeSet.contains(currentNode)) {
+                this.writer.write(HTMLIncludePrefix);
+            } else {
+                this.writer.write(HTMLExcludePrefix);
+            }
 
-                        case '&':
-                                this._writer.write("&amp;amp;");
-                                break;
-
-                        case '<':
-                                this._writer.write("&amp;lt;");
-                                break;
-
-                        case '"':
-                                this._writer.write("&amp;quot;");
-                                break;
+            this.writer.write("&lt;");
+            this.writer.write(currentElement.getTagName());
 
-                        case 0x09: // '\t'
-                                this._writer.write("&amp;#x9;");
-                                break;
-
-                        case 0x0A: // '\n'
-                                this._writer.write("&amp;#xA;");
-                                break;
-
-                        case 0x0D: // '\r'
-                                this._writer.write("&amp;#xD;");
-                                break;
+            this.writer.write(HTMLIncludeOrExcludeSuffix);
 
-                        default:
-                                this._writer.write(c);
-                                break;
-                        }
-                }
-
-                this._writer.write("\"");
-        }
+            // we output all Attrs which are available
+            NamedNodeMap attrs = currentElement.getAttributes();
+            int attrsLength = attrs.getLength();
+            Attr attrs2[] = new Attr[attrsLength];
 
-        /**
-         * Normalizes a {@link org.w3c.dom.Comment} value
-         *
-         * @param currentPI
-         * @throws IOException
-         */
-        private void outputPItoWriter(ProcessingInstruction currentPI)
-                        throws IOException {
+            for (int i = 0; i < attrsLength; i++) {
+                attrs2[i] = (Attr)attrs.item(i);
+            }
 
-                if (currentPI == null) {
-                        return;
-                }
-
-                this._writer.write("&lt;?");
-
-                String target = currentPI.getTarget();
-                int length = target.length();
-
-                for (int i = 0; i < length; i++) {
-                        char c = target.charAt(i);
+            Arrays.sort(attrs2, ATTR_COMPARE);
+            Object attrs3[] = attrs2;
 
-                        switch (c) {
-
-                        case 0x0D:
-                                this._writer.write("&amp;#xD;");
-                                break;
-
-                        case ' ':
-                                this._writer.write("&middot;");
-                                break;
-
-                        case '\n':
-                                this._writer.write("&para;\n");
-                                break;
+            for (int i = 0; i < attrsLength; i++) {
+                Attr a = (Attr) attrs3[i];
+                boolean included = this.xpathNodeSet.contains(a);
+                boolean inclusive = this.inclusiveNamespaces.contains(a.getName());
 
-                        default:
-                                this._writer.write(c);
-                                break;
-                        }
-                }
-
-                String data = currentPI.getData();
-
-                length = data.length();
-
-                if (length > 0) {
-                    this._writer.write(" ");
-
-                    for (int i = 0; i < length; i++) {
-                        char c = data.charAt(i);
-
-                        switch (c) {
-
-                            case 0x0D:
-                                this._writer.write("&amp;#xD;");
-                                break;
-
-                            default:
-                                this._writer.write(c);
-                                break;
-                        }
+                if (included) {
+                    if (inclusive) {
+                        // included and inclusive
+                        this.writer.write(HTMLIncludedInclusiveNamespacePrefix);
+                    } else {
+                        // included and not inclusive
+                        this.writer.write(HTMLIncludePrefix);
+                    }
+                } else {
+                    if (inclusive) {
+                        // excluded and inclusive
+                        this.writer.write(HTMLExcludedInclusiveNamespacePrefix);
+                    } else {
+                        // excluded and not inclusive
+                        this.writer.write(HTMLExcludePrefix);
                     }
                 }
 
-                this._writer.write("?&gt;");
+                this.outputAttrToWriter(a.getNodeName(), a.getNodeValue());
+                this.writer.write(HTMLIncludeOrExcludeSuffix);
+            }
+
+            if (this.xpathNodeSet.contains(currentNode)) {
+                this.writer.write(HTMLIncludePrefix);
+            } else {
+                this.writer.write(HTMLExcludePrefix);
+            }
+
+            this.writer.write("&gt;");
+
+            this.writer.write(HTMLIncludeOrExcludeSuffix);
+
+            // traversal
+            for (Node currentChild = currentNode.getFirstChild();
+                currentChild != null;
+                currentChild = currentChild.getNextSibling()) {
+                this.canonicalizeXPathNodeSet(currentChild);
+            }
+
+            if (this.xpathNodeSet.contains(currentNode)) {
+                this.writer.write(HTMLIncludePrefix);
+            } else {
+                this.writer.write(HTMLExcludePrefix);
+            }
+
+            this.writer.write("&lt;/");
+            this.writer.write(currentElement.getTagName());
+            this.writer.write("&gt;");
+
+            this.writer.write(HTMLIncludeOrExcludeSuffix);
+            break;
+
+        case Node.DOCUMENT_TYPE_NODE:
+        default:
+            break;
+        }
+    }
+
+    /**
+     * Checks whether a Comment or ProcessingInstruction is before or after the
+     * document element. This is needed for prepending or appending "\n"s.
+     *
+     * @param currentNode
+     *            comment or pi to check
+     * @return NODE_BEFORE_DOCUMENT_ELEMENT,
+     *         NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT or
+     *         NODE_AFTER_DOCUMENT_ELEMENT
+     * @see #NODE_BEFORE_DOCUMENT_ELEMENT
+     * @see #NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT
+     * @see #NODE_AFTER_DOCUMENT_ELEMENT
+     */
+    private int getPositionRelativeToDocumentElement(Node currentNode) {
+        if (currentNode == null) {
+            return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
+        }
+
+        Document doc = currentNode.getOwnerDocument();
+
+        if (currentNode.getParentNode() != doc) {
+            return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
+        }
+
+        Element documentElement = doc.getDocumentElement();
+
+        if (documentElement == null) {
+            return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
         }
 
-        /**
-         * Method outputCommentToWriter
-         *
-         * @param currentComment
-         * @throws IOException
-         */
-        private void outputCommentToWriter(Comment currentComment)
-                        throws IOException {
+        if (documentElement == currentNode) {
+            return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
+        }
+
+        for (Node x = currentNode; x != null; x = x.getNextSibling()) {
+            if (x == documentElement) {
+                return NODE_BEFORE_DOCUMENT_ELEMENT;
+            }
+        }
+
+        return NODE_AFTER_DOCUMENT_ELEMENT;
+    }
 
-                if (currentComment == null) {
-                        return;
-                }
-
-                this._writer.write("&lt;!--");
-
-                String data = currentComment.getData();
-                int length = data.length();
-
-                for (int i = 0; i < length; i++) {
-                        char c = data.charAt(i);
+    /**
+     * Normalizes an {@link Attr}ibute value
+     *
+     * The string value of the node is modified by replacing
+     * <UL>
+     * <LI>all ampersands (&) with <CODE>&amp;amp;</CODE></LI>
+     * <LI>all open angle brackets (<) with <CODE>&amp;lt;</CODE></LI>
+     * <LI>all quotation mark characters with <CODE>&amp;quot;</CODE></LI>
+     * <LI>and the whitespace characters <CODE>#x9</CODE>, #xA, and #xD,
+     * with character references. The character references are written in
+     * uppercase hexadecimal with no leading zeroes (for example, <CODE>#xD</CODE>
+     * is represented by the character reference <CODE>&amp;#xD;</CODE>)</LI>
+     * </UL>
+     *
+     * @param name
+     * @param value
+     * @throws IOException
+     */
+    private void outputAttrToWriter(String name, String value) throws IOException {
+        this.writer.write(" ");
+        this.writer.write(name);
+        this.writer.write("=\"");
 
-                        switch (c) {
+        int length = value.length();
+
+        for (int i = 0; i < length; i++) {
+            char c = value.charAt(i);
+
+            switch (c) {
 
-                        case 0x0D:
-                                this._writer.write("&amp;#xD;");
-                                break;
+            case '&':
+                this.writer.write("&amp;amp;");
+                break;
 
-                        case ' ':
-                                this._writer.write("&middot;");
-                                break;
+            case '<':
+                this.writer.write("&amp;lt;");
+                break;
 
-                        case '\n':
-                                this._writer.write("&para;\n");
-                                break;
+            case '"':
+                this.writer.write("&amp;quot;");
+                break;
+
+            case 0x09: // '\t'
+                this.writer.write("&amp;#x9;");
+                break;
 
-                        default:
-                                this._writer.write(c);
-                                break;
-                        }
-                }
+            case 0x0A: // '\n'
+                this.writer.write("&amp;#xA;");
+                break;
 
-                this._writer.write("--&gt;");
+            case 0x0D: // '\r'
+                this.writer.write("&amp;#xD;");
+                break;
+
+            default:
+                this.writer.write(c);
+                break;
+            }
         }
 
-        /**
-         * Method outputTextToWriter
-         *
-         * @param text
-         * @throws IOException
-         */
-        private void outputTextToWriter(String text) throws IOException {
+        this.writer.write("\"");
+    }
+
+    /**
+     * Normalizes a {@link org.w3c.dom.Comment} value
+     *
+     * @param currentPI
+     * @throws IOException
+     */
+    private void outputPItoWriter(ProcessingInstruction currentPI) throws IOException {
+
+        if (currentPI == null) {
+            return;
+        }
+
+        this.writer.write("&lt;?");
+
+        String target = currentPI.getTarget();
+        int length = target.length();
+
+        for (int i = 0; i < length; i++) {
+            char c = target.charAt(i);
+
+            switch (c) {
+
+            case 0x0D:
+                this.writer.write("&amp;#xD;");
+                break;
 
-                if (text == null) {
-                        return;
+            case ' ':
+                this.writer.write("&middot;");
+                break;
+
+            case '\n':
+                this.writer.write("&para;\n");
+                break;
+
+            default:
+                this.writer.write(c);
+                break;
+            }
+        }
+
+        String data = currentPI.getData();
+
+        length = data.length();
+
+        if (length > 0) {
+            this.writer.write(" ");
+
+            for (int i = 0; i < length; i++) {
+                char c = data.charAt(i);
+
+                switch (c) {
+
+                case 0x0D:
+                    this.writer.write("&amp;#xD;");
+                    break;
+
+                default:
+                    this.writer.write(c);
+                    break;
                 }
-
-                int length = text.length();
+            }
+        }
 
-                for (int i = 0; i < length; i++) {
-                        char c = text.charAt(i);
+        this.writer.write("?&gt;");
+    }
 
-                        switch (c) {
+    /**
+     * Method outputCommentToWriter
+     *
+     * @param currentComment
+     * @throws IOException
+     */
+    private void outputCommentToWriter(Comment currentComment) throws IOException {
 
-                        case '&':
-                                this._writer.write("&amp;amp;");
-                                break;
+        if (currentComment == null) {
+            return;
+        }
 
-                        case '<':
-                                this._writer.write("&amp;lt;");
-                                break;
+        this.writer.write("&lt;!--");
+
+        String data = currentComment.getData();
+        int length = data.length();
+
+        for (int i = 0; i < length; i++) {
+            char c = data.charAt(i);
+
+            switch (c) {
+
+            case 0x0D:
+                this.writer.write("&amp;#xD;");
+                break;
 
-                        case '>':
-                                this._writer.write("&amp;gt;");
-                                break;
+            case ' ':
+                this.writer.write("&middot;");
+                break;
+
+            case '\n':
+                this.writer.write("&para;\n");
+                break;
 
-                        case 0xD:
-                                this._writer.write("&amp;#xD;");
-                                break;
+            default:
+                this.writer.write(c);
+                break;
+            }
+        }
+
+        this.writer.write("--&gt;");
+    }
 
-                        case ' ':
-                                this._writer.write("&middot;");
-                                break;
+    /**
+     * Method outputTextToWriter
+     *
+     * @param text
+     * @throws IOException
+     */
+    private void outputTextToWriter(String text) throws IOException {
+        if (text == null) {
+            return;
+        }
 
-                        case '\n':
-                                this._writer.write("&para;\n");
-                                break;
+        int length = text.length();
+
+        for (int i = 0; i < length; i++) {
+            char c = text.charAt(i);
+
+            switch (c) {
+
+            case '&':
+                this.writer.write("&amp;amp;");
+                break;
 
-                        default:
-                                this._writer.write(c);
-                                break;
-                        }
-                }
+            case '<':
+                this.writer.write("&amp;lt;");
+                break;
+
+            case '>':
+                this.writer.write("&amp;gt;");
+                break;
+
+            case 0xD:
+                this.writer.write("&amp;#xD;");
+                break;
+
+            case ' ':
+                this.writer.write("&middot;");
+                break;
+
+            case '\n':
+                this.writer.write("&para;\n");
+                break;
+
+            default:
+                this.writer.write(c);
+                break;
+            }
         }
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,34 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/*
+ * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
+ */
+/*
+ * $Id$
+ */
+package com.sun.org.apache.xml.internal.security.signature.reference;
+
+/**
+ * An abstract representation of the result of dereferencing a ds:Reference URI.
+ */
+public interface ReferenceData { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,53 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/*
+ * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
+ */
+/*
+ * $Id$
+ */
+package com.sun.org.apache.xml.internal.security.signature.reference;
+
+import java.util.Iterator;
+
+import org.w3c.dom.Node;
+
+/**
+ * An abstract representation of a <code>ReferenceData</code> type containing a node-set.
+ */
+public interface ReferenceNodeSetData extends ReferenceData {
+
+    /**
+     * Returns a read-only iterator over the nodes contained in this
+     * <code>NodeSetData</code> in
+     * <a href="http://www.w3.org/TR/1999/REC-xpath-19991116#dt-document-order">
+     * document order</a>. Attempts to modify the returned iterator
+     * via the <code>remove</code> method throw
+     * <code>UnsupportedOperationException</code>.
+     *
+     * @return an <code>Iterator</code> over the nodes in this
+     *    <code>NodeSetData</code> in document order
+     */
+    Iterator<Node> iterator();
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,105 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/*
+ * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
+ */
+/*
+ * $Id$
+ */
+package com.sun.org.apache.xml.internal.security.signature.reference;
+
+import java.io.InputStream;
+
+/**
+ * A representation of a <code>ReferenceData</code> type containing an OctetStream.
+ */
+public class ReferenceOctetStreamData implements ReferenceData {
+    private InputStream octetStream;
+    private String uri;
+    private String mimeType;
+
+    /**
+     * Creates a new <code>ReferenceOctetStreamData</code>.
+     *
+     * @param octetStream the input stream containing the octets
+     * @throws NullPointerException if <code>octetStream</code> is
+     *    <code>null</code>
+     */
+    public ReferenceOctetStreamData(InputStream octetStream) {
+        if (octetStream == null) {
+            throw new NullPointerException("octetStream is null");
+        }
+        this.octetStream = octetStream;
+    }
+
+    /**
+     * Creates a new <code>ReferenceOctetStreamData</code>.
+     *
+     * @param octetStream the input stream containing the octets
+     * @param uri the URI String identifying the data object (may be
+     *    <code>null</code>)
+     * @param mimeType the MIME type associated with the data object (may be
+     *    <code>null</code>)
+     * @throws NullPointerException if <code>octetStream</code> is
+     *    <code>null</code>
+     */
+    public ReferenceOctetStreamData(InputStream octetStream, String uri,
+        String mimeType) {
+        if (octetStream == null) {
+            throw new NullPointerException("octetStream is null");
+        }
+        this.octetStream = octetStream;
+        this.uri = uri;
+        this.mimeType = mimeType;
+    }
+
+    /**
+     * Returns the input stream of this <code>ReferenceOctetStreamData</code>.
+     *
+     * @return the input stream of this <code>ReferenceOctetStreamData</code>.
+     */
+    public InputStream getOctetStream() {
+        return octetStream;
+    }
+
+    /**
+     * Returns the URI String identifying the data object represented by this
+     * <code>ReferenceOctetStreamData</code>.
+     *
+     * @return the URI String or <code>null</code> if not applicable
+     */
+    public String getURI() {
+        return uri;
+    }
+
+    /**
+     * Returns the MIME type associated with the data object represented by this
+     * <code>ReferenceOctetStreamData</code>.
+     *
+     * @return the MIME type or <code>null</code> if not applicable
+     */
+    public String getMimeType() {
+        return mimeType;
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,181 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/*
+ * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
+ */
+/*
+ * $Id$
+ */
+package com.sun.org.apache.xml.internal.security.signature.reference;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.NoSuchElementException;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+
+/**
+ * A representation of a <code>ReferenceNodeSetData</code> type containing a node-set.
+ * This is a subtype of NodeSetData that represents a dereferenced
+ * same-document URI as the root of a subdocument. The main reason is
+ * for efficiency and performance, as some transforms can operate
+ * directly on the subdocument and there is no need to convert it
+ * first to an XPath node-set.
+ */
+public class ReferenceSubTreeData implements ReferenceNodeSetData {
+
+    private boolean excludeComments;
+    private Node root;
+
+    public ReferenceSubTreeData(Node root, boolean excludeComments) {
+        this.root = root;
+        this.excludeComments = excludeComments;
+    }
+
+    public Iterator<Node> iterator() {
+        return new DelayedNodeIterator(root, excludeComments);
+    }
+
+    public Node getRoot() {
+        return root;
+    }
+
+    public boolean excludeComments() {
+        return excludeComments;
+    }
+
+    /**
+     * This is an Iterator that contains a backing node-set that is
+     * not populated until the caller first attempts to advance the iterator.
+     */
+    static class DelayedNodeIterator implements Iterator<Node> {
+        private Node root;
+        private List<Node> nodeSet;
+        private ListIterator<Node> li;
+        private boolean withComments;
+
+        DelayedNodeIterator(Node root, boolean excludeComments) {
+            this.root = root;
+            this.withComments = !excludeComments;
+        }
+
+        public boolean hasNext() {
+            if (nodeSet == null) {
+                nodeSet = dereferenceSameDocumentURI(root);
+                li = nodeSet.listIterator();
+            }
+            return li.hasNext();
+        }
+
+        public Node next() {
+            if (nodeSet == null) {
+                nodeSet = dereferenceSameDocumentURI(root);
+                li = nodeSet.listIterator();
+            }
+            if (li.hasNext()) {
+                return li.next();
+            } else {
+                throw new NoSuchElementException();
+            }
+        }
+
+        public void remove() {
+            throw new UnsupportedOperationException();
+        }
+
+        /**
+         * Dereferences a same-document URI fragment.
+         *
+         * @param node the node (document or element) referenced by the
+         *        URI fragment. If null, returns an empty set.
+         * @return a set of nodes (minus any comment nodes)
+         */
+        private List<Node> dereferenceSameDocumentURI(Node node) {
+            List<Node> nodeSet = new ArrayList<Node>();
+            if (node != null) {
+                nodeSetMinusCommentNodes(node, nodeSet, null);
+            }
+            return nodeSet;
+        }
+
+        /**
+         * Recursively traverses the subtree, and returns an XPath-equivalent
+         * node-set of all nodes traversed, excluding any comment nodes,
+         * if specified.
+         *
+         * @param node the node to traverse
+         * @param nodeSet the set of nodes traversed so far
+         * @param the previous sibling node
+         */
+        @SuppressWarnings("fallthrough")
+        private void nodeSetMinusCommentNodes(Node node, List<Node> nodeSet,
+                                              Node prevSibling)
+        {
+            switch (node.getNodeType()) {
+                case Node.ELEMENT_NODE :
+                    nodeSet.add(node);
+                    NamedNodeMap attrs = node.getAttributes();
+                    if (attrs != null) {
+                        for (int i = 0, len = attrs.getLength(); i < len; i++) {
+                            nodeSet.add(attrs.item(i));
+                        }
+                    }
+                    Node pSibling = null;
+                    for (Node child = node.getFirstChild(); child != null;
+                        child = child.getNextSibling()) {
+                        nodeSetMinusCommentNodes(child, nodeSet, pSibling);
+                        pSibling = child;
+                    }
+                    break;
+                case Node.DOCUMENT_NODE :
+                    pSibling = null;
+                    for (Node child = node.getFirstChild(); child != null;
+                        child = child.getNextSibling()) {
+                        nodeSetMinusCommentNodes(child, nodeSet, pSibling);
+                        pSibling = child;
+                    }
+                    break;
+                case Node.TEXT_NODE :
+                case Node.CDATA_SECTION_NODE:
+                    // emulate XPath which only returns the first node in
+                    // contiguous text/cdata nodes
+                    if (prevSibling != null &&
+                        (prevSibling.getNodeType() == Node.TEXT_NODE ||
+                         prevSibling.getNodeType() == Node.CDATA_SECTION_NODE)) {
+                        return;
+                    }
+                    nodeSet.add(node);
+                    break;
+                case Node.PROCESSING_INSTRUCTION_NODE :
+                    nodeSet.add(node);
+                    break;
+                case Node.COMMENT_NODE:
+                    if (withComments) {
+                        nodeSet.add(node);
+                    }
+            }
+        }
+    }
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,86 +2,84 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms;
 
-
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 
-
 /**
  *
  * @author Christian Geuer-Pollmann
  */
 public class InvalidTransformException extends XMLSecurityException {
 
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
 
-   /**
-    * Constructor InvalidTransformException
-    *
-    */
-   public InvalidTransformException() {
-      super();
-   }
+    /**
+     * Constructor InvalidTransformException
+     *
+     */
+    public InvalidTransformException() {
+        super();
+    }
 
-   /**
-    * Constructor InvalidTransformException
-    *
-    * @param _msgId
-    */
-   public InvalidTransformException(String _msgId) {
-      super(_msgId);
-   }
+    /**
+     * Constructor InvalidTransformException
+     *
+     * @param msgId
+     */
+    public InvalidTransformException(String msgId) {
+        super(msgId);
+    }
 
-   /**
-    * Constructor InvalidTransformException
-    *
-    * @param _msgId
-    * @param exArgs
-    */
-   public InvalidTransformException(String _msgId, Object exArgs[]) {
-      super(_msgId, exArgs);
-   }
+    /**
+     * Constructor InvalidTransformException
+     *
+     * @param msgId
+     * @param exArgs
+     */
+    public InvalidTransformException(String msgId, Object exArgs[]) {
+        super(msgId, exArgs);
+    }
 
-   /**
-    * Constructor InvalidTransformException
-    *
-    * @param _msgId
-    * @param _originalException
-    */
-   public InvalidTransformException(String _msgId, Exception _originalException) {
-      super(_msgId, _originalException);
-   }
+    /**
+     * Constructor InvalidTransformException
+     *
+     * @param msgId
+     * @param originalException
+     */
+    public InvalidTransformException(String msgId, Exception originalException) {
+        super(msgId, originalException);
+    }
 
-   /**
-    * Constructor InvalidTransformException
-    *
-    * @param _msgId
-    * @param exArgs
-    * @param _originalException
-    */
-   public InvalidTransformException(String _msgId, Object exArgs[],
-                                    Exception _originalException) {
-      super(_msgId, exArgs, _originalException);
-   }
+    /**
+     * Constructor InvalidTransformException
+     *
+     * @param msgId
+     * @param exArgs
+     * @param originalException
+     */
+    public InvalidTransformException(String msgId, Object exArgs[], Exception originalException) {
+        super(msgId, exArgs, originalException);
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java	Mon Jul 22 17:37:15 2013 -0700
@@ -263,7 +263,7 @@
      * @return the URI representation of Transformation algorithm
      */
     public String getURI() {
-        return this._constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
     }
 
     /**
@@ -329,7 +329,7 @@
     private TransformSpi initializeTransform(String algorithmURI, NodeList contextNodes)
         throws InvalidTransformException {
 
-        this._constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI);
+        this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI);
 
         Class<? extends TransformSpi> transformSpiClass = transformSpiHash.get(algorithmURI);
         if (transformSpiClass == null) {
@@ -360,7 +360,7 @@
         // give it to the current document
         if (contextNodes != null) {
             for (int i = 0; i < contextNodes.getLength(); i++) {
-                this._constructionElement.appendChild(contextNodes.item(i).cloneNode(true));
+                this.constructionElement.appendChild(contextNodes.item(i).cloneNode(true));
             }
         }
         return newTransformSpi;
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,29 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 
 package com.sun.org.apache.xml.internal.security.transforms;
 
-/**
- *
- * @author $Author: mullan $
- */
-
 public interface TransformParam {
-}
+}
\ No newline at end of file
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms;
 
@@ -37,28 +39,13 @@
  * @author Christian Geuer-Pollmann
  */
 public abstract class TransformSpi {
-    /**
-     * For API compatibility not thread safe.
-     * @deprecated
-     */
-    @Deprecated
-    protected Transform _transformObject = null;
-    /**
-     * Set the transform object.
-     * Depeprecated For API compatibility.
-     * @param transform the Transform
-     * @deprecated
-     */
-    @Deprecated
-    protected void setTransform(Transform transform) {
-        this._transformObject = transform;
-    }
+
     /**
      * The mega method which MUST be implemented by the Transformation Algorithm.
      *
      * @param input {@link XMLSignatureInput} as the input of transformation
      * @param os where to output this transformation.
-     * @param _transformObject the Transform
+     * @param transformObject the Transform object
      * @return {@link XMLSignatureInput} as the result of transformation
      * @throws CanonicalizationException
      * @throws IOException
@@ -68,13 +55,12 @@
      * @throws TransformationException
      */
     protected XMLSignatureInput enginePerformTransform(
-        XMLSignatureInput input, OutputStream os, Transform _transformObject)
-        throws IOException,
-               CanonicalizationException, InvalidCanonicalizerException,
-               TransformationException, ParserConfigurationException,
-               SAXException {
-        return enginePerformTransform(input, _transformObject);
+        XMLSignatureInput input, OutputStream os, Transform transformObject
+    ) throws IOException, CanonicalizationException, InvalidCanonicalizerException,
+        TransformationException, ParserConfigurationException, SAXException {
+        throw new UnsupportedOperationException();
     }
+
     /**
      * The mega method which MUST be implemented by the Transformation Algorithm.
      * In order to be compatible with preexisting Transform implementations,
@@ -83,7 +69,7 @@
      * implementation.
      *
      * @param input {@link XMLSignatureInput} as the input of transformation
-     * @param _transformObject the Transform
+     * @param transformObject the Transform object
      * @return {@link XMLSignatureInput} as the result of transformation
      * @throws CanonicalizationException
      * @throws IOException
@@ -93,26 +79,14 @@
      * @throws TransformationException
      */
     protected XMLSignatureInput enginePerformTransform(
-        XMLSignatureInput input, Transform _transformObject)
-        throws IOException,
-               CanonicalizationException, InvalidCanonicalizerException,
-               TransformationException, ParserConfigurationException,
-               SAXException {
-        //Default implementation overide with a much better
-        try {
-                TransformSpi tmp = (TransformSpi) getClass().newInstance();
-            tmp.setTransform(_transformObject);
-            return tmp.enginePerformTransform(input);
-        } catch (InstantiationException e) {
-            throw new TransformationException("",e);
-        } catch (IllegalAccessException e) {
-            throw new TransformationException("",e);
-        }
+        XMLSignatureInput input, Transform transformObject
+    ) throws IOException, CanonicalizationException, InvalidCanonicalizerException,
+        TransformationException, ParserConfigurationException, SAXException {
+        return enginePerformTransform(input, null, transformObject);
     }
 
     /**
      * The mega method which MUST be implemented by the Transformation Algorithm.
-     * @deprecated
      * @param input {@link XMLSignatureInput} as the input of transformation
      * @return {@link XMLSignatureInput} as the result of transformation
      * @throws CanonicalizationException
@@ -122,15 +96,13 @@
      * @throws SAXException
      * @throws TransformationException
      */
-    @Deprecated
     protected XMLSignatureInput enginePerformTransform(
-        XMLSignatureInput input)
-        throws IOException,
-               CanonicalizationException, InvalidCanonicalizerException,
-               TransformationException, ParserConfigurationException,
-               SAXException {
-        throw new UnsupportedOperationException();
+        XMLSignatureInput input
+    ) throws IOException, CanonicalizationException, InvalidCanonicalizerException,
+        TransformationException, ParserConfigurationException, SAXException {
+        return enginePerformTransform(input, null);
     }
+
     /**
      * Returns the URI representation of <code>Transformation algorithm</code>
      *
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,86 +2,83 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms;
 
-
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 
-
 /**
  *
  * @author Christian Geuer-Pollmann
  */
 public class TransformationException extends XMLSecurityException {
-
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
 
-   /**
-    * Constructor TransformationException
-    *
-    */
-   public TransformationException() {
-      super();
-   }
+    /**
+     * Constructor TransformationException
+     *
+     */
+    public TransformationException() {
+        super();
+    }
 
-   /**
-    * Constructor TransformationException
-    *
-    * @param _msgID
-    */
-   public TransformationException(String _msgID) {
-      super(_msgID);
-   }
+    /**
+     * Constructor TransformationException
+     *
+     * @param msgID
+     */
+    public TransformationException(String msgID) {
+        super(msgID);
+    }
 
-   /**
-    * Constructor TransformationException
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public TransformationException(String _msgID, Object exArgs[]) {
-      super(_msgID, exArgs);
-   }
+    /**
+     * Constructor TransformationException
+     *
+     * @param msgID
+     * @param exArgs
+     */
+    public TransformationException(String msgID, Object exArgs[]) {
+        super(msgID, exArgs);
+    }
 
-   /**
-    * Constructor TransformationException
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public TransformationException(String _msgID, Exception _originalException) {
-      super(_msgID, _originalException);
-   }
+    /**
+     * Constructor TransformationException
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public TransformationException(String msgID, Exception originalException) {
+        super(msgID, originalException);
+    }
 
-   /**
-    * Constructor TransformationException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public TransformationException(String _msgID, Object exArgs[],
-                                  Exception _originalException) {
-      super(_msgID, exArgs, _originalException);
-   }
+    /**
+     * Constructor TransformationException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public TransformationException(String msgID, Object exArgs[], Exception originalException) {
+        super(msgID, exArgs, originalException);
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2008 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms;
 
@@ -51,56 +53,64 @@
  */
 public class Transforms extends SignatureElementProxy {
 
-    /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(Transforms.class.getName());
     /** Canonicalization - Required Canonical XML (omits comments) */
     public static final String TRANSFORM_C14N_OMIT_COMMENTS
         = Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS;
+
     /** Canonicalization - Recommended Canonical XML with Comments */
     public static final String TRANSFORM_C14N_WITH_COMMENTS
         = Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS;
+
     /** Canonicalization - Required Canonical XML 1.1 (omits comments) */
     public static final String TRANSFORM_C14N11_OMIT_COMMENTS
         = Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS;
+
     /** Canonicalization - Recommended Canonical XML 1.1 with Comments */
     public static final String TRANSFORM_C14N11_WITH_COMMENTS
         = Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS;
+
     /** Canonicalization - Required Exclusive Canonicalization (omits comments) */
     public static final String TRANSFORM_C14N_EXCL_OMIT_COMMENTS
         = Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS;
+
     /** Canonicalization - Recommended Exclusive Canonicalization with Comments */
     public static final String TRANSFORM_C14N_EXCL_WITH_COMMENTS
         = Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS;
+
     /** Transform - Optional XSLT */
     public static final String TRANSFORM_XSLT
         = "http://www.w3.org/TR/1999/REC-xslt-19991116";
+
     /** Transform - Required base64 decoding */
     public static final String TRANSFORM_BASE64_DECODE
         = Constants.SignatureSpecNS + "base64";
+
     /** Transform - Recommended XPath */
     public static final String TRANSFORM_XPATH
         = "http://www.w3.org/TR/1999/REC-xpath-19991116";
+
     /** Transform - Required Enveloped Signature */
     public static final String TRANSFORM_ENVELOPED_SIGNATURE
         = Constants.SignatureSpecNS + "enveloped-signature";
+
     /** Transform - XPointer */
     public static final String TRANSFORM_XPOINTER
         = "http://www.w3.org/TR/2001/WD-xptr-20010108";
-    /** Transform - XPath Filter v2.0 */
-    public static final String TRANSFORM_XPATH2FILTER04
-        = "http://www.w3.org/2002/04/xmldsig-filter2";
+
     /** Transform - XPath Filter */
     public static final String TRANSFORM_XPATH2FILTER
         = "http://www.w3.org/2002/06/xmldsig-filter2";
-    /** Transform - XPath Filter  CHGP private */
-    public static final String TRANSFORM_XPATHFILTERCHGP
-        = "http://www.nue.et-inf.uni-siegen.de/~geuer-pollmann/#xpathFilter";
 
-    Element []transforms;
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(Transforms.class.getName());
+
+    private Element[] transforms;
 
     protected Transforms() { };
 
+    private boolean secureValidation;
+
     /**
      * Constructs {@link Transforms}.
      *
@@ -109,7 +119,7 @@
      */
     public Transforms(Document doc) {
         super(doc);
-        XMLUtils.addReturnToElement(this._constructionElement);
+        XMLUtils.addReturnToElement(this.constructionElement);
     }
 
     /**
@@ -125,25 +135,28 @@
      * @throws XMLSignatureException
      */
     public Transforms(Element element, String BaseURI)
-           throws DOMException, XMLSignatureException,
-                  InvalidTransformException, TransformationException,
-                  XMLSecurityException {
-
+        throws DOMException, XMLSignatureException, InvalidTransformException,
+            TransformationException, XMLSecurityException {
         super(element, BaseURI);
 
         int numberOfTransformElems = this.getLength();
 
         if (numberOfTransformElems == 0) {
-
             // At least one Transform element must be present. Bad.
-            Object exArgs[] = { Constants._TAG_TRANSFORM,
-                                Constants._TAG_TRANSFORMS };
+            Object exArgs[] = { Constants._TAG_TRANSFORM, Constants._TAG_TRANSFORMS };
 
             throw new TransformationException("xml.WrongContent", exArgs);
         }
     }
 
     /**
+     * Set whether secure validation is enabled or not. The default is false.
+     */
+    public void setSecureValidation(boolean secureValidation) {
+        this.secureValidation = secureValidation;
+    }
+
+    /**
      * Adds the <code>Transform</code> with the specified <code>Transform
      * algorithm URI</code>
      *
@@ -151,14 +164,13 @@
      * transformation is applied to data
      * @throws TransformationException
      */
-    public void addTransform(String transformURI)
-           throws TransformationException {
-
+    public void addTransform(String transformURI) throws TransformationException {
         try {
-            if (log.isLoggable(java.util.logging.Level.FINE))
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
                 log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")");
+            }
 
-            Transform transform = new Transform(this._doc, transformURI);
+            Transform transform = new Transform(this.doc, transformURI);
 
             this.addTransform(transform);
         } catch (InvalidTransformException ex) {
@@ -174,16 +186,15 @@
      * transformation is applied to data
      * @param contextElement
      * @throws TransformationException
-     * @see Transform#getInstance(Document doc, String algorithmURI, Element childElement)
      */
     public void addTransform(String transformURI, Element contextElement)
-           throws TransformationException {
-
+       throws TransformationException {
         try {
-            if (log.isLoggable(java.util.logging.Level.FINE))
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
                 log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")");
+            }
 
-            Transform transform = new Transform(this._doc, transformURI, contextElement);
+            Transform transform = new Transform(this.doc, transformURI, contextElement);
 
             this.addTransform(transform);
         } catch (InvalidTransformException ex) {
@@ -199,13 +210,12 @@
      * transformation is applied to data
      * @param contextNodes
      * @throws TransformationException
-     * @see Transform#getInstance(Document doc, String algorithmURI, NodeList contextNodes)
      */
     public void addTransform(String transformURI, NodeList contextNodes)
-           throws TransformationException {
+       throws TransformationException {
 
         try {
-            Transform transform = new Transform(this._doc, transformURI, contextNodes);
+            Transform transform = new Transform(this.doc, transformURI, contextNodes);
             this.addTransform(transform);
         } catch (InvalidTransformException ex) {
             throw new TransformationException("empty", ex);
@@ -218,13 +228,14 @@
      * @param transform {@link Transform} object
      */
     private void addTransform(Transform transform) {
-        if (log.isLoggable(java.util.logging.Level.FINE))
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
             log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transform.getURI() + ")");
+        }
 
         Element transformElement = transform.getElement();
 
-        this._constructionElement.appendChild(transformElement);
-        XMLUtils.addReturnToElement(this._constructionElement);
+        this.constructionElement.appendChild(transformElement);
+        XMLUtils.addReturnToElement(this.constructionElement);
     }
 
     /**
@@ -236,7 +247,8 @@
      * @throws TransformationException
      */
     public XMLSignatureInput performTransforms(
-        XMLSignatureInput xmlSignatureInput) throws TransformationException {
+        XMLSignatureInput xmlSignatureInput
+    ) throws TransformationException {
         return performTransforms(xmlSignatureInput, null);
     }
 
@@ -250,21 +262,22 @@
      * @throws TransformationException
      */
     public XMLSignatureInput performTransforms(
-        XMLSignatureInput xmlSignatureInput, OutputStream os)
-        throws TransformationException {
-
+        XMLSignatureInput xmlSignatureInput, OutputStream os
+    ) throws TransformationException {
         try {
-            int last=this.getLength()-1;
+            int last = this.getLength() - 1;
             for (int i = 0; i < last; i++) {
                 Transform t = this.item(i);
+                String uri = t.getURI();
                 if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Perform the (" + i + ")th " + t.getURI()
-                        + " transform");
+                    log.log(java.util.logging.Level.FINE, "Perform the (" + i + ")th " + uri + " transform");
                 }
+                checkSecureValidation(t);
                 xmlSignatureInput = t.performTransform(xmlSignatureInput);
             }
-            if (last>=0) {
+            if (last >= 0) {
                 Transform t = this.item(last);
+                checkSecureValidation(t);
                 xmlSignatureInput = t.performTransform(xmlSignatureInput, os);
             }
 
@@ -278,16 +291,26 @@
         }
     }
 
+    private void checkSecureValidation(Transform transform) throws TransformationException {
+        String uri = transform.getURI();
+        if (secureValidation && Transforms.TRANSFORM_XSLT.equals(uri)) {
+            Object exArgs[] = { uri };
+
+            throw new TransformationException(
+                "signature.Transform.ForbiddenTransform", exArgs
+            );
+        }
+    }
+
     /**
      * Return the nonnegative number of transformations.
      *
      * @return the number of transformations
      */
-    public int getLength()
-    {
+    public int getLength() {
         if (transforms == null) {
-            transforms = XMLUtils.selectDsNodes
-                (this._constructionElement.getFirstChild(), "Transform");
+            transforms =
+                XMLUtils.selectDsNodes(this.constructionElement.getFirstChild(), "Transform");
         }
         return transforms.length;
     }
@@ -301,13 +324,12 @@
      * @throws TransformationException
      */
     public Transform item(int i) throws TransformationException {
-
         try {
             if (transforms == null) {
-                transforms = XMLUtils.selectDsNodes
-                    (this._constructionElement.getFirstChild(), "Transform");
+                transforms =
+                    XMLUtils.selectDsNodes(this.constructionElement.getFirstChild(), "Transform");
             }
-            return new Transform(transforms[i], this._baseURI);
+            return new Transform(transforms[i], this.baseURI);
         } catch (XMLSecurityException ex) {
             throw new TransformationException("empty", ex);
         }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.implementations;
 
-
-
 import javax.xml.transform.TransformerException;
 
 import com.sun.org.apache.xml.internal.dtm.DTM;
@@ -36,7 +36,6 @@
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
 
-
 /**
  * The 'here()' function returns a node-set containing the attribute or
  * processing instruction node or the parent element of the text node
@@ -56,107 +55,98 @@
  */
 public class FuncHere extends Function {
 
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
 
-   /**
-    * The here function returns a node-set containing the attribute or
-    * processing instruction node or the parent element of the text node
-    * that directly bears the XPath expression.  This expression results
-    * in an error if the containing XPath expression does not appear in the
-    * same XML document against which the XPath expression is being evaluated.
-    *
-    * @param xctxt
-    * @return the xobject
-    * @throws javax.xml.transform.TransformerException
-    */
-   public XObject execute(XPathContext xctxt)
-           throws javax.xml.transform.TransformerException {
+    /**
+     * The here function returns a node-set containing the attribute or
+     * processing instruction node or the parent element of the text node
+     * that directly bears the XPath expression.  This expression results
+     * in an error if the containing XPath expression does not appear in the
+     * same XML document against which the XPath expression is being evaluated.
+     *
+     * @param xctxt
+     * @return the xobject
+     * @throws javax.xml.transform.TransformerException
+     */
+    @Override
+    public XObject execute(XPathContext xctxt)
+        throws javax.xml.transform.TransformerException {
 
-      Node xpathOwnerNode = (Node) xctxt.getOwnerObject();
-
-      if (xpathOwnerNode == null) {
-         return null;
-      }
+        Node xpathOwnerNode = (Node) xctxt.getOwnerObject();
 
-      int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode);
-
-      int currentNode = xctxt.getCurrentNode();
-      DTM dtm = xctxt.getDTM(currentNode);
-      int docContext = dtm.getDocument();
+        if (xpathOwnerNode == null) {
+            return null;
+        }
 
-      if (DTM.NULL == docContext) {
-         error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null);
-      }
+        int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode);
 
-      {
+        int currentNode = xctxt.getCurrentNode();
+        DTM dtm = xctxt.getDTM(currentNode);
+        int docContext = dtm.getDocument();
 
-         // check whether currentNode and the node containing the XPath expression
-         // are in the same document
-         Document currentDoc =
-            XMLUtils.getOwnerDocument(dtm.getNode(currentNode));
-         Document xpathOwnerDoc = XMLUtils.getOwnerDocument(xpathOwnerNode);
+        if (DTM.NULL == docContext) {
+            error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null);
+        }
 
-         if (currentDoc != xpathOwnerDoc) {
-            throw new TransformerException(I18n
-               .translate("xpath.funcHere.documentsDiffer"));
-         }
-      }
+        {
+            // check whether currentNode and the node containing the XPath expression
+            // are in the same document
+            Document currentDoc =
+                XMLUtils.getOwnerDocument(dtm.getNode(currentNode));
+            Document xpathOwnerDoc = XMLUtils.getOwnerDocument(xpathOwnerNode);
 
-      XNodeSet nodes = new XNodeSet(xctxt.getDTMManager());
-      NodeSetDTM nodeSet = nodes.mutableNodeset();
+            if (currentDoc != xpathOwnerDoc) {
+                throw new TransformerException(I18n.translate("xpath.funcHere.documentsDiffer"));
+            }
+        }
 
-      {
-         int hereNode = DTM.NULL;
-
-         switch (dtm.getNodeType(xpathOwnerNodeDTM)) {
+        XNodeSet nodes = new XNodeSet(xctxt.getDTMManager());
+        NodeSetDTM nodeSet = nodes.mutableNodeset();
 
-         case Node.ATTRIBUTE_NODE : {
-            // returns a node-set containing the attribute
-            hereNode = xpathOwnerNodeDTM;
+        {
+            int hereNode = DTM.NULL;
 
-            nodeSet.addNode(hereNode);
+            switch (dtm.getNodeType(xpathOwnerNodeDTM)) {
 
-            break;
-         }
-         case Node.PROCESSING_INSTRUCTION_NODE : {
-            // returns a node-set containing the processing instruction node
-            hereNode = xpathOwnerNodeDTM;
+            case Node.ATTRIBUTE_NODE :
+            case Node.PROCESSING_INSTRUCTION_NODE : {
+                // returns a node-set containing the attribute /  processing instruction node
+                hereNode = xpathOwnerNodeDTM;
+
+                nodeSet.addNode(hereNode);
 
-            nodeSet.addNode(hereNode);
+                break;
+            }
+            case Node.TEXT_NODE : {
+                // returns a node-set containing the parent element of the
+                // text node that directly bears the XPath expression
+                hereNode = dtm.getParent(xpathOwnerNodeDTM);
 
-            break;
-         }
-         case Node.TEXT_NODE : {
-            // returns a node-set containing the parent element of the
-            // text node that directly bears the XPath expression
-            hereNode = dtm.getParent(xpathOwnerNodeDTM);
+                nodeSet.addNode(hereNode);
 
-            nodeSet.addNode(hereNode);
+                break;
+            }
+            default :
+                break;
+            }
+        }
 
-            break;
-         }
-         default :
-            break;
-         }
-      }
-
-      /** $todo$ Do I have to do this detach() call? */
-      nodeSet.detach();
+        /** $todo$ Do I have to do this detach() call? */
+        nodeSet.detach();
 
-      return nodes;
-   }
+        return nodes;
+    }
 
-   /**
-    * No arguments to process, so this does nothing.
-    * @param vars
-    * @param globalsSize
-    */
-   @SuppressWarnings("rawtypes")
-   public void fixupVariables(java.util.Vector vars, int globalsSize) {
-
-      // do nothing
-   }
+    /**
+     * No arguments to process, so this does nothing.
+     * @param vars
+     * @param globalsSize
+     */
+    @SuppressWarnings("rawtypes")
+    public void fixupVariables(java.util.Vector vars, int globalsSize) {
+        // do nothing
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java	Thu Jul 18 03:38:49 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,143 +0,0 @@
-/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
- */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- */
-package com.sun.org.apache.xml.internal.security.transforms.implementations;
-
-
-
-import com.sun.org.apache.xml.internal.dtm.DTMManager;
-import com.sun.org.apache.xml.internal.security.utils.I18n;
-import com.sun.org.apache.xpath.internal.CachedXPathAPI;
-import com.sun.org.apache.xpath.internal.XPathContext;
-import org.w3c.dom.Node;
-
-
-/**
- * {@link FuncHereContext} extends {@link XPathContext} for supplying context
- * for the <CODE>here()</CODE> function. The here() function needs to know
- * <I>where</I> in an XML instance the XPath text string appeared. This can be
- * in {@link org.w3c.dom.Text}, {@link org.w3c.dom.Attr}ibutes and {@ProcessingInstrinction} nodes. The
- * correct node must be supplied to the constructor of {@link FuncHereContext}.
- * The supplied Node MUST contain the XPath which is to be executed.
- *
- * <PRE>
- * From: Scott_Boag\@lotus.com
- * To: Christian Geuer-Pollmann <maillist\@nue.et-inf.uni-siegen.de>
- * CC: xalan-dev@xml.apache.org
- * Subject: Re: Cleanup of XPathContext & definition of XSLTContext
- * Date: Tue, 21 Aug 2001 18:36:24 -0400
- *
- * > My point is to say to get this baby to run, the XPath must have a
- * > possibility to retrieve the information where itself occured in a
- * > document.
- *
- * It sounds to me like you have to derive an XMLSigContext from the
- * XPathContext?
- *
- * > and supplied the Node which contains the xpath string as "owner". Question:
- * > Is this the correct use of the owner object? It works, but I don't know
- * > whether this is correct from the xalan-philosophy...
- *
- * Philosophically it's fine.  The owner is the TransformerImpl if XPath is
- * running under XSLT.  If it is not running under XSLT, it can be whatever
- * you want.
- *
- * -scott
- * </PRE>
- *
- * @author $Author: mullan $
- * @see com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHere
- * @see com.sun.org.apache.xml.internal.security.utils.XPathFuncHereAPI
- * @see <A HREF="http://www.w3.org/Signature/Drafts/xmldsig-core/Overview.html#function-here">XML Signature - The here() function</A>
- */
-public class FuncHereContext extends XPathContext {
-
-   /**
-    * This constuctor is disabled because if we use the here() function we
-    * <I>always</I> need to know in which node the XPath occured.
-    */
-   private FuncHereContext() {}
-
-   /**
-    * Constructor FuncHereContext
-    *
-    * @param owner
-    */
-   public FuncHereContext(Node owner) {
-      super(owner);
-   }
-
-   /**
-    * Constructor FuncHereContext
-    *
-    * @param owner
-    * @param xpathContext
-    */
-   public FuncHereContext(Node owner, XPathContext xpathContext) {
-
-      super(owner);
-
-      try {
-         super.m_dtmManager = xpathContext.getDTMManager();
-      } catch (IllegalAccessError iae) {
-         throw new IllegalAccessError(I18n.translate("endorsed.jdk1.4.0")
-                                      + " Original message was \""
-                                      + iae.getMessage() + "\"");
-      }
-   }
-
-   /**
-    * Constructor FuncHereContext
-    *
-    * @param owner
-    * @param previouslyUsed
-    */
-   public FuncHereContext(Node owner, CachedXPathAPI previouslyUsed) {
-
-      super(owner);
-
-      try {
-         super.m_dtmManager = previouslyUsed.getXPathContext().getDTMManager();
-      } catch (IllegalAccessError iae) {
-         throw new IllegalAccessError(I18n.translate("endorsed.jdk1.4.0")
-                                      + " Original message was \""
-                                      + iae.getMessage() + "\"");
-      }
-   }
-
-   /**
-    * Constructor FuncHereContext
-    *
-    * @param owner
-    * @param dtmManager
-    */
-   public FuncHereContext(Node owner, DTMManager dtmManager) {
-
-      super(owner);
-
-      try {
-         super.m_dtmManager = dtmManager;
-      } catch (IllegalAccessError iae) {
-         throw new IllegalAccessError(I18n.translate("endorsed.jdk1.4.0")
-                                      + " Original message was \""
-                                      + iae.getMessage() + "\"");
-      }
-   }
-}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.implementations;
 
-
-
 import java.io.BufferedInputStream;
 import java.io.IOException;
 import java.io.OutputStream;
@@ -72,115 +72,106 @@
  */
 public class TransformBase64Decode extends TransformSpi {
 
-   /** Field implementedTransformURI */
-   public static final String implementedTransformURI =
-      Transforms.TRANSFORM_BASE64_DECODE;
+    /** Field implementedTransformURI */
+    public static final String implementedTransformURI =
+        Transforms.TRANSFORM_BASE64_DECODE;
+
+    /**
+     * Method engineGetURI
+     *
+     * @inheritDoc
+     */
+    protected String engineGetURI() {
+        return TransformBase64Decode.implementedTransformURI;
+    }
 
-   /**
-    * Method engineGetURI
-    *
-    * @inheritDoc
-    */
-   protected String engineGetURI() {
-      return TransformBase64Decode.implementedTransformURI;
-   }
+    /**
+     * Method enginePerformTransform
+     *
+     * @param input
+     * @return {@link XMLSignatureInput} as the result of transformation
+     * @inheritDoc
+     * @throws CanonicalizationException
+     * @throws IOException
+     * @throws TransformationException
+     */
+    protected XMLSignatureInput enginePerformTransform(
+        XMLSignatureInput input, Transform transformObject
+    ) throws IOException, CanonicalizationException, TransformationException {
+        return enginePerformTransform(input, null, transformObject);
+    }
 
-   /**
-    * Method enginePerformTransform
-    *
-    * @param input
-    * @return {@link XMLSignatureInput} as the result of transformation
-    * @inheritDoc
-    * @throws CanonicalizationException
-    * @throws IOException
-    * @throws TransformationException
-    */
-   protected XMLSignatureInput enginePerformTransform
-        (XMLSignatureInput input, Transform _transformObject)
-           throws IOException, CanonicalizationException,
-                  TransformationException {
-        return enginePerformTransform(input, null, _transformObject);
-   }
+    protected XMLSignatureInput enginePerformTransform(
+        XMLSignatureInput input, OutputStream os, Transform transformObject
+    ) throws IOException, CanonicalizationException, TransformationException {
+        try {
+            if (input.isElement()) {
+                Node el = input.getSubNode();
+                if (input.getSubNode().getNodeType() == Node.TEXT_NODE) {
+                    el = el.getParentNode();
+                }
+                StringBuilder sb = new StringBuilder();
+                traverseElement((Element)el, sb);
+                if (os == null) {
+                    byte[] decodedBytes = Base64.decode(sb.toString());
+                    return new XMLSignatureInput(decodedBytes);
+                }
+                Base64.decode(sb.toString(), os);
+                XMLSignatureInput output = new XMLSignatureInput((byte[])null);
+                output.setOutputStream(os);
+                return output;
+            }
 
-    protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,
-            OutputStream os, Transform _transformObject)
-    throws IOException, CanonicalizationException,
-           TransformationException {
-         try {
-      if (input.isElement()) {
-         Node el=input.getSubNode();
-         if (input.getSubNode().getNodeType()==Node.TEXT_NODE) {
-            el=el.getParentNode();
-         }
-         StringBuffer sb=new StringBuffer();
-         traverseElement((Element)el,sb);
-         if (os==null) {
+            if (input.isOctetStream() || input.isNodeSet()) {
+                if (os == null) {
+                    byte[] base64Bytes = input.getBytes();
+                    byte[] decodedBytes = Base64.decode(base64Bytes);
+                    return new XMLSignatureInput(decodedBytes);
+                }
+                if (input.isByteArray() || input.isNodeSet()) {
+                    Base64.decode(input.getBytes(), os);
+                } else {
+                    Base64.decode(new BufferedInputStream(input.getOctetStreamReal()), os);
+                }
+                XMLSignatureInput output = new XMLSignatureInput((byte[])null);
+                output.setOutputStream(os);
+                return output;
+            }
+
+            try {
+                //Exceptional case there is current not text case testing this(Before it was a
+                //a common case).
+                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+                dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
+                Document doc =
+                    dbf.newDocumentBuilder().parse(input.getOctetStream());
+
+                Element rootNode = doc.getDocumentElement();
+                StringBuilder sb = new StringBuilder();
+                traverseElement(rootNode, sb);
                 byte[] decodedBytes = Base64.decode(sb.toString());
                 return new XMLSignatureInput(decodedBytes);
-         }
-                Base64.decode(sb.toString(),os);
-            XMLSignatureInput output=new XMLSignatureInput((byte[])null);
-            output.setOutputStream(os);
-            return output;
-
-      }
-      if (input.isOctetStream() || input.isNodeSet()) {
-
-
-        if (os==null) {
-            byte[] base64Bytes = input.getBytes();
-            byte[] decodedBytes = Base64.decode(base64Bytes);
-            return new XMLSignatureInput(decodedBytes);
-         }
-        if (input.isByteArray() || input.isNodeSet()) {
-               Base64.decode(input.getBytes(),os);
-        } else {
-            Base64.decode(new BufferedInputStream(input.getOctetStreamReal())
-                    ,os);
-        }
-            XMLSignatureInput output=new XMLSignatureInput((byte[])null);
-            output.setOutputStream(os);
-            return output;
-
-
-      }
-
-         try {
-            // Exceptional case there is current not text case testing this
-            // (before it was a a common case).
-            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
-                           Boolean.TRUE);
-            Document doc =
-                dbf.newDocumentBuilder().parse(input.getOctetStream());
-
-            Element rootNode = doc.getDocumentElement();
-            StringBuffer sb = new StringBuffer();
-            traverseElement(rootNode,sb);
-            byte[] decodedBytes = Base64.decode(sb.toString());
-
-            return new XMLSignatureInput(decodedBytes);
-         } catch (ParserConfigurationException e) {
-            throw new TransformationException("c14n.Canonicalizer.Exception",e);
-         } catch (SAXException e) {
-            throw new TransformationException("SAX exception", e);
-         }
+            } catch (ParserConfigurationException e) {
+                throw new TransformationException("c14n.Canonicalizer.Exception",e);
+            } catch (SAXException e) {
+                throw new TransformationException("SAX exception", e);
+            }
         } catch (Base64DecodingException e) {
             throw new TransformationException("Base64Decoding", e);
         }
-   }
+    }
 
-   void traverseElement(org.w3c.dom.Element node,StringBuffer sb) {
-            Node sibling=node.getFirstChild();
-        while (sibling!=null) {
-                switch (sibling.getNodeType()) {
-                        case Node.ELEMENT_NODE:
-                    traverseElement((Element)sibling,sb);
-                    break;
-               case Node.TEXT_NODE:
-                    sb.append(((Text)sibling).getData());
+    void traverseElement(org.w3c.dom.Element node, StringBuilder sb) {
+        Node sibling = node.getFirstChild();
+        while (sibling != null) {
+            switch (sibling.getNodeType()) {
+            case Node.ELEMENT_NODE:
+                traverseElement((Element)sibling, sb);
+                break;
+            case Node.TEXT_NODE:
+                sb.append(((Text)sibling).getData());
             }
-            sibling=sibling.getNextSibling();
+            sibling = sibling.getNextSibling();
         }
-   }
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.implementations;
 
@@ -37,39 +39,30 @@
  */
 public class TransformC14N extends TransformSpi {
 
-   /** Field implementedTransformURI */
-   public static final String implementedTransformURI =
-      Transforms.TRANSFORM_C14N_OMIT_COMMENTS;
-
+    /** Field implementedTransformURI */
+    public static final String implementedTransformURI =
+        Transforms.TRANSFORM_C14N_OMIT_COMMENTS;
 
-   /**
-    * @inheritDoc
-    */
-   protected String engineGetURI() {
-      return TransformC14N.implementedTransformURI;
-   }
+    /**
+     * @inheritDoc
+     */
+    protected String engineGetURI() {
+        return TransformC14N.implementedTransformURI;
+    }
 
-   /**
-    *  @inheritDoc
-    */
-   protected XMLSignatureInput enginePerformTransform
-        (XMLSignatureInput input, Transform _transformObject)
-           throws CanonicalizationException {
-            return enginePerformTransform(input, null, _transformObject);
-   }
-
-    protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject)
-    throws CanonicalizationException {
-         Canonicalizer20010315OmitComments c14n = new Canonicalizer20010315OmitComments();
-         if (os!=null) {
-                c14n.setWriter(os);
-         }
-         byte[] result = null;
-         result=c14n.engineCanonicalize(input);
-         XMLSignatureInput output=new XMLSignatureInput(result);
-         if (os!=null) {
+    protected XMLSignatureInput enginePerformTransform(
+        XMLSignatureInput input, OutputStream os, Transform transformObject
+    ) throws CanonicalizationException {
+        Canonicalizer20010315OmitComments c14n = new Canonicalizer20010315OmitComments();
+        if (os != null) {
+            c14n.setWriter(os);
+        }
+        byte[] result = null;
+        result = c14n.engineCanonicalize(input);
+        XMLSignatureInput output = new XMLSignatureInput(result);
+        if (os != null) {
             output.setOutputStream(os);
-         }
-         return output;
-   }
+        }
+        return output;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2008 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.implementations;
 
@@ -41,15 +43,9 @@
         return Transforms.TRANSFORM_C14N11_OMIT_COMMENTS;
     }
 
-    protected XMLSignatureInput enginePerformTransform
-        (XMLSignatureInput input, Transform transform)
-        throws CanonicalizationException {
-        return enginePerformTransform(input, null, transform);
-    }
-
-    protected XMLSignatureInput enginePerformTransform
-        (XMLSignatureInput input, OutputStream os, Transform transform)
-        throws CanonicalizationException {
+    protected XMLSignatureInput enginePerformTransform(
+        XMLSignatureInput input, OutputStream os, Transform transform
+    ) throws CanonicalizationException {
         Canonicalizer11_OmitComments c14n = new Canonicalizer11_OmitComments();
         if (os != null) {
             c14n.setWriter(os);
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2008 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.implementations;
 
@@ -41,15 +43,9 @@
         return Transforms.TRANSFORM_C14N11_WITH_COMMENTS;
     }
 
-    protected XMLSignatureInput enginePerformTransform
-        (XMLSignatureInput input, Transform transform)
-        throws CanonicalizationException {
-        return enginePerformTransform(input, null, transform);
-    }
-
-    protected XMLSignatureInput enginePerformTransform
-        (XMLSignatureInput input, OutputStream os, Transform transform)
-        throws CanonicalizationException {
+    protected XMLSignatureInput enginePerformTransform(
+        XMLSignatureInput input, OutputStream os, Transform transform
+    ) throws CanonicalizationException {
 
         Canonicalizer11_WithComments c14n = new Canonicalizer11_WithComments();
         if (os != null) {
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.implementations;
 
@@ -36,71 +38,59 @@
 /**
  * Class TransformC14NExclusive
  *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
  */
 public class TransformC14NExclusive extends TransformSpi {
 
-   /** Field implementedTransformURI */
-   public static final String implementedTransformURI =
-      Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS;
-
-   /**
-    * Method engineGetURI
-    *
-    * @inheritDoc
-    */
-   protected String engineGetURI() {
-      return implementedTransformURI;
-   }
+    /** Field implementedTransformURI */
+    public static final String implementedTransformURI =
+        Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS;
 
-   /**
-    * Method enginePerformTransform
-    *
-    * @param input
-    * @return the transformed of the input
-    * @throws CanonicalizationException
-    */
-   protected XMLSignatureInput enginePerformTransform
-        (XMLSignatureInput input, Transform _transformObject)
-           throws CanonicalizationException {
-            return enginePerformTransform(input, null, _transformObject);
-   }
+    /**
+     * Method engineGetURI
+     *
+     * @inheritDoc
+     */
+    protected String engineGetURI() {
+        return implementedTransformURI;
+    }
 
-    protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject)
-    throws CanonicalizationException {
-      try {
-         String inclusiveNamespaces = null;
+    protected XMLSignatureInput enginePerformTransform(
+        XMLSignatureInput input, OutputStream os, Transform transformObject
+    ) throws CanonicalizationException {
+        try {
+            String inclusiveNamespaces = null;
 
-         if (_transformObject
-                 .length(InclusiveNamespaces
-                    .ExclusiveCanonicalizationNamespace, InclusiveNamespaces
-                    ._TAG_EC_INCLUSIVENAMESPACES) == 1) {
-            Element inclusiveElement =
-                XMLUtils.selectNode(
-               _transformObject.getElement().getFirstChild(),
-                  InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
-                  InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0);
+            if (transformObject.length(
+                InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
+                InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1
+            ) {
+                Element inclusiveElement =
+                    XMLUtils.selectNode(
+                        transformObject.getElement().getFirstChild(),
+                        InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
+                        InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,
+                        0
+                    );
 
-            inclusiveNamespaces = new InclusiveNamespaces(inclusiveElement,
-                    _transformObject.getBaseURI()).getInclusiveNamespaces();
-         }
+                inclusiveNamespaces =
+                    new InclusiveNamespaces(
+                        inclusiveElement, transformObject.getBaseURI()).getInclusiveNamespaces();
+            }
 
-         Canonicalizer20010315ExclOmitComments c14n =
-            new Canonicalizer20010315ExclOmitComments();
-         if (os!=null) {
-            c14n.setWriter(os);
-         }
-         byte []result;
-         result =c14n.engineCanonicalize(input, inclusiveNamespaces);
+            Canonicalizer20010315ExclOmitComments c14n =
+                new Canonicalizer20010315ExclOmitComments();
+            if (os != null) {
+                c14n.setWriter(os);
+            }
+            byte[] result = c14n.engineCanonicalize(input, inclusiveNamespaces);
 
-         XMLSignatureInput output=new XMLSignatureInput(result);
-         if (os!=null) {
-            output.setOutputStream(os);
-         }
-         return output;
-      } catch (XMLSecurityException ex) {
-         throw new CanonicalizationException("empty", ex);
-      }
-   }
+            XMLSignatureInput output = new XMLSignatureInput(result);
+            if (os != null) {
+                output.setOutputStream(os);
+            }
+            return output;
+        } catch (XMLSecurityException ex) {
+            throw new CanonicalizationException("empty", ex);
+        }
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.implementations;
 
@@ -41,59 +43,54 @@
  */
 public class TransformC14NExclusiveWithComments extends TransformSpi {
 
-   /** Field implementedTransformURI */
-   public static final String implementedTransformURI =
-      Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS;
-
-   /**
-    * Method engineGetURI
-    *@inheritDoc
-    *
-    */
-   protected String engineGetURI() {
-      return implementedTransformURI;
-   }
+    /** Field implementedTransformURI */
+    public static final String implementedTransformURI =
+        Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS;
 
-   /**
-    * @inheritDoc
-    */
-   protected XMLSignatureInput enginePerformTransform
-        (XMLSignatureInput input, Transform _transformObject)
-           throws CanonicalizationException {
-            return enginePerformTransform(input, null, _transformObject);
-   }
+    /**
+     * Method engineGetURI
+     *@inheritDoc
+     *
+     */
+    protected String engineGetURI() {
+        return implementedTransformURI;
+    }
 
-    protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject)
-    throws CanonicalizationException {
-     try {
-        String inclusiveNamespaces = null;
+    protected XMLSignatureInput enginePerformTransform(
+        XMLSignatureInput input, OutputStream os, Transform transformObject
+    ) throws CanonicalizationException {
+        try {
+            String inclusiveNamespaces = null;
 
-        if (_transformObject
-                .length(InclusiveNamespaces
-                   .ExclusiveCanonicalizationNamespace, InclusiveNamespaces
-                   ._TAG_EC_INCLUSIVENAMESPACES) == 1) {
-           Element inclusiveElement =
-               XMLUtils.selectNode(
-              _transformObject.getElement().getFirstChild(),
-                 InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
-                 InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0);
-
-           inclusiveNamespaces = new InclusiveNamespaces(inclusiveElement,
-                   _transformObject.getBaseURI()).getInclusiveNamespaces();
-        }
+            if (transformObject.length(
+                InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
+                InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1
+            ) {
+                Element inclusiveElement =
+                    XMLUtils.selectNode(
+                        transformObject.getElement().getFirstChild(),
+                        InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
+                        InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,
+                        0
+                    );
 
-        Canonicalizer20010315ExclWithComments c14n =
-            new Canonicalizer20010315ExclWithComments();
-        if (os!=null) {
-           c14n.setWriter( os);
+                inclusiveNamespaces =
+                    new InclusiveNamespaces(
+                        inclusiveElement, transformObject.getBaseURI()
+                    ).getInclusiveNamespaces();
+            }
+
+            Canonicalizer20010315ExclWithComments c14n =
+                new Canonicalizer20010315ExclWithComments();
+            if (os != null) {
+                c14n.setWriter(os);
+            }
+            byte[] result = c14n.engineCanonicalize(input, inclusiveNamespaces);
+            XMLSignatureInput output = new XMLSignatureInput(result);
+
+            return output;
+        } catch (XMLSecurityException ex) {
+            throw new CanonicalizationException("empty", ex);
         }
-        byte []result;
-        result =c14n.engineCanonicalize(input, inclusiveNamespaces);
-        XMLSignatureInput output=new XMLSignatureInput(result);
-
-        return output;
-     } catch (XMLSecurityException ex) {
-        throw new CanonicalizationException("empty", ex);
-     }
-   }
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.implementations;
 
@@ -37,37 +39,31 @@
  */
 public class TransformC14NWithComments extends TransformSpi {
 
-   /** Field implementedTransformURI */
-   public static final String implementedTransformURI =
-      Transforms.TRANSFORM_C14N_WITH_COMMENTS;
-
-   /** @inheritDoc */
-   protected String engineGetURI() {
-      return implementedTransformURI;
-   }
+    /** Field implementedTransformURI */
+    public static final String implementedTransformURI =
+        Transforms.TRANSFORM_C14N_WITH_COMMENTS;
 
-   /** @inheritDoc */
-   protected XMLSignatureInput enginePerformTransform
-        (XMLSignatureInput input, Transform _transformObject)
-        throws CanonicalizationException {
-            return enginePerformTransform(input, null, _transformObject);
-   }
+    /** @inheritDoc */
+    protected String engineGetURI() {
+        return implementedTransformURI;
+    }
 
-   /** @inheritDoc */
-   protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject)
-           throws CanonicalizationException {
+    /** @inheritDoc */
+    protected XMLSignatureInput enginePerformTransform(
+        XMLSignatureInput input, OutputStream os, Transform transformObject
+    ) throws CanonicalizationException {
 
         Canonicalizer20010315WithComments c14n = new Canonicalizer20010315WithComments();
-        if (os!=null) {
-                c14n.setWriter( os);
+        if (os != null) {
+            c14n.setWriter(os);
         }
 
-         byte[] result = null;
-         result=c14n.engineCanonicalize(input);
-         XMLSignatureInput output=new XMLSignatureInput(result);
-         if (os!=null) {
-                output.setOutputStream(os);
-         }
-         return output;
-   }
+        byte[] result = null;
+        result = c14n.engineCanonicalize(input);
+        XMLSignatureInput output = new XMLSignatureInput(result);
+        if (os != null) {
+            output.setOutputStream(os);
+        }
+        return output;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,24 +2,28 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.implementations;
 
+import java.io.OutputStream;
+
 import com.sun.org.apache.xml.internal.security.signature.NodeFilter;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import com.sun.org.apache.xml.internal.security.transforms.Transform;
@@ -39,99 +43,99 @@
  */
 public class TransformEnvelopedSignature extends TransformSpi {
 
-   /** Field implementedTransformURI */
-   public static final String implementedTransformURI =
-      Transforms.TRANSFORM_ENVELOPED_SIGNATURE;
-
-   /**
-    * Method engineGetURI
-    *
-    * @inheritDoc
-    */
-   protected String engineGetURI() {
-      return implementedTransformURI;
-   }
+    /** Field implementedTransformURI */
+    public static final String implementedTransformURI =
+        Transforms.TRANSFORM_ENVELOPED_SIGNATURE;
 
-   /**
-    * @inheritDoc
-    */
-   protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject)
-           throws TransformationException {
-
-
-
-         /**
-          * If the actual input is an octet stream, then the application MUST
-          * convert the octet stream to an XPath node-set suitable for use by
-          * Canonical XML with Comments. (A subsequent application of the
-          * REQUIRED Canonical XML algorithm would strip away these comments.)
-          *
-          * ...
-          *
-          * The evaluation of this expression includes all of the document's nodes
-          * (including comments) in the node-set representing the octet stream.
-          */
+    /**
+     * Method engineGetURI
+     *
+     * @inheritDoc
+     */
+    protected String engineGetURI() {
+        return implementedTransformURI;
+    }
 
-         Node signatureElement = _transformObject.getElement();
-
+    /**
+     * @inheritDoc
+     */
+    protected XMLSignatureInput enginePerformTransform(
+        XMLSignatureInput input, OutputStream os, Transform transformObject
+    ) throws TransformationException {
+        /**
+         * If the actual input is an octet stream, then the application MUST
+         * convert the octet stream to an XPath node-set suitable for use by
+         * Canonical XML with Comments. (A subsequent application of the
+         * REQUIRED Canonical XML algorithm would strip away these comments.)
+         *
+         * ...
+         *
+         * The evaluation of this expression includes all of the document's nodes
+         * (including comments) in the node-set representing the octet stream.
+         */
 
-         signatureElement = searchSignatureElement(signatureElement);
-                input.setExcludeNode(signatureElement);
-                input.addNodeFilter(new EnvelopedNodeFilter(signatureElement));
-                return input;
-
-         //
-
-
-   }
+        Node signatureElement = transformObject.getElement();
 
-   /**
-    * @param signatureElement
-    * @return the node that is the signature
-    * @throws TransformationException
-    */
-    private static Node searchSignatureElement(Node signatureElement) throws TransformationException {
-            boolean found=false;
+        signatureElement = searchSignatureElement(signatureElement);
+        input.setExcludeNode(signatureElement);
+        input.addNodeFilter(new EnvelopedNodeFilter(signatureElement));
+        return input;
+    }
 
-            while (true) {
-                if ((signatureElement == null)
-                    || (signatureElement.getNodeType() == Node.DOCUMENT_NODE)) {
-                        break;
-                }
-                Element el=(Element)signatureElement;
-                if (el.getNamespaceURI().equals(Constants.SignatureSpecNS)
-                    &&
-                       el.getLocalName().equals(Constants._TAG_SIGNATURE)) {
-                        found = true;
-                        break;
-                }
+    /**
+     * @param signatureElement
+     * @return the node that is the signature
+     * @throws TransformationException
+     */
+    private static Node searchSignatureElement(Node signatureElement)
+        throws TransformationException {
+        boolean found = false;
 
-                signatureElement = signatureElement.getParentNode();
+        while (true) {
+            if (signatureElement == null
+                || signatureElement.getNodeType() == Node.DOCUMENT_NODE) {
+                break;
+            }
+            Element el = (Element) signatureElement;
+            if (el.getNamespaceURI().equals(Constants.SignatureSpecNS)
+                && el.getLocalName().equals(Constants._TAG_SIGNATURE)) {
+                found = true;
+                break;
             }
 
-            if (!found) {
-              throw new TransformationException(
-               "envelopedSignatureTransformNotInSignatureElement");
-            }
-            return signatureElement;
+            signatureElement = signatureElement.getParentNode();
+        }
+
+        if (!found) {
+            throw new TransformationException(
+                "transform.envelopedSignatureTransformNotInSignatureElement");
+        }
+        return signatureElement;
     }
+
     static class EnvelopedNodeFilter implements NodeFilter {
+
         Node exclude;
+
         EnvelopedNodeFilter(Node n) {
-            exclude=n;
+            exclude = n;
         }
-    public int isNodeIncludeDO(Node n, int level) {
-        if ((n==exclude))
-                        return -1;
-        return 1;
-    }
+
+        public int isNodeIncludeDO(Node n, int level) {
+            if (n == exclude) {
+                return -1;
+            }
+            return 1;
+        }
+
         /**
          * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node)
          */
         public int isNodeInclude(Node n) {
-                if ((n==exclude) || XMLUtils.isDescendantOrSelf(exclude,n))
-                        return -1;
-                return 1;
+            if (n == exclude || XMLUtils.isDescendantOrSelf(exclude, n)) {
+                return -1;
+            }
+            return 1;
             //return !XMLUtils.isDescendantOrSelf(exclude,n);
         }
     }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,24 +2,28 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.implementations;
 
+import java.io.OutputStream;
+
 import javax.xml.transform.TransformerException;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityRuntimeException;
@@ -29,12 +33,10 @@
 import com.sun.org.apache.xml.internal.security.transforms.TransformSpi;
 import com.sun.org.apache.xml.internal.security.transforms.TransformationException;
 import com.sun.org.apache.xml.internal.security.transforms.Transforms;
-import com.sun.org.apache.xml.internal.security.utils.CachedXPathAPIHolder;
-import com.sun.org.apache.xml.internal.security.utils.CachedXPathFuncHereAPI;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
-import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault;
-import com.sun.org.apache.xpath.internal.objects.XObject;
+import com.sun.org.apache.xml.internal.security.utils.XPathAPI;
+import com.sun.org.apache.xml.internal.security.utils.XPathFactory;
 import org.w3c.dom.DOMException;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
@@ -51,118 +53,112 @@
  */
 public class TransformXPath extends TransformSpi {
 
-   /** Field implementedTransformURI */
-   public static final String implementedTransformURI =
-      Transforms.TRANSFORM_XPATH;
+    /** Field implementedTransformURI */
+    public static final String implementedTransformURI = Transforms.TRANSFORM_XPATH;
 
-   /**
-    * Method engineGetURI
-    *
-    * @inheritDoc
-    */
-   protected String engineGetURI() {
-      return implementedTransformURI;
-   }
-
-   /**
-    * Method enginePerformTransform
-    * @inheritDoc
-    * @param input
-    *
-    * @throws TransformationException
-    */
-   protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject)
-           throws TransformationException {
-
-      try {
+    /**
+     * Method engineGetURI
+     *
+     * @inheritDoc
+     */
+    protected String engineGetURI() {
+        return implementedTransformURI;
+    }
 
-         /**
-          * If the actual input is an octet stream, then the application MUST
-          * convert the octet stream to an XPath node-set suitable for use by
-          * Canonical XML with Comments. (A subsequent application of the
-          * REQUIRED Canonical XML algorithm would strip away these comments.)
-          *
-          * ...
-          *
-          * The evaluation of this expression includes all of the document's nodes
-          * (including comments) in the node-set representing the octet stream.
-          */
-                  CachedXPathAPIHolder.setDoc(_transformObject.getElement().getOwnerDocument());
-
-
-
-         Element xpathElement =XMLUtils.selectDsNode(
-            _transformObject.getElement().getFirstChild(),
-               Constants._TAG_XPATH,0);
-
-         if (xpathElement == null) {
-            Object exArgs[] = { "ds:XPath", "Transform" };
+    /**
+     * Method enginePerformTransform
+     * @inheritDoc
+     * @param input
+     *
+     * @throws TransformationException
+     */
+    protected XMLSignatureInput enginePerformTransform(
+        XMLSignatureInput input, OutputStream os, Transform transformObject
+    ) throws TransformationException {
+        try {
+            /**
+             * If the actual input is an octet stream, then the application MUST
+             * convert the octet stream to an XPath node-set suitable for use by
+             * Canonical XML with Comments. (A subsequent application of the
+             * REQUIRED Canonical XML algorithm would strip away these comments.)
+             *
+             * ...
+             *
+             * The evaluation of this expression includes all of the document's nodes
+             * (including comments) in the node-set representing the octet stream.
+             */
+            Element xpathElement =
+                XMLUtils.selectDsNode(
+                    transformObject.getElement().getFirstChild(), Constants._TAG_XPATH, 0);
 
-            throw new TransformationException("xml.WrongContent", exArgs);
-         }
-         Node xpathnode = xpathElement.getChildNodes().item(0);
-         String str=CachedXPathFuncHereAPI.getStrFromNode(xpathnode);
-         input.setNeedsToBeExpanded(needsCircunvent(str));
-         if (xpathnode == null) {
-            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
-                                   "Text must be in ds:Xpath");
-         }
+            if (xpathElement == null) {
+                Object exArgs[] = { "ds:XPath", "Transform" };
 
+                throw new TransformationException("xml.WrongContent", exArgs);
+            }
+            Node xpathnode = xpathElement.getChildNodes().item(0);
+            String str = XMLUtils.getStrFromNode(xpathnode);
+            input.setNeedsToBeExpanded(needsCircumvent(str));
+            if (xpathnode == null) {
+                throw new DOMException(
+                    DOMException.HIERARCHY_REQUEST_ERR, "Text must be in ds:Xpath"
+                );
+            }
 
-         input.addNodeFilter(new XPathNodeFilter( xpathElement, xpathnode, str));
-         input.setNodeSet(true);
-         return input;
-      } catch (DOMException ex) {
-         throw new TransformationException("empty", ex);
-      }
-   }
+            XPathFactory xpathFactory = XPathFactory.newInstance();
+            XPathAPI xpathAPIInstance = xpathFactory.newXPathAPI();
+            input.addNodeFilter(new XPathNodeFilter(xpathElement, xpathnode, str, xpathAPIInstance));
+            input.setNodeSet(true);
+            return input;
+        } catch (DOMException ex) {
+            throw new TransformationException("empty", ex);
+        }
+    }
 
-   /**
-    *  @param str
-    * @return true if needs to be circunvent for bug.
-    */
-    private boolean needsCircunvent(String str) {
-        //return true;
-        //return false;
+    /**
+     * @param str
+     * @return true if needs to be circumvent for bug.
+     */
+    private boolean needsCircumvent(String str) {
         return (str.indexOf("namespace") != -1) || (str.indexOf("name()") != -1);
     }
 
     static class XPathNodeFilter implements NodeFilter {
-        PrefixResolverDefault prefixResolver;
-        CachedXPathFuncHereAPI xPathFuncHereAPI =
-            new CachedXPathFuncHereAPI(CachedXPathAPIHolder.getCachedXPathAPI());
+
+        XPathAPI xPathAPI;
         Node xpathnode;
+        Element xpathElement;
         String str;
-        XPathNodeFilter(Element xpathElement,
-                        Node xpathnode, String str) {
-            this.xpathnode=xpathnode;
-            this.str=str;
-            prefixResolver =new PrefixResolverDefault(xpathElement);
+
+        XPathNodeFilter(Element xpathElement, Node xpathnode, String str, XPathAPI xPathAPI) {
+            this.xpathnode = xpathnode;
+            this.str = str;
+            this.xpathElement = xpathElement;
+            this.xPathAPI = xPathAPI;
         }
 
         /**
          * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node)
          */
         public int isNodeInclude(Node currentNode) {
-            XObject includeInResult;
             try {
-                includeInResult = xPathFuncHereAPI.eval(currentNode,
-                                xpathnode, str,prefixResolver);
-                if (includeInResult.bool())
-                        return 1;
+                boolean include = xPathAPI.evaluate(currentNode, xpathnode, str, xpathElement);
+                if (include) {
+                    return 1;
+                }
                 return 0;
             } catch (TransformerException e) {
                 Object[] eArgs = {currentNode};
-                throw new XMLSecurityRuntimeException
-                    ("signature.Transform.node", eArgs, e);
+                throw new XMLSecurityRuntimeException("signature.Transform.node", eArgs, e);
             } catch (Exception e) {
-                Object[] eArgs = {currentNode, new Short(currentNode.getNodeType())};
-                throw new XMLSecurityRuntimeException
-                    ("signature.Transform.nodeAndType",eArgs, e);
+                Object[] eArgs = {currentNode, Short.valueOf(currentNode.getNodeType())};
+                throw new XMLSecurityRuntimeException("signature.Transform.nodeAndType",eArgs, e);
             }
         }
+
         public int isNodeIncludeDO(Node n, int level) {
-                return isNodeInclude(n);
+            return isNodeInclude(n);
         }
+
     }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,30 +2,30 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.implementations;
 
-
-
 import java.io.IOException;
+import java.io.OutputStream;
 import java.util.ArrayList;
 import java.util.HashSet;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Set;
 
@@ -42,9 +42,9 @@
 import com.sun.org.apache.xml.internal.security.transforms.TransformationException;
 import com.sun.org.apache.xml.internal.security.transforms.Transforms;
 import com.sun.org.apache.xml.internal.security.transforms.params.XPath2FilterContainer;
-import com.sun.org.apache.xml.internal.security.utils.CachedXPathAPIHolder;
-import com.sun.org.apache.xml.internal.security.utils.CachedXPathFuncHereAPI;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
+import com.sun.org.apache.xml.internal.security.utils.XPathAPI;
+import com.sun.org.apache.xml.internal.security.utils.XPathFactory;
 import org.w3c.dom.DOMException;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -55,254 +55,241 @@
 /**
  * Implements the <I>XML Signature XPath Filter v2.0</I>
  *
- * @author $Author: mullan $
  * @see <A HREF="http://www.w3.org/TR/xmldsig-filter2/">XPath Filter v2.0 (TR)</A>
- * @see <a HREF="http://www.w3.org/Signature/Drafts/xmldsig-xfilter2/">XPath Filter v2.0 (editors copy)</a>
  */
 public class TransformXPath2Filter extends TransformSpi {
 
-   /** {@link java.util.logging} logging facility */
-//    static java.util.logging.Logger log =
-//        java.util.logging.Logger.getLogger(
-//                            TransformXPath2Filter.class.getName());
-
-   /** Field implementedTransformURI */
-   public static final String implementedTransformURI =
-      Transforms.TRANSFORM_XPATH2FILTER;
-   //J-
-   // contains the type of the filter
+    /** Field implementedTransformURI */
+    public static final String implementedTransformURI =
+        Transforms.TRANSFORM_XPATH2FILTER;
 
-   // contains the node set
-
-   /**
-    * Method engineGetURI
-    *
-    * @inheritDoc
-    */
-   protected String engineGetURI() {
-      return implementedTransformURI;
-   }
-
-
+    /**
+     * Method engineGetURI
+     *
+     * @inheritDoc
+     */
+    protected String engineGetURI() {
+        return implementedTransformURI;
+    }
 
-   /**
-    * Method enginePerformTransform
-    * @inheritDoc
-    * @param input
-    *
-    * @throws TransformationException
-    */
-   protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject)
-           throws TransformationException {
-          CachedXPathAPIHolder.setDoc(_transformObject.getElement().getOwnerDocument());
-      try {
-          List<NodeList> unionNodes=new ArrayList<NodeList>();
-          List<NodeList> substractNodes=new ArrayList<NodeList>();
-          List<NodeList> intersectNodes=new ArrayList<NodeList>();
+    /**
+     * Method enginePerformTransform
+     * @inheritDoc
+     * @param input
+     *
+     * @throws TransformationException
+     */
+    protected XMLSignatureInput enginePerformTransform(
+        XMLSignatureInput input, OutputStream os, Transform transformObject
+    ) throws TransformationException {
+        try {
+            List<NodeList> unionNodes = new ArrayList<NodeList>();
+            List<NodeList> subtractNodes = new ArrayList<NodeList>();
+            List<NodeList> intersectNodes = new ArrayList<NodeList>();
 
-         CachedXPathFuncHereAPI xPathFuncHereAPI =
-            new CachedXPathFuncHereAPI(CachedXPathAPIHolder.getCachedXPathAPI());
-
+            Element[] xpathElements =
+                XMLUtils.selectNodes(
+                    transformObject.getElement().getFirstChild(),
+                    XPath2FilterContainer.XPathFilter2NS,
+                    XPath2FilterContainer._TAG_XPATH2
+                );
+            if (xpathElements.length == 0) {
+                Object exArgs[] = { Transforms.TRANSFORM_XPATH2FILTER, "XPath" };
 
-         Element []xpathElements =XMLUtils.selectNodes(
-                _transformObject.getElement().getFirstChild(),
-                   XPath2FilterContainer.XPathFilter2NS,
-                   XPath2FilterContainer._TAG_XPATH2);
-         int noOfSteps = xpathElements.length;
+                throw new TransformationException("xml.WrongContent", exArgs);
+            }
 
-
-         if (noOfSteps == 0) {
-            Object exArgs[] = { Transforms.TRANSFORM_XPATH2FILTER, "XPath" };
+            Document inputDoc = null;
+            if (input.getSubNode() != null) {
+                inputDoc = XMLUtils.getOwnerDocument(input.getSubNode());
+            } else {
+                inputDoc = XMLUtils.getOwnerDocument(input.getNodeSet());
+            }
 
-            throw new TransformationException("xml.WrongContent", exArgs);
-         }
+            for (int i = 0; i < xpathElements.length; i++) {
+                Element xpathElement = xpathElements[i];
 
-         Document inputDoc = null;
-         if (input.getSubNode() != null) {
-            inputDoc = XMLUtils.getOwnerDocument(input.getSubNode());
-         } else {
-            inputDoc = XMLUtils.getOwnerDocument(input.getNodeSet());
-         }
+                XPath2FilterContainer xpathContainer =
+                    XPath2FilterContainer.newInstance(xpathElement, input.getSourceURI());
 
-         for (int i = 0; i < noOfSteps; i++) {
-            Element xpathElement =XMLUtils.selectNode(
-               _transformObject.getElement().getFirstChild(),
-                  XPath2FilterContainer.XPathFilter2NS,
-                  XPath2FilterContainer._TAG_XPATH2,i);
-            XPath2FilterContainer xpathContainer =
-               XPath2FilterContainer.newInstance(xpathElement,
-                                                   input.getSourceURI());
+                String str =
+                    XMLUtils.getStrFromNode(xpathContainer.getXPathFilterTextNode());
 
+                XPathFactory xpathFactory = XPathFactory.newInstance();
+                XPathAPI xpathAPIInstance = xpathFactory.newXPathAPI();
 
-            NodeList subtreeRoots = xPathFuncHereAPI.selectNodeList(inputDoc,
-                                       xpathContainer.getXPathFilterTextNode(),
-                                       CachedXPathFuncHereAPI.getStrFromNode(xpathContainer.getXPathFilterTextNode()),
-                                       xpathContainer.getElement());
-            if (xpathContainer.isIntersect()) {
-                intersectNodes.add(subtreeRoots);
-             } else if (xpathContainer.isSubtract()) {
-                 substractNodes.add(subtreeRoots);
-             } else if (xpathContainer.isUnion()) {
-                unionNodes.add(subtreeRoots);
-             }
-         }
-
+                NodeList subtreeRoots =
+                    xpathAPIInstance.selectNodeList(
+                        inputDoc,
+                        xpathContainer.getXPathFilterTextNode(),
+                        str,
+                        xpathContainer.getElement());
+                if (xpathContainer.isIntersect()) {
+                    intersectNodes.add(subtreeRoots);
+                } else if (xpathContainer.isSubtract()) {
+                    subtractNodes.add(subtreeRoots);
+                } else if (xpathContainer.isUnion()) {
+                    unionNodes.add(subtreeRoots);
+                }
+            }
 
-         input.addNodeFilter(new XPath2NodeFilter(unionNodes, substractNodes,
-                                                  intersectNodes));
-         input.setNodeSet(true);
-         return input;
-      } catch (TransformerException ex) {
-         throw new TransformationException("empty", ex);
-      } catch (DOMException ex) {
-         throw new TransformationException("empty", ex);
-      } catch (CanonicalizationException ex) {
-         throw new TransformationException("empty", ex);
-      } catch (InvalidCanonicalizerException ex) {
-         throw new TransformationException("empty", ex);
-      } catch (XMLSecurityException ex) {
-         throw new TransformationException("empty", ex);
-      } catch (SAXException ex) {
-         throw new TransformationException("empty", ex);
-      } catch (IOException ex) {
-         throw new TransformationException("empty", ex);
-      } catch (ParserConfigurationException ex) {
-         throw new TransformationException("empty", ex);
-      }
-   }
+            input.addNodeFilter(
+                new XPath2NodeFilter(unionNodes, subtractNodes, intersectNodes)
+            );
+            input.setNodeSet(true);
+            return input;
+        } catch (TransformerException ex) {
+            throw new TransformationException("empty", ex);
+        } catch (DOMException ex) {
+            throw new TransformationException("empty", ex);
+        } catch (CanonicalizationException ex) {
+            throw new TransformationException("empty", ex);
+        } catch (InvalidCanonicalizerException ex) {
+            throw new TransformationException("empty", ex);
+        } catch (XMLSecurityException ex) {
+            throw new TransformationException("empty", ex);
+        } catch (SAXException ex) {
+            throw new TransformationException("empty", ex);
+        } catch (IOException ex) {
+            throw new TransformationException("empty", ex);
+        } catch (ParserConfigurationException ex) {
+            throw new TransformationException("empty", ex);
+        }
+    }
 }
 
 class XPath2NodeFilter implements NodeFilter {
-        boolean hasUnionFilter;
-        boolean hasSubstractFilter;
-        boolean hasIntersectFilter;
-        XPath2NodeFilter(List<NodeList> unionNodes, List<NodeList> substractNodes,
-                        List<NodeList> intersectNodes) {
-                hasUnionFilter=!unionNodes.isEmpty();
-                this.unionNodes=convertNodeListToSet(unionNodes);
-                hasSubstractFilter=!substractNodes.isEmpty();
-                this.substractNodes=convertNodeListToSet(substractNodes);
-                hasIntersectFilter=!intersectNodes.isEmpty();
-                this.intersectNodes=convertNodeListToSet(intersectNodes);
-        }
-        Set<Node> unionNodes;
-        Set<Node> substractNodes;
-        Set<Node> intersectNodes;
 
+    boolean hasUnionFilter;
+    boolean hasSubtractFilter;
+    boolean hasIntersectFilter;
+    Set<Node> unionNodes;
+    Set<Node> subtractNodes;
+    Set<Node> intersectNodes;
+    int inSubtract = -1;
+    int inIntersect = -1;
+    int inUnion = -1;
+
+    XPath2NodeFilter(List<NodeList> unionNodes, List<NodeList> subtractNodes,
+                     List<NodeList> intersectNodes) {
+        hasUnionFilter = !unionNodes.isEmpty();
+        this.unionNodes = convertNodeListToSet(unionNodes);
+        hasSubtractFilter = !subtractNodes.isEmpty();
+        this.subtractNodes = convertNodeListToSet(subtractNodes);
+        hasIntersectFilter = !intersectNodes.isEmpty();
+        this.intersectNodes = convertNodeListToSet(intersectNodes);
+    }
 
-   /**
-    * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node)
-    */
-   public int isNodeInclude(Node currentNode) {
-           int result=1;
+    /**
+     * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node)
+     */
+    public int isNodeInclude(Node currentNode) {
+        int result = 1;
+
+        if (hasSubtractFilter && rooted(currentNode, subtractNodes)) {
+            result = -1;
+        } else if (hasIntersectFilter && !rooted(currentNode, intersectNodes)) {
+            result = 0;
+        }
 
-           if (hasSubstractFilter && rooted(currentNode, substractNodes)) {
-                      result = -1;
-           } else if (hasIntersectFilter && !rooted(currentNode, intersectNodes)) {
-                   result = 0;
-           }
-
-          //TODO OPTIMIZE
-      if (result==1)
-          return 1;
-      if (hasUnionFilter) {
-          if (rooted(currentNode, unionNodes)) {
-                   return 1;
-          }
-          result=0;
-      }
-      return result;
+        //TODO OPTIMIZE
+        if (result == 1) {
+            return 1;
+        }
+        if (hasUnionFilter) {
+            if (rooted(currentNode, unionNodes)) {
+                return 1;
+            }
+            result = 0;
+        }
+        return result;
+    }
 
-   }
-   int inSubstract=-1;
-   int inIntersect=-1;
-   int inUnion=-1;
-   public int isNodeIncludeDO(Node n, int level) {
-           int result=1;
-           if (hasSubstractFilter) {
-                   if ((inSubstract==-1) || (level<=inSubstract)) {
-                           if (inList(n,  substractNodes)) {
-                                   inSubstract=level;
-                           } else {
-                                   inSubstract=-1;
-                           }
-                   }
-                   if (inSubstract!=-1){
-                           result=-1;
-                   }
-           }
-           if (result!=-1){
-                   if (hasIntersectFilter) {
-                   if ((inIntersect==-1) || (level<=inIntersect)) {
-                           if (!inList(n,  intersectNodes)) {
-                                   inIntersect=-1;
-                                   result=0;
-                           } else {
-                                   inIntersect=level;
-                           }
-                   }
-                   }
-           }
+    public int isNodeIncludeDO(Node n, int level) {
+        int result = 1;
+        if (hasSubtractFilter) {
+            if ((inSubtract == -1) || (level <= inSubtract)) {
+                if (inList(n, subtractNodes)) {
+                    inSubtract = level;
+                } else {
+                    inSubtract = -1;
+                }
+            }
+            if (inSubtract != -1){
+                result = -1;
+            }
+        }
+        if (result != -1 && hasIntersectFilter
+            && ((inIntersect == -1) || (level <= inIntersect))) {
+            if (!inList(n, intersectNodes)) {
+                inIntersect = -1;
+                result = 0;
+            } else {
+                inIntersect = level;
+            }
+        }
 
-          if (level<=inUnion)
-                   inUnion=-1;
-      if (result==1)
-          return 1;
-      if (hasUnionFilter) {
-          if ((inUnion==-1) && inList(n,  unionNodes)) {
-                  inUnion=level;
-          }
-          if (inUnion!=-1)
-                  return 1;
-          result=0;
-      }
+        if (level <= inUnion) {
+            inUnion = -1;
+        }
+        if (result == 1) {
+            return 1;
+        }
+        if (hasUnionFilter) {
+            if ((inUnion == -1) && inList(n, unionNodes)) {
+                inUnion = level;
+            }
+            if (inUnion != -1) {
+                return 1;
+            }
+            result=0;
+        }
+
+        return result;
+    }
 
-      return result;
-   }
-
-   /**
-    * Method rooted
-    * @param currentNode
-    * @param nodeList
-    *
-    * @return if rooted bye the rootnodes
-    */
-   static boolean  rooted(Node currentNode, Set<Node> nodeList ) {
-           if (nodeList.isEmpty()) {
-               return false;
-           }
-           if (nodeList.contains(currentNode)) {
-                   return true;
-           }
+    /**
+     * Method rooted
+     * @param currentNode
+     * @param nodeList
+     *
+     * @return if rooted bye the rootnodes
+     */
+    static boolean rooted(Node currentNode, Set<Node> nodeList) {
+        if (nodeList.isEmpty()) {
+            return false;
+        }
+        if (nodeList.contains(currentNode)) {
+            return true;
+        }
+        for (Node rootNode : nodeList) {
+            if (XMLUtils.isDescendantOrSelf(rootNode, currentNode)) {
+                return true;
+            }
+        }
+        return false;
+    }
 
-           for(Node rootNode : nodeList) {
-               if (XMLUtils.isDescendantOrSelf(rootNode,currentNode)) {
-                   return true;
-               }
-           }
-           return false;
-   }
+    /**
+     * Method rooted
+     * @param currentNode
+     * @param nodeList
+     *
+     * @return if rooted bye the rootnodes
+     */
+    static boolean inList(Node currentNode, Set<Node> nodeList) {
+        return nodeList.contains(currentNode);
+    }
 
-      /**
-       * Method rooted
-       * @param currentNode
-       * @param nodeList
-       *
-       * @return if rooted bye the rootnodes
-       */
-      static boolean  inList(Node currentNode, Set<Node> nodeList ) {
-              return nodeList.contains(currentNode);
-      }
+    private static Set<Node> convertNodeListToSet(List<NodeList> l) {
+        Set<Node> result = new HashSet<Node>();
+        for (NodeList rootNodes : l) {
+            int length = rootNodes.getLength();
 
-    private static Set<Node> convertNodeListToSet(List<NodeList> l){
-        Set<Node> result=new HashSet<Node>();
-
-        for (NodeList rootNodes : l) {
-             int length = rootNodes.getLength();
-             for (int i = 0; i < length; i++) {
-                 Node rootNode = rootNodes.item(i);
-                 result.add(rootNode);
-             }
+            for (int i = 0; i < length; i++) {
+                Node rootNode = rootNodes.item(i);
+                result.add(rootNode);
+            }
         }
         return result;
     }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,27 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.implementations;
 
-
-
+import java.io.OutputStream;
 
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import com.sun.org.apache.xml.internal.security.transforms.Transform;
@@ -29,8 +30,6 @@
 import com.sun.org.apache.xml.internal.security.transforms.TransformationException;
 import com.sun.org.apache.xml.internal.security.transforms.Transforms;
 
-
-
 /**
  * Class TransformXPointer
  *
@@ -38,30 +37,29 @@
  */
 public class TransformXPointer extends TransformSpi {
 
-   /** Field implementedTransformURI */
-   public static final String implementedTransformURI =
-      Transforms.TRANSFORM_XPOINTER;
+    /** Field implementedTransformURI */
+    public static final String implementedTransformURI =
+        Transforms.TRANSFORM_XPOINTER;
 
 
-   /** @inheritDoc */
-   protected String engineGetURI() {
-      return implementedTransformURI;
-   }
+    /** @inheritDoc */
+    protected String engineGetURI() {
+        return implementedTransformURI;
+    }
 
-   /**
-    * Method enginePerformTransform
-    *
-    * @param input
-    * @return  {@link XMLSignatureInput} as the result of transformation
-    * @throws TransformationException
-    *
-    */
-   protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject)
-           throws  TransformationException {
+    /**
+     * Method enginePerformTransform
+     *
+     * @param input
+     * @return  {@link XMLSignatureInput} as the result of transformation
+     * @throws TransformationException
+     */
+    protected XMLSignatureInput enginePerformTransform(
+        XMLSignatureInput input, OutputStream os, Transform transformObject
+    ) throws TransformationException {
 
-      Object exArgs[] = { implementedTransformURI };
+        Object exArgs[] = { implementedTransformURI };
 
-      throw new TransformationException(
-         "signature.Transform.NotYetImplemented", exArgs);
-   }
+        throw new TransformationException("signature.Transform.NotYetImplemented", exArgs);
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 1999-2007 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.implementations;
 
@@ -24,7 +26,6 @@
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.OutputStream;
-import java.lang.reflect.Method;
 
 import javax.xml.XMLConstants;
 import javax.xml.transform.Source;
@@ -55,132 +56,112 @@
  */
 public class TransformXSLT extends TransformSpi {
 
-   /** Field implementedTransformURI */
-   public static final String implementedTransformURI =
-      Transforms.TRANSFORM_XSLT;
-   //J-
-   static final String XSLTSpecNS              = "http://www.w3.org/1999/XSL/Transform";
-   static final String defaultXSLTSpecNSprefix = "xslt";
-   static final String XSLTSTYLESHEET          = "stylesheet";
+    /** Field implementedTransformURI */
+    public static final String implementedTransformURI =
+        Transforms.TRANSFORM_XSLT;
+
+    static final String XSLTSpecNS              = "http://www.w3.org/1999/XSL/Transform";
+    static final String defaultXSLTSpecNSprefix = "xslt";
+    static final String XSLTSTYLESHEET          = "stylesheet";
 
-   static java.util.logging.Logger log =
-      java.util.logging.Logger.getLogger(
-         TransformXSLT.class.getName());
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(TransformXSLT.class.getName());
 
-   /**
-    * Method engineGetURI
-    *
-    * @inheritDoc
-    */
-   protected String engineGetURI() {
-      return implementedTransformURI;
-   }
+    /**
+     * Method engineGetURI
+     *
+     * @inheritDoc
+     */
+    protected String engineGetURI() {
+        return implementedTransformURI;
+    }
 
-   /**
-    * Method enginePerformTransform
-    *
-    * @param input the input for this transform
-    * @return the result of this Transform
-    * @throws IOException
-    * @throws TransformationException
-    */
-   protected XMLSignatureInput enginePerformTransform
-        (XMLSignatureInput input, Transform _transformObject)
-           throws IOException,
-                  TransformationException {
-        return enginePerformTransform(input, null, _transformObject);
-   }
+    protected XMLSignatureInput enginePerformTransform(
+        XMLSignatureInput input, OutputStream baos, Transform transformObject
+    ) throws IOException, TransformationException {
+        try {
+            Element transformElement = transformObject.getElement();
+
+            Element xsltElement =
+                XMLUtils.selectNode(transformElement.getFirstChild(), XSLTSpecNS, "stylesheet", 0);
+
+            if (xsltElement == null) {
+                Object exArgs[] = { "xslt:stylesheet", "Transform" };
 
-    protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream baos, Transform _transformObject)
-    throws IOException,
-           TransformationException {
-      try {
-         Element transformElement = _transformObject.getElement();
+                throw new TransformationException("xml.WrongContent", exArgs);
+            }
+
+            TransformerFactory tFactory = TransformerFactory.newInstance();
+            // Process XSLT stylesheets in a secure manner
+            tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
 
-         Element _xsltElement =
-            XMLUtils.selectNode(transformElement.getFirstChild(),
-                                                XSLTSpecNS,"stylesheet", 0);
-
-         if (_xsltElement == null) {
-            Object exArgs[] = { "xslt:stylesheet", "Transform" };
-
-            throw new TransformationException("xml.WrongContent", exArgs);
-         }
-
-         TransformerFactory tFactory = TransformerFactory.newInstance();
+            /*
+             * This transform requires an octet stream as input. If the actual
+             * input is an XPath node-set, then the signature application should
+             * attempt to convert it to octets (apply Canonical XML]) as described
+             * in the Reference Processing Model (section 4.3.3.2).
+             */
+            Source xmlSource =
+                new StreamSource(new ByteArrayInputStream(input.getBytes()));
+            Source stylesheet;
 
-         // Process XSLT stylesheets in a secure manner
-         tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
-                             Boolean.TRUE);
-         /*
-          * This transform requires an octet stream as input. If the actual
-          * input is an XPath node-set, then the signature application should
-          * attempt to convert it to octets (apply Canonical XML]) as described
-          * in the Reference Processing Model (section 4.3.3.2).
-          */
-         Source xmlSource =
-            new StreamSource(new ByteArrayInputStream(input.getBytes()));
-         Source stylesheet;
+            /*
+             * This complicated transformation of the stylesheet itself is necessary
+             * because of the need to get the pure style sheet. If we simply say
+             * Source stylesheet = new DOMSource(this.xsltElement);
+             * whereby this.xsltElement is not the rootElement of the Document,
+             * this causes problems;
+             * so we convert the stylesheet to byte[] and use this as input stream
+             */
+            {
+                ByteArrayOutputStream os = new ByteArrayOutputStream();
+                Transformer transformer = tFactory.newTransformer();
+                DOMSource source = new DOMSource(xsltElement);
+                StreamResult result = new StreamResult(os);
 
-         /*
-          * This complicated transformation of the stylesheet itself is necessary
-          * because of the need to get the pure style sheet. If we simply say
-          * Source stylesheet = new DOMSource(this._xsltElement);
-          * whereby this._xsltElement is not the rootElement of the Document,
-          * this causes problems;
-          * so we convert the stylesheet to byte[] and use this as input stream
-          */
-         {
-            ByteArrayOutputStream os = new ByteArrayOutputStream();
-            Transformer transformer = tFactory.newTransformer();
-            DOMSource source = new DOMSource(_xsltElement);
-            StreamResult result = new StreamResult(os);
+                transformer.transform(source, result);
 
-            transformer.transform(source, result);
+                stylesheet =
+                    new StreamSource(new ByteArrayInputStream(os.toByteArray()));
+            }
 
-            stylesheet =
-               new StreamSource(new ByteArrayInputStream(os.toByteArray()));
-         }
-
-         Transformer transformer = tFactory.newTransformer(stylesheet);
+            Transformer transformer = tFactory.newTransformer(stylesheet);
 
-         // Force Xalan to use \n as line separator on all OSes. This
-         // avoids OS specific signature validation failures due to line
-         // separator differences in the transformed output. Unfortunately,
-         // this is not a standard JAXP property so will not work with non-Xalan
-         // implementations.
-         try {
-            transformer.setOutputProperty
-               ("{http://xml.apache.org/xalan}line-separator", "\n");
-         } catch (Exception e) {
-            log.log(java.util.logging.Level.WARNING, "Unable to set Xalan line-separator property: "
-               + e.getMessage());
-         }
+            // Force Xalan to use \n as line separator on all OSes. This
+            // avoids OS specific signature validation failures due to line
+            // separator differences in the transformed output. Unfortunately,
+            // this is not a standard JAXP property so will not work with non-Xalan
+            // implementations.
+            try {
+                transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", "\n");
+            } catch (Exception e) {
+                log.log(java.util.logging.Level.WARNING, "Unable to set Xalan line-separator property: " + e.getMessage());
+            }
 
-         if (baos==null) {
-            ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
-            StreamResult outputTarget = new StreamResult(baos1);
+            if (baos == null) {
+                ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
+                StreamResult outputTarget = new StreamResult(baos1);
+                transformer.transform(xmlSource, outputTarget);
+                return new XMLSignatureInput(baos1.toByteArray());
+            }
+            StreamResult outputTarget = new StreamResult(baos);
+
             transformer.transform(xmlSource, outputTarget);
-            return new XMLSignatureInput(baos1.toByteArray());
-         }
-         StreamResult outputTarget = new StreamResult(baos);
-
-         transformer.transform(xmlSource, outputTarget);
-         XMLSignatureInput output=new XMLSignatureInput((byte[])null);
-         output.setOutputStream(baos);
-         return output;
-      } catch (XMLSecurityException ex) {
-         Object exArgs[] = { ex.getMessage() };
+            XMLSignatureInput output = new XMLSignatureInput((byte[])null);
+            output.setOutputStream(baos);
+            return output;
+        } catch (XMLSecurityException ex) {
+            Object exArgs[] = { ex.getMessage() };
 
-         throw new TransformationException("generic.EmptyMessage", exArgs, ex);
-      } catch (TransformerConfigurationException ex) {
-         Object exArgs[] = { ex.getMessage() };
+            throw new TransformationException("generic.EmptyMessage", exArgs, ex);
+        } catch (TransformerConfigurationException ex) {
+            Object exArgs[] = { ex.getMessage() };
 
-         throw new TransformationException("generic.EmptyMessage", exArgs, ex);
-      } catch (TransformerException ex) {
-         Object exArgs[] = { ex.getMessage() };
+            throw new TransformationException("generic.EmptyMessage", exArgs, ex);
+        } catch (TransformerException ex) {
+            Object exArgs[] = { ex.getMessage() };
 
-         throw new TransformationException("generic.EmptyMessage", exArgs, ex);
-      }
-   }
+            throw new TransformationException("generic.EmptyMessage", exArgs, ex);
+        }
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,30 +2,28 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.params;
 
-
-
-import java.util.Iterator;
 import java.util.Set;
 import java.util.SortedSet;
-import java.util.StringTokenizer;
 import java.util.TreeSet;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
@@ -34,7 +32,6 @@
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-
 /**
  * This Object serves as Content for the ds:Transforms for exclusive
  * Canonicalization.
@@ -44,136 +41,130 @@
  *
  * @author Christian Geuer-Pollmann
  */
-public class InclusiveNamespaces extends ElementProxy
-        implements TransformParam {
+public class InclusiveNamespaces extends ElementProxy implements TransformParam {
+
+    /** Field _TAG_EC_INCLUSIVENAMESPACES */
+    public static final String _TAG_EC_INCLUSIVENAMESPACES =
+        "InclusiveNamespaces";
 
-   /** Field _TAG_EC_INCLUSIVENAMESPACES */
-   public static final String _TAG_EC_INCLUSIVENAMESPACES =
-      "InclusiveNamespaces";
+    /** Field _ATT_EC_PREFIXLIST */
+    public static final String _ATT_EC_PREFIXLIST = "PrefixList";
 
-   /** Field _ATT_EC_PREFIXLIST */
-   public static final String _ATT_EC_PREFIXLIST = "PrefixList";
+    /** Field ExclusiveCanonicalizationNamespace */
+    public static final String ExclusiveCanonicalizationNamespace =
+        "http://www.w3.org/2001/10/xml-exc-c14n#";
 
-   /** Field ExclusiveCanonicalizationNamespace */
-   public static final String ExclusiveCanonicalizationNamespace =
-      "http://www.w3.org/2001/10/xml-exc-c14n#";
+    /**
+     * Constructor XPathContainer
+     *
+     * @param doc
+     * @param prefixList
+     */
+    public InclusiveNamespaces(Document doc, String prefixList) {
+        this(doc, InclusiveNamespaces.prefixStr2Set(prefixList));
+    }
 
-   /**
-    * Constructor XPathContainer
-    *
-    * @param doc
-    * @param prefixList
-    */
-   public InclusiveNamespaces(Document doc, String prefixList) {
-      this(doc, InclusiveNamespaces.prefixStr2Set(prefixList));
-   }
+    /**
+     * Constructor InclusiveNamespaces
+     *
+     * @param doc
+     * @param prefixes
+     */
+    public InclusiveNamespaces(Document doc, Set<String> prefixes) {
+        super(doc);
 
-   /**
-    * Constructor InclusiveNamespaces
-    *
-    * @param doc
-    * @param prefixes
-    */
-   public InclusiveNamespaces(Document doc, Set<String> prefixes) {
+        SortedSet<String> prefixList = null;
+        if (prefixes instanceof SortedSet<?>) {
+            prefixList = (SortedSet<String>)prefixes;
+        } else {
+            prefixList = new TreeSet<String>(prefixes);
+        }
 
-      super(doc);
-
-      StringBuffer sb = new StringBuffer();
-      SortedSet<String> prefixList = new TreeSet<String>(prefixes);
-
-
+        StringBuilder sb = new StringBuilder();
+        for (String prefix : prefixList) {
+            if (prefix.equals("xmlns")) {
+                sb.append("#default ");
+            } else {
+                sb.append(prefix + " ");
+            }
+        }
 
-      for (String prefix : prefixList) {
-         if (prefix.equals("xmlns")) {
-            sb.append("#default ");
-         } else {
-            sb.append(prefix + " ");
-         }
-      }
+        this.constructionElement.setAttributeNS(
+            null, InclusiveNamespaces._ATT_EC_PREFIXLIST, sb.toString().trim());
+    }
 
-      this._constructionElement
-         .setAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST,
-                       sb.toString().trim());
-   }
-
-   /**
-    * Method getInclusiveNamespaces
-    *
-    * @return The Inclusive Namespace string
-    */
-   public String getInclusiveNamespaces() {
-      return this._constructionElement
-         .getAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST);
-   }
+    /**
+     * Constructor InclusiveNamespaces
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public InclusiveNamespaces(Element element, String BaseURI)
+        throws XMLSecurityException {
+        super(element, BaseURI);
+    }
 
-   /**
-    * Constructor InclusiveNamespaces
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public InclusiveNamespaces(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
-   }
+    /**
+     * Method getInclusiveNamespaces
+     *
+     * @return The Inclusive Namespace string
+     */
+    public String getInclusiveNamespaces() {
+        return this.constructionElement.getAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST);
+    }
 
-   /**
-    * Decodes the <code>inclusiveNamespaces</code> String and returns all
-    * selected namespace prefixes as a Set. The <code>#default</code>
-    * namespace token is represented as an empty namespace prefix
-    * (<code>"xmlns"</code>).
-    * <BR/>
-    * The String <code>inclusiveNamespaces=" xenc    ds #default"</code>
-    * is returned as a Set containing the following Strings:
-    * <UL>
-    * <LI><code>xmlns</code></LI>
-    * <LI><code>xenc</code></LI>
-    * <LI><code>ds</code></LI>
-    * </UL>
-    *
-    * @param inclusiveNamespaces
-    * @return A set to string
-    */
-   public static SortedSet<String> prefixStr2Set(String inclusiveNamespaces) {
-
-      SortedSet<String> prefixes = new TreeSet<String>();
+    /**
+     * Decodes the <code>inclusiveNamespaces</code> String and returns all
+     * selected namespace prefixes as a Set. The <code>#default</code>
+     * namespace token is represented as an empty namespace prefix
+     * (<code>"xmlns"</code>).
+     * <BR/>
+     * The String <code>inclusiveNamespaces=" xenc    ds #default"</code>
+     * is returned as a Set containing the following Strings:
+     * <UL>
+     * <LI><code>xmlns</code></LI>
+     * <LI><code>xenc</code></LI>
+     * <LI><code>ds</code></LI>
+     * </UL>
+     *
+     * @param inclusiveNamespaces
+     * @return A set to string
+     */
+    public static SortedSet<String> prefixStr2Set(String inclusiveNamespaces) {
+        SortedSet<String> prefixes = new TreeSet<String>();
 
-      if ((inclusiveNamespaces == null)
-              || (inclusiveNamespaces.length() == 0)) {
-         return prefixes;
-      }
-
-      StringTokenizer st = new StringTokenizer(inclusiveNamespaces, " \t\r\n");
+        if ((inclusiveNamespaces == null) || (inclusiveNamespaces.length() == 0)) {
+            return prefixes;
+        }
 
-      while (st.hasMoreTokens()) {
-         String prefix = st.nextToken();
+        String[] tokens = inclusiveNamespaces.split("\\s");
+        for (String prefix : tokens) {
+            if (prefix.equals("#default")) {
+                prefixes.add("xmlns");
+            } else {
+                prefixes.add(prefix);
+            }
+        }
 
-         if (prefix.equals("#default")) {
-            prefixes.add("xmlns" );
-         } else {
-            prefixes.add( prefix);
-         }
-      }
+        return prefixes;
+    }
 
-      return prefixes;
-   }
+    /**
+     * Method getBaseNamespace
+     *
+     * @inheritDoc
+     */
+    public String getBaseNamespace() {
+        return InclusiveNamespaces.ExclusiveCanonicalizationNamespace;
+    }
 
-   /**
-    * Method getBaseNamespace
-    *
-    * @inheritDoc
-    */
-   public String getBaseNamespace() {
-      return InclusiveNamespaces.ExclusiveCanonicalizationNamespace;
-   }
-
-   /**
-    * Method getBaseLocalName
-    *
-    * @inheritDoc
-    */
-   public String getBaseLocalName() {
-      return InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES;
-   }
+    /**
+     * Method getBaseLocalName
+     *
+     * @inheritDoc
+     */
+    public String getBaseLocalName() {
+        return InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.params;
 
-
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.transforms.TransformParam;
 import com.sun.org.apache.xml.internal.security.utils.ElementProxy;
@@ -32,284 +32,261 @@
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 
-
 /**
  * Implements the parameters for the <A
  * HREF="http://www.w3.org/TR/xmldsig-filter2/">XPath Filter v2.0</A>.
  *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  * @see <A HREF="http://www.w3.org/TR/xmldsig-filter2/">XPath Filter v2.0 (TR)</A>
- * @see <A HREF="http://www.w3.org/Signature/Drafts/xmldsig-xfilter2/">XPath Filter v2.0 (editors copy)</A>
  */
-public class XPath2FilterContainer extends ElementProxy
-        implements TransformParam {
+public class XPath2FilterContainer extends ElementProxy implements TransformParam {
+
+    /** Field _ATT_FILTER */
+    private static final String _ATT_FILTER = "Filter";
 
-   /** Field _ATT_FILTER */
-   private static final String _ATT_FILTER = "Filter";
+    /** Field _ATT_FILTER_VALUE_INTERSECT */
+    private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect";
 
-   /** Field _ATT_FILTER_VALUE_INTERSECT */
-   private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect";
+    /** Field _ATT_FILTER_VALUE_SUBTRACT */
+    private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract";
 
-   /** Field _ATT_FILTER_VALUE_SUBTRACT */
-   private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract";
+    /** Field _ATT_FILTER_VALUE_UNION */
+    private static final String _ATT_FILTER_VALUE_UNION = "union";
 
-   /** Field _ATT_FILTER_VALUE_UNION */
-   private static final String _ATT_FILTER_VALUE_UNION = "union";
+    /** Field INTERSECT */
+    public static final String INTERSECT =
+        XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT;
 
-   /** Field INTERSECT */
-   public static final String INTERSECT =
-      XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT;
+    /** Field SUBTRACT */
+    public static final String SUBTRACT =
+        XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT;
 
-   /** Field SUBTRACT */
-   public static final String SUBTRACT =
-      XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT;
-
-   /** Field UNION */
-   public static final String UNION =
-      XPath2FilterContainer._ATT_FILTER_VALUE_UNION;
+    /** Field UNION */
+    public static final String UNION =
+        XPath2FilterContainer._ATT_FILTER_VALUE_UNION;
 
-   /** Field _TAG_XPATH2 */
-   public static final String _TAG_XPATH2 = "XPath";
+    /** Field _TAG_XPATH2 */
+    public static final String _TAG_XPATH2 = "XPath";
 
-   /** Field XPathFiler2NS */
-   public static final String XPathFilter2NS =
-      "http://www.w3.org/2002/06/xmldsig-filter2";
+    /** Field XPathFiler2NS */
+    public static final String XPathFilter2NS =
+        "http://www.w3.org/2002/06/xmldsig-filter2";
 
-   /**
-    * Constructor XPath2FilterContainer
-    *
-    */
-   private XPath2FilterContainer() {
-
-      // no instantiation
-   }
+    /**
+     * Constructor XPath2FilterContainer
+     *
+     */
+    private XPath2FilterContainer() {
+        // no instantiation
+    }
 
-   /**
-    * Constructor XPath2FilterContainer
-    *
-    * @param doc
-    * @param xpath2filter
-    * @param filterType
-    */
-   private XPath2FilterContainer(Document doc, String xpath2filter,
-                                 String filterType) {
+    /**
+     * Constructor XPath2FilterContainer
+     *
+     * @param doc
+     * @param xpath2filter
+     * @param filterType
+     */
+    private XPath2FilterContainer(Document doc, String xpath2filter, String filterType) {
+        super(doc);
 
-      super(doc);
-
-      this._constructionElement
-         .setAttributeNS(null, XPath2FilterContainer._ATT_FILTER, filterType);
-      this._constructionElement.appendChild(doc.createTextNode(xpath2filter));
-   }
+        this.constructionElement.setAttributeNS(
+            null, XPath2FilterContainer._ATT_FILTER, filterType);
+        this.constructionElement.appendChild(doc.createTextNode(xpath2filter));
+    }
 
-   /**
-    * Constructor XPath2FilterContainer
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   private XPath2FilterContainer(Element element, String BaseURI)
-           throws XMLSecurityException {
+    /**
+     * Constructor XPath2FilterContainer
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    private XPath2FilterContainer(Element element, String BaseURI) throws XMLSecurityException {
 
-      super(element, BaseURI);
+        super(element, BaseURI);
 
-      String filterStr = this._constructionElement.getAttributeNS(null,
-                            XPath2FilterContainer._ATT_FILTER);
+        String filterStr =
+            this.constructionElement.getAttributeNS(null, XPath2FilterContainer._ATT_FILTER);
 
-      if (!filterStr
-              .equals(XPath2FilterContainer
-              ._ATT_FILTER_VALUE_INTERSECT) &&!filterStr
-                 .equals(XPath2FilterContainer
-                 ._ATT_FILTER_VALUE_SUBTRACT) &&!filterStr
-                    .equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION)) {
-         Object exArgs[] = { XPath2FilterContainer._ATT_FILTER, filterStr,
-                             XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT
-                             + ", "
-                             + XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT
-                             + " or "
-                             + XPath2FilterContainer._ATT_FILTER_VALUE_UNION };
+        if (!filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT)
+            && !filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT)
+            && !filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION)) {
+            Object exArgs[] = { XPath2FilterContainer._ATT_FILTER, filterStr,
+                                XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT
+                                + ", "
+                                + XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT
+                                + " or "
+                                + XPath2FilterContainer._ATT_FILTER_VALUE_UNION };
 
-         throw new XMLSecurityException("attributeValueIllegal", exArgs);
-      }
-   }
+            throw new XMLSecurityException("attributeValueIllegal", exArgs);
+        }
+    }
 
-   /**
-    * Creates a new XPath2FilterContainer with the filter type "intersect".
-    *
-    * @param doc
-    * @param xpath2filter
-    * @return the filter.
-    */
-   public static XPath2FilterContainer newInstanceIntersect(Document doc,
-           String xpath2filter) {
-
-      return new XPath2FilterContainer(doc, xpath2filter,
-                                       XPath2FilterContainer
-                                          ._ATT_FILTER_VALUE_INTERSECT);
-   }
+    /**
+     * Creates a new XPath2FilterContainer with the filter type "intersect".
+     *
+     * @param doc
+     * @param xpath2filter
+     * @return the filter.
+     */
+    public static XPath2FilterContainer newInstanceIntersect(
+        Document doc, String xpath2filter
+    ) {
+        return new XPath2FilterContainer(
+            doc, xpath2filter, XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT);
+    }
 
-   /**
-    * Creates a new XPath2FilterContainer with the filter type "subtract".
-    *
-    * @param doc
-    * @param xpath2filter
-    * @return the filter.
-    */
-   public static XPath2FilterContainer newInstanceSubtract(Document doc,
-           String xpath2filter) {
+    /**
+     * Creates a new XPath2FilterContainer with the filter type "subtract".
+     *
+     * @param doc
+     * @param xpath2filter
+     * @return the filter.
+     */
+    public static XPath2FilterContainer newInstanceSubtract(Document doc, String xpath2filter) {
+        return new XPath2FilterContainer(
+            doc, xpath2filter, XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT);
+    }
 
-      return new XPath2FilterContainer(doc, xpath2filter,
-                                       XPath2FilterContainer
-                                          ._ATT_FILTER_VALUE_SUBTRACT);
-   }
-
-   /**
-    * Creates a new XPath2FilterContainer with the filter type "union".
-    *
-    * @param doc
-    * @param xpath2filter
-    * @return the filter
-    */
-   public static XPath2FilterContainer newInstanceUnion(Document doc,
-           String xpath2filter) {
+    /**
+     * Creates a new XPath2FilterContainer with the filter type "union".
+     *
+     * @param doc
+     * @param xpath2filter
+     * @return the filter
+     */
+    public static XPath2FilterContainer newInstanceUnion(Document doc, String xpath2filter) {
+        return new XPath2FilterContainer(
+            doc, xpath2filter, XPath2FilterContainer._ATT_FILTER_VALUE_UNION);
+    }
 
-      return new XPath2FilterContainer(doc, xpath2filter,
-                                       XPath2FilterContainer
-                                          ._ATT_FILTER_VALUE_UNION);
-   }
+    /**
+     * Method newInstances
+     *
+     * @param doc
+     * @param params
+     * @return the nodelist with the data
+     */
+    public static NodeList newInstances(Document doc, String[][] params) {
+        HelperNodeList nl = new HelperNodeList();
 
-   /**
-    * Method newInstances
-    *
-    * @param doc
-    * @param params
-    * @return the nodelist with the data
-    */
-   public static NodeList newInstances(Document doc, String[][] params) {
-
-      HelperNodeList nl = new HelperNodeList();
+        XMLUtils.addReturnToElement(doc, nl);
 
-      XMLUtils.addReturnToElement(doc, nl);
-
-      for (int i = 0; i < params.length; i++) {
-         String type = params[i][0];
-         String xpath = params[i][1];
+        for (int i = 0; i < params.length; i++) {
+            String type = params[i][0];
+            String xpath = params[i][1];
 
-         if (!(type.equals(XPath2FilterContainer
-                 ._ATT_FILTER_VALUE_INTERSECT) || type
-                    .equals(XPath2FilterContainer
-                    ._ATT_FILTER_VALUE_SUBTRACT) || type
-                       .equals(XPath2FilterContainer
-                          ._ATT_FILTER_VALUE_UNION))) {
-            throw new IllegalArgumentException("The type(" + i + ")=\"" + type
-                                               + "\" is illegal");
-         }
+            if (!(type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT)
+                || type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT)
+                || type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION))){
+                throw new IllegalArgumentException("The type(" + i + ")=\"" + type
+                                                   + "\" is illegal");
+            }
+
+            XPath2FilterContainer c = new XPath2FilterContainer(doc, xpath, type);
+
+            nl.appendChild(c.getElement());
+            XMLUtils.addReturnToElement(doc, nl);
+        }
 
-         XPath2FilterContainer c = new XPath2FilterContainer(doc, xpath, type);
-
-         nl.appendChild(c.getElement());
-         XMLUtils.addReturnToElement(doc, nl);
-      }
-
-      return nl;
-   }
+        return nl;
+    }
 
-   /**
-    * Creates a XPath2FilterContainer from an existing Element; needed for verification.
-    *
-    * @param element
-    * @param BaseURI
-    * @return the filter
-    *
-    * @throws XMLSecurityException
-    */
-   public static XPath2FilterContainer newInstance(
-           Element element, String BaseURI) throws XMLSecurityException {
-      return new XPath2FilterContainer(element, BaseURI);
-   }
+    /**
+     * Creates a XPath2FilterContainer from an existing Element; needed for verification.
+     *
+     * @param element
+     * @param BaseURI
+     * @return the filter
+     *
+     * @throws XMLSecurityException
+     */
+    public static XPath2FilterContainer newInstance(
+        Element element, String BaseURI
+    ) throws XMLSecurityException {
+        return new XPath2FilterContainer(element, BaseURI);
+    }
 
-   /**
-    * Returns <code>true</code> if the <code>Filter</code> attribute has value "intersect".
-    *
-    * @return <code>true</code> if the <code>Filter</code> attribute has value "intersect".
-    */
-   public boolean isIntersect() {
-
-      return this._constructionElement
-         .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER)
-         .equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT);
-   }
+    /**
+     * Returns <code>true</code> if the <code>Filter</code> attribute has value "intersect".
+     *
+     * @return <code>true</code> if the <code>Filter</code> attribute has value "intersect".
+     */
+    public boolean isIntersect() {
+        return this.constructionElement.getAttributeNS(
+            null, XPath2FilterContainer._ATT_FILTER
+        ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT);
+    }
 
-   /**
-    * Returns <code>true</code> if the <code>Filter</code> attribute has value "subtract".
-    *
-    * @return <code>true</code> if the <code>Filter</code> attribute has value "subtract".
-    */
-   public boolean isSubtract() {
-
-      return this._constructionElement
-         .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER)
-         .equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT);
-   }
+    /**
+     * Returns <code>true</code> if the <code>Filter</code> attribute has value "subtract".
+     *
+     * @return <code>true</code> if the <code>Filter</code> attribute has value "subtract".
+     */
+    public boolean isSubtract() {
+        return this.constructionElement.getAttributeNS(
+            null, XPath2FilterContainer._ATT_FILTER
+        ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT);
+    }
 
-   /**
-    * Returns <code>true</code> if the <code>Filter</code> attribute has value "union".
-    *
-    * @return <code>true</code> if the <code>Filter</code> attribute has value "union".
-    */
-   public boolean isUnion() {
+    /**
+     * Returns <code>true</code> if the <code>Filter</code> attribute has value "union".
+     *
+     * @return <code>true</code> if the <code>Filter</code> attribute has value "union".
+     */
+    public boolean isUnion() {
+        return this.constructionElement.getAttributeNS(
+            null, XPath2FilterContainer._ATT_FILTER
+        ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION);
+    }
 
-      return this._constructionElement
-         .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER)
-         .equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION);
-   }
-
-   /**
-    * Returns the XPath 2 Filter String
-    *
-    * @return the XPath 2 Filter String
-    */
-   public String getXPathFilterStr() {
-      return this.getTextFromTextChild();
-   }
+    /**
+     * Returns the XPath 2 Filter String
+     *
+     * @return the XPath 2 Filter String
+     */
+    public String getXPathFilterStr() {
+        return this.getTextFromTextChild();
+    }
 
-   /**
-    * Returns the first Text node which contains information from the XPath 2
-    * Filter String. We must use this stupid hook to enable the here() function
-    * to work.
-    *
-    * $todo$ I dunno whether this crashes: <XPath> here()<!-- comment -->/ds:Signature[1]</XPath>
-    * @return the first Text node which contains information from the XPath 2 Filter String
-    */
-   public Node getXPathFilterTextNode() {
+    /**
+     * Returns the first Text node which contains information from the XPath 2
+     * Filter String. We must use this stupid hook to enable the here() function
+     * to work.
+     *
+     * $todo$ I dunno whether this crashes: <XPath> here()<!-- comment -->/ds:Signature[1]</XPath>
+     * @return the first Text node which contains information from the XPath 2 Filter String
+     */
+    public Node getXPathFilterTextNode() {
 
-      NodeList children = this._constructionElement.getChildNodes();
-      int length = children.getLength();
+        NodeList children = this.constructionElement.getChildNodes();
+        int length = children.getLength();
 
-      for (int i = 0; i < length; i++) {
-         if (children.item(i).getNodeType() == Node.TEXT_NODE) {
-            return children.item(i);
-         }
-      }
+        for (int i = 0; i < length; i++) {
+            if (children.item(i).getNodeType() == Node.TEXT_NODE) {
+                return children.item(i);
+            }
+        }
 
-      return null;
-   }
+        return null;
+    }
 
-   /**
-    * Method getBaseLocalName
-    *
-    * @return the XPATH2 tag
-    */
-   public final String getBaseLocalName() {
-      return XPath2FilterContainer._TAG_XPATH2;
-   }
+    /**
+     * Method getBaseLocalName
+     *
+     * @return the XPATH2 tag
+     */
+    public final String getBaseLocalName() {
+        return XPath2FilterContainer._TAG_XPATH2;
+    }
 
-   /**
-    * Method getBaseNamespace
-    *
-    * @return XPATH2 tag namespace
-    */
-   public final String getBaseNamespace() {
-      return XPath2FilterContainer.XPathFilter2NS;
-   }
+    /**
+     * Method getBaseNamespace
+     *
+     * @return XPATH2 tag namespace
+     */
+    public final String getBaseNamespace() {
+        return XPath2FilterContainer.XPathFilter2NS;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.params;
 
-
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.transforms.TransformParam;
 import com.sun.org.apache.xml.internal.security.utils.ElementProxy;
@@ -31,237 +31,222 @@
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 
-
 /**
  * Implements the parameters for the <A
  * HREF="http://www.w3.org/TR/xmldsig-filter2/">XPath Filter v2.0</A>.
  *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  * @see <A HREF="http://www.w3.org/TR/xmldsig-filter2/">XPath Filter v2.0 (TR)</A>
- * @see <A HREF="http://www.w3.org/Signature/Drafts/xmldsig-xfilter2/">XPath Filter v2.0 (editors copy)</A>
  */
-public class XPath2FilterContainer04 extends ElementProxy
-        implements TransformParam {
+public class XPath2FilterContainer04 extends ElementProxy implements TransformParam {
 
-   /** Field _ATT_FILTER */
-   private static final String _ATT_FILTER = "Filter";
+    /** Field _ATT_FILTER */
+    private static final String _ATT_FILTER = "Filter";
 
-   /** Field _ATT_FILTER_VALUE_INTERSECT */
-   private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect";
+    /** Field _ATT_FILTER_VALUE_INTERSECT */
+    private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect";
 
-   /** Field _ATT_FILTER_VALUE_SUBTRACT */
-   private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract";
+    /** Field _ATT_FILTER_VALUE_SUBTRACT */
+    private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract";
 
-   /** Field _ATT_FILTER_VALUE_UNION */
-   private static final String _ATT_FILTER_VALUE_UNION = "union";
+    /** Field _ATT_FILTER_VALUE_UNION */
+    private static final String _ATT_FILTER_VALUE_UNION = "union";
 
-   /** Field _TAG_XPATH2 */
-   public static final String _TAG_XPATH2 = "XPath";
+    /** Field _TAG_XPATH2 */
+    public static final String _TAG_XPATH2 = "XPath";
 
-   /** Field XPathFiler2NS */
-   public static final String XPathFilter2NS =
-      "http://www.w3.org/2002/04/xmldsig-filter2";
+    /** Field XPathFiler2NS */
+    public static final String XPathFilter2NS =
+        "http://www.w3.org/2002/04/xmldsig-filter2";
 
-   /**
-    * Constructor XPath2FilterContainer04
-    *
-    */
-   private XPath2FilterContainer04() {
+    /**
+     * Constructor XPath2FilterContainer04
+     *
+     */
+    private XPath2FilterContainer04() {
 
-      // no instantiation
-   }
+        // no instantiation
+    }
 
-   /**
-    * Constructor XPath2FilterContainer04
-    *
-    * @param doc
-    * @param xpath2filter
-    * @param filterType
-    */
-   private XPath2FilterContainer04(Document doc, String xpath2filter,
-                                 String filterType) {
+    /**
+     * Constructor XPath2FilterContainer04
+     *
+     * @param doc
+     * @param xpath2filter
+     * @param filterType
+     */
+    private XPath2FilterContainer04(Document doc, String xpath2filter, String filterType) {
+        super(doc);
 
-      super(doc);
-
-      this._constructionElement.setAttributeNS(null, XPath2FilterContainer04._ATT_FILTER,
-                                             filterType);
+        this.constructionElement.setAttributeNS(
+            null, XPath2FilterContainer04._ATT_FILTER, filterType);
 
-      if ((xpath2filter.length() > 2)
-              && (!Character.isWhitespace(xpath2filter.charAt(0)))) {
-         XMLUtils.addReturnToElement(this._constructionElement);
-         this._constructionElement.appendChild(doc.createTextNode(xpath2filter));
-         XMLUtils.addReturnToElement(this._constructionElement);
-      } else {
-         this._constructionElement
-            .appendChild(doc.createTextNode(xpath2filter));
-      }
-   }
+        if ((xpath2filter.length() > 2)
+            && (!Character.isWhitespace(xpath2filter.charAt(0)))) {
+            XMLUtils.addReturnToElement(this.constructionElement);
+            this.constructionElement.appendChild(doc.createTextNode(xpath2filter));
+            XMLUtils.addReturnToElement(this.constructionElement);
+        } else {
+            this.constructionElement.appendChild(doc.createTextNode(xpath2filter));
+        }
+    }
 
-   /**
-    * Constructor XPath2FilterContainer04
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   private XPath2FilterContainer04(Element element, String BaseURI)
-           throws XMLSecurityException {
+    /**
+     * Constructor XPath2FilterContainer04
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    private XPath2FilterContainer04(Element element, String BaseURI)
+        throws XMLSecurityException {
 
-      super(element, BaseURI);
+        super(element, BaseURI);
 
-      String filterStr =
-         this._constructionElement
-            .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER);
+        String filterStr =
+            this.constructionElement.getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER);
 
-      if (!filterStr
-              .equals(XPath2FilterContainer04
-              ._ATT_FILTER_VALUE_INTERSECT) &&!filterStr
-                 .equals(XPath2FilterContainer04
-                 ._ATT_FILTER_VALUE_SUBTRACT) &&!filterStr
-                    .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION)) {
-         Object exArgs[] = { XPath2FilterContainer04._ATT_FILTER, filterStr,
-                             XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT
-                             + ", "
-                             + XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT
-                             + " or "
-                             + XPath2FilterContainer04._ATT_FILTER_VALUE_UNION };
+        if (!filterStr.equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT)
+            && !filterStr.equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT)
+            && !filterStr.equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION)) {
+            Object exArgs[] = { XPath2FilterContainer04._ATT_FILTER, filterStr,
+                                XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT
+                                + ", "
+                                + XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT
+                                + " or "
+                                + XPath2FilterContainer04._ATT_FILTER_VALUE_UNION };
+
+            throw new XMLSecurityException("attributeValueIllegal", exArgs);
+        }
+    }
 
-         throw new XMLSecurityException("attributeValueIllegal", exArgs);
-      }
-   }
-
-   /**
-    * Creates a new XPath2FilterContainer04 with the filter type "intersect".
-    *
-    * @param doc
-    * @param xpath2filter
-    * @return the instance
-    */
-   public static XPath2FilterContainer04 newInstanceIntersect(Document doc,
-           String xpath2filter) {
-
-      return new XPath2FilterContainer04(doc, xpath2filter,
-                                       XPath2FilterContainer04
-                                          ._ATT_FILTER_VALUE_INTERSECT);
-   }
+    /**
+     * Creates a new XPath2FilterContainer04 with the filter type "intersect".
+     *
+     * @param doc
+     * @param xpath2filter
+     * @return the instance
+     */
+    public static XPath2FilterContainer04 newInstanceIntersect(
+        Document doc, String xpath2filter
+    ) {
+        return new XPath2FilterContainer04(
+            doc, xpath2filter, XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT);
+    }
 
-   /**
-    * Creates a new XPath2FilterContainer04 with the filter type "subtract".
-    *
-    * @param doc
-    * @param xpath2filter
-    * @return the instance
-    */
-   public static XPath2FilterContainer04 newInstanceSubtract(Document doc,
-           String xpath2filter) {
-
-      return new XPath2FilterContainer04(doc, xpath2filter,
-                                       XPath2FilterContainer04
-                                          ._ATT_FILTER_VALUE_SUBTRACT);
-   }
-
-   /**
-    * Creates a new XPath2FilterContainer04 with the filter type "union".
-    *
-    * @param doc
-    * @param xpath2filter
-    * @return the instance
-    */
-   public static XPath2FilterContainer04 newInstanceUnion(Document doc,
-           String xpath2filter) {
+    /**
+     * Creates a new XPath2FilterContainer04 with the filter type "subtract".
+     *
+     * @param doc
+     * @param xpath2filter
+     * @return the instance
+     */
+    public static XPath2FilterContainer04 newInstanceSubtract(
+        Document doc, String xpath2filter
+    ) {
+        return new XPath2FilterContainer04(
+            doc, xpath2filter, XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT);
+    }
 
-      return new XPath2FilterContainer04(doc, xpath2filter,
-                                       XPath2FilterContainer04
-                                          ._ATT_FILTER_VALUE_UNION);
-   }
+    /**
+     * Creates a new XPath2FilterContainer04 with the filter type "union".
+     *
+     * @param doc
+     * @param xpath2filter
+     * @return the instance
+     */
+    public static XPath2FilterContainer04 newInstanceUnion(
+        Document doc, String xpath2filter
+    ) {
+        return new XPath2FilterContainer04(
+            doc, xpath2filter, XPath2FilterContainer04._ATT_FILTER_VALUE_UNION);
+    }
 
-   /**
-    * Creates a XPath2FilterContainer04 from an existing Element; needed for verification.
-    *
-    * @param element
-    * @param BaseURI
-    * @return the instance
-    *
-    * @throws XMLSecurityException
-    */
-   public static XPath2FilterContainer04 newInstance(
-           Element element, String BaseURI) throws XMLSecurityException {
-      return new XPath2FilterContainer04(element, BaseURI);
-   }
+    /**
+     * Creates a XPath2FilterContainer04 from an existing Element; needed for verification.
+     *
+     * @param element
+     * @param BaseURI
+     * @return the instance
+     *
+     * @throws XMLSecurityException
+     */
+    public static XPath2FilterContainer04 newInstance(
+        Element element, String BaseURI
+    ) throws XMLSecurityException {
+        return new XPath2FilterContainer04(element, BaseURI);
+    }
 
-   /**
-    * Returns <code>true</code> if the <code>Filter</code> attribute has value "intersect".
-    *
-    * @return <code>true</code> if the <code>Filter</code> attribute has value "intersect".
-    */
-   public boolean isIntersect() {
-
-      return this._constructionElement
-         .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER)
-         .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT);
-   }
+    /**
+     * Returns <code>true</code> if the <code>Filter</code> attribute has value "intersect".
+     *
+     * @return <code>true</code> if the <code>Filter</code> attribute has value "intersect".
+     */
+    public boolean isIntersect() {
+        return this.constructionElement.getAttributeNS(
+            null, XPath2FilterContainer04._ATT_FILTER
+        ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT);
+    }
 
-   /**
-    * Returns <code>true</code> if the <code>Filter</code> attribute has value "subtract".
-    *
-    * @return <code>true</code> if the <code>Filter</code> attribute has value "subtract".
-    */
-   public boolean isSubtract() {
-
-      return this._constructionElement
-         .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER)
-         .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT);
-   }
+    /**
+     * Returns <code>true</code> if the <code>Filter</code> attribute has value "subtract".
+     *
+     * @return <code>true</code> if the <code>Filter</code> attribute has value "subtract".
+     */
+    public boolean isSubtract() {
+        return this.constructionElement.getAttributeNS(
+            null, XPath2FilterContainer04._ATT_FILTER
+        ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT);
+    }
 
-   /**
-    * Returns <code>true</code> if the <code>Filter</code> attribute has value "union".
-    *
-    * @return <code>true</code> if the <code>Filter</code> attribute has value "union".
-    */
-   public boolean isUnion() {
+    /**
+     * Returns <code>true</code> if the <code>Filter</code> attribute has value "union".
+     *
+     * @return <code>true</code> if the <code>Filter</code> attribute has value "union".
+     */
+    public boolean isUnion() {
+        return this.constructionElement.getAttributeNS(
+            null, XPath2FilterContainer04._ATT_FILTER
+        ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION);
+    }
 
-      return this._constructionElement
-         .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER)
-         .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION);
-   }
+    /**
+     * Returns the XPath 2 Filter String
+     *
+     * @return the XPath 2 Filter String
+     */
+    public String getXPathFilterStr() {
+        return this.getTextFromTextChild();
+    }
 
-   /**
-    * Returns the XPath 2 Filter String
-    *
-    * @return the XPath 2 Filter String
-    */
-   public String getXPathFilterStr() {
-      return this.getTextFromTextChild();
-   }
+    /**
+     * Returns the first Text node which contains information from the XPath 2
+     * Filter String. We must use this stupid hook to enable the here() function
+     * to work.
+     *
+     * $todo$ I dunno whether this crashes: <XPath> here()<!-- comment -->/ds:Signature[1]</XPath>
+     * @return the first Text node which contains information from the XPath 2 Filter String
+     */
+    public Node getXPathFilterTextNode() {
+        NodeList children = this.constructionElement.getChildNodes();
+        int length = children.getLength();
 
-   /**
-    * Returns the first Text node which contains information from the XPath 2
-    * Filter String. We must use this stupid hook to enable the here() function
-    * to work.
-    *
-    * $todo$ I dunno whether this crashes: <XPath> here()<!-- comment -->/ds:Signature[1]</XPath>
-    * @return the first Text node which contains information from the XPath 2 Filter String
-    */
-   public Node getXPathFilterTextNode() {
-      NodeList children = this._constructionElement.getChildNodes();
-      int length = children.getLength();
+        for (int i = 0; i < length; i++) {
+            if (children.item(i).getNodeType() == Node.TEXT_NODE) {
+                return children.item(i);
+            }
+        }
+
+        return null;
+    }
 
-      for (int i = 0; i < length; i++) {
-         if (children.item(i).getNodeType() == Node.TEXT_NODE) {
-            return children.item(i);
-         }
-      }
-
-      return null;
-   }
+    /** @inheritDoc */
+    public final String getBaseLocalName() {
+        return XPath2FilterContainer04._TAG_XPATH2;
+    }
 
-   /** @inheritDoc */
-   public final String getBaseLocalName() {
-      return XPath2FilterContainer04._TAG_XPATH2;
-   }
-
-   /** @inheritDoc */
-   public final String getBaseNamespace() {
-      return XPath2FilterContainer04.XPathFilter2NS;
-   }
+    /** @inheritDoc */
+    public final String getBaseNamespace() {
+        return XPath2FilterContainer04.XPathFilter2NS;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,27 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.params;
 
 
-
 import com.sun.org.apache.xml.internal.security.transforms.TransformParam;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
@@ -29,7 +30,6 @@
 import org.w3c.dom.NodeList;
 import org.w3c.dom.Text;
 
-
 /**
  * This Object serves both as namespace prefix resolver and as container for
  * the <CODE>ds:XPath</CODE> Element. It implements the {@link org.w3c.dom.Element} interface
@@ -39,45 +39,44 @@
  */
 public class XPathContainer extends SignatureElementProxy implements TransformParam {
 
-   /**
-    * Constructor XPathContainer
-    *
-    * @param doc
-    */
-   public XPathContainer(Document doc) {
-      super(doc);
-   }
+    /**
+     * Constructor XPathContainer
+     *
+     * @param doc
+     */
+    public XPathContainer(Document doc) {
+        super(doc);
+    }
 
-   /**
-    * Sets the TEXT value of the <CODE>ds:XPath</CODE> Element.
-    *
-    * @param xpath
-    */
-   public void setXPath(String xpath) {
-
-      if (this._constructionElement.getChildNodes() != null) {
-         NodeList nl = this._constructionElement.getChildNodes();
+    /**
+     * Sets the TEXT value of the <CODE>ds:XPath</CODE> Element.
+     *
+     * @param xpath
+     */
+    public void setXPath(String xpath) {
+        if (this.constructionElement.getChildNodes() != null) {
+            NodeList nl = this.constructionElement.getChildNodes();
 
-         for (int i = 0; i < nl.getLength(); i++) {
-            this._constructionElement.removeChild(nl.item(i));
-         }
-      }
+            for (int i = 0; i < nl.getLength(); i++) {
+                this.constructionElement.removeChild(nl.item(i));
+            }
+        }
 
-      Text xpathText = this._doc.createTextNode(xpath);
-      this._constructionElement.appendChild(xpathText);
-   }
+        Text xpathText = this.doc.createTextNode(xpath);
+        this.constructionElement.appendChild(xpathText);
+    }
 
-   /**
-    * Returns the TEXT value of the <CODE>ds:XPath</CODE> Element.
-    *
-    * @return the TEXT value of the <CODE>ds:XPath</CODE> Element.
-    */
-   public String getXPath() {
-      return this.getTextFromTextChild();
-   }
+    /**
+     * Returns the TEXT value of the <CODE>ds:XPath</CODE> Element.
+     *
+     * @return the TEXT value of the <CODE>ds:XPath</CODE> Element.
+     */
+    public String getXPath() {
+        return this.getTextFromTextChild();
+    }
 
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_XPATH;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_XPATH;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,320 +2,315 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms.params;
 
 
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.transforms.TransformParam;
-import com.sun.org.apache.xml.internal.security.transforms.Transforms;
 import com.sun.org.apache.xml.internal.security.utils.ElementProxy;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
-
 /**
  * Implements the parameters for a custom Transform which has a better performance
- * thatn the xfilter2.
+ * than the xfilter2.
  *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  */
-public class XPathFilterCHGPContainer extends ElementProxy
-        implements TransformParam {
+public class XPathFilterCHGPContainer extends ElementProxy implements TransformParam {
+
+    public static final String TRANSFORM_XPATHFILTERCHGP =
+        "http://www.nue.et-inf.uni-siegen.de/~geuer-pollmann/#xpathFilter";
 
-   /** Field _ATT_FILTER_VALUE_INTERSECT */
-   private static final String _TAG_INCLUDE_BUT_SEARCH = "IncludeButSearch";
+    /** Field _ATT_FILTER_VALUE_INTERSECT */
+    private static final String _TAG_INCLUDE_BUT_SEARCH = "IncludeButSearch";
 
-   /** Field _ATT_FILTER_VALUE_SUBTRACT */
-   private static final String _TAG_EXCLUDE_BUT_SEARCH = "ExcludeButSearch";
+    /** Field _ATT_FILTER_VALUE_SUBTRACT */
+    private static final String _TAG_EXCLUDE_BUT_SEARCH = "ExcludeButSearch";
 
-   /** Field _ATT_FILTER_VALUE_UNION */
-   private static final String _TAG_EXCLUDE = "Exclude";
+    /** Field _ATT_FILTER_VALUE_UNION */
+    private static final String _TAG_EXCLUDE = "Exclude";
 
-   /** Field _TAG_XPATHCHGP */
-   public static final String _TAG_XPATHCHGP = "XPathAlternative";
+    /** Field _TAG_XPATHCHGP */
+    public static final String _TAG_XPATHCHGP = "XPathAlternative";
 
-   /** Field _ATT_INCLUDESLASH */
-   public static final String _ATT_INCLUDESLASH = "IncludeSlashPolicy";
+    /** Field _ATT_INCLUDESLASH */
+    public static final String _ATT_INCLUDESLASH = "IncludeSlashPolicy";
 
-   /** Field IncludeSlash           */
-   public static final boolean IncludeSlash = true;
+    /** Field IncludeSlash           */
+    public static final boolean IncludeSlash = true;
 
-   /** Field ExcludeSlash           */
-   public static final boolean ExcludeSlash = false;
+    /** Field ExcludeSlash           */
+    public static final boolean ExcludeSlash = false;
 
-   /**
-    * Constructor XPathFilterCHGPContainer
-    *
-    */
-   private XPathFilterCHGPContainer() {
-
-      // no instantiation
-   }
+    /**
+     * Constructor XPathFilterCHGPContainer
+     *
+     */
+    private XPathFilterCHGPContainer() {
+        // no instantiation
+    }
 
-   /**
-    * Constructor XPathFilterCHGPContainer
-    *
-    * @param doc
-    * @param includeSlashPolicy
-    * @param includeButSearch
-    * @param excludeButSearch
-    * @param exclude
-    */
-   private XPathFilterCHGPContainer(Document doc, boolean includeSlashPolicy,
-                                    String includeButSearch,
-                                    String excludeButSearch, String exclude) {
-
-      super(doc);
+    /**
+     * Constructor XPathFilterCHGPContainer
+     *
+     * @param doc
+     * @param includeSlashPolicy
+     * @param includeButSearch
+     * @param excludeButSearch
+     * @param exclude
+     */
+    private XPathFilterCHGPContainer(
+        Document doc, boolean includeSlashPolicy, String includeButSearch,
+        String excludeButSearch, String exclude
+    ) {
+        super(doc);
 
-      if (includeSlashPolicy) {
-         this._constructionElement
-            .setAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "true");
-      } else {
-         this._constructionElement
-            .setAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "false");
-      }
-
-      if ((includeButSearch != null)
-              && (includeButSearch.trim().length() > 0)) {
-         Element includeButSearchElem =
-            ElementProxy.createElementForFamily(doc, this.getBaseNamespace(),
-                                        XPathFilterCHGPContainer
-                                           ._TAG_INCLUDE_BUT_SEARCH);
+        if (includeSlashPolicy) {
+            this.constructionElement.setAttributeNS(
+                null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "true"
+            );
+        } else {
+            this.constructionElement.setAttributeNS(
+                null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "false"
+            );
+        }
 
-         includeButSearchElem
-            .appendChild(this._doc
-               .createTextNode(indentXPathText(includeButSearch)));
-         XMLUtils.addReturnToElement(this._constructionElement);
-         this._constructionElement.appendChild(includeButSearchElem);
-      }
+        if ((includeButSearch != null) && (includeButSearch.trim().length() > 0)) {
+            Element includeButSearchElem =
+                ElementProxy.createElementForFamily(
+                    doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH
+                );
 
-      if ((excludeButSearch != null)
-              && (excludeButSearch.trim().length() > 0)) {
-         Element excludeButSearchElem =
-         ElementProxy.createElementForFamily(doc, this.getBaseNamespace(),
-                                        XPathFilterCHGPContainer
-                                           ._TAG_EXCLUDE_BUT_SEARCH);
+            includeButSearchElem.appendChild(
+                this.doc.createTextNode(indentXPathText(includeButSearch))
+            );
+            XMLUtils.addReturnToElement(this.constructionElement);
+            this.constructionElement.appendChild(includeButSearchElem);
+        }
 
-         excludeButSearchElem
-            .appendChild(this._doc
-               .createTextNode(indentXPathText(excludeButSearch)));
-         XMLUtils.addReturnToElement(this._constructionElement);
-         this._constructionElement.appendChild(excludeButSearchElem);
-      }
+        if ((excludeButSearch != null) && (excludeButSearch.trim().length() > 0)) {
+            Element excludeButSearchElem =
+                ElementProxy.createElementForFamily(
+                    doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH
+                );
+
+            excludeButSearchElem.appendChild(
+                this.doc.createTextNode(indentXPathText(excludeButSearch)));
 
-      if ((exclude != null) && (exclude.trim().length() > 0)) {
-         Element excludeElem = ElementProxy.createElementForFamily(doc,
-                                  this.getBaseNamespace(),
-                                  XPathFilterCHGPContainer._TAG_EXCLUDE);
+            XMLUtils.addReturnToElement(this.constructionElement);
+            this.constructionElement.appendChild(excludeButSearchElem);
+        }
 
-         excludeElem
-            .appendChild(this._doc.createTextNode(indentXPathText(exclude)));
-         XMLUtils.addReturnToElement(this._constructionElement);
-         this._constructionElement.appendChild(excludeElem);
-      }
-
-      XMLUtils.addReturnToElement(this._constructionElement);
-   }
+        if ((exclude != null) && (exclude.trim().length() > 0)) {
+            Element excludeElem =
+                ElementProxy.createElementForFamily(
+                   doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_EXCLUDE);
 
-   /**
-    * Method indentXPathText
-    *
-    * @param xp
-    * @return the string with enters
-    */
-   static String indentXPathText(String xp) {
+            excludeElem.appendChild(this.doc.createTextNode(indentXPathText(exclude)));
+            XMLUtils.addReturnToElement(this.constructionElement);
+            this.constructionElement.appendChild(excludeElem);
+        }
 
-      if ((xp.length() > 2) && (!Character.isWhitespace(xp.charAt(0)))) {
-         return "\n" + xp + "\n";
-      }
-      return xp;
-
-   }
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-   /**
-    * Constructor XPathFilterCHGPContainer
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   private XPathFilterCHGPContainer(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
-   }
+    /**
+     * Method indentXPathText
+     *
+     * @param xp
+     * @return the string with enters
+     */
+    static String indentXPathText(String xp) {
+        if ((xp.length() > 2) && (!Character.isWhitespace(xp.charAt(0)))) {
+            return "\n" + xp + "\n";
+        }
+        return xp;
+    }
 
-   /**
-    * Creates a new XPathFilterCHGPContainer; needed for generation.
-    *
-    * @param doc
-    * @param includeSlashPolicy
-    * @param includeButSearch
-    * @param excludeButSearch
-    * @param exclude
-    * @return the created object
-    */
-   public static XPathFilterCHGPContainer getInstance(Document doc,
-           boolean includeSlashPolicy, String includeButSearch,
-           String excludeButSearch, String exclude) {
+    /**
+     * Constructor XPathFilterCHGPContainer
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    private XPathFilterCHGPContainer(Element element, String BaseURI)
+        throws XMLSecurityException {
+        super(element, BaseURI);
+    }
 
-      return new XPathFilterCHGPContainer(doc, includeSlashPolicy,
-                                          includeButSearch, excludeButSearch,
-                                          exclude);
-   }
+    /**
+     * Creates a new XPathFilterCHGPContainer; needed for generation.
+     *
+     * @param doc
+     * @param includeSlashPolicy
+     * @param includeButSearch
+     * @param excludeButSearch
+     * @param exclude
+     * @return the created object
+     */
+    public static XPathFilterCHGPContainer getInstance(
+        Document doc, boolean includeSlashPolicy, String includeButSearch,
+        String excludeButSearch, String exclude
+    ) {
+        return new XPathFilterCHGPContainer(
+            doc, includeSlashPolicy, includeButSearch, excludeButSearch, exclude);
+    }
 
-   /**
-    * Creates a XPathFilterCHGPContainer from an existing Element; needed for verification.
-    *
-    * @param element
-    * @param BaseURI
-    *
-    * @throws XMLSecurityException
-    * @return the created object.
-    */
-   public static XPathFilterCHGPContainer getInstance(
-           Element element, String BaseURI) throws XMLSecurityException {
-      return new XPathFilterCHGPContainer(element, BaseURI);
-   }
-
-   /**
-    * Method getXStr
-    *
-    * @param type
-    * @return The Xstr
-    */
-   private String getXStr(String type) {
-
-      if (this.length(this.getBaseNamespace(), type) != 1) {
-         return "";
-      }
-
-      Element xElem = XMLUtils.selectNode(this._constructionElement.getFirstChild(), this.getBaseNamespace(),
-                         type,0);
+    /**
+     * Creates a XPathFilterCHGPContainer from an existing Element; needed for verification.
+     *
+     * @param element
+     * @param BaseURI
+     *
+     * @throws XMLSecurityException
+     * @return the created object.
+     */
+    public static XPathFilterCHGPContainer getInstance(
+        Element element, String BaseURI
+    ) throws XMLSecurityException {
+        return new XPathFilterCHGPContainer(element, BaseURI);
+    }
 
-      return XMLUtils.getFullTextChildrenFromElement(xElem);
-   }
+    /**
+     * Method getXStr
+     *
+     * @param type
+     * @return The Xstr
+     */
+    private String getXStr(String type) {
+        if (this.length(this.getBaseNamespace(), type) != 1) {
+            return "";
+        }
 
-   /**
-    * Method getIncludeButSearch
-    *
-    * @return the string
-    */
-   public String getIncludeButSearch() {
-      return this.getXStr(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH);
-   }
+        Element xElem =
+            XMLUtils.selectNode(
+                this.constructionElement.getFirstChild(), this.getBaseNamespace(), type, 0
+            );
 
-   /**
-    * Method getExcludeButSearch
-    *
-    * @return the string
-    */
-   public String getExcludeButSearch() {
-      return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH);
-   }
+        return XMLUtils.getFullTextChildrenFromElement(xElem);
+    }
 
-   /**
-    * Method getExclude
-    *
-    * @return the string
-    */
-   public String getExclude() {
-      return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE);
-   }
+    /**
+     * Method getIncludeButSearch
+     *
+     * @return the string
+     */
+    public String getIncludeButSearch() {
+        return this.getXStr(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH);
+    }
 
-   /**
-    * Method getIncludeSlashPolicy
-    *
-    * @return the string
-    */
-   public boolean getIncludeSlashPolicy() {
+    /**
+     * Method getExcludeButSearch
+     *
+     * @return the string
+     */
+    public String getExcludeButSearch() {
+        return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH);
+    }
 
-      return this._constructionElement
-         .getAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH)
-         .equals("true");
-   }
+    /**
+     * Method getExclude
+     *
+     * @return the string
+     */
+    public String getExclude() {
+        return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE);
+    }
 
-   /**
-    * Returns the first Text node which contains information from the XPath
-    * Filter String. We must use this stupid hook to enable the here() function
-    * to work.
-    *
-    * $todo$ I dunno whether this crashes: <XPath> he<!-- comment -->re()/ds:Signature[1]</XPath>
-    * @param type
-    * @return the first Text node which contains information from the XPath 2 Filter String
-    */
-   private Node getHereContextNode(String type) {
+    /**
+     * Method getIncludeSlashPolicy
+     *
+     * @return the string
+     */
+    public boolean getIncludeSlashPolicy() {
+        return this.constructionElement.getAttributeNS(
+            null, XPathFilterCHGPContainer._ATT_INCLUDESLASH).equals("true");
+    }
 
-      if (this.length(this.getBaseNamespace(), type) != 1) {
-         return null;
-      }
-
-      return XMLUtils.selectNodeText(this._constructionElement.getFirstChild(), this.getBaseNamespace(),
-                         type,0);
-   }
+    /**
+     * Returns the first Text node which contains information from the XPath
+     * Filter String. We must use this stupid hook to enable the here() function
+     * to work.
+     *
+     * $todo$ I dunno whether this crashes: <XPath> he<!-- comment -->re()/ds:Signature[1]</XPath>
+     * @param type
+     * @return the first Text node which contains information from the XPath 2 Filter String
+     */
+    private Node getHereContextNode(String type) {
 
-   /**
-    * Method getHereContextNodeIncludeButSearch
-    *
-    * @return the string
-    */
-   public Node getHereContextNodeIncludeButSearch() {
-      return this
-         .getHereContextNode(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH);
-   }
+        if (this.length(this.getBaseNamespace(), type) != 1) {
+            return null;
+        }
+
+        return XMLUtils.selectNodeText(
+            this.constructionElement.getFirstChild(), this.getBaseNamespace(), type, 0
+        );
+    }
 
-   /**
-    * Method getHereContextNodeExcludeButSearch
-    *
-    * @return the string
-    */
-   public Node getHereContextNodeExcludeButSearch() {
-      return this
-         .getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH);
-   }
+    /**
+     * Method getHereContextNodeIncludeButSearch
+     *
+     * @return the string
+     */
+    public Node getHereContextNodeIncludeButSearch() {
+        return this.getHereContextNode(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH);
+    }
 
-   /**
-    * Method getHereContextNodeExclude
-    *
-    * @return the string
-    */
-   public Node getHereContextNodeExclude() {
-      return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE);
-   }
+    /**
+     * Method getHereContextNodeExcludeButSearch
+     *
+     * @return the string
+     */
+    public Node getHereContextNodeExcludeButSearch() {
+        return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH);
+    }
 
-   /**
-    * Method getBaseLocalName
-    *
-    * @inheritDoc
-    */
-   public final String getBaseLocalName() {
-      return XPathFilterCHGPContainer._TAG_XPATHCHGP;
-   }
+    /**
+     * Method getHereContextNodeExclude
+     *
+     * @return the string
+     */
+    public Node getHereContextNodeExclude() {
+        return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE);
+    }
 
-   /**
-    * Method getBaseNamespace
-    *
-    * @inheritDoc
-    */
-   public final String getBaseNamespace() {
-      return Transforms.TRANSFORM_XPATHFILTERCHGP;
-   }
+    /**
+     * Method getBaseLocalName
+     *
+     * @inheritDoc
+     */
+    public final String getBaseLocalName() {
+        return XPathFilterCHGPContainer._TAG_XPATHCHGP;
+    }
+
+    /**
+     * Method getBaseNamespace
+     *
+     * @inheritDoc
+     */
+    public final String getBaseNamespace() {
+        return TRANSFORM_XPATHFILTERCHGP;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
@@ -32,762 +34,765 @@
 import org.w3c.dom.Node;
 import org.w3c.dom.Text;
 
-
 /**
  * Implementation of MIME's Base64 encoding and decoding conversions.
  * Optimized code. (raw version taken from oreilly.jonathan.util,
- * and currently com.sun.org.apache.xerces.internal.ds.util.Base64)
+ * and currently org.apache.xerces.ds.util.Base64)
  *
  * @author Raul Benito(Of the xerces copy, and little adaptations).
  * @author Anli Shundi
  * @author Christian Geuer-Pollmann
- * @see <A HREF="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</A>
+ * @see <A HREF="ftp://ftp.isi.edu/in-notes/rfc2045.txt">RFC 2045</A>
  * @see com.sun.org.apache.xml.internal.security.transforms.implementations.TransformBase64Decode
  */
 public class Base64 {
 
-
-   /** Field BASE64DEFAULTLENGTH */
-   public static final int BASE64DEFAULTLENGTH = 76;
+    /** Field BASE64DEFAULTLENGTH */
+    public static final int BASE64DEFAULTLENGTH = 76;
 
-   private Base64() {
-     // we don't allow instantiation
-   }
+    private static final int BASELENGTH = 255;
+    private static final int LOOKUPLENGTH = 64;
+    private static final int TWENTYFOURBITGROUP = 24;
+    private static final int EIGHTBIT = 8;
+    private static final int SIXTEENBIT = 16;
+    private static final int FOURBYTE = 4;
+    private static final int SIGN = -128;
+    private static final char PAD = '=';
+    private static final byte [] base64Alphabet = new byte[BASELENGTH];
+    private static final char [] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
 
-   /**
-    * Returns a byte-array representation of a <code>{@link BigInteger}<code>.
-    * No sign-bit is outputed.
-    *
-    * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray
-    * retunrs eventually longer arrays because of the leading sign-bit.
-    *
-    * @param big <code>BigInteger<code> to be converted
-    * @param bitlen <code>int<code> the desired length in bits of the representation
-    * @return a byte array with <code>bitlen</code> bits of <code>big</code>
-    */
-   static final byte[] getBytes(BigInteger big, int bitlen) {
+    static {
+        for (int i = 0; i < BASELENGTH; i++) {
+            base64Alphabet[i] = -1;
+        }
+        for (int i = 'Z'; i >= 'A'; i--) {
+            base64Alphabet[i] = (byte) (i - 'A');
+        }
+        for (int i = 'z'; i>= 'a'; i--) {
+            base64Alphabet[i] = (byte) (i - 'a' + 26);
+        }
+
+        for (int i = '9'; i >= '0'; i--) {
+            base64Alphabet[i] = (byte) (i - '0' + 52);
+        }
+
+        base64Alphabet['+'] = 62;
+        base64Alphabet['/'] = 63;
+
+        for (int i = 0; i <= 25; i++) {
+            lookUpBase64Alphabet[i] = (char)('A' + i);
+        }
+
+        for (int i = 26,  j = 0; i <= 51; i++, j++) {
+            lookUpBase64Alphabet[i] = (char)('a' + j);
+        }
 
-      //round bitlen
-      bitlen = ((bitlen + 7) >> 3) << 3;
+        for (int i = 52,  j = 0; i <= 61; i++, j++) {
+            lookUpBase64Alphabet[i] = (char)('0' + j);
+        }
+        lookUpBase64Alphabet[62] = '+';
+        lookUpBase64Alphabet[63] = '/';
+    }
 
-      if (bitlen < big.bitLength()) {
-         throw new IllegalArgumentException(I18n
-            .translate("utils.Base64.IllegalBitlength"));
-      }
-
-      byte[] bigBytes = big.toByteArray();
+    private Base64() {
+        // we don't allow instantiation
+    }
 
-      if (((big.bitLength() % 8) != 0)
-              && (((big.bitLength() / 8) + 1) == (bitlen / 8))) {
-         return bigBytes;
-      }
+    /**
+     * Returns a byte-array representation of a <code>{@link BigInteger}<code>.
+     * No sign-bit is output.
+     *
+     * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray
+     * returns eventually longer arrays because of the leading sign-bit.
+     *
+     * @param big <code>BigInteger<code> to be converted
+     * @param bitlen <code>int<code> the desired length in bits of the representation
+     * @return a byte array with <code>bitlen</code> bits of <code>big</code>
+     */
+    static final byte[] getBytes(BigInteger big, int bitlen) {
+
+        //round bitlen
+        bitlen = ((bitlen + 7) >> 3) << 3;
 
-         // some copying needed
-         int startSrc = 0;    // no need to skip anything
-         int bigLen = bigBytes.length;    //valid length of the string
+        if (bitlen < big.bitLength()) {
+            throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength"));
+        }
+
+        byte[] bigBytes = big.toByteArray();
 
-         if ((big.bitLength() % 8) == 0) {    // correct values
+        if (((big.bitLength() % 8) != 0)
+            && (((big.bitLength() / 8) + 1) == (bitlen / 8))) {
+            return bigBytes;
+        }
+
+        // some copying needed
+        int startSrc = 0;    // no need to skip anything
+        int bigLen = bigBytes.length;    //valid length of the string
+
+        if ((big.bitLength() % 8) == 0) {    // correct values
             startSrc = 1;    // skip sign bit
 
             bigLen--;    // valid length of the string
-         }
+        }
+
+        int startDst = bitlen / 8 - bigLen;    //pad with leading nulls
+        byte[] resizedBytes = new byte[bitlen / 8];
 
-         int startDst = bitlen / 8 - bigLen;    //pad with leading nulls
-         byte[] resizedBytes = new byte[bitlen / 8];
+        System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen);
 
-         System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen);
-
-         return resizedBytes;
+        return resizedBytes;
+    }
 
-   }
-
-   /**
-    * Encode in Base64 the given <code>{@link BigInteger}<code>.
-    *
-    * @param big
-    * @return String with Base64 encoding
-    */
-   public static final String encode(BigInteger big) {
-      return encode(getBytes(big, big.bitLength()));
-   }
+    /**
+     * Encode in Base64 the given <code>{@link BigInteger}<code>.
+     *
+     * @param big
+     * @return String with Base64 encoding
+     */
+    public static final String encode(BigInteger big) {
+        return encode(getBytes(big, big.bitLength()));
+    }
 
-   /**
-    * Returns a byte-array representation of a <code>{@link BigInteger}<code>.
-    * No sign-bit is outputed.
-    *
-    * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray
-    * retunrs eventually longer arrays because of the leading sign-bit.
-    *
-    * @param big <code>BigInteger<code> to be converted
-    * @param bitlen <code>int<code> the desired length in bits of the representation
-    * @return a byte array with <code>bitlen</code> bits of <code>big</code>
-    */
-   public static final  byte[] encode(BigInteger big, int bitlen) {
+    /**
+     * Returns a byte-array representation of a <code>{@link BigInteger}<code>.
+     * No sign-bit is output.
+     *
+     * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray
+     * returns eventually longer arrays because of the leading sign-bit.
+     *
+     * @param big <code>BigInteger<code> to be converted
+     * @param bitlen <code>int<code> the desired length in bits of the representation
+     * @return a byte array with <code>bitlen</code> bits of <code>big</code>
+     */
+    public static final  byte[] encode(BigInteger big, int bitlen) {
 
-      //round bitlen
-      bitlen = ((bitlen + 7) >> 3) << 3;
+        //round bitlen
+        bitlen = ((bitlen + 7) >> 3) << 3;
 
-      if (bitlen < big.bitLength()) {
-         throw new IllegalArgumentException(I18n
-            .translate("utils.Base64.IllegalBitlength"));
-      }
+        if (bitlen < big.bitLength()) {
+            throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength"));
+        }
 
-      byte[] bigBytes = big.toByteArray();
+        byte[] bigBytes = big.toByteArray();
 
-      if (((big.bitLength() % 8) != 0)
-              && (((big.bitLength() / 8) + 1) == (bitlen / 8))) {
-         return bigBytes;
-      }
+        if (((big.bitLength() % 8) != 0)
+            && (((big.bitLength() / 8) + 1) == (bitlen / 8))) {
+            return bigBytes;
+        }
 
-         // some copying needed
-         int startSrc = 0;    // no need to skip anything
-         int bigLen = bigBytes.length;    //valid length of the string
+        // some copying needed
+        int startSrc = 0;    // no need to skip anything
+        int bigLen = bigBytes.length;    //valid length of the string
 
-         if ((big.bitLength() % 8) == 0) {    // correct values
+        if ((big.bitLength() % 8) == 0) {    // correct values
             startSrc = 1;    // skip sign bit
 
             bigLen--;    // valid length of the string
-         }
+        }
+
+        int startDst = bitlen / 8 - bigLen;    //pad with leading nulls
+        byte[] resizedBytes = new byte[bitlen / 8];
 
-         int startDst = bitlen / 8 - bigLen;    //pad with leading nulls
-         byte[] resizedBytes = new byte[bitlen / 8];
+        System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen);
+
+        return resizedBytes;
+    }
 
-         System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen);
-
-         return resizedBytes;
-
-   }
+    /**
+     * Method decodeBigIntegerFromElement
+     *
+     * @param element
+     * @return the biginteger obtained from the node
+     * @throws Base64DecodingException
+     */
+    public static final BigInteger decodeBigIntegerFromElement(Element element)
+        throws Base64DecodingException {
+        return new BigInteger(1, Base64.decode(element));
+    }
 
-   /**
-    * Method decodeBigIntegerFromElement
-    *
-    * @param element
-    * @return the biginter obtained from the node
-    * @throws Base64DecodingException
-    */
-   public static final BigInteger decodeBigIntegerFromElement(Element element) throws Base64DecodingException
-   {
-      return new BigInteger(1, Base64.decode(element));
-   }
+    /**
+     * Method decodeBigIntegerFromText
+     *
+     * @param text
+     * @return the biginter obtained from the text node
+     * @throws Base64DecodingException
+     */
+    public static final BigInteger decodeBigIntegerFromText(Text text)
+        throws Base64DecodingException {
+        return new BigInteger(1, Base64.decode(text.getData()));
+    }
+
+    /**
+     * This method takes an (empty) Element and a BigInteger and adds the
+     * base64 encoded BigInteger to the Element.
+     *
+     * @param element
+     * @param biginteger
+     */
+    public static final void fillElementWithBigInteger(Element element, BigInteger biginteger) {
+
+        String encodedInt = encode(biginteger);
+
+        if (!XMLUtils.ignoreLineBreaks() && encodedInt.length() > BASE64DEFAULTLENGTH) {
+            encodedInt = "\n" + encodedInt + "\n";
+        }
 
-   /**
-    * Method decodeBigIntegerFromText
-    *
-    * @param text
-    * @return the biginter obtained from the text node
-    * @throws Base64DecodingException
-    */
-   public static final BigInteger decodeBigIntegerFromText(Text text) throws Base64DecodingException
-   {
-      return new BigInteger(1, Base64.decode(text.getData()));
-   }
+        Document doc = element.getOwnerDocument();
+        Text text = doc.createTextNode(encodedInt);
+
+        element.appendChild(text);
+    }
+
+    /**
+     * Method decode
+     *
+     * Takes the <CODE>Text</CODE> children of the Element and interprets
+     * them as input for the <CODE>Base64.decode()</CODE> function.
+     *
+     * @param element
+     * @return the byte obtained of the decoding the element
+     * $todo$ not tested yet
+     * @throws Base64DecodingException
+     */
+    public static final byte[] decode(Element element) throws Base64DecodingException {
+
+        Node sibling = element.getFirstChild();
+        StringBuffer sb = new StringBuffer();
+
+        while (sibling != null) {
+            if (sibling.getNodeType() == Node.TEXT_NODE) {
+                Text t = (Text) sibling;
 
-   /**
-    * This method takes an (empty) Element and a BigInteger and adds the
-    * base64 encoded BigInteger to the Element.
-    *
-    * @param element
-    * @param biginteger
-    */
-   public static final void fillElementWithBigInteger(Element element,
-           BigInteger biginteger) {
+                sb.append(t.getData());
+            }
+            sibling = sibling.getNextSibling();
+        }
+
+        return decode(sb.toString());
+    }
 
-      String encodedInt = encode(biginteger);
-
-      if (encodedInt.length() > 76) {
-         encodedInt = "\n" + encodedInt + "\n";
-      }
+    /**
+     * Method encodeToElement
+     *
+     * @param doc
+     * @param localName
+     * @param bytes
+     * @return an Element with the base64 encoded in the text.
+     *
+     */
+    public static final Element encodeToElement(Document doc, String localName, byte[] bytes) {
+        Element el = XMLUtils.createElementInSignatureSpace(doc, localName);
+        Text text = doc.createTextNode(encode(bytes));
 
-      Document doc = element.getOwnerDocument();
-      Text text = doc.createTextNode(encodedInt);
+        el.appendChild(text);
 
-      element.appendChild(text);
-   }
+        return el;
+    }
 
-   /**
-    * Method decode
-    *
-    * Takes the <CODE>Text</CODE> children of the Element and interprets
-    * them as input for the <CODE>Base64.decode()</CODE> function.
-    *
-    * @param element
-    * @return the byte obtained of the decoding the element
-    * $todo$ not tested yet
-    * @throws Base64DecodingException
-    */
-   public static final byte[] decode(Element element) throws Base64DecodingException {
+    /**
+     * Method decode
+     *
+     * @param base64
+     * @return the UTF bytes of the base64
+     * @throws Base64DecodingException
+     *
+     */
+    public static final byte[] decode(byte[] base64) throws Base64DecodingException  {
+        return decodeInternal(base64, -1);
+    }
+
+    /**
+     * Encode a byte array and fold lines at the standard 76th character unless
+     * ignore line breaks property is set.
+     *
+     * @param binaryData <code>byte[]<code> to be base64 encoded
+     * @return the <code>String<code> with encoded data
+     */
+    public static final String encode(byte[] binaryData) {
+        return XMLUtils.ignoreLineBreaks()
+            ? encode(binaryData, Integer.MAX_VALUE)
+            : encode(binaryData, BASE64DEFAULTLENGTH);
+    }
 
-      Node sibling = element.getFirstChild();
-      StringBuffer sb = new StringBuffer();
-
-      while (sibling!=null) {
-         if (sibling.getNodeType() == Node.TEXT_NODE) {
-            Text t = (Text) sibling;
+    /**
+     * Base64 decode the lines from the reader and return an InputStream
+     * with the bytes.
+     *
+     * @param reader
+     * @return InputStream with the decoded bytes
+     * @exception IOException passes what the reader throws
+     * @throws IOException
+     * @throws Base64DecodingException
+     */
+    public static final byte[] decode(BufferedReader reader)
+        throws IOException, Base64DecodingException {
 
-            sb.append(t.getData());
-         }
-         sibling=sibling.getNextSibling();
-      }
+        byte[] retBytes = null;
+        UnsyncByteArrayOutputStream baos = null;
+        try {
+            baos = new UnsyncByteArrayOutputStream();
+            String line;
 
-      return decode(sb.toString());
-   }
+            while (null != (line = reader.readLine())) {
+                byte[] bytes = decode(line);
+                baos.write(bytes);
+            }
+            retBytes = baos.toByteArray();
+        } finally {
+            baos.close();
+        }
+
+        return retBytes;
+    }
+
+    protected static final boolean isWhiteSpace(byte octect) {
+        return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
+    }
 
-   /**
-    * Method encodeToElement
-    *
-    * @param doc
-    * @param localName
-    * @param bytes
-    * @return an Element with the base64 encoded in the text.
-    *
-    */
-   public static final Element encodeToElement(Document doc, String localName,
-                                         byte[] bytes) {
+    protected static final boolean isPad(byte octect) {
+        return (octect == PAD);
+    }
 
-      Element el = XMLUtils.createElementInSignatureSpace(doc, localName);
-      Text text = doc.createTextNode(encode(bytes));
+    /**
+     * Encodes hex octets into Base64
+     *
+     * @param binaryData Array containing binaryData
+     * @return Encoded Base64 array
+     */
+    /**
+     * Encode a byte array in Base64 format and return an optionally
+     * wrapped line.
+     *
+     * @param binaryData <code>byte[]</code> data to be encoded
+     * @param length <code>int<code> length of wrapped lines; No wrapping if less than 4.
+     * @return a <code>String</code> with encoded data
+     */
+    public static final String  encode(byte[] binaryData,int length) {
+        if (length < 4) {
+            length = Integer.MAX_VALUE;
+        }
 
-      el.appendChild(text);
+        if (binaryData == null) {
+            return null;
+        }
 
-      return el;
-   }
+        int lengthDataBits = binaryData.length * EIGHTBIT;
+        if (lengthDataBits == 0) {
+            return "";
+        }
+
+        int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
+        int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
+        int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
+        int quartesPerLine = length / 4;
+        int numberLines = (numberQuartet - 1) / quartesPerLine;
+        char encodedData[] = null;
+
+        encodedData = new char[numberQuartet * 4 + numberLines];
 
-   /**
-    * Method decode
-    *
-    *
-    * @param base64
-    * @return the UTF bytes of the base64
-    * @throws Base64DecodingException
-    *
-    */
-   public final static byte[] decode(byte[] base64) throws Base64DecodingException  {
-         return decodeInternal(base64, -1);
-   }
+        byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
+        int encodedIndex = 0;
+        int dataIndex = 0;
+        int i = 0;
 
+        for (int line = 0; line < numberLines; line++) {
+            for (int quartet = 0; quartet < 19; quartet++) {
+                b1 = binaryData[dataIndex++];
+                b2 = binaryData[dataIndex++];
+                b3 = binaryData[dataIndex++];
+
+                l  = (byte)(b2 & 0x0f);
+                k  = (byte)(b1 & 0x03);
+
+                byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2): (byte)((b1) >> 2 ^ 0xc0);
+
+                byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0);
+                byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc);
 
 
-   /**
-    * Encode a byte array and fold lines at the standard 76th character unless
-    * ignore line breaks property is set.
-    *
-    * @param binaryData <code>byte[]<code> to be base64 encoded
-    * @return the <code>String<code> with encoded data
-    */
-   public static final String encode(byte[] binaryData) {
-      return XMLUtils.ignoreLineBreaks()
-         ? encode(binaryData, Integer.MAX_VALUE)
-         : encode(binaryData, BASE64DEFAULTLENGTH);
-   }
+                encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
+                encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
+                encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
+                encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
 
-   /**
-    * Base64 decode the lines from the reader and return an InputStream
-    * with the bytes.
-    *
-    *
-    * @param reader
-    * @return InputStream with the decoded bytes
-    * @exception IOException passes what the reader throws
-    * @throws IOException
-    * @throws Base64DecodingException
-    */
-   public final static byte[] decode(BufferedReader reader)
-           throws IOException, Base64DecodingException {
-
-      UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream();
-      String line;
-
-      while (null != (line = reader.readLine())) {
-         byte[] bytes = decode(line);
-
-         baos.write(bytes);
-      }
-
-      return baos.toByteArray();
-   }
+                i++;
+            }
+            encodedData[encodedIndex++] = 0xa;
+        }
 
-   static private final int  BASELENGTH         = 255;
-   static private final int  LOOKUPLENGTH       = 64;
-   static private final int  TWENTYFOURBITGROUP = 24;
-   static private final int  EIGHTBIT           = 8;
-   static private final int  SIXTEENBIT         = 16;
-   static private final int  FOURBYTE           = 4;
-   static private final int  SIGN               = -128;
-   static private final char PAD                = '=';
-   static final private byte [] base64Alphabet        = new byte[BASELENGTH];
-   static final private char [] lookUpBase64Alphabet  = new char[LOOKUPLENGTH];
-
-   static {
-
-       for (int i = 0; i<BASELENGTH; i++) {
-           base64Alphabet[i] = -1;
-       }
-       for (int i = 'Z'; i >= 'A'; i--) {
-           base64Alphabet[i] = (byte) (i-'A');
-       }
-       for (int i = 'z'; i>= 'a'; i--) {
-           base64Alphabet[i] = (byte) ( i-'a' + 26);
-       }
+        for (; i < numberTriplets; i++) {
+            b1 = binaryData[dataIndex++];
+            b2 = binaryData[dataIndex++];
+            b3 = binaryData[dataIndex++];
 
-       for (int i = '9'; i >= '0'; i--) {
-           base64Alphabet[i] = (byte) (i-'0' + 52);
-       }
-
-       base64Alphabet['+']  = 62;
-       base64Alphabet['/']  = 63;
-
-       for (int i = 0; i<=25; i++)
-           lookUpBase64Alphabet[i] = (char)('A'+i);
-
-       for (int i = 26,  j = 0; i<=51; i++, j++)
-           lookUpBase64Alphabet[i] = (char)('a'+ j);
+            l  = (byte)(b2 & 0x0f);
+            k  = (byte)(b1 & 0x03);
 
-       for (int i = 52,  j = 0; i<=61; i++, j++)
-           lookUpBase64Alphabet[i] = (char)('0' + j);
-       lookUpBase64Alphabet[62] = '+';
-       lookUpBase64Alphabet[63] = '/';
-
-   }
+            byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0);
 
-   protected static final boolean isWhiteSpace(byte octect) {
-       return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
-   }
-
-   protected static final boolean isPad(byte octect) {
-       return (octect == PAD);
-   }
+            byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0);
+            byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc);
 
 
-   /**
-    * Encodes hex octects into Base64
-    *
-    * @param binaryData Array containing binaryData
-    * @return Encoded Base64 array
-    */
-   /**
-    * Encode a byte array in Base64 format and return an optionally
-    * wrapped line.
-    *
-    * @param binaryData <code>byte[]</code> data to be encoded
-    * @param length <code>int<code> length of wrapped lines; No wrapping if less than 4.
-    * @return a <code>String</code> with encoded data
-    */
-    public static final String  encode(byte[] binaryData,int length) {
-
-        if (length<4) {
-                length=Integer.MAX_VALUE;
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
         }
 
-       if (binaryData == null)
-           return null;
-
-       int      lengthDataBits    = binaryData.length*EIGHTBIT;
-       if (lengthDataBits == 0) {
-           return "";
-       }
-
-       int      fewerThan24bits   = lengthDataBits%TWENTYFOURBITGROUP;
-       int      numberTriplets    = lengthDataBits/TWENTYFOURBITGROUP;
-       int      numberQuartet     = fewerThan24bits != 0 ? numberTriplets+1 : numberTriplets;
-       int      quartesPerLine    = length/4;
-       int      numberLines       = (numberQuartet-1)/quartesPerLine;
-       char     encodedData[]     = null;
-
-       encodedData = new char[numberQuartet*4+numberLines];
-
-       byte k=0, l=0, b1=0,b2=0,b3=0;
-
-       int encodedIndex = 0;
-       int dataIndex   = 0;
-       int i           = 0;
-
-
-       for (int line = 0; line < numberLines; line++) {
-           for (int quartet = 0; quartet < 19; quartet++) {
-               b1 = binaryData[dataIndex++];
-               b2 = binaryData[dataIndex++];
-               b3 = binaryData[dataIndex++];
-
-
-               l  = (byte)(b2 & 0x0f);
-               k  = (byte)(b1 & 0x03);
-
-               byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
-
-               byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0);
-               byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc);
-
-
-               encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ];
-               encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )];
-               encodedData[encodedIndex++] = lookUpBase64Alphabet[ (l <<2 ) | val3 ];
-               encodedData[encodedIndex++] = lookUpBase64Alphabet[ b3 & 0x3f ];
-
-               i++;
-           }
-                encodedData[encodedIndex++] = 0xa;
-       }
+        // form integral number of 6-bit groups
+        if (fewerThan24bits == EIGHTBIT) {
+            b1 = binaryData[dataIndex];
+            k = (byte) (b1 &0x03);
+            byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2):(byte)((b1) >> 2 ^ 0xc0);
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
+            encodedData[encodedIndex++] = PAD;
+            encodedData[encodedIndex++] = PAD;
+        } else if (fewerThan24bits == SIXTEENBIT) {
+            b1 = binaryData[dataIndex];
+            b2 = binaryData[dataIndex +1 ];
+            l = ( byte ) (b2 & 0x0f);
+            k = ( byte ) (b1 & 0x03);
 
-       for (; i<numberTriplets; i++) {
-           b1 = binaryData[dataIndex++];
-           b2 = binaryData[dataIndex++];
-           b3 = binaryData[dataIndex++];
-
-
-           l  = (byte)(b2 & 0x0f);
-           k  = (byte)(b1 & 0x03);
-
-           byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
-
-           byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0);
-           byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc);
-
-
-           encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ];
-           encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )];
-           encodedData[encodedIndex++] = lookUpBase64Alphabet[ (l <<2 ) | val3 ];
-           encodedData[encodedIndex++] = lookUpBase64Alphabet[ b3 & 0x3f ];
-       }
+            byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0);
+            byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0);
 
-       // form integral number of 6-bit groups
-       if (fewerThan24bits == EIGHTBIT) {
-           b1 = binaryData[dataIndex];
-           k = (byte) ( b1 &0x03 );
-          byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
-           encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ];
-           encodedData[encodedIndex++] = lookUpBase64Alphabet[ k<<4 ];
-           encodedData[encodedIndex++] = PAD;
-           encodedData[encodedIndex++] = PAD;
-       } else if (fewerThan24bits == SIXTEENBIT) {
-           b1 = binaryData[dataIndex];
-           b2 = binaryData[dataIndex +1 ];
-           l = ( byte ) ( b2 &0x0f );
-           k = ( byte ) ( b1 &0x03 );
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
+            encodedData[encodedIndex++] = PAD;
+        }
 
-           byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
-           byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0);
+        //encodedData[encodedIndex] = 0xa;
 
-           encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ];
-           encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )];
-           encodedData[encodedIndex++] = lookUpBase64Alphabet[ l<<2 ];
-           encodedData[encodedIndex++] = PAD;
-       }
-
-       //encodedData[encodedIndex] = 0xa;
-
-       return new String(encodedData);
-   }
+        return new String(encodedData);
+    }
 
     /**
-     * Decodes Base64 data into octects
+     * Decodes Base64 data into octets
      *
      * @param encoded String containing base64 encoded data
      * @return byte array containing the decoded data
      * @throws Base64DecodingException if there is a problem decoding the data
      */
-    public final static byte[] decode(String encoded) throws Base64DecodingException {
-
-        if (encoded == null)
-                return null;
-        byte []bytes=new byte[encoded.length()];
-        int len=getBytesInternal(encoded, bytes);
+    public static final byte[] decode(String encoded) throws Base64DecodingException {
+        if (encoded == null) {
+            return null;
+        }
+        byte[] bytes = new byte[encoded.length()];
+        int len = getBytesInternal(encoded, bytes);
         return decodeInternal(bytes, len);
-        }
+    }
 
-    protected static final int getBytesInternal(String s,byte[] result) {
-        int length=s.length();
+    protected static final int getBytesInternal(String s, byte[] result) {
+        int length = s.length();
 
-        int newSize=0;
+        int newSize = 0;
         for (int i = 0; i < length; i++) {
-            byte dataS=(byte)s.charAt(i);
-            if (!isWhiteSpace(dataS))
+            byte dataS = (byte)s.charAt(i);
+            if (!isWhiteSpace(dataS)) {
                 result[newSize++] = dataS;
+            }
         }
         return newSize;
-
     }
-   protected final static byte[] decodeInternal(byte[] base64Data, int len) throws Base64DecodingException {
-       // remove white spaces
-           if (len==-1)
-          len = removeWhiteSpace(base64Data);
 
-       if (len%FOURBYTE != 0) {
-           throw new Base64DecodingException("decoding.divisible.four");
-           //should be divisible by four
-       }
+    protected static final byte[] decodeInternal(byte[] base64Data, int len)
+        throws Base64DecodingException {
+        // remove white spaces
+        if (len == -1) {
+            len = removeWhiteSpace(base64Data);
+        }
 
-       int      numberQuadruple    = (len/FOURBYTE );
+        if (len % FOURBYTE != 0) {
+            throw new Base64DecodingException("decoding.divisible.four");
+            //should be divisible by four
+        }
 
-       if (numberQuadruple == 0)
-           return new byte[0];
+        int numberQuadruple = (len / FOURBYTE);
 
-       byte     decodedData[]      = null;
-       byte     b1=0,b2=0,b3=0, b4=0;
-
+        if (numberQuadruple == 0) {
+            return new byte[0];
+        }
 
-       int i = 0;
-       int encodedIndex = 0;
-       int dataIndex    = 0;
+        byte decodedData[] = null;
+        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
 
-       //decodedData      = new byte[ (numberQuadruple)*3];
-       dataIndex=(numberQuadruple-1)*4;
-       encodedIndex=(numberQuadruple-1)*3;
-       //first last bits.
-       b1 = base64Alphabet[base64Data[dataIndex++]];
-       b2 = base64Alphabet[base64Data[dataIndex++]];
-       if ((b1==-1) || (b2==-1)) {
-                throw new Base64DecodingException("decoding.general");//if found "no data" just return null
+        int i = 0;
+        int encodedIndex = 0;
+        int dataIndex = 0;
+
+        //decodedData = new byte[ (numberQuadruple)*3];
+        dataIndex = (numberQuadruple - 1) * 4;
+        encodedIndex = (numberQuadruple - 1) * 3;
+        //first last bits.
+        b1 = base64Alphabet[base64Data[dataIndex++]];
+        b2 = base64Alphabet[base64Data[dataIndex++]];
+        if ((b1==-1) || (b2==-1)) {
+             //if found "no data" just return null
+            throw new Base64DecodingException("decoding.general");
         }
 
 
-        byte d3,d4;
-        b3 = base64Alphabet[d3=base64Data[dataIndex++]];
-        b4 = base64Alphabet[d4=base64Data[dataIndex++]];
-        if ((b3==-1 ) || (b4==-1) ) {
-                //Check if they are PAD characters
-            if (isPad( d3 ) && isPad( d4)) {               //Two PAD e.g. 3c[Pad][Pad]
-                if ((b2 & 0xf) != 0)//last 4 bits should be zero
-                        throw new Base64DecodingException("decoding.general");
-                decodedData = new byte[ encodedIndex + 1 ];
-                decodedData[encodedIndex]   = (byte)(  b1 <<2 | b2>>4 ) ;
-            } else if (!isPad( d3) && isPad(d4)) {               //One PAD  e.g. 3cQ[Pad]
-                if ((b3 & 0x3 ) != 0)//last 2 bits should be zero
-                        throw new Base64DecodingException("decoding.general");
-                decodedData = new byte[ encodedIndex + 2 ];
-                decodedData[encodedIndex++] = (byte)(  b1 <<2 | b2>>4 );
-                decodedData[encodedIndex]   = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
+        byte d3, d4;
+        b3 = base64Alphabet[d3 = base64Data[dataIndex++]];
+        b4 = base64Alphabet[d4 = base64Data[dataIndex++]];
+        if ((b3 == -1) || (b4 == -1) ) {
+            //Check if they are PAD characters
+            if (isPad(d3) && isPad(d4)) {               //Two PAD e.g. 3c[Pad][Pad]
+                if ((b2 & 0xf) != 0) { //last 4 bits should be zero
+                    throw new Base64DecodingException("decoding.general");
+                }
+                decodedData = new byte[encodedIndex + 1];
+                decodedData[encodedIndex]   = (byte)(b1 << 2 | b2 >> 4) ;
+            } else if (!isPad(d3) && isPad(d4)) {               //One PAD  e.g. 3cQ[Pad]
+                if ((b3 & 0x3) != 0) { //last 2 bits should be zero
+                    throw new Base64DecodingException("decoding.general");
+                }
+                decodedData = new byte[encodedIndex + 2];
+                decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4);
+                decodedData[encodedIndex] = (byte)(((b2 & 0xf) << 4) |((b3 >> 2) & 0xf));
             } else {
-                throw new Base64DecodingException("decoding.general");//an error  like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data
+                //an error  like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data
+                throw new Base64DecodingException("decoding.general");
             }
         } else {
             //No PAD e.g 3cQl
             decodedData = new byte[encodedIndex+3];
-            decodedData[encodedIndex++] = (byte)(  b1 <<2 | b2>>4 ) ;
-            decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
-            decodedData[encodedIndex++] = (byte)( b3<<6 | b4 );
+            decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4) ;
+            decodedData[encodedIndex++] = (byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
+            decodedData[encodedIndex++] = (byte)(b3 << 6 | b4);
         }
-        encodedIndex=0;
-        dataIndex=0;
-       //the begin
-       for (i=numberQuadruple-1; i>0; i--) {
-           b1 = base64Alphabet[base64Data[dataIndex++]];
-           b2 = base64Alphabet[base64Data[dataIndex++]];
-           b3 = base64Alphabet[base64Data[dataIndex++]];
-           b4 = base64Alphabet[base64Data[dataIndex++]];
+        encodedIndex = 0;
+        dataIndex = 0;
+        //the begin
+        for (i = numberQuadruple - 1; i > 0; i--) {
+            b1 = base64Alphabet[base64Data[dataIndex++]];
+            b2 = base64Alphabet[base64Data[dataIndex++]];
+            b3 = base64Alphabet[base64Data[dataIndex++]];
+            b4 = base64Alphabet[base64Data[dataIndex++]];
 
-           if ( (b1==-1) ||
-                        (b2==-1) ||
-                        (b3==-1) ||
-                        (b4==-1) ) {
-                   throw new Base64DecodingException("decoding.general");//if found "no data" just return null
-           }
+            if ((b1 == -1) ||
+                (b2 == -1) ||
+                (b3 == -1) ||
+                (b4 == -1)) {
+                //if found "no data" just return null
+                throw new Base64DecodingException("decoding.general");
+            }
 
-           decodedData[encodedIndex++] = (byte)(  b1 <<2 | b2>>4 ) ;
-           decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
-           decodedData[encodedIndex++] = (byte)( b3<<6 | b4 );
-       }
-       return decodedData;
-   }
-   /**
-    * Decodes Base64 data into  outputstream
-    *
-    * @param base64Data String containing Base64 data
-    * @param os the outputstream
-    * @throws IOException
-    * @throws Base64DecodingException
-    */
-   public final static void decode(String base64Data,
-        OutputStream os) throws Base64DecodingException, IOException {
-           byte[] bytes=new byte[base64Data.length()];
-           int len=getBytesInternal(base64Data, bytes);
-           decode(bytes,os,len);
-   }
-   /**
-    * Decodes Base64 data into  outputstream
-    *
-    * @param base64Data Byte array containing Base64 data
-    * @param os the outputstream
-    * @throws IOException
-    * @throws Base64DecodingException
-    */
-   public final static void decode(byte[] base64Data,
-        OutputStream os) throws Base64DecodingException, IOException {
-            decode(base64Data,os,-1);
-   }
-   protected final static void decode(byte[] base64Data,
-                        OutputStream os,int len) throws Base64DecodingException, IOException {
+            decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4) ;
+            decodedData[encodedIndex++] = (byte)(((b2 & 0xf) << 4) |((b3 >> 2) & 0xf));
+            decodedData[encodedIndex++] = (byte)(b3 << 6 | b4 );
+        }
+        return decodedData;
+    }
 
-        // remove white spaces
-    if (len==-1)
-       len = removeWhiteSpace(base64Data);
-
-    if (len%FOURBYTE != 0) {
-        throw new Base64DecodingException("decoding.divisible.four");
-        //should be divisible by four
+    /**
+     * Decodes Base64 data into outputstream
+     *
+     * @param base64Data String containing Base64 data
+     * @param os the outputstream
+     * @throws IOException
+     * @throws Base64DecodingException
+     */
+    public static final void decode(String base64Data, OutputStream os)
+        throws Base64DecodingException, IOException {
+        byte[] bytes = new byte[base64Data.length()];
+        int len = getBytesInternal(base64Data, bytes);
+        decode(bytes,os,len);
     }
 
-    int      numberQuadruple    = (len/FOURBYTE );
+    /**
+     * Decodes Base64 data into outputstream
+     *
+     * @param base64Data Byte array containing Base64 data
+     * @param os the outputstream
+     * @throws IOException
+     * @throws Base64DecodingException
+     */
+    public static final void decode(byte[] base64Data, OutputStream os)
+        throws Base64DecodingException, IOException {
+        decode(base64Data,os,-1);
+    }
 
-    if (numberQuadruple == 0)
-        return;
+    protected static final void decode(byte[] base64Data, OutputStream os, int len)
+        throws Base64DecodingException, IOException {
+        // remove white spaces
+        if (len == -1) {
+            len = removeWhiteSpace(base64Data);
+        }
+
+        if (len % FOURBYTE != 0) {
+            throw new Base64DecodingException("decoding.divisible.four");
+            //should be divisible by four
+        }
+
+        int numberQuadruple = (len / FOURBYTE);
 
-    //byte     decodedData[]      = null;
-    byte     b1=0,b2=0,b3=0, b4=0;
+        if (numberQuadruple == 0) {
+            return;
+        }
 
-    int i = 0;
+        //byte decodedData[] = null;
+        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
+
+        int i = 0;
+        int dataIndex = 0;
 
-    int dataIndex    = 0;
+        //the begin
+        for (i=numberQuadruple - 1; i > 0; i--) {
+            b1 = base64Alphabet[base64Data[dataIndex++]];
+            b2 = base64Alphabet[base64Data[dataIndex++]];
+            b3 = base64Alphabet[base64Data[dataIndex++]];
+            b4 = base64Alphabet[base64Data[dataIndex++]];
+            if ((b1 == -1) ||
+                (b2 == -1) ||
+                (b3 == -1) ||
+                (b4 == -1) ) {
+                //if found "no data" just return null
+                throw new Base64DecodingException("decoding.general");
+            }
 
-    //the begin
-    for (i=numberQuadruple-1; i>0; i--) {
+            os.write((byte)(b1 << 2 | b2 >> 4));
+            os.write((byte)(((b2 & 0xf) << 4 ) | ((b3 >> 2) & 0xf)));
+            os.write( (byte)(b3 << 6 | b4));
+        }
         b1 = base64Alphabet[base64Data[dataIndex++]];
         b2 = base64Alphabet[base64Data[dataIndex++]];
-        b3 = base64Alphabet[base64Data[dataIndex++]];
-        b4 = base64Alphabet[base64Data[dataIndex++]];
-        if ( (b1==-1) ||
-                (b2==-1) ||
-                (b3==-1) ||
-                (b4==-1) )
-         throw new Base64DecodingException("decoding.general");//if found "no data" just return null
 
-
-
-        os.write((byte)(  b1 <<2 | b2>>4 ) );
-        os.write((byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ));
-        os.write( (byte)( b3<<6 | b4 ));
-    }
-    b1 = base64Alphabet[base64Data[dataIndex++]];
-    b2 = base64Alphabet[base64Data[dataIndex++]];
-
-    //  first last bits.
-    if ((b1==-1) ||
-        (b2==-1) ){
-             throw new Base64DecodingException("decoding.general");//if found "no data" just return null
-     }
-
-     byte d3,d4;
-     b3= base64Alphabet[d3 = base64Data[dataIndex++]];
-     b4= base64Alphabet[d4 = base64Data[dataIndex++]];
-     if ((b3==-1 ) ||
-          (b4==-1) ) {//Check if they are PAD characters
-         if (isPad( d3 ) && isPad( d4)) {               //Two PAD e.g. 3c[Pad][Pad]
-             if ((b2 & 0xf) != 0)//last 4 bits should be zero
-                     throw new Base64DecodingException("decoding.general");
-             os.write( (byte)(  b1 <<2 | b2>>4 ) );
-         } else if (!isPad( d3) && isPad(d4)) {               //One PAD  e.g. 3cQ[Pad]
-             if ((b3 & 0x3 ) != 0)//last 2 bits should be zero
-                     throw new Base64DecodingException("decoding.general");
-             os.write( (byte)(  b1 <<2 | b2>>4 ));
-             os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ));
-         } else {
-             throw new Base64DecodingException("decoding.general");//an error  like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data
-         }
-     } else {
-         //No PAD e.g 3cQl
-         os.write((byte)(  b1 <<2 | b2>>4 ) );
-         os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ));
-         os.write((byte)( b3<<6 | b4 ));
-     }
-    return ;
-   }
-
-   /**
-    * Decodes Base64 data into  outputstream
-    *
-    * @param is containing Base64 data
-    * @param os the outputstream
-    * @throws IOException
-    * @throws Base64DecodingException
-    */
-   public final static void decode(InputStream is,
-        OutputStream os) throws Base64DecodingException, IOException {
-        //byte     decodedData[]      = null;
-    byte     b1=0,b2=0,b3=0, b4=0;
-
-    int index=0;
-    byte []data=new byte[4];
-    int read;
-    //the begin
-    while ((read=is.read())>0) {
-        byte readed=(byte)read;
-        if (isWhiteSpace(readed)) {
-                continue;
-        }
-        if (isPad(readed)) {
-            data[index++]=readed;
-            if (index==3)
-                data[index++]=(byte)is.read();
-            break;
+        //  first last bits.
+        if ((b1 == -1) || (b2 == -1) ) {
+            //if found "no data" just return null
+            throw new Base64DecodingException("decoding.general");
         }
 
-
-        if ((data[index++]=readed)==-1) {
-            throw new Base64DecodingException("decoding.general");//if found "no data" just return null
-           }
-
-        if (index!=4) {
-                continue;
+        byte d3, d4;
+        b3 = base64Alphabet[d3 = base64Data[dataIndex++]];
+        b4 = base64Alphabet[d4 = base64Data[dataIndex++]];
+        if ((b3 == -1 ) || (b4 == -1) ) { //Check if they are PAD characters
+            if (isPad(d3) && isPad(d4)) {               //Two PAD e.g. 3c[Pad][Pad]
+                if ((b2 & 0xf) != 0) { //last 4 bits should be zero
+                    throw new Base64DecodingException("decoding.general");
+                }
+                os.write((byte)(b1 << 2 | b2 >> 4));
+            } else if (!isPad(d3) && isPad(d4)) {               //One PAD  e.g. 3cQ[Pad]
+                if ((b3 & 0x3 ) != 0) { //last 2 bits should be zero
+                    throw new Base64DecodingException("decoding.general");
+                }
+                os.write((byte)(b1 << 2 | b2 >> 4));
+                os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)));
+            } else {
+                //an error  like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data
+                throw new Base64DecodingException("decoding.general");
+            }
+        } else {
+            //No PAD e.g 3cQl
+            os.write((byte)(b1 << 2 | b2 >> 4));
+            os.write( (byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)));
+            os.write((byte)(b3 << 6 | b4));
         }
-        index=0;
-        b1 = base64Alphabet[data[0]];
-        b2 = base64Alphabet[data[1]];
-        b3 = base64Alphabet[data[2]];
-        b4 = base64Alphabet[data[3]];
-
-        os.write((byte)(  b1 <<2 | b2>>4 ) );
-        os.write((byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ));
-        os.write( (byte)( b3<<6 | b4 ));
     }
 
+    /**
+     * Decodes Base64 data into  outputstream
+     *
+     * @param is containing Base64 data
+     * @param os the outputstream
+     * @throws IOException
+     * @throws Base64DecodingException
+     */
+    public static final void decode(InputStream is, OutputStream os)
+        throws Base64DecodingException, IOException {
+        //byte decodedData[] = null;
+        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
 
-    byte     d1=data[0],d2=data[1],d3=data[2], d4=data[3];
-    b1 = base64Alphabet[d1];
-    b2 = base64Alphabet[d2];
-    b3 = base64Alphabet[ d3 ];
-    b4 = base64Alphabet[ d4 ];
-     if ((b3==-1 ) ||
-         (b4==-1) ) {//Check if they are PAD characters
-         if (isPad( d3 ) && isPad( d4)) {               //Two PAD e.g. 3c[Pad][Pad]
-             if ((b2 & 0xf) != 0)//last 4 bits should be zero
-                     throw new Base64DecodingException("decoding.general");
-             os.write( (byte)(  b1 <<2 | b2>>4 ) );
-         } else if (!isPad( d3) && isPad(d4)) {               //One PAD  e.g. 3cQ[Pad]
-             b3 = base64Alphabet[ d3 ];
-             if ((b3 & 0x3 ) != 0)//last 2 bits should be zero
-                     throw new Base64DecodingException("decoding.general");
-             os.write( (byte)(  b1 <<2 | b2>>4 ));
-             os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ));
-         } else {
-             throw new Base64DecodingException("decoding.general");//an error  like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data
-         }
-     } else {
-         //No PAD e.g 3cQl
+        int index=0;
+        byte[] data = new byte[4];
+        int read;
+        //the begin
+        while ((read = is.read()) > 0) {
+            byte readed = (byte)read;
+            if (isWhiteSpace(readed)) {
+                continue;
+            }
+            if (isPad(readed)) {
+                data[index++] = readed;
+                if (index == 3) {
+                    data[index++] = (byte)is.read();
+                }
+                break;
+            }
+
+            if ((data[index++] = readed) == -1) {
+                //if found "no data" just return null
+                throw new Base64DecodingException("decoding.general");
+            }
+
+            if (index != 4) {
+                continue;
+            }
+            index = 0;
+            b1 = base64Alphabet[data[0]];
+            b2 = base64Alphabet[data[1]];
+            b3 = base64Alphabet[data[2]];
+            b4 = base64Alphabet[data[3]];
+
+            os.write((byte)(b1 << 2 | b2 >> 4));
+            os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)));
+            os.write((byte)(b3 << 6 | b4));
+        }
 
-         os.write((byte)(  b1 <<2 | b2>>4 ) );
-         os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ));
-         os.write((byte)( b3<<6 | b4 ));
-     }
+        byte d1 = data[0], d2 = data[1], d3 = data[2], d4 = data[3];
+        b1 = base64Alphabet[d1];
+        b2 = base64Alphabet[d2];
+        b3 = base64Alphabet[d3];
+        b4 = base64Alphabet[d4];
+        if ((b3 == -1) || (b4 == -1)) { //Check if they are PAD characters
+            if (isPad(d3) && isPad(d4)) {               //Two PAD e.g. 3c[Pad][Pad]
+                if ((b2 & 0xf) != 0) { //last 4 bits should be zero
+                    throw new Base64DecodingException("decoding.general");
+                }
+                os.write((byte)(b1 << 2 | b2 >> 4));
+            } else if (!isPad(d3) && isPad(d4)) {               //One PAD  e.g. 3cQ[Pad]
+                b3 = base64Alphabet[d3];
+                if ((b3 & 0x3) != 0) { //last 2 bits should be zero
+                    throw new Base64DecodingException("decoding.general");
+                }
+                os.write((byte)(b1 << 2 | b2 >> 4));
+                os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)));
+            } else {
+                //an error  like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data
+                throw new Base64DecodingException("decoding.general");
+            }
+        } else {
+            //No PAD e.g 3cQl
+            os.write((byte)(b1 << 2 | b2 >> 4));
+            os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)));
+            os.write((byte)(b3 << 6 | b4));
+        }
+    }
 
-    return ;
-   }
-   /**
-    * remove WhiteSpace from MIME containing encoded Base64 data.
-    *
-    * @param data  the byte array of base64 data (with WS)
-    * @return      the new length
-    */
-   protected static final int removeWhiteSpace(byte[] data) {
-       if (data == null)
-           return 0;
+    /**
+     * remove WhiteSpace from MIME containing encoded Base64 data.
+     *
+     * @param data  the byte array of base64 data (with WS)
+     * @return      the new length
+     */
+    protected static final int removeWhiteSpace(byte[] data) {
+        if (data == null) {
+            return 0;
+        }
 
-       // count characters that's not whitespace
-       int newSize = 0;
-       int len = data.length;
-       for (int i = 0; i < len; i++) {
-           byte dataS=data[i];
-           if (!isWhiteSpace(dataS))
-               data[newSize++] = dataS;
-       }
-       return newSize;
-   }
+        // count characters that's not whitespace
+        int newSize = 0;
+        int len = data.length;
+        for (int i = 0; i < len; i++) {
+            byte dataS = data[i];
+            if (!isWhiteSpace(dataS)) {
+                data[newSize++] = dataS;
+            }
+        }
+        return newSize;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java	Thu Jul 18 03:38:49 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
- */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- */
-package com.sun.org.apache.xml.internal.security.utils;
-
-import com.sun.org.apache.xpath.internal.CachedXPathAPI;
-import org.w3c.dom.Document;
-
-/**
- * @author Raul Benito
- */
-public class CachedXPathAPIHolder {
-
-    static ThreadLocal<CachedXPathAPI>  local=new ThreadLocal<CachedXPathAPI>();
-    static ThreadLocal<Document> localDoc=new ThreadLocal<Document>();
-
-    /**
-     * Sets the doc for the xpath transformation. Resets the cache if needed
-     * @param doc
-     */
-    public static void setDoc(Document doc) {
-        if (localDoc.get()!=doc) {
-            CachedXPathAPI cx=local.get();
-            if (cx==null) {
-                cx=new CachedXPathAPI();
-                local.set(cx);
-                localDoc.set(doc);
-                return;
-            }
-            //Different docs reset.
-            cx.getXPathContext().reset();
-            localDoc.set(doc);
-        }
-    }
-
-    /**
-     * @return the cachexpathapi for this thread
-     */
-    public static CachedXPathAPI getCachedXPathAPI() {
-        CachedXPathAPI cx=local.get();
-        if (cx==null) {
-            cx=new CachedXPathAPI();
-            local.set(cx);
-            localDoc.set(null);
-        }
-        return cx;
-    }
-}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java	Thu Jul 18 03:38:49 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,466 +0,0 @@
-/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
- */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- */
-package com.sun.org.apache.xml.internal.security.utils;
-
-
-
-import com.sun.org.apache.xml.internal.dtm.DTMManager;
-import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHere;
-import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHereContext;
-import com.sun.org.apache.xml.internal.utils.PrefixResolver;
-import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault;
-import com.sun.org.apache.xpath.internal.CachedXPathAPI;
-import com.sun.org.apache.xpath.internal.Expression;
-import com.sun.org.apache.xpath.internal.XPath;
-import com.sun.org.apache.xpath.internal.XPathContext;
-import com.sun.org.apache.xpath.internal.compiler.FunctionTable;
-import com.sun.org.apache.xpath.internal.objects.XObject;
-import org.w3c.dom.*;
-import org.w3c.dom.traversal.NodeIterator;
-
-import javax.xml.transform.ErrorListener;
-import javax.xml.transform.SourceLocator;
-import javax.xml.transform.TransformerException;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-
-/**
- *
- * @author $Author: mullan $
- */
-public class CachedXPathFuncHereAPI {
-
-    static java.util.logging.Logger log =
-           java.util.logging.Logger.getLogger(CachedXPathFuncHereAPI.class.getName());
-   /**
-    * XPathContext, and thus DTMManager and DTMs, persists through multiple
-    *   calls to this object.
-    */
-   FuncHereContext _funcHereContext = null;
-
-   /** Field _dtmManager */
-   DTMManager _dtmManager = null;
-
-   XPathContext _context = null;
-
-   String xpathStr=null;
-
-   XPath xpath=null;
-
-   static FunctionTable _funcTable = null;
-
-    static {
-        fixupFunctionTable();
-    }
-
-   /**
-    * Method getFuncHereContext
-    * @return the context for this object
-    *
-    */
-   public FuncHereContext getFuncHereContext() {
-      return this._funcHereContext;
-   }
-
-   /**
-    * Constructor CachedXPathFuncHereAPI
-    *
-    */
-   private CachedXPathFuncHereAPI() {}
-
-   /**
-    * Constructor CachedXPathFuncHereAPI
-    *
-    * @param existingXPathContext
-    */
-   public CachedXPathFuncHereAPI(XPathContext existingXPathContext) {
-      this._dtmManager = existingXPathContext.getDTMManager();
-      this._context=existingXPathContext;
-   }
-
-   /**
-    * Constructor CachedXPathFuncHereAPI
-    *
-    * @param previouslyUsed
-    */
-   public CachedXPathFuncHereAPI(CachedXPathAPI previouslyUsed) {
-      this._dtmManager = previouslyUsed.getXPathContext().getDTMManager();
-      this._context=previouslyUsed.getXPathContext();
-   }
-
-   /**
-    * Use an XPath string to select a single node. XPath namespace
-    * prefixes are resolved from the context node, which may not
-    * be what you want (see the next method).
-    *
-    * @param contextNode The node to start searching from.
-    * @param xpathnode A Node containing a valid XPath string.
-    * @return The first node found that matches the XPath, or null.
-    *
-    * @throws TransformerException
-    */
-   public Node selectSingleNode(Node contextNode, Node xpathnode)
-           throws TransformerException {
-      return selectSingleNode(contextNode, xpathnode, contextNode);
-   }
-
-   /**
-    * Use an XPath string to select a single node.
-    * XPath namespace prefixes are resolved from the namespaceNode.
-    *
-    * @param contextNode The node to start searching from.
-    * @param xpathnode
-    * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
-    * @return The first node found that matches the XPath, or null.
-    *
-    * @throws TransformerException
-    */
-   public Node selectSingleNode(
-           Node contextNode, Node xpathnode, Node namespaceNode)
-              throws TransformerException {
-
-      // Have the XObject return its result as a NodeSetDTM.
-      NodeIterator nl = selectNodeIterator(contextNode, xpathnode,
-                                           namespaceNode);
-
-      // Return the first node, or null
-      return nl.nextNode();
-   }
-
-   /**
-    *   Use an XPath string to select a nodelist.
-    *   XPath namespace prefixes are resolved from the contextNode.
-    *
-    *   @param contextNode The node to start searching from.
-    *   @param xpathnode
-    *   @return A NodeIterator, should never be null.
-    *
-    *  @throws TransformerException
-    */
-   public NodeIterator selectNodeIterator(Node contextNode, Node xpathnode)
-           throws TransformerException {
-      return selectNodeIterator(contextNode, xpathnode, contextNode);
-   }
-
-   /**
-    *  Use an XPath string to select a nodelist.
-    *  XPath namespace prefixes are resolved from the namespaceNode.
-    *
-    *  @param contextNode The node to start searching from.
-    * @param xpathnode
-    *  @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
-    *  @return A NodeIterator, should never be null.
-    *
-    * @throws TransformerException
-    * @deprecated
-    */
-   @Deprecated
-   public NodeIterator selectNodeIterator(
-           Node contextNode, Node xpathnode, Node namespaceNode)
-              throws TransformerException {
-
-      // Execute the XPath, and have it return the result
-      XObject list = eval(contextNode, xpathnode, getStrFromNode(xpathnode), namespaceNode);
-
-      // Have the XObject return its result as a NodeSetDTM.
-      return list.nodeset();
-   }
-
-   /**
-    *  Use an XPath string to select a nodelist.
-    *  XPath namespace prefixes are resolved from the contextNode.
-    *
-    *  @param contextNode The node to start searching from.
-    * @param xpathnode
-    *  @return A NodeIterator, should never be null.
-    *
-    * @throws TransformerException
-    * @deprecated
-    */
-   @Deprecated
-   public NodeList selectNodeList(Node contextNode, Node xpathnode)
-           throws TransformerException {
-      return selectNodeList(contextNode, xpathnode, getStrFromNode(xpathnode), contextNode);
-   }
-
-   /**
-    *  Use an XPath string to select a nodelist.
-    *  XPath namespace prefixes are resolved from the namespaceNode.
-    *
-    *  @param contextNode The node to start searching from.
-    * @param xpathnode
-    * @param str
-    *  @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
-    *  @return A NodeIterator, should never be null.
-    *
-    * @throws TransformerException
-    */
-   public NodeList selectNodeList(
-           Node contextNode, Node xpathnode, String str, Node namespaceNode)
-              throws TransformerException {
-
-      // Execute the XPath, and have it return the result
-      XObject list = eval(contextNode, xpathnode, str, namespaceNode);
-
-      // Return a NodeList.
-      return list.nodelist();
-   }
-
-   /**
-    *  Evaluate XPath string to an XObject.  Using this method,
-    *  XPath namespace prefixes will be resolved from the namespaceNode.
-    *  @param contextNode The node to start searching from.
-    * @param xpathnode
-    *  @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null.
-    *  @see com.sun.org.apache.xpath.internal.objects.XObject
-    *  @see com.sun.org.apache.xpath.internal.objects.XNull
-    *  @see com.sun.org.apache.xpath.internal.objects.XBoolean
-    *  @see com.sun.org.apache.xpath.internal.objects.XNumber
-    *  @see com.sun.org.apache.xpath.internal.objects.XString
-    *  @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag
-    *
-    * @throws TransformerException
-    * @deprecated
-    */
-   @Deprecated
-   public XObject eval(Node contextNode, Node xpathnode)
-           throws TransformerException {
-      return eval(contextNode, xpathnode, getStrFromNode(xpathnode),contextNode);
-   }
-
-   /**
-    *  Evaluate XPath string to an XObject.
-    *  XPath namespace prefixes are resolved from the namespaceNode.
-    *  The implementation of this is a little slow, since it creates
-    *  a number of objects each time it is called.  This could be optimized
-    *  to keep the same objects around, but then thread-safety issues would arise.
-    *
-    *  @param contextNode The node to start searching from.
-    * @param xpathnode
-    * @param str
-    *  @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
-    *  @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null.
-    *  @see com.sun.org.apache.xpath.internal.objects.XObject
-    *  @see com.sun.org.apache.xpath.internal.objects.XNull
-    *  @see com.sun.org.apache.xpath.internal.objects.XBoolean
-    *  @see com.sun.org.apache.xpath.internal.objects.XNumber
-    *  @see com.sun.org.apache.xpath.internal.objects.XString
-    *  @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag
-    *
-    * @throws TransformerException
-    */
-   public XObject eval(Node contextNode, Node xpathnode, String str, Node namespaceNode)
-           throws TransformerException {
-      //  Create the XPath object.
-      //String str = CachedXPathFuncHereAPI.getStrFromNode(xpathnode);
-
-      // Since we don't have a XML Parser involved here, install some default support
-      // for things like namespaces, etc.
-      // (Changed from: XPathContext xpathSupport = new XPathContext();
-      //    because XPathContext is weak in a number of areas... perhaps
-      //    XPathContext should be done away with.)
-      if (this._funcHereContext == null) {
-         this._funcHereContext = new FuncHereContext(xpathnode,
-                                                     this._dtmManager);
-      }
-
-      // Create an object to resolve namespace prefixes.
-      // XPath namespaces are resolved from the input context node's document element
-      // if it is a root node, or else the current context node (for lack of a better
-      // resolution space, given the simplicity of this sample code).
-      PrefixResolverDefault prefixResolver =
-         new PrefixResolverDefault((namespaceNode.getNodeType()
-                                    == Node.DOCUMENT_NODE)
-                                   ? ((Document) namespaceNode)
-                                      .getDocumentElement()
-                                   : namespaceNode);
-
-      // only check if string points to different object (for performance)
-      if (str!=xpathStr) {
-        if (str.indexOf("here()")>0) {
-            _context.reset();
-            _dtmManager=_context.getDTMManager();
-        }
-        xpath = createXPath(str, prefixResolver);
-        xpathStr=str;
-      }
-
-      // Execute the XPath, and have it return the result
-      // return xpath.execute(xpathSupport, contextNode, prefixResolver);
-      int ctxtNode = this._funcHereContext.getDTMHandleFromNode(contextNode);
-
-      return xpath.execute(this._funcHereContext, ctxtNode, prefixResolver);
-   }
-
-   /**
-    *   Evaluate XPath string to an XObject.
-    *   XPath namespace prefixes are resolved from the namespaceNode.
-    *   The implementation of this is a little slow, since it creates
-    *   a number of objects each time it is called.  This could be optimized
-    *   to keep the same objects around, but then thread-safety issues would arise.
-    *
-    *   @param contextNode The node to start searching from.
-    * @param xpathnode
-    * @param str
-    *   @param prefixResolver Will be called if the parser encounters namespace
-    *                         prefixes, to resolve the prefixes to URLs.
-    *   @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null.
-    *   @see com.sun.org.apache.xpath.internal.objects.XObject
-    *   @see com.sun.org.apache.xpath.internal.objects.XNull
-    *   @see com.sun.org.apache.xpath.internal.objects.XBoolean
-    *   @see com.sun.org.apache.xpath.internal.objects.XNumber
-    *   @see com.sun.org.apache.xpath.internal.objects.XString
-    *   @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag
-    *
-    * @throws TransformerException
-    */
-   public XObject eval(
-           Node contextNode, Node xpathnode, String str, PrefixResolver prefixResolver)
-              throws TransformerException {
-
-      // Since we don't have a XML Parser involved here, install some default support
-      // for things like namespaces, etc.
-      // (Changed from: XPathContext xpathSupport = new XPathContext();
-      //    because XPathContext is weak in a number of areas... perhaps
-      //    XPathContext should be done away with.)
-      // Create the XPath object.
-      //String str = CachedXPathFuncHereAPI.getStrFromNode(xpathnode);
-    // only check if string points to different object (for performance)
-    if (str!=xpathStr) {
-        if (str.indexOf("here()")>0) {
-            _context.reset();
-            _dtmManager=_context.getDTMManager();
-        }
-        try {
-            xpath = createXPath(str, prefixResolver);
-        } catch (TransformerException ex) {
-            //Try to see if it is a problem with the classloader.
-            Throwable th= ex.getCause();
-            if (th instanceof ClassNotFoundException) {
-                 if (th.getMessage().indexOf("FuncHere")>0) {
-                     throw new RuntimeException(I18n.translate("endorsed.jdk1.4.0")/*,*/+ex);
-                 }
-              }
-              throw ex;
-        }
-        xpathStr=str;
-    }
-
-      // Execute the XPath, and have it return the result
-      if (this._funcHereContext == null) {
-         this._funcHereContext = new FuncHereContext(xpathnode,
-                                                     this._dtmManager);
-      }
-
-      int ctxtNode = this._funcHereContext.getDTMHandleFromNode(contextNode);
-
-      return xpath.execute(this._funcHereContext, ctxtNode, prefixResolver);
-   }
-
-    private XPath createXPath(String str, PrefixResolver prefixResolver) throws TransformerException {
-        XPath xpath = null;
-        Class<?>[] classes = new Class<?>[]{String.class, SourceLocator.class, PrefixResolver.class, int.class,
-                ErrorListener.class, FunctionTable.class};
-        Object[] objects = new Object[]{str, null, prefixResolver, new Integer(XPath.SELECT), null, _funcTable};
-        try {
-            Constructor<XPath> constructor = XPath.class.getConstructor(classes);
-            xpath = constructor.newInstance(objects);
-        } catch (Throwable t) {
-        }
-        if (xpath == null) {
-            xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null);
-        }
-        return xpath;
-    }
-
-    /**
-     * Method getStrFromNode
-     *
-     * @param xpathnode
-     * @return the string for the node.
-     */
-    public static String getStrFromNode(Node xpathnode) {
-
-       if (xpathnode.getNodeType() == Node.TEXT_NODE) {
-
-          // we iterate over all siblings of the context node because eventually,
-          // the text is "polluted" with pi's or comments
-          StringBuffer sb = new StringBuffer();
-
-          for (Node currentSibling = xpathnode.getParentNode().getFirstChild();
-               currentSibling != null;
-               currentSibling = currentSibling.getNextSibling()) {
-             if (currentSibling.getNodeType() == Node.TEXT_NODE) {
-                sb.append(((Text) currentSibling).getData());
-             }
-          }
-
-          return sb.toString();
-       } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) {
-          return ((Attr) xpathnode).getNodeValue();
-       } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
-          return ((ProcessingInstruction) xpathnode).getNodeValue();
-       }
-
-       return null;
-    }
-
-    private static void fixupFunctionTable() {
-        boolean installed = false;
-        log.log(java.util.logging.Level.INFO, "Registering Here function");
-        /**
-         * Try to register our here() implementation as internal function.
-         */
-        try {
-            Class []args = {String.class, Expression.class};
-            Method installFunction = FunctionTable.class.getMethod("installFunction", args);
-            if ((installFunction.getModifiers() & Modifier.STATIC) != 0) {
-                Object []params = {"here", new FuncHere()};
-                installFunction.invoke(null, params);
-                installed = true;
-            }
-        } catch (Throwable t) {
-            log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", t);
-        }
-        if(!installed) {
-            try {
-                _funcTable = new FunctionTable();
-                Class []args = {String.class, Class.class};
-                Method installFunction = FunctionTable.class.getMethod("installFunction", args);
-                Object []params = {"here", FuncHere.class};
-                installFunction.invoke(_funcTable, params);
-                installed = true;
-            } catch (Throwable t) {
-                log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", t);
-            }
-        }
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            if (installed) {
-                log.log(java.util.logging.Level.FINE, "Registered class " + FuncHere.class.getName()
-                        + " for XPath function 'here()' function in internal table");
-            } else {
-                log.log(java.util.logging.Level.FINE, "Unable to register class " + FuncHere.class.getName()
-                        + " for XPath function 'here()' function in internal table");
-            }
-        }
-    }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,277 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package com.sun.org.apache.xml.internal.security.utils;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.List;
+
+/**
+ * This class is extremely useful for loading resources and classes in a fault
+ * tolerant manner that works across different applications servers. Do not
+ * touch this unless you're a grizzled classloading guru veteran who is going to
+ * verify any change on 6 different application servers.
+ */
+final class ClassLoaderUtils {
+
+    /** {@link org.apache.commons.logging} logging facility */
+    private static final java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(ClassLoaderUtils.class.getName());
+
+    private ClassLoaderUtils() {
+    }
+
+    /**
+     * Load a given resource. <p/> This method will try to load the resource
+     * using the following methods (in order):
+     * <ul>
+     * <li>From Thread.currentThread().getContextClassLoader()
+     * <li>From ClassLoaderUtil.class.getClassLoader()
+     * <li>callingClass.getClassLoader()
+     * </ul>
+     *
+     * @param resourceName The name of the resource to load
+     * @param callingClass The Class object of the calling object
+     */
+    static URL getResource(String resourceName, Class<?> callingClass) {
+        URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName);
+        if (url == null && resourceName.startsWith("/")) {
+            //certain classloaders need it without the leading /
+            url =
+                Thread.currentThread().getContextClassLoader().getResource(
+                    resourceName.substring(1)
+                );
+        }
+
+        ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader();
+        if (cluClassloader == null) {
+            cluClassloader = ClassLoader.getSystemClassLoader();
+        }
+        if (url == null) {
+            url = cluClassloader.getResource(resourceName);
+        }
+        if (url == null && resourceName.startsWith("/")) {
+            //certain classloaders need it without the leading /
+            url = cluClassloader.getResource(resourceName.substring(1));
+        }
+
+        if (url == null) {
+            ClassLoader cl = callingClass.getClassLoader();
+
+            if (cl != null) {
+                url = cl.getResource(resourceName);
+            }
+        }
+
+        if (url == null) {
+            url = callingClass.getResource(resourceName);
+        }
+
+        if ((url == null) && (resourceName != null) && (resourceName.charAt(0) != '/')) {
+            return getResource('/' + resourceName, callingClass);
+        }
+
+        return url;
+    }
+
+    /**
+     * Load a given resources. <p/> This method will try to load the resources
+     * using the following methods (in order):
+     * <ul>
+     * <li>From Thread.currentThread().getContextClassLoader()
+     * <li>From ClassLoaderUtil.class.getClassLoader()
+     * <li>callingClass.getClassLoader()
+     * </ul>
+     *
+     * @param resourceName The name of the resource to load
+     * @param callingClass The Class object of the calling object
+     */
+    static List<URL> getResources(String resourceName, Class<?> callingClass) {
+        List<URL> ret = new ArrayList<URL>();
+        Enumeration<URL> urls = new Enumeration<URL>() {
+            public boolean hasMoreElements() {
+                return false;
+            }
+            public URL nextElement() {
+                return null;
+            }
+
+        };
+        try {
+            urls = Thread.currentThread().getContextClassLoader().getResources(resourceName);
+        } catch (IOException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+            }
+            //ignore
+        }
+        if (!urls.hasMoreElements() && resourceName.startsWith("/")) {
+            //certain classloaders need it without the leading /
+            try {
+                urls =
+                    Thread.currentThread().getContextClassLoader().getResources(
+                        resourceName.substring(1)
+                    );
+            } catch (IOException e) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+                }
+                // ignore
+            }
+        }
+
+        ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader();
+        if (cluClassloader == null) {
+            cluClassloader = ClassLoader.getSystemClassLoader();
+        }
+        if (!urls.hasMoreElements()) {
+            try {
+                urls = cluClassloader.getResources(resourceName);
+            } catch (IOException e) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+                }
+                // ignore
+            }
+        }
+        if (!urls.hasMoreElements() && resourceName.startsWith("/")) {
+            //certain classloaders need it without the leading /
+            try {
+                urls = cluClassloader.getResources(resourceName.substring(1));
+            } catch (IOException e) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+                }
+                // ignore
+            }
+        }
+
+        if (!urls.hasMoreElements()) {
+            ClassLoader cl = callingClass.getClassLoader();
+
+            if (cl != null) {
+                try {
+                    urls = cl.getResources(resourceName);
+                } catch (IOException e) {
+                    if (log.isLoggable(java.util.logging.Level.FINE)) {
+                        log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+                    }
+                    // ignore
+                }
+            }
+        }
+
+        if (!urls.hasMoreElements()) {
+            URL url = callingClass.getResource(resourceName);
+            if (url != null) {
+                ret.add(url);
+            }
+        }
+        while (urls.hasMoreElements()) {
+            ret.add(urls.nextElement());
+        }
+
+
+        if (ret.isEmpty() && (resourceName != null) && (resourceName.charAt(0) != '/')) {
+            return getResources('/' + resourceName, callingClass);
+        }
+        return ret;
+    }
+
+
+    /**
+     * This is a convenience method to load a resource as a stream. <p/> The
+     * algorithm used to find the resource is given in getResource()
+     *
+     * @param resourceName The name of the resource to load
+     * @param callingClass The Class object of the calling object
+     */
+    static InputStream getResourceAsStream(String resourceName, Class<?> callingClass) {
+        URL url = getResource(resourceName, callingClass);
+
+        try {
+            return (url != null) ? url.openStream() : null;
+        } catch (IOException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+            }
+            return null;
+        }
+    }
+
+    /**
+     * Load a class with a given name. <p/> It will try to load the class in the
+     * following order:
+     * <ul>
+     * <li>From Thread.currentThread().getContextClassLoader()
+     * <li>Using the basic Class.forName()
+     * <li>From ClassLoaderUtil.class.getClassLoader()
+     * <li>From the callingClass.getClassLoader()
+     * </ul>
+     *
+     * @param className The name of the class to load
+     * @param callingClass The Class object of the calling object
+     * @throws ClassNotFoundException If the class cannot be found anywhere.
+     */
+    static Class<?> loadClass(String className, Class<?> callingClass)
+        throws ClassNotFoundException {
+        try {
+            ClassLoader cl = Thread.currentThread().getContextClassLoader();
+
+            if (cl != null) {
+                return cl.loadClass(className);
+            }
+        } catch (ClassNotFoundException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+            }
+            //ignore
+        }
+        return loadClass2(className, callingClass);
+    }
+
+    private static Class<?> loadClass2(String className, Class<?> callingClass)
+        throws ClassNotFoundException {
+        try {
+            return Class.forName(className);
+        } catch (ClassNotFoundException ex) {
+            try {
+                if (ClassLoaderUtils.class.getClassLoader() != null) {
+                    return ClassLoaderUtils.class.getClassLoader().loadClass(className);
+                }
+            } catch (ClassNotFoundException exc) {
+                if (callingClass != null && callingClass.getClassLoader() != null) {
+                    return callingClass.getClassLoader().loadClass(className);
+                }
+            }
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
+            }
+            throw ex;
+        }
+    }
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
-import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
-
 /**
  * Provides all constants and some translation functions for i18n.
  *
@@ -29,202 +29,245 @@
  * <A HREF="http://www.w3.org/TR/xmldsig-core/#sec-TransformAlg">XML
  * Signature specification</A>.
  *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  */
 public class Constants {
 
-   /** Field configurationFile */
-   public static final String configurationFile = "data/websig.conf";
+    /** Field configurationFile */
+    public static final String configurationFile = "data/websig.conf";
+
+    /** Field configurationFileNew */
+    public static final String configurationFileNew = ".xmlsecurityconfig";
+
+    /** Field exceptionMessagesResourceBundleDir */
+    public static final String exceptionMessagesResourceBundleDir =
+        "com/sun/org/apache/xml/internal/security/resource";
 
-   /** Field configurationFileNew */
-   public static final String configurationFileNew = ".xmlsecurityconfig";
+    /** Field exceptionMessagesResourceBundleBase is the location of the <CODE>ResourceBundle</CODE> */
+    public static final String exceptionMessagesResourceBundleBase =
+        exceptionMessagesResourceBundleDir + "/" + "xmlsecurity";
+
+    /**
+     * The URL of the
+     * <A HREF="http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/">XML Signature specification</A>
+     */
+    public static final String SIGNATURESPECIFICATION_URL =
+        "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/";
+
+    /**
+     * The namespace of the
+     * <A HREF="http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/">XML Signature specification</A>
+     */
+    public static final String SignatureSpecNS = "http://www.w3.org/2000/09/xmldsig#";
 
-   /** Field exceptionMessagesResourceBundleDir */
-   public static final String exceptionMessagesResourceBundleDir =
-      "com/sun/org/apache/xml/internal/security/resource";
+    /**
+     * The namespace of the
+     * <A HREF="http://www.w3.org/TR/xmldsig-core1/">XML Signature specification</A>
+     */
+    public static final String SignatureSpec11NS = "http://www.w3.org/2009/xmldsig11#";
+
+    /** The URL for more algorithms **/
+    public static final String MoreAlgorithmsSpecNS = "http://www.w3.org/2001/04/xmldsig-more#";
+
+    /** The URI for XML spec*/
+    public static final String XML_LANG_SPACE_SpecNS = "http://www.w3.org/XML/1998/namespace";
+
+    /** The URI for XMLNS spec*/
+    public static final String NamespaceSpecNS = "http://www.w3.org/2000/xmlns/";
 
-   /** Field exceptionMessagesResourceBundleBase is the location of the <CODE>ResourceBundle</CODE> */
-   public static final String exceptionMessagesResourceBundleBase =
-      exceptionMessagesResourceBundleDir + "/" + "xmlsecurity";
-   //J-
-   /**
-    * The URL of the <A HREF="http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/">XML Signature specification</A>
-    */
-   public static final String SIGNATURESPECIFICATION_URL = "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/";
+    /** Tag of Attr Algorithm**/
+    public static final String _ATT_ALGORITHM = "Algorithm";
+
+    /** Tag of Attr URI**/
+    public static final String _ATT_URI = "URI";
+
+    /** Tag of Attr Type**/
+    public static final String _ATT_TYPE = "Type";
+
+    /** Tag of Attr Id**/
+    public static final String _ATT_ID = "Id";
+
+    /** Tag of Attr MimeType**/
+    public static final String _ATT_MIMETYPE = "MimeType";
 
-   /**
-    * The namespace of the <A HREF="http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/">XML Signature specification</A>
-    */
-   public static final String SignatureSpecNS   = "http://www.w3.org/2000/09/xmldsig#";
-   /** The URL for more algorithm **/
-   public static final String MoreAlgorithmsSpecNS   = "http://www.w3.org/2001/04/xmldsig-more#";
-   /** The URI for XML spec*/
-   public static final String XML_LANG_SPACE_SpecNS = "http://www.w3.org/XML/1998/namespace";
-   /** The URI for XMLNS spec*/
-   public static final String NamespaceSpecNS = "http://www.w3.org/2000/xmlns/";
+    /** Tag of Attr Encoding**/
+    public static final String _ATT_ENCODING = "Encoding";
+
+    /** Tag of Attr Target**/
+    public static final String _ATT_TARGET = "Target";
+
+    // KeyInfo (KeyName|KeyValue|RetrievalMethod|X509Data|PGPData|SPKIData|MgmtData)
+    // KeyValue (DSAKeyValue|RSAKeyValue)
+    // DSAKeyValue (P, Q, G, Y, J?, (Seed, PgenCounter)?)
+    // RSAKeyValue (Modulus, Exponent)
+    // RetrievalMethod (Transforms?)
+    // X509Data ((X509IssuerSerial | X509SKI | X509SubjectName | X509Certificate)+ | X509CRL)
+    // X509IssuerSerial (X509IssuerName, X509SerialNumber)
+    // PGPData ((PGPKeyID, PGPKeyPacket?) | (PGPKeyPacket))
+    // SPKIData (SPKISexp)
+
+    /** Tag of Element CanonicalizationMethod **/
+    public static final String _TAG_CANONICALIZATIONMETHOD = "CanonicalizationMethod";
+
+    /** Tag of Element DigestMethod **/
+    public static final String _TAG_DIGESTMETHOD = "DigestMethod";
+
+    /** Tag of Element DigestValue **/
+    public static final String _TAG_DIGESTVALUE = "DigestValue";
+
+    /** Tag of Element Manifest **/
+    public static final String _TAG_MANIFEST = "Manifest";
 
-   /** Tag of Attr Algorithm**/
-   public static final String _ATT_ALGORITHM              = "Algorithm";
-   /** Tag of Attr URI**/
-   public static final String _ATT_URI                    = "URI";
-   /** Tag of Attr Type**/
-   public static final String _ATT_TYPE                   = "Type";
-   /** Tag of Attr Id**/
-   public static final String _ATT_ID                     = "Id";
-   /** Tag of Attr MimeType**/
-   public static final String _ATT_MIMETYPE               = "MimeType";
-   /** Tag of Attr Encoding**/
-   public static final String _ATT_ENCODING               = "Encoding";
-   /** Tag of Attr Target**/
-   public static final String _ATT_TARGET                 = "Target";
+    /** Tag of Element Methods **/
+    public static final String _TAG_METHODS = "Methods";
+
+    /** Tag of Element Object **/
+    public static final String _TAG_OBJECT = "Object";
+
+    /** Tag of Element Reference **/
+    public static final String _TAG_REFERENCE = "Reference";
+
+    /** Tag of Element Signature **/
+    public static final String _TAG_SIGNATURE = "Signature";
+
+    /** Tag of Element SignatureMethod **/
+    public static final String _TAG_SIGNATUREMETHOD = "SignatureMethod";
 
-   // KeyInfo (KeyName|KeyValue|RetrievalMethod|X509Data|PGPData|SPKIData|MgmtData)
-   // KeyValue (DSAKeyValue|RSAKeyValue)
-   // DSAKeyValue (P, Q, G, Y, J?, (Seed, PgenCounter)?)
-   // RSAKeyValue (Modulus, Exponent)
-   // RetrievalMethod (Transforms?)
-   // X509Data ((X509IssuerSerial | X509SKI | X509SubjectName | X509Certificate)+ | X509CRL)
-   // X509IssuerSerial (X509IssuerName, X509SerialNumber)
-   // PGPData ((PGPKeyID, PGPKeyPacket?) | (PGPKeyPacket))
-   // SPKIData (SPKISexp)
+    /** Tag of Element HMACOutputLength **/
+    public static final String _TAG_HMACOUTPUTLENGTH = "HMACOutputLength";
+
+    /** Tag of Element SignatureProperties **/
+    public static final String _TAG_SIGNATUREPROPERTIES = "SignatureProperties";
+
+    /** Tag of Element SignatureProperty **/
+    public static final String _TAG_SIGNATUREPROPERTY = "SignatureProperty";
+
+    /** Tag of Element SignatureValue **/
+    public static final String _TAG_SIGNATUREVALUE = "SignatureValue";
+
+    /** Tag of Element SignedInfo **/
+    public static final String _TAG_SIGNEDINFO = "SignedInfo";
+
+    /** Tag of Element Transform **/
+    public static final String _TAG_TRANSFORM = "Transform";
 
-   /** Tag of Element CanonicalizationMethod **/
-   public static final String _TAG_CANONICALIZATIONMETHOD = "CanonicalizationMethod";
-   /** Tag of Element DigestMethod **/
-   public static final String _TAG_DIGESTMETHOD           = "DigestMethod";
-   /** Tag of Element DigestValue **/
-   public static final String _TAG_DIGESTVALUE            = "DigestValue";
-   /** Tag of Element Manifest **/
-   public static final String _TAG_MANIFEST               = "Manifest";
-   /** Tag of Element Methods **/
-   public static final String _TAG_METHODS                = "Methods";
-   /** Tag of Element Object **/
-   public static final String _TAG_OBJECT                 = "Object";
-   /** Tag of Element Reference **/
-   public static final String _TAG_REFERENCE              = "Reference";
-   /** Tag of Element Signature **/
-   public static final String _TAG_SIGNATURE              = "Signature";
-   /** Tag of Element SignatureMethod **/
-   public static final String _TAG_SIGNATUREMETHOD        = "SignatureMethod";
-   /** Tag of Element HMACOutputLength **/
-   public static final String _TAG_HMACOUTPUTLENGTH       = "HMACOutputLength";
-   /** Tag of Element SignatureProperties **/
-   public static final String _TAG_SIGNATUREPROPERTIES    = "SignatureProperties";
-   /** Tag of Element SignatureProperty **/
-   public static final String _TAG_SIGNATUREPROPERTY      = "SignatureProperty";
-   /** Tag of Element SignatureValue **/
-   public static final String _TAG_SIGNATUREVALUE         = "SignatureValue";
-   /** Tag of Element SignedInfo **/
-   public static final String _TAG_SIGNEDINFO             = "SignedInfo";
-   /** Tag of Element Transform **/
-   public static final String _TAG_TRANSFORM              = "Transform";
-   /** Tag of Element Transforms **/
-   public static final String _TAG_TRANSFORMS             = "Transforms";
-   /** Tag of Element XPath **/
-   public static final String _TAG_XPATH                  = "XPath";
-   /** Tag of Element KeyInfo **/
-   public static final String _TAG_KEYINFO                = "KeyInfo";
-   /** Tag of Element KeyName **/
-   public static final String _TAG_KEYNAME                = "KeyName";
-   /** Tag of Element KeyValue **/
-   public static final String _TAG_KEYVALUE               = "KeyValue";
-   /** Tag of Element RetrievalMethod **/
-   public static final String _TAG_RETRIEVALMETHOD        = "RetrievalMethod";
-   /** Tag of Element X509Data **/
-   public static final String _TAG_X509DATA               = "X509Data";
-   /** Tag of Element PGPData **/
-   public static final String _TAG_PGPDATA                = "PGPData";
-   /** Tag of Element SPKIData **/
-   public static final String _TAG_SPKIDATA               = "SPKIData";
-   /** Tag of Element MgmtData **/
-   public static final String _TAG_MGMTDATA               = "MgmtData";
-   /** Tag of Element RSAKeyValue **/
-   public static final String _TAG_RSAKEYVALUE            = "RSAKeyValue";
-   /** Tag of Element Exponent **/
-   public static final String _TAG_EXPONENT               = "Exponent";
-   /** Tag of Element Modulus **/
-   public static final String _TAG_MODULUS                = "Modulus";
-   /** Tag of Element DSAKeyValue **/
-   public static final String _TAG_DSAKEYVALUE            = "DSAKeyValue";
-   /** Tag of Element P **/
-   public static final String _TAG_P                      = "P";
-   /** Tag of Element Q **/
-   public static final String _TAG_Q                      = "Q";
-   /** Tag of Element G **/
-   public static final String _TAG_G                      = "G";
-   /** Tag of Element Y **/
-   public static final String _TAG_Y                      = "Y";
-   /** Tag of Element J **/
-   public static final String _TAG_J                      = "J";
-   /** Tag of Element Seed **/
-   public static final String _TAG_SEED                   = "Seed";
-   /** Tag of Element PgenCounter **/
-   public static final String _TAG_PGENCOUNTER            = "PgenCounter";
-   /** Tag of Element rawX509Certificate **/
-   public static final String _TAG_RAWX509CERTIFICATE     = "rawX509Certificate";
-   /** Tag of Element X509IssuerSerial **/
-   public static final String _TAG_X509ISSUERSERIAL       = "X509IssuerSerial";
-   /** Tag of Element X509SKI **/
-   public static final String _TAG_X509SKI                = "X509SKI";
-   /** Tag of Element X509SubjectName **/
-   public static final String _TAG_X509SUBJECTNAME        = "X509SubjectName";
-   /** Tag of Element X509Certificate **/
-   public static final String _TAG_X509CERTIFICATE        = "X509Certificate";
-   /** Tag of Element X509CRL **/
-   public static final String _TAG_X509CRL                = "X509CRL";
-   /** Tag of Element X509IssuerName **/
-   public static final String _TAG_X509ISSUERNAME         = "X509IssuerName";
-   /** Tag of Element X509SerialNumber **/
-   public static final String _TAG_X509SERIALNUMBER       = "X509SerialNumber";
-   /** Tag of Element PGPKeyID **/
-   public static final String _TAG_PGPKEYID               = "PGPKeyID";
-   /** Tag of Element PGPKeyPacket **/
-   public static final String _TAG_PGPKEYPACKET           = "PGPKeyPacket";
-   /** Tag of Element SPKISexp **/
-   public static final String _TAG_SPKISEXP               = "SPKISexp";
+    /** Tag of Element Transforms **/
+    public static final String _TAG_TRANSFORMS = "Transforms";
+
+    /** Tag of Element XPath **/
+    public static final String _TAG_XPATH = "XPath";
+
+    /** Tag of Element KeyInfo **/
+    public static final String _TAG_KEYINFO = "KeyInfo";
+
+    /** Tag of Element KeyName **/
+    public static final String _TAG_KEYNAME = "KeyName";
+
+    /** Tag of Element KeyValue **/
+    public static final String _TAG_KEYVALUE = "KeyValue";
+
+    /** Tag of Element RetrievalMethod **/
+    public static final String _TAG_RETRIEVALMETHOD = "RetrievalMethod";
+
+    /** Tag of Element X509Data **/
+    public static final String _TAG_X509DATA = "X509Data";
+
+    /** Tag of Element PGPData **/
+    public static final String _TAG_PGPDATA = "PGPData";
+
+    /** Tag of Element SPKIData **/
+    public static final String _TAG_SPKIDATA = "SPKIData";
+
+    /** Tag of Element MgmtData **/
+    public static final String _TAG_MGMTDATA = "MgmtData";
+
+    /** Tag of Element RSAKeyValue **/
+    public static final String _TAG_RSAKEYVALUE = "RSAKeyValue";
+
+    /** Tag of Element Exponent **/
+    public static final String _TAG_EXPONENT = "Exponent";
+
+    /** Tag of Element Modulus **/
+    public static final String _TAG_MODULUS = "Modulus";
+
+    /** Tag of Element DSAKeyValue **/
+    public static final String _TAG_DSAKEYVALUE = "DSAKeyValue";
+
+    /** Tag of Element P **/
+    public static final String _TAG_P = "P";
+
+    /** Tag of Element Q **/
+    public static final String _TAG_Q   = "Q";
+
+    /** Tag of Element G **/
+    public static final String _TAG_G = "G";
+
+    /** Tag of Element Y **/
+    public static final String _TAG_Y = "Y";
+
+    /** Tag of Element J **/
+    public static final String _TAG_J = "J";
+
+    /** Tag of Element Seed **/
+    public static final String _TAG_SEED = "Seed";
 
-   /** Digest - Required SHA1 */
-   public static final String ALGO_ID_DIGEST_SHA1        = SignatureSpecNS + "sha1";
+    /** Tag of Element PgenCounter **/
+    public static final String _TAG_PGENCOUNTER = "PgenCounter";
+
+    /** Tag of Element rawX509Certificate **/
+    public static final String _TAG_RAWX509CERTIFICATE = "rawX509Certificate";
+
+    /** Tag of Element X509IssuerSerial **/
+    public static final String _TAG_X509ISSUERSERIAL= "X509IssuerSerial";
+
+    /** Tag of Element X509SKI **/
+    public static final String _TAG_X509SKI = "X509SKI";
+
+    /** Tag of Element X509SubjectName **/
+    public static final String _TAG_X509SUBJECTNAME = "X509SubjectName";
 
-   /**
-    * @see <A HREF="http://www.ietf.org/internet-drafts/draft-blake-wilson-xmldsig-ecdsa-02.txt">
-    *  draft-blake-wilson-xmldsig-ecdsa-02.txt</A>
-    */
-   public static final String ALGO_ID_SIGNATURE_ECDSA_CERTICOM = "http://www.certicom.com/2000/11/xmlecdsig#ecdsa-sha1";
-   //J+
+    /** Tag of Element X509Certificate **/
+    public static final String _TAG_X509CERTIFICATE = "X509Certificate";
+
+    /** Tag of Element X509CRL **/
+    public static final String _TAG_X509CRL = "X509CRL";
 
-   private Constants() {
-     // we don't allow instantiation
-   }
+    /** Tag of Element X509IssuerName **/
+    public static final String _TAG_X509ISSUERNAME = "X509IssuerName";
+
+    /** Tag of Element X509SerialNumber **/
+    public static final String _TAG_X509SERIALNUMBER = "X509SerialNumber";
+
+    /** Tag of Element PGPKeyID **/
+    public static final String _TAG_PGPKEYID = "PGPKeyID";
 
-   /**
-    * Sets the namespace prefix which will be used to identify elements in the
-    * XML Signature Namespace.
-    *
-    * <pre>
-    * Constants.setSignatureSpecNSprefix("dsig");
-    * </pre>
-    *
-    * @param newPrefix is the new namespace prefix.
-    * @throws XMLSecurityException
-    * @see com.sun.org.apache.xml.internal.security.utils.Constants#getSignatureSpecNSprefix
-    * $todo$ Add consistency checking for valid prefix
-    */
-   public static void setSignatureSpecNSprefix(String newPrefix) throws XMLSecurityException {
-      ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, newPrefix);
-   }
+    /** Tag of Element PGPKeyPacket **/
+    public static final String _TAG_PGPKEYPACKET = "PGPKeyPacket";
+
+    /** Tag of Element PGPKeyPacket **/
+    public static final String _TAG_DERENCODEDKEYVALUE = "DEREncodedKeyValue";
+
+    /** Tag of Element PGPKeyPacket **/
+    public static final String _TAG_KEYINFOREFERENCE = "KeyInfoReference";
+
+    /** Tag of Element PGPKeyPacket **/
+    public static final String _TAG_X509DIGEST = "X509Digest";
+
+    /** Tag of Element SPKISexp **/
+    public static final String _TAG_SPKISEXP = "SPKISexp";
 
-   /**
-    * Returns the XML namespace prefix which is used for elements in the XML
-    * Signature namespace.
-    *
-    * It is defaulted to <code>dsig</code>, but can be changed using the
-    * {@link #setSignatureSpecNSprefix} function.
-    *
-    * @return the current used namespace prefix
-    * @see #setSignatureSpecNSprefix
-    */
-   public static String getSignatureSpecNSprefix() {
-      return ElementProxy.getDefaultPrefix(Constants.SignatureSpecNS);
-   }
+    /** Digest - Required SHA1 */
+    public static final String ALGO_ID_DIGEST_SHA1 = SignatureSpecNS + "sha1";
+
+    /**
+     * @see <A HREF="http://www.ietf.org/internet-drafts/draft-blake-wilson-xmldsig-ecdsa-02.txt">
+     *  draft-blake-wilson-xmldsig-ecdsa-02.txt</A>
+     */
+    public static final String ALGO_ID_SIGNATURE_ECDSA_CERTICOM =
+        "http://www.certicom.com/2000/11/xmlecdsig#ecdsa-sha1";
+
+    private Constants() {
+        // we don't allow instantiation
+    }
+
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,79 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.utils;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import javax.xml.namespace.NamespaceContext;
+
+import org.w3c.dom.Attr;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+
+/**
+ */
+public class DOMNamespaceContext implements NamespaceContext {
+
+    private Map<String, String> namespaceMap = new HashMap<String, String>();
+
+    public DOMNamespaceContext(Node contextNode) {
+        addNamespaces(contextNode);
+    }
+
+    public String getNamespaceURI(String arg0) {
+        return namespaceMap.get(arg0);
+    }
+
+    public String getPrefix(String arg0) {
+        for (String key : namespaceMap.keySet()) {
+            String value = namespaceMap.get(key);
+            if (value.equals(arg0)) {
+                return key;
+            }
+        }
+        return null;
+    }
+
+    public Iterator<String> getPrefixes(String arg0) {
+        return namespaceMap.keySet().iterator();
+    }
+
+    private void addNamespaces(Node element) {
+        if (element.getParentNode() != null) {
+            addNamespaces(element.getParentNode());
+        }
+        if (element instanceof Element) {
+            Element el = (Element)element;
+            NamedNodeMap map = el.getAttributes();
+            for (int x = 0; x < map.getLength(); x++) {
+                Attr attr = (Attr)map.item(x);
+                if ("xmlns".equals(attr.getPrefix())) {
+                    namespaceMap.put(attr.getLocalName(), attr.getValue());
+                }
+            }
+        }
+    }
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 1999-2008 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
@@ -29,16 +31,16 @@
  *
  */
 public class DigesterOutputStream extends ByteArrayOutputStream {
+    private static final java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(DigesterOutputStream.class.getName());
+
     final MessageDigestAlgorithm mda;
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger
-        (DigesterOutputStream.class.getName());
 
     /**
      * @param mda
      */
     public DigesterOutputStream(MessageDigestAlgorithm mda) {
-        this.mda=mda;
+        this.mda = mda;
     }
 
     /** @inheritDoc */
@@ -55,9 +57,9 @@
     public void write(byte[] arg0, int arg1, int arg2) {
         if (log.isLoggable(java.util.logging.Level.FINE)) {
             log.log(java.util.logging.Level.FINE, "Pre-digested input:");
-            StringBuffer sb = new StringBuffer(arg2);
-            for (int i=arg1; i<(arg1+arg2); i++) {
-                sb.append((char) arg0[i]);
+            StringBuilder sb = new StringBuilder(arg2);
+            for (int i = arg1; i < (arg1 + arg2); i++) {
+                sb.append((char)arg0[i]);
             }
             log.log(java.util.logging.Level.FINE, sb.toString());
         }
@@ -68,6 +70,6 @@
      * @return the digest value
      */
     public byte[] getDigestValue() {
-         return mda.digest();
+        return mda.digest();
     }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,17 +1,41 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
 package com.sun.org.apache.xml.internal.security.utils;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
+/**@deprecated*/
+@Deprecated
 public interface ElementChecker {
-         /**
-          * Check that the elemnt is the one expect
-          *
-          * @throws XMLSecurityException
-          */
-           public void guaranteeThatElementInCorrectSpace(ElementProxy expected, Element actual)
-                   throws XMLSecurityException;
+    /**
+     * Check that the element is the one expect
+     *
+     * @throws XMLSecurityException
+     */
+    void guaranteeThatElementInCorrectSpace(ElementProxy expected, Element actual)
+        throws XMLSecurityException;
 
-           public boolean isNamespaceElement(Node el, String type, String ns);
+    boolean isNamespaceElement(Node el, String type, String ns);
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,60 +1,90 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
 package com.sun.org.apache.xml.internal.security.utils;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
+/**@deprecated*/
+@Deprecated
 public abstract class ElementCheckerImpl implements ElementChecker {
-        public boolean isNamespaceElement(Node el, String type, String ns) {
-                if ((el == null) ||
-                   ns!=el.getNamespaceURI() || !el.getLocalName().equals(type)){
-                   return false;
-                }
 
-                return true;
-        }
-        /** A checker for DOM that interns NS */
-        public static class InternedNsChecker extends ElementCheckerImpl{
-                public void guaranteeThatElementInCorrectSpace(ElementProxy expected,
-                                Element actual) throws XMLSecurityException {
-
-                      String localnameSHOULDBE = expected.getBaseLocalName();
-                      String namespaceSHOULDBE = expected.getBaseNamespace();
-
-                      String localnameIS = actual.getLocalName();
-                      String namespaceIS = actual.getNamespaceURI();
-                      if ((namespaceSHOULDBE!=namespaceIS) ||
-                       !localnameSHOULDBE.equals(localnameIS) ) {
-                         Object exArgs[] = { namespaceIS +":"+ localnameIS,
-                           namespaceSHOULDBE +":"+ localnameSHOULDBE};
-                         throw new XMLSecurityException("xml.WrongElement", exArgs);
-                      }
-                }
+    public boolean isNamespaceElement(Node el, String type, String ns) {
+        if ((el == null) ||
+            ns != el.getNamespaceURI() || !el.getLocalName().equals(type)){
+            return false;
         }
 
-        /** A checker for DOM that interns NS */
-        public static class FullChecker extends ElementCheckerImpl {
-                public void guaranteeThatElementInCorrectSpace(ElementProxy expected,
-                                Element actual) throws XMLSecurityException {
+        return true;
+    }
+
+    /** A checker for DOM that interns NS */
+    public static class InternedNsChecker extends ElementCheckerImpl {
+        public void guaranteeThatElementInCorrectSpace(
+            ElementProxy expected, Element actual
+        ) throws XMLSecurityException {
+
+            String expectedLocalname = expected.getBaseLocalName();
+            String expectedNamespace = expected.getBaseNamespace();
 
-                      String localnameSHOULDBE = expected.getBaseLocalName();
-                      String namespaceSHOULDBE = expected.getBaseNamespace();
+            String localnameIS = actual.getLocalName();
+            String namespaceIS = actual.getNamespaceURI();
+            if ((expectedNamespace != namespaceIS) ||
+                !expectedLocalname.equals(localnameIS)) {
+                Object exArgs[] = { namespaceIS + ":" + localnameIS,
+                                    expectedNamespace + ":" + expectedLocalname};
+                throw new XMLSecurityException("xml.WrongElement", exArgs);
+            }
+        }
+    }
+
+    /** A checker for DOM that interns NS */
+    public static class FullChecker extends ElementCheckerImpl {
 
-                      String localnameIS = actual.getLocalName();
-                      String namespaceIS = actual.getNamespaceURI();
-                      if ((!namespaceSHOULDBE.equals(namespaceIS)) ||
-                       !localnameSHOULDBE.equals(localnameIS) ) {
-                         Object exArgs[] = { namespaceIS +":"+ localnameIS,
-                           namespaceSHOULDBE +":"+ localnameSHOULDBE};
-                         throw new XMLSecurityException("xml.WrongElement", exArgs);
-                      }
-                }
+        public void guaranteeThatElementInCorrectSpace(
+            ElementProxy expected, Element actual
+        ) throws XMLSecurityException {
+            String expectedLocalname = expected.getBaseLocalName();
+            String expectedNamespace = expected.getBaseNamespace();
+
+            String localnameIS = actual.getLocalName();
+            String namespaceIS = actual.getNamespaceURI();
+            if ((!expectedNamespace.equals(namespaceIS)) ||
+                !expectedLocalname.equals(localnameIS) ) {
+                Object exArgs[] = { namespaceIS + ":" + localnameIS,
+                                    expectedNamespace + ":" + expectedLocalname};
+                throw new XMLSecurityException("xml.WrongElement", exArgs);
+            }
         }
+    }
 
-        /** An empty checker if schema checking is used */
-        public static class EmptyChecker extends ElementCheckerImpl {
-                public void guaranteeThatElementInCorrectSpace(ElementProxy expected,
-                                Element actual) throws XMLSecurityException {
-                }
+    /** An empty checker if schema checking is used */
+    public static class EmptyChecker extends ElementCheckerImpl {
+        public void guaranteeThatElementInCorrectSpace(
+            ElementProxy expected, Element actual
+        ) throws XMLSecurityException {
+            // empty
         }
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java	Mon Jul 22 17:37:15 2013 -0700
@@ -45,13 +45,13 @@
         java.util.logging.Logger.getLogger(ElementProxy.class.getName());
 
     /** Field constructionElement */
-    protected Element _constructionElement = null;
+    protected Element constructionElement = null;
 
     /** Field baseURI */
-    protected String _baseURI = null;
+    protected String baseURI = null;
 
     /** Field doc */
-    protected Document _doc = null;
+    protected Document doc = null;
 
     /** Field prefixMappings */
     private static Map<String, String> prefixMappings = new ConcurrentHashMap<String, String>();
@@ -73,9 +73,9 @@
             throw new RuntimeException("Document is null");
         }
 
-        this._doc = doc;
-        this._constructionElement =
-            createElementForFamilyLocal(this._doc, this.getBaseNamespace(), this.getBaseLocalName());
+        this.doc = doc;
+        this.constructionElement =
+            createElementForFamilyLocal(this.doc, this.getBaseNamespace(), this.getBaseLocalName());
     }
 
     /**
@@ -94,9 +94,9 @@
             log.log(java.util.logging.Level.FINE, "setElement(\"" + element.getTagName() + "\", \"" + BaseURI + "\")");
         }
 
-        this._doc = element.getOwnerDocument();
-        this._constructionElement = element;
-        this._baseURI = BaseURI;
+        this.doc = element.getOwnerDocument();
+        this.constructionElement = element;
+        this.baseURI = BaseURI;
 
         this.guaranteeThatElementInCorrectSpace();
     }
@@ -184,9 +184,9 @@
             log.log(java.util.logging.Level.FINE, "setElement(" + element.getTagName() + ", \"" + BaseURI + "\"");
         }
 
-        this._doc = element.getOwnerDocument();
-        this._constructionElement = element;
-        this._baseURI = BaseURI;
+        this.doc = element.getOwnerDocument();
+        this.constructionElement = element;
+        this.baseURI = BaseURI;
     }
 
 
@@ -196,7 +196,7 @@
      * @return the Element which was constructed by the Object.
      */
     public final Element getElement() {
-        return this._constructionElement;
+        return this.constructionElement;
     }
 
     /**
@@ -208,9 +208,9 @@
 
         HelperNodeList nl = new HelperNodeList();
 
-        nl.appendChild(this._doc.createTextNode("\n"));
+        nl.appendChild(this.doc.createTextNode("\n"));
         nl.appendChild(this.getElement());
-        nl.appendChild(this._doc.createTextNode("\n"));
+        nl.appendChild(this.doc.createTextNode("\n"));
 
         return nl;
     }
@@ -221,7 +221,7 @@
      * @return the Document where this element is contained.
      */
     public Document getDocument() {
-        return this._doc;
+        return this.doc;
     }
 
     /**
@@ -230,7 +230,7 @@
      * @return the base uri of the namespace of this element
      */
     public String getBaseURI() {
-        return this._baseURI;
+        return this.baseURI;
     }
 
     /**
@@ -243,8 +243,8 @@
         String expectedLocalName = this.getBaseLocalName();
         String expectedNamespaceUri = this.getBaseNamespace();
 
-        String actualLocalName = this._constructionElement.getLocalName();
-        String actualNamespaceUri = this._constructionElement.getNamespaceURI();
+        String actualLocalName = this.constructionElement.getLocalName();
+        String actualNamespaceUri = this.constructionElement.getNamespaceURI();
 
         if(!expectedNamespaceUri.equals(actualNamespaceUri)
             && !expectedLocalName.equals(actualLocalName)) {
@@ -262,11 +262,11 @@
      */
     public void addBigIntegerElement(BigInteger bi, String localname) {
         if (bi != null) {
-            Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname);
+            Element e = XMLUtils.createElementInSignatureSpace(this.doc, localname);
 
             Base64.fillElementWithBigInteger(e, bi);
-            this._constructionElement.appendChild(e);
-            XMLUtils.addReturnToElement(this._constructionElement);
+            this.constructionElement.appendChild(e);
+            XMLUtils.addReturnToElement(this.constructionElement);
         }
     }
 
@@ -278,11 +278,11 @@
      */
     public void addBase64Element(byte[] bytes, String localname) {
         if (bytes != null) {
-            Element e = Base64.encodeToElement(this._doc, localname, bytes);
+            Element e = Base64.encodeToElement(this.doc, localname, bytes);
 
-            this._constructionElement.appendChild(e);
+            this.constructionElement.appendChild(e);
             if (!XMLUtils.ignoreLineBreaks()) {
-                this._constructionElement.appendChild(this._doc.createTextNode("\n"));
+                this.constructionElement.appendChild(this.doc.createTextNode("\n"));
             }
         }
     }
@@ -294,12 +294,12 @@
      * @param localname
      */
     public void addTextElement(String text, String localname) {
-        Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname);
-        Text t = this._doc.createTextNode(text);
+        Element e = XMLUtils.createElementInSignatureSpace(this.doc, localname);
+        Text t = this.doc.createTextNode(text);
 
         e.appendChild(t);
-        this._constructionElement.appendChild(e);
-        XMLUtils.addReturnToElement(this._constructionElement);
+        this.constructionElement.appendChild(e);
+        XMLUtils.addReturnToElement(this.constructionElement);
     }
 
     /**
@@ -310,9 +310,9 @@
     public void addBase64Text(byte[] bytes) {
         if (bytes != null) {
             Text t = XMLUtils.ignoreLineBreaks()
-                ? this._doc.createTextNode(Base64.encode(bytes))
-                : this._doc.createTextNode("\n" + Base64.encode(bytes) + "\n");
-            this._constructionElement.appendChild(t);
+                ? this.doc.createTextNode(Base64.encode(bytes))
+                : this.doc.createTextNode("\n" + Base64.encode(bytes) + "\n");
+            this.constructionElement.appendChild(t);
         }
     }
 
@@ -323,9 +323,9 @@
      */
     public void addText(String text) {
         if (text != null) {
-            Text t = this._doc.createTextNode(text);
+            Text t = this.doc.createTextNode(text);
 
-            this._constructionElement.appendChild(t);
+            this.constructionElement.appendChild(t);
         }
     }
 
@@ -342,7 +342,7 @@
     ) throws Base64DecodingException {
         return Base64.decodeBigIntegerFromText(
             XMLUtils.selectNodeText(
-                this._constructionElement.getFirstChild(), namespace, localname, 0
+                this.constructionElement.getFirstChild(), namespace, localname, 0
             )
         );
     }
@@ -360,7 +360,7 @@
         throws XMLSecurityException {
         Element e =
             XMLUtils.selectNode(
-                this._constructionElement.getFirstChild(), namespace, localname, 0
+                this.constructionElement.getFirstChild(), namespace, localname, 0
             );
 
         return Base64.decode(e);
@@ -375,7 +375,7 @@
      */
     public String getTextFromChildElement(String localname, String namespace) {
         return XMLUtils.selectNode(
-                this._constructionElement.getFirstChild(),
+                this.constructionElement.getFirstChild(),
                 namespace,
                 localname,
                 0).getTextContent();
@@ -388,7 +388,7 @@
      * @throws XMLSecurityException
      */
     public byte[] getBytesFromTextChild() throws XMLSecurityException {
-        return Base64.decode(XMLUtils.getFullTextChildrenFromElement(this._constructionElement));
+        return Base64.decode(XMLUtils.getFullTextChildrenFromElement(this.constructionElement));
     }
 
     /**
@@ -398,7 +398,7 @@
      *    element
      */
     public String getTextFromTextChild() {
-        return XMLUtils.getFullTextChildrenFromElement(this._constructionElement);
+        return XMLUtils.getFullTextChildrenFromElement(this.constructionElement);
     }
 
     /**
@@ -410,7 +410,7 @@
      */
     public int length(String namespace, String localname) {
         int number = 0;
-        Node sibling = this._constructionElement.getFirstChild();
+        Node sibling = this.constructionElement.getFirstChild();
         while (sibling != null) {
             if (localname.equals(sibling.getLocalName())
                 && namespace.equals(sibling.getNamespaceURI())) {
@@ -448,18 +448,18 @@
             ns = "xmlns:" + prefix;
         }
 
-        Attr a = this._constructionElement.getAttributeNodeNS(Constants.NamespaceSpecNS, ns);
+        Attr a = this.constructionElement.getAttributeNodeNS(Constants.NamespaceSpecNS, ns);
 
         if (a != null) {
             if (!a.getNodeValue().equals(uri)) {
-                Object exArgs[] = { ns, this._constructionElement.getAttributeNS(null, ns) };
+                Object exArgs[] = { ns, this.constructionElement.getAttributeNS(null, ns) };
 
                 throw new XMLSecurityException("namespacePrefixAlreadyUsedByOtherURI", exArgs);
             }
             return;
         }
 
-        this._constructionElement.setAttributeNS(Constants.NamespaceSpecNS, ns, uri);
+        this.constructionElement.setAttributeNS(Constants.NamespaceSpecNS, ns, uri);
     }
 
     /**
@@ -515,16 +515,4 @@
         return prefixMappings.get(namespace);
     }
 
-    protected void setLocalIdAttribute(String attrName, String value) {
-
-        if (value != null) {
-            Attr attr = getDocument().createAttributeNS(null, attrName);
-            attr.setValue(value);
-            getElement().setAttributeNodeNS(attr);
-            getElement().setIdAttributeNode(attr, true);
-        }
-        else {
-            getElement().removeAttributeNS(null, attrName);
-        }
-    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,179 +2,238 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
+public class EncryptionConstants {
+    // Attributes that exist in XML Signature in the same way
+    /** Tag of Attr Algorithm **/
+    public static final String _ATT_ALGORITHM              = Constants._ATT_ALGORITHM;
 
+    /** Tag of Attr Id**/
+    public static final String _ATT_ID                     = Constants._ATT_ID;
+
+    /** Tag of Attr Target **/
+    public static final String _ATT_TARGET                 = Constants._ATT_TARGET;
+
+    /** Tag of Attr Type **/
+    public static final String _ATT_TYPE                   = Constants._ATT_TYPE;
+
+    /** Tag of Attr URI **/
+    public static final String _ATT_URI                    = Constants._ATT_URI;
+
+    // Attributes new in XML Encryption
+    /** Tag of Attr encoding **/
+    public static final String _ATT_ENCODING               = "Encoding";
+
+    /** Tag of Attr recipient **/
+    public static final String _ATT_RECIPIENT              = "Recipient";
+
+    /** Tag of Attr mimetype **/
+    public static final String _ATT_MIMETYPE               = "MimeType";
+
+    /** Tag of Element CarriedKeyName **/
+    public static final String _TAG_CARRIEDKEYNAME         = "CarriedKeyName";
+
+    /** Tag of Element CipherData **/
+    public static final String _TAG_CIPHERDATA             = "CipherData";
+
+    /** Tag of Element CipherReference **/
+    public static final String _TAG_CIPHERREFERENCE        = "CipherReference";
+
+    /** Tag of Element CipherValue **/
+    public static final String _TAG_CIPHERVALUE            = "CipherValue";
+
+    /** Tag of Element DataReference **/
+    public static final String _TAG_DATAREFERENCE          = "DataReference";
+
+    /** Tag of Element EncryptedData **/
+    public static final String _TAG_ENCRYPTEDDATA          = "EncryptedData";
+
+    /** Tag of Element EncryptedKey **/
+    public static final String _TAG_ENCRYPTEDKEY           = "EncryptedKey";
+
+    /** Tag of Element EncryptionMethod **/
+    public static final String _TAG_ENCRYPTIONMETHOD       = "EncryptionMethod";
+
+    /** Tag of Element EncryptionProperties **/
+    public static final String _TAG_ENCRYPTIONPROPERTIES   = "EncryptionProperties";
+
+    /** Tag of Element EncryptionProperty **/
+    public static final String _TAG_ENCRYPTIONPROPERTY     = "EncryptionProperty";
+
+    /** Tag of Element KeyReference **/
+    public static final String _TAG_KEYREFERENCE           = "KeyReference";
+
+    /** Tag of Element KeySize **/
+    public static final String _TAG_KEYSIZE                = "KeySize";
+
+    /** Tag of Element OAEPparams **/
+    public static final String _TAG_OAEPPARAMS             = "OAEPparams";
+
+    /** Tag of Element MGF **/
+    public static final String _TAG_MGF                    = "MGF";
+
+    /** Tag of Element ReferenceList **/
+    public static final String _TAG_REFERENCELIST          = "ReferenceList";
+
+    /** Tag of Element Transforms **/
+    public static final String _TAG_TRANSFORMS             = "Transforms";
+
+    /** Tag of Element AgreementMethod **/
+    public static final String _TAG_AGREEMENTMETHOD        = "AgreementMethod";
+
+    /** Tag of Element KA-Nonce **/
+    public static final String _TAG_KA_NONCE               = "KA-Nonce";
+
+    /** Tag of Element OriginatorKeyInfo **/
+    public static final String _TAG_ORIGINATORKEYINFO      = "OriginatorKeyInfo";
+
+    /** Tag of Element RecipientKeyInfo **/
+    public static final String _TAG_RECIPIENTKEYINFO       = "RecipientKeyInfo";
+
+    /** Field ENCRYPTIONSPECIFICATION_URL */
+    public static final String ENCRYPTIONSPECIFICATION_URL =
+        "http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/";
+
+    /** The namespace of the
+     * <A HREF="http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/">
+     * XML Encryption Syntax and Processing</A> */
+    public static final String EncryptionSpecNS =
+        "http://www.w3.org/2001/04/xmlenc#";
+
+    /**
+     * The namespace of the XML Encryption 1.1 specification
+     */
+    public static final String EncryptionSpec11NS =
+        "http://www.w3.org/2009/xmlenc11#";
 
-import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+    /** URI for content*/
+    public static final String TYPE_CONTENT                = EncryptionSpecNS + "Content";
+
+    /** URI for element*/
+    public static final String TYPE_ELEMENT                = EncryptionSpecNS + "Element";
+
+    /** URI for mediatype*/
+    public static final String TYPE_MEDIATYPE              =
+        "http://www.isi.edu/in-notes/iana/assignments/media-types/";
+
+    /** Block Encryption - REQUIRED TRIPLEDES */
+    public static final String ALGO_ID_BLOCKCIPHER_TRIPLEDES =
+        EncryptionConstants.EncryptionSpecNS + "tripledes-cbc";
+
+    /** Block Encryption - REQUIRED AES-128 */
+    public static final String ALGO_ID_BLOCKCIPHER_AES128 =
+        EncryptionConstants.EncryptionSpecNS + "aes128-cbc";
+
+    /** Block Encryption - REQUIRED AES-256 */
+    public static final String ALGO_ID_BLOCKCIPHER_AES256 =
+        EncryptionConstants.EncryptionSpecNS + "aes256-cbc";
+
+    /** Block Encryption - OPTIONAL AES-192 */
+    public static final String ALGO_ID_BLOCKCIPHER_AES192 =
+        EncryptionConstants.EncryptionSpecNS + "aes192-cbc";
+
+    /** Block Encryption - OPTIONAL AES-128-GCM */
+    public static final String ALGO_ID_BLOCKCIPHER_AES128_GCM =
+        "http://www.w3.org/2009/xmlenc11#aes128-gcm";
+
+    /** Block Encryption - OPTIONAL AES-192-GCM */
+    public static final String ALGO_ID_BLOCKCIPHER_AES192_GCM =
+        "http://www.w3.org/2009/xmlenc11#aes192-gcm";
+
+    /** Block Encryption - OPTIONAL AES-256-GCM */
+    public static final String ALGO_ID_BLOCKCIPHER_AES256_GCM =
+        "http://www.w3.org/2009/xmlenc11#aes256-gcm";
+
+    /** Key Transport - REQUIRED RSA-v1.5*/
+    public static final String ALGO_ID_KEYTRANSPORT_RSA15 =
+        EncryptionConstants.EncryptionSpecNS + "rsa-1_5";
+
+    /** Key Transport - REQUIRED RSA-OAEP */
+    public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP =
+        EncryptionConstants.EncryptionSpecNS + "rsa-oaep-mgf1p";
+
+    /** Key Transport - OPTIONAL RSA-OAEP_11 */
+    public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP_11 =
+        EncryptionConstants.EncryptionSpec11NS + "rsa-oaep";
+
+    /** Key Agreement - OPTIONAL Diffie-Hellman */
+    public static final String ALGO_ID_KEYAGREEMENT_DH =
+        EncryptionConstants.EncryptionSpecNS + "dh";
+
+    /** Symmetric Key Wrap - REQUIRED TRIPLEDES KeyWrap */
+    public static final String ALGO_ID_KEYWRAP_TRIPLEDES =
+        EncryptionConstants.EncryptionSpecNS + "kw-tripledes";
+
+    /** Symmetric Key Wrap - REQUIRED AES-128 KeyWrap */
+    public static final String ALGO_ID_KEYWRAP_AES128 =
+        EncryptionConstants.EncryptionSpecNS + "kw-aes128";
+
+    /** Symmetric Key Wrap - REQUIRED AES-256 KeyWrap */
+    public static final String ALGO_ID_KEYWRAP_AES256 =
+        EncryptionConstants.EncryptionSpecNS + "kw-aes256";
+
+    /** Symmetric Key Wrap - OPTIONAL AES-192 KeyWrap */
+    public static final String ALGO_ID_KEYWRAP_AES192 =
+        EncryptionConstants.EncryptionSpecNS + "kw-aes192";
+
+    /** Message Authentication - RECOMMENDED XML Digital Signature */
+    public static final String ALGO_ID_AUTHENTICATION_XMLSIGNATURE =
+        "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/";
+
+    /** Canonicalization - OPTIONAL Canonical XML with Comments */
+    public static final String ALGO_ID_C14N_WITHCOMMENTS =
+        "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments";
+
+    /** Canonicalization - OPTIONAL Canonical XML (omits comments) */
+    public static final String ALGO_ID_C14N_OMITCOMMENTS =
+        "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
+
+    /** Encoding - REQUIRED base64 */
+    public static final String ALGO_ID_ENCODING_BASE64 =
+        "http://www.w3.org/2000/09/xmldsig#base64";
+
+    /** MGF1 with SHA-1 */
+    public static final String MGF1_SHA1 =
+        EncryptionConstants.EncryptionSpec11NS + "mgf1sha1";
+
+    /** MGF1 with SHA-224 */
+    public static final String MGF1_SHA224 =
+        EncryptionConstants.EncryptionSpec11NS + "mgf1sha224";
+
+    /** MGF1 with SHA-256 */
+    public static final String MGF1_SHA256 =
+        EncryptionConstants.EncryptionSpec11NS + "mgf1sha256";
+
+    /** MGF1 with SHA-384 */
+    public static final String MGF1_SHA384 =
+        EncryptionConstants.EncryptionSpec11NS + "mgf1sha384";
+
+    /** MGF1 with SHA-512 */
+    public static final String MGF1_SHA512 =
+        EncryptionConstants.EncryptionSpec11NS + "mgf1sha512";
 
 
-/**
- *
- * @author $Author: mullan $
- */
-public class EncryptionConstants {
-   //J-
-   // Attributes that exist in XML Signature in the same way
-    /** Tag of Attr Algorithm **/
-   public static final String _ATT_ALGORITHM              = Constants._ATT_ALGORITHM;
-   /** Tag of Attr Id**/
-   public static final String _ATT_ID                     = Constants._ATT_ID;
-   /** Tag of Attr Target **/
-   public static final String _ATT_TARGET                 = Constants._ATT_TARGET;
-   /** Tag of Attr Type **/
-   public static final String _ATT_TYPE                   = Constants._ATT_TYPE;
-   /** Tag of Attr URI **/
-   public static final String _ATT_URI                    = Constants._ATT_URI;
-
-   // Attributes new in XML Encryption
-   /** Tag of Attr encoding **/
-   public static final String _ATT_ENCODING               = "Encoding";
-   /** Tag of Attr recipient **/
-   public static final String _ATT_RECIPIENT              = "Recipient";
-   /** Tag of Attr mimetype **/
-   public static final String _ATT_MIMETYPE               = "MimeType";
-
-   /** Tag of Element CarriedKeyName **/
-   public static final String _TAG_CARRIEDKEYNAME         = "CarriedKeyName";
-   /** Tag of Element CipherData **/
-   public static final String _TAG_CIPHERDATA             = "CipherData";
-   /** Tag of Element CipherReference **/
-   public static final String _TAG_CIPHERREFERENCE        = "CipherReference";
-   /** Tag of Element CipherValue **/
-   public static final String _TAG_CIPHERVALUE            = "CipherValue";
-   /** Tag of Element DataReference **/
-   public static final String _TAG_DATAREFERENCE          = "DataReference";
-   /** Tag of Element EncryptedData **/
-   public static final String _TAG_ENCRYPTEDDATA          = "EncryptedData";
-   /** Tag of Element EncryptedKey **/
-   public static final String _TAG_ENCRYPTEDKEY           = "EncryptedKey";
-   /** Tag of Element EncryptionMethod **/
-   public static final String _TAG_ENCRYPTIONMETHOD       = "EncryptionMethod";
-   /** Tag of Element EncryptionProperties **/
-   public static final String _TAG_ENCRYPTIONPROPERTIES   = "EncryptionProperties";
-   /** Tag of Element EncryptionProperty **/
-   public static final String _TAG_ENCRYPTIONPROPERTY     = "EncryptionProperty";
-   /** Tag of Element KeyReference **/
-   public static final String _TAG_KEYREFERENCE           = "KeyReference";
-   /** Tag of Element KeySize **/
-   public static final String _TAG_KEYSIZE                = "KeySize";
-   /** Tag of Element OAEPparams **/
-   public static final String _TAG_OAEPPARAMS             = "OAEPparams";
-   /** Tag of Element ReferenceList **/
-   public static final String _TAG_REFERENCELIST          = "ReferenceList";
-   /** Tag of Element Transforms **/
-   public static final String _TAG_TRANSFORMS             = "Transforms";
-   /** Tag of Element AgreementMethod **/
-   public static final String _TAG_AGREEMENTMETHOD        = "AgreementMethod";
-   /** Tag of Element KA-Nonce **/
-   public static final String _TAG_KA_NONCE               = "KA-Nonce";
-   /** Tag of Element OriginatorKeyInfo **/
-   public static final String _TAG_ORIGINATORKEYINFO      = "OriginatorKeyInfo";
-   /** Tag of Element RecipientKeyInfo **/
-   public static final String _TAG_RECIPIENTKEYINFO       = "RecipientKeyInfo";
-
-   /** Field ENCRYPTIONSPECIFICATION_URL */
-   public static final String ENCRYPTIONSPECIFICATION_URL = "http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/";
-
-   /** The namespace of the <A HREF="http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/">XML Encryption Syntax and Processing</A> */
-   public static final String EncryptionSpecNS = "http://www.w3.org/2001/04/xmlenc#";
+    private EncryptionConstants() {
+        // we don't allow instantiation
+    }
 
-   /** URI for content*/
-   public static final String TYPE_CONTENT                = EncryptionSpecNS + "Content";
-   /** URI for element*/
-   public static final String TYPE_ELEMENT                = EncryptionSpecNS + "Element";
-   /** URI for mediatype*/
-   public static final String TYPE_MEDIATYPE              = "http://www.isi.edu/in-notes/iana/assignments/media-types/"; // + "*/*";
-
-   /** Block Encryption - REQUIRED TRIPLEDES */
-   public static final String ALGO_ID_BLOCKCIPHER_TRIPLEDES = EncryptionConstants.EncryptionSpecNS + "tripledes-cbc";
-   /** Block Encryption - REQUIRED AES-128 */
-   public static final String ALGO_ID_BLOCKCIPHER_AES128 = EncryptionConstants.EncryptionSpecNS + "aes128-cbc";
-   /** Block Encryption - REQUIRED AES-256 */
-   public static final String ALGO_ID_BLOCKCIPHER_AES256 = EncryptionConstants.EncryptionSpecNS + "aes256-cbc";
-   /** Block Encryption - OPTIONAL AES-192 */
-   public static final String ALGO_ID_BLOCKCIPHER_AES192 = EncryptionConstants.EncryptionSpecNS + "aes192-cbc";
-
-   /** Key Transport - REQUIRED RSA-v1.5*/
-   public static final String ALGO_ID_KEYTRANSPORT_RSA15 = EncryptionConstants.EncryptionSpecNS + "rsa-1_5";
-   /** Key Transport - REQUIRED RSA-OAEP */
-   public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP = EncryptionConstants.EncryptionSpecNS + "rsa-oaep-mgf1p";
-
-   /** Key Agreement - OPTIONAL Diffie-Hellman */
-   public static final String ALGO_ID_KEYAGREEMENT_DH = EncryptionConstants.EncryptionSpecNS + "dh";
-
-   /** Symmetric Key Wrap - REQUIRED TRIPLEDES KeyWrap */
-   public static final String ALGO_ID_KEYWRAP_TRIPLEDES = EncryptionConstants.EncryptionSpecNS + "kw-tripledes";
-   /** Symmetric Key Wrap - REQUIRED AES-128 KeyWrap */
-   public static final String ALGO_ID_KEYWRAP_AES128 = EncryptionConstants.EncryptionSpecNS + "kw-aes128";
-   /** Symmetric Key Wrap - REQUIRED AES-256 KeyWrap */
-   public static final String ALGO_ID_KEYWRAP_AES256 = EncryptionConstants.EncryptionSpecNS + "kw-aes256";
-   /** Symmetric Key Wrap - OPTIONAL AES-192 KeyWrap */
-   public static final String ALGO_ID_KEYWRAP_AES192 = EncryptionConstants.EncryptionSpecNS + "kw-aes192";
-
-   /*
-   // Message Digest - REQUIRED SHA1
-   public static final String ALGO_ID_DIGEST_SHA160 = Constants.ALGO_ID_DIGEST_SHA1;
-   // Message Digest - RECOMMENDED SHA256
-   public static final String ALGO_ID_DIGEST_SHA256 = EncryptionConstants.EncryptionSpecNS + "sha256";
-   // Message Digest - OPTIONAL SHA512
-   public static final String ALGO_ID_DIGEST_SHA512 = EncryptionConstants.EncryptionSpecNS + "sha512";
-   // Message Digest - OPTIONAL RIPEMD-160
-   public static final String ALGO_ID_DIGEST_RIPEMD160 = EncryptionConstants.EncryptionSpecNS + "ripemd160";
-   */
-
-   /** Message Authentication - RECOMMENDED XML Digital Signature */
-   public static final String ALGO_ID_AUTHENTICATION_XMLSIGNATURE = "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/";
-
-   /** Canonicalization - OPTIONAL Canonical XML with Comments */
-   public static final String ALGO_ID_C14N_WITHCOMMENTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments";
-   /** Canonicalization - OPTIONAL Canonical XML (omits comments) */
-   public static final String ALGO_ID_C14N_OMITCOMMENTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
-
-   /** Encoding - REQUIRED base64 */
-   public static final String ALGO_ID_ENCODING_BASE64 = "http://www.w3.org/2000/09/xmldsig#base64";
-   //J+
-
-   private EncryptionConstants() {
-     // we don't allow instantiation
-   }
-
-   /**
-    * Method setEncryptionSpecNSprefix
-    *
-    * @param newPrefix
-    * @throws XMLSecurityException
-    */
-   public static void setEncryptionSpecNSprefix(String newPrefix)
-           throws XMLSecurityException {
-      ElementProxy.setDefaultPrefix(EncryptionConstants.EncryptionSpecNS,
-                                    newPrefix);
-   }
-
-   /**
-    * Method getEncryptionSpecNSprefix
-    *
-    * @return the prefix for this node.
-    */
-   public static String getEncryptionSpecNSprefix() {
-      return ElementProxy
-         .getDefaultPrefix(EncryptionConstants.EncryptionSpecNS);
-   }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,62 +2,62 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
 
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-
 /**
  * This is the base object for all objects which map directly to an Element from
  * the xenc spec.
  *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  */
 public abstract class EncryptionElementProxy extends ElementProxy {
 
-   /**
-    * Constructor EncryptionElementProxy
-    *
-    * @param doc
-    */
-   public EncryptionElementProxy(Document doc) {
-      super(doc);
-   }
+    /**
+     * Constructor EncryptionElementProxy
+     *
+     * @param doc
+     */
+    public EncryptionElementProxy(Document doc) {
+        super(doc);
+    }
 
-   /**
-    * Constructor EncryptionElementProxy
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public EncryptionElementProxy(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
-   }
+    /**
+     * Constructor EncryptionElementProxy
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public EncryptionElementProxy(Element element, String BaseURI)
+        throws XMLSecurityException {
+        super(element, BaseURI);
+    }
 
-   /** @inheritDoc */
-   public final String getBaseNamespace() {
-      return EncryptionConstants.EncryptionSpecNS;
-   }
+    /** @inheritDoc */
+    public final String getBaseNamespace() {
+        return EncryptionConstants.EncryptionSpecNS;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
@@ -28,75 +30,69 @@
 import org.w3c.dom.NodeList;
 
 /**
- *
  * @author Christian Geuer-Pollmann
- *
  */
 public class HelperNodeList implements NodeList {
 
-   /** Field nodes */
-   List<Node> nodes = new ArrayList<Node>(20);
-   boolean _allNodesMustHaveSameParent = false;
+    /** Field nodes */
+    List<Node> nodes = new ArrayList<Node>();
+    boolean allNodesMustHaveSameParent = false;
 
-   /**
-    *
-    */
-   public HelperNodeList() {
-      this(false);
-   }
+    /**
+     *
+     */
+    public HelperNodeList() {
+        this(false);
+    }
 
 
-   /**
-    * @param allNodesMustHaveSameParent
-    */
-   public HelperNodeList(boolean allNodesMustHaveSameParent) {
-      this._allNodesMustHaveSameParent = allNodesMustHaveSameParent;
-   }
+    /**
+     * @param allNodesMustHaveSameParent
+     */
+    public HelperNodeList(boolean allNodesMustHaveSameParent) {
+        this.allNodesMustHaveSameParent = allNodesMustHaveSameParent;
+    }
 
-   /**
-    * Method item
-    *
-    * @param index
-    * @return node with inde i
-    */
-   public Node item(int index) {
-
-      // log.log(java.util.logging.Level.FINE, "item(" + index + ") of " + this.getLength() + " nodes");
-
-      return nodes.get(index);
-   }
+    /**
+     * Method item
+     *
+     * @param index
+     * @return node with index i
+     */
+    public Node item(int index) {
+        return nodes.get(index);
+    }
 
-   /**
-    * Method getLength
-    *
-    *  @return length of the list
-    */
-   public int getLength() {
-      return nodes.size();
-   }
+    /**
+     * Method getLength
+     *
+     *  @return length of the list
+     */
+    public int getLength() {
+        return nodes.size();
+    }
 
-   /**
-    * Method appendChild
-    *
-    * @param node
-    * @throws IllegalArgumentException
-    */
-   public void appendChild(Node node) throws IllegalArgumentException {
-      if (this._allNodesMustHaveSameParent && this.getLength() > 0) {
-         if (this.item(0).getParentNode() != node.getParentNode()) {
+    /**
+     * Method appendChild
+     *
+     * @param node
+     * @throws IllegalArgumentException
+     */
+    public void appendChild(Node node) throws IllegalArgumentException {
+        if (this.allNodesMustHaveSameParent && this.getLength() > 0
+            && this.item(0).getParentNode() != node.getParentNode()) {
             throw new IllegalArgumentException("Nodes have not the same Parent");
-         }
-      }
-      nodes.add(node);
-   }
+        }
+        nodes.add(node);
+    }
 
-   /**
-    * @return the document that contains this nodelist
-    */
-   public Document getOwnerDocument() {
-      if (this.getLength() == 0) {
-         return null;
-      }
-      return XMLUtils.getOwnerDocument(this.item(0));
-   }
+    /**
+     * @return the document that contains this nodelist
+     */
+    public Document getOwnerDocument() {
+        if (this.getLength() == 0) {
+            return null;
+        }
+        return XMLUtils.getOwnerDocument(this.item(0));
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,85 +2,42 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
-import java.lang.ref.WeakReference;
-import java.util.Arrays;
-import java.util.WeakHashMap;
-import java.util.Map;
-
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
 
 
 /**
  * Purpose of this class is to enable the XML Parser to keep track of ID
  * attributes. This is done by 'registering' attributes of type ID at the
- * IdResolver. This is necessary if we create a document from scratch and we
- * sign some resources with a URI using a fragent identifier...
- * <BR />
- * The problem is that if you do not validate a document, you cannot use the
- * <CODE>getElementByID</CODE> functionality. So this modules uses some implicit
- * knowledge on selected Schemas and DTDs to pick the right Element for a given
- * ID: We know that all <CODE>@Id</CODE> attributes in an Element from the XML
- * Signature namespace are of type <CODE>ID</CODE>.
- *
- * @author $Author: mullan $
- * @see <A HREF="http://www.xml.com/lpt/a/2001/11/07/id.html">"Identity Crisis" on xml.com</A>
+ * IdResolver.
+ * @deprecated
  */
+@Deprecated
 public class IdResolver {
 
-    /** {@link java.util.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(IdResolver.class.getName());
-
-    private static Map<Document, Map<String, WeakReference<Element>>> docMap =
-                    new WeakHashMap<Document, Map<String, WeakReference<Element>>>();
-
-    /**
-     * Constructor IdResolver
-     *
-     */
     private IdResolver() {
-       // we don't allow instantiation
-    }
-
-    /**
-     * Method registerElementById
-     *
-     * @param element the element to register
-     * @param idValue the value of the ID attribute
-     */
-    public static void registerElementById(Element element, String idValue) {
-        Document doc = element.getOwnerDocument();
-        Map<String, WeakReference<Element>> elementMap;
-        synchronized (docMap) {
-            elementMap = docMap.get(doc);
-            if (elementMap == null) {
-                elementMap = new WeakHashMap<String, WeakReference<Element>>();
-                docMap.put(doc, elementMap);
-            }
-        }
-        elementMap.put(idValue, new WeakReference<Element>(element));
+        // we don't allow instantiation
     }
 
     /**
@@ -90,7 +47,7 @@
      * @param id the ID attribute
      */
     public static void registerElementById(Element element, Attr id) {
-        IdResolver.registerElementById(element, id.getNodeValue());
+        element.setIdAttributeNode(id, true);
     }
 
     /**
@@ -101,194 +58,7 @@
      * @return the element obtained by the id, or null if it is not found.
      */
     public static Element getElementById(Document doc, String id) {
-
-        Element result = IdResolver.getElementByIdType(doc, id);
-
-        if (result != null) {
-            log.log(java.util.logging.Level.FINE,
-            "I could find an Element using the simple getElementByIdType method: "
-            + result.getTagName());
-
-            return result;
-        }
-
-        result = IdResolver.getElementByIdUsingDOM(doc, id);
-
-        if (result != null) {
-            log.log(java.util.logging.Level.FINE,
-             "I could find an Element using the simple getElementByIdUsingDOM method: "
-            + result.getTagName());
-
-            return result;
-        }
-        // this must be done so that Xalan can catch ALL namespaces
-        //XMLUtils.circumventBug2650(doc);
-        result = IdResolver.getElementBySearching(doc, id);
-
-        if (result != null) {
-            IdResolver.registerElementById(result, id);
-
-            return result;
-        }
-
-        return null;
-    }
-
-
-    /**
-     * Method getElementByIdUsingDOM
-     *
-     * @param doc the document
-     * @param id the value of the ID
-     * @return the element obtained by the id, or null if it is not found.
-     */
-    private static Element getElementByIdUsingDOM(Document doc, String id) {
-        if (log.isLoggable(java.util.logging.Level.FINE))
-            log.log(java.util.logging.Level.FINE, "getElementByIdUsingDOM() Search for ID " + id);
         return doc.getElementById(id);
     }
 
-    /**
-     * Method getElementByIdType
-     *
-     * @param doc the document
-     * @param id the value of the ID
-     * @return the element obtained by the id, or null if it is not found.
-     */
-    private static Element getElementByIdType(Document doc, String id) {
-        if (log.isLoggable(java.util.logging.Level.FINE))
-            log.log(java.util.logging.Level.FINE, "getElementByIdType() Search for ID " + id);
-        Map<String, WeakReference<Element>> elementMap;
-        synchronized (docMap) {
-            elementMap = docMap.get(doc);
-        }
-        if (elementMap != null) {
-            WeakReference<Element> weakReference =  elementMap.get(id);
-            if (weakReference != null) {
-                return weakReference.get();
-            }
-        }
-        return null;
-    }
-
-    private static java.util.List<String> names;
-    private static int namesLength;
-    static {
-        String namespaces[]={
-            Constants.SignatureSpecNS,
-            EncryptionConstants.EncryptionSpecNS,
-            "http://schemas.xmlsoap.org/soap/security/2000-12",
-            "http://www.w3.org/2002/03/xkms#",
-            "urn:oasis:names:tc:SAML:1.0:assertion",
-            "urn:oasis:names:tc:SAML:1.0:protocol"
-        };
-        names = Arrays.asList(namespaces);
-        namesLength = names.size();
-    }
-
-
-    private static Element getElementBySearching(Node root,String id) {
-        Element []els=new Element[namesLength + 1];
-        getEl(root,id,els);
-        for (int i=0;i<els.length;i++) {
-            if (els[i]!=null) {
-                return els[i];
-            }
-        }
-        return null;
-    }
-
-    private static int getEl(Node currentNode,String id,Element []els) {
-        Node sibling=null;
-        Node parentNode=null;
-        do {
-                switch (currentNode.getNodeType()) {
-                case Node.DOCUMENT_FRAGMENT_NODE :
-                case Node.DOCUMENT_NODE :
-                        sibling= currentNode.getFirstChild();
-                        break;
-
-
-                case Node.ELEMENT_NODE :
-                        Element currentElement = (Element) currentNode;
-                        if (isElement(currentElement, id, els)==1)
-                                return 1;
-                        sibling= currentNode.getFirstChild();
-                        if (sibling==null) {
-                            if (parentNode != null) {
-                                        sibling= currentNode.getNextSibling();
-                                    }
-                        } else {
-                                parentNode=currentElement;
-                        }
-                        break;
-        } while (sibling==null  && parentNode!=null) {
-                        sibling=parentNode.getNextSibling();
-                        parentNode=parentNode.getParentNode();
-                        if (parentNode != null && parentNode.getNodeType() != Node.ELEMENT_NODE) {
-                                parentNode=null;
-                        }
-                }
-                if (sibling==null)
-                        return 1;
-                currentNode=sibling;
-                sibling=currentNode.getNextSibling();
-        } while(true);
-
-    }
-    public static int isElement(Element el, String id,Element[] els) {
-        if (!el.hasAttributes()) {
-                return 0;
-        }
-        NamedNodeMap ns=el.getAttributes();
-        int elementIndex=names.indexOf(el.getNamespaceURI());
-            elementIndex=(elementIndex<0) ? namesLength : elementIndex;
-        for (int length=ns.getLength(), i=0; i<length; i++) {
-                Attr n=(Attr)ns.item(i);
-                String s=n.getNamespaceURI();
-
-                    int index=s==null ? elementIndex : names.indexOf(n.getNamespaceURI());
-                    index=(index<0) ? namesLength : index;
-                    String name=n.getLocalName();
-                    if (name == null)
-                        name = n.getName();
-                    if (name.length()>2)
-                        continue;
-                    String value=n.getNodeValue();
-                    if (name.charAt(0)=='I') {
-                        char ch=name.charAt(1);
-                        if (ch=='d' && value.equals(id)) {
-                                els[index]=el;
-                                if (index==0) {
-                                        return 1;
-                                }
-                        } else if (ch=='D' &&value.endsWith(id)) {
-                                if (index!=3) {
-                                    index=namesLength;
-                                }
-                                els[index]=el;
-                        }
-                    } else if ( "id".equals(name) && value.equals(id) ) {
-                        if (index!=2) {
-                                index=namesLength;
-                        }
-                        els[index]=el;
-                    }
-        }
-        //For an element namespace search for importants
-        if ((elementIndex==3)&&(
-                    el.getAttribute("OriginalRequestID").equals(id) ||
-                    el.getAttribute("RequestID").equals(id) ||
-                    el.getAttribute("ResponseID").equals(id))) {
-                    els[3]=el;
-        } else if ((elementIndex==4)&&(
-                    el.getAttribute("AssertionID").equals(id))) {
-                    els[4]=el;
-        } else if ((elementIndex==5)&&(
-                    el.getAttribute("RequestID").equals(id) ||
-                    el.getAttribute("ResponseID").equals(id))) {
-                    els[5]=el;
-                 }
-        return 0;
-    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,82 +2,80 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
-
 import org.xml.sax.ErrorHandler;
 import org.xml.sax.SAXException;
 import org.xml.sax.SAXParseException;
 
-
 /**
- * This {@link org.xml.sax.ErrorHandler} does absulutely nothing but logging
+ * This {@link org.xml.sax.ErrorHandler} does absolutely nothing but log
  * the events.
  *
  * @author Christian Geuer-Pollmann
  */
 public class IgnoreAllErrorHandler implements ErrorHandler {
 
-        /** {@link java.util.logging} logging facility */
-        static java.util.logging.Logger log =
-                java.util.logging.Logger.getLogger(
-                        IgnoreAllErrorHandler.class.getName());
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(IgnoreAllErrorHandler.class.getName());
 
-        /** Field throwExceptions */
-        static final boolean warnOnExceptions = System.getProperty(
-                "com.sun.org.apache.xml.internal.security.test.warn.on.exceptions", "false").equals("true");
+    /** Field throwExceptions */
+    private static final boolean warnOnExceptions =
+        System.getProperty("com.sun.org.apache.xml.internal.security.test.warn.on.exceptions", "false").equals("true");
 
-        /** Field throwExceptions           */
-        static final boolean throwExceptions = System.getProperty(
-                "com.sun.org.apache.xml.internal.security.test.throw.exceptions", "false").equals("true");
+    /** Field throwExceptions           */
+    private static final boolean throwExceptions =
+        System.getProperty("com.sun.org.apache.xml.internal.security.test.throw.exceptions", "false").equals("true");
 
 
-        /** @inheritDoc */
-        public void warning(SAXParseException ex) throws SAXException {
-                if (IgnoreAllErrorHandler.warnOnExceptions) {
-                        log.log(java.util.logging.Level.WARNING, "", ex);
-                }
-                if (IgnoreAllErrorHandler.throwExceptions) {
-                        throw ex;
-                }
+    /** @inheritDoc */
+    public void warning(SAXParseException ex) throws SAXException {
+        if (IgnoreAllErrorHandler.warnOnExceptions) {
+            log.log(java.util.logging.Level.WARNING, "", ex);
         }
+        if (IgnoreAllErrorHandler.throwExceptions) {
+            throw ex;
+        }
+    }
 
 
-        /** @inheritDoc */
-        public void error(SAXParseException ex) throws SAXException {
-                if (IgnoreAllErrorHandler.warnOnExceptions) {
-                        log.log(java.util.logging.Level.SEVERE, "", ex);
-                }
-                if (IgnoreAllErrorHandler.throwExceptions) {
-                        throw ex;
-                }
+    /** @inheritDoc */
+    public void error(SAXParseException ex) throws SAXException {
+        if (IgnoreAllErrorHandler.warnOnExceptions) {
+            log.log(java.util.logging.Level.SEVERE, "", ex);
         }
+        if (IgnoreAllErrorHandler.throwExceptions) {
+            throw ex;
+        }
+    }
 
 
-
-        /** @inheritDoc */
-        public void fatalError(SAXParseException ex) throws SAXException {
-                if (IgnoreAllErrorHandler.warnOnExceptions) {
-                        log.log(java.util.logging.Level.WARNING, "", ex);
-                }
-                if (IgnoreAllErrorHandler.throwExceptions) {
-                        throw ex;
-                }
+    /** @inheritDoc */
+    public void fatalError(SAXParseException ex) throws SAXException {
+        if (IgnoreAllErrorHandler.warnOnExceptions) {
+            log.log(java.util.logging.Level.WARNING, "", ex);
         }
+        if (IgnoreAllErrorHandler.throwExceptions) {
+            throw ex;
+        }
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,132 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.utils;
+
+import javax.xml.XMLConstants;
+import javax.xml.transform.TransformerException;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathExpression;
+import javax.xml.xpath.XPathExpressionException;
+import javax.xml.xpath.XPathFactory;
+import javax.xml.xpath.XPathFactoryConfigurationException;
+
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * An implementation for XPath evaluation that uses the JDK API.
+ */
+public class JDKXPathAPI implements XPathAPI {
+
+    private XPathFactory xpf;
+
+    private String xpathStr;
+
+    private XPathExpression xpathExpression;
+
+    /**
+     *  Use an XPath string to select a nodelist.
+     *  XPath namespace prefixes are resolved from the namespaceNode.
+     *
+     *  @param contextNode The node to start searching from.
+     *  @param xpathnode
+     *  @param str
+     *  @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
+     *  @return A NodeIterator, should never be null.
+     *
+     * @throws TransformerException
+     */
+    public NodeList selectNodeList(
+        Node contextNode, Node xpathnode, String str, Node namespaceNode
+    ) throws TransformerException {
+        if (!str.equals(xpathStr) || xpathExpression == null) {
+            if (xpf == null) {
+                xpf = XPathFactory.newInstance();
+                try {
+                    xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
+                } catch (XPathFactoryConfigurationException ex) {
+                    throw new TransformerException("empty", ex);
+                }
+            }
+            XPath xpath = xpf.newXPath();
+            xpath.setNamespaceContext(new DOMNamespaceContext(namespaceNode));
+            xpathStr = str;
+            try {
+                xpathExpression = xpath.compile(xpathStr);
+            } catch (XPathExpressionException ex) {
+                throw new TransformerException("empty", ex);
+            }
+        }
+        try {
+            return (NodeList)xpathExpression.evaluate(contextNode, XPathConstants.NODESET);
+        } catch (XPathExpressionException ex) {
+            throw new TransformerException("empty", ex);
+        }
+    }
+
+    /**
+     * Evaluate an XPath string and return true if the output is to be included or not.
+     *  @param contextNode The node to start searching from.
+     *  @param xpathnode The XPath node
+     *  @param str The XPath expression
+     *  @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
+     */
+    public boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode)
+        throws TransformerException {
+        if (!str.equals(xpathStr) || xpathExpression == null) {
+            if (xpf == null) {
+                xpf = XPathFactory.newInstance();
+                try {
+                    xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
+                } catch (XPathFactoryConfigurationException ex) {
+                    throw new TransformerException("empty", ex);
+                }
+            }
+            XPath xpath = xpf.newXPath();
+            xpath.setNamespaceContext(new DOMNamespaceContext(namespaceNode));
+            xpathStr = str;
+            try {
+                xpathExpression = xpath.compile(xpathStr);
+            } catch (XPathExpressionException ex) {
+                throw new TransformerException("empty", ex);
+            }
+        }
+        try {
+            Boolean result = (Boolean)xpathExpression.evaluate(contextNode, XPathConstants.BOOLEAN);
+            return result.booleanValue();
+        } catch (XPathExpressionException ex) {
+            throw new TransformerException("empty", ex);
+        }
+    }
+
+    /**
+     * Clear any context information from this object
+     */
+    public void clear() {
+        xpathStr = null;
+        xpathExpression = null;
+        xpf = null;
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathFactory.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,37 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.utils;
+
+
+/**
+ * A Factory to return a JDKXPathAPI instance.
+ */
+public class JDKXPathFactory extends XPathFactory {
+
+    /**
+     * Get a new XPathAPI instance
+     */
+    public XPathAPI newXPathAPI() {
+        return new JDKXPathAPI();
+    }
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
@@ -33,8 +35,8 @@
  */
 public class JavaUtils {
 
-    /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(JavaUtils.class.getName());
 
     private JavaUtils() {
@@ -45,7 +47,7 @@
      * Method getBytesFromFile
      *
      * @param fileName
-     * @return the bytes readed from the file
+     * @return the bytes read from the file
      *
      * @throws FileNotFoundException
      * @throws IOException
@@ -55,9 +57,11 @@
 
         byte refBytes[] = null;
 
-        FileInputStream fisRef = new FileInputStream(fileName);
+        FileInputStream fisRef = null;
+        UnsyncByteArrayOutputStream baos = null;
         try {
-            UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream();
+            fisRef = new FileInputStream(fileName);
+            baos = new UnsyncByteArrayOutputStream();
             byte buf[] = new byte[1024];
             int len;
 
@@ -67,7 +71,12 @@
 
             refBytes = baos.toByteArray();
         } finally {
-            fisRef.close();
+            if (baos != null) {
+                baos.close();
+            }
+            if (fisRef != null) {
+                fisRef.close();
+            }
         }
 
         return refBytes;
@@ -80,7 +89,6 @@
      * @param bytes
      */
     public static void writeBytesToFilename(String filename, byte[] bytes) {
-
         FileOutputStream fos = null;
         try {
             if (filename != null && bytes != null) {
@@ -91,13 +99,19 @@
                 fos.write(bytes);
                 fos.close();
             } else {
-                log.log(java.util.logging.Level.FINE, "writeBytesToFilename got null byte[] pointed");
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "writeBytesToFilename got null byte[] pointed");
+                }
             }
         } catch (IOException ex) {
             if (fos != null) {
                 try {
                     fos.close();
-                } catch (IOException ioe) {}
+                } catch (IOException ioe) {
+                    if (log.isLoggable(java.util.logging.Level.FINE)) {
+                        log.log(java.util.logging.Level.FINE, ioe.getMessage(), ioe);
+                    }
+                }
             }
         }
     }
@@ -107,25 +121,28 @@
      * returns them as a byte array.
      *
      * @param inputStream
-     * @return the bytes readed from the stream
+     * @return the bytes read from the stream
      *
      * @throws FileNotFoundException
      * @throws IOException
      */
-    public static byte[] getBytesFromStream(InputStream inputStream)
-        throws IOException {
-
-        byte refBytes[] = null;
+    public static byte[] getBytesFromStream(InputStream inputStream) throws IOException {
+        UnsyncByteArrayOutputStream baos = null;
 
-        UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream();
-        byte buf[] = new byte[1024];
-        int len;
+        byte[] retBytes = null;
+        try {
+            baos = new UnsyncByteArrayOutputStream();
+            byte buf[] = new byte[4 * 1024];
+            int len;
 
-        while ((len = inputStream.read(buf)) > 0) {
-            baos.write(buf, 0, len);
+            while ((len = inputStream.read(buf)) > 0) {
+                baos.write(buf, 0, len);
+            }
+            retBytes = baos.toByteArray();
+        } finally {
+            baos.close();
         }
 
-        refBytes = baos.toByteArray();
-        return refBytes;
+        return retBytes;
     }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,573 +2,473 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
-
-
 import java.io.IOException;
 import java.io.StringReader;
 
-
-/**
- *
- * @author $Author: mullan $
- */
 public class RFC2253Parser {
 
+    /**
+     * Method rfc2253toXMLdsig
+     *
+     * @param dn
+     * @return normalized string
+     */
+    public static String rfc2253toXMLdsig(String dn) {
+        // Transform from RFC1779 to RFC2253
+        String normalized = normalize(dn, true);
 
-   /** {@link java.util.logging} logging facility */
-   /* static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(RFC2253Parser.class.getName());
-   */
-
-   static boolean _TOXML = true;
+        return rfctoXML(normalized);
+    }
 
-   /**
-    * Method rfc2253toXMLdsig
-    *
-    * @param dn
-    * @return normalized string
-    *
-    */
-   public static String rfc2253toXMLdsig(String dn) {
+    /**
+     * Method xmldsigtoRFC2253
+     *
+     * @param dn
+     * @return normalized string
+     */
+    public static String xmldsigtoRFC2253(String dn) {
+        // Transform from RFC1779 to RFC2253
+        String normalized = normalize(dn, false);
 
-      _TOXML = true;
+        return xmltoRFC(normalized);
+    }
 
-      // Transform from RFC1779 to RFC2253
-      String normalized = normalize(dn);
-
-      return rfctoXML(normalized);
-   }
+    /**
+     * Method normalize
+     *
+     * @param dn
+     * @return normalized string
+     */
+    public static String normalize(String dn) {
+        return normalize(dn, true);
+    }
 
-   /**
-    * Method xmldsigtoRFC2253
-    *
-    * @param dn
-    * @return normalized string
-    */
-   public static String xmldsigtoRFC2253(String dn) {
+    /**
+     * Method normalize
+     *
+     * @param dn
+     * @param toXml
+     * @return normalized string
+     */
+    public static String normalize(String dn, boolean toXml) {
+        //if empty string
+        if ((dn == null) || dn.equals("")) {
+            return "";
+        }
 
-      _TOXML = false;
-
-      // Transform from RFC1779 to RFC2253
-      String normalized = normalize(dn);
+        try {
+            String DN = semicolonToComma(dn);
+            StringBuilder sb = new StringBuilder();
+            int i = 0;
+            int l = 0;
+            int k;
 
-      return xmltoRFC(normalized);
-   }
+            //for name component
+            for (int j = 0; (k = DN.indexOf(',', j)) >= 0; j = k + 1) {
+                l += countQuotes(DN, j, k);
+
+                if ((k > 0) && (DN.charAt(k - 1) != '\\') && (l % 2) == 0) {
+                    sb.append(parseRDN(DN.substring(i, k).trim(), toXml) + ",");
 
-   /**
-    * Method normalize
-    *
-    * @param dn
-    * @return normalized string
-    */
-   public static String normalize(String dn) {
+                    i = k + 1;
+                    l = 0;
+                }
+            }
 
-      //if empty string
-      if ((dn == null) || dn.equals("")) {
-         return "";
-      }
+            sb.append(parseRDN(trim(DN.substring(i)), toXml));
+
+            return sb.toString();
+        } catch (IOException ex) {
+            return dn;
+        }
+    }
 
-      try {
-         String _DN = semicolonToComma(dn);
-         StringBuffer sb = new StringBuffer();
-         int i = 0;
-         int l = 0;
-         int k;
+    /**
+     * Method parseRDN
+     *
+     * @param str
+     * @param toXml
+     * @return normalized string
+     * @throws IOException
+     */
+    static String parseRDN(String str, boolean toXml) throws IOException {
+        StringBuilder sb = new StringBuilder();
+        int i = 0;
+        int l = 0;
+        int k;
 
-         //for name component
-         for (int j = 0; (k = _DN.indexOf(",", j)) >= 0; j = k + 1) {
-            l += countQuotes(_DN, j, k);
+        for (int j = 0; (k = str.indexOf('+', j)) >= 0; j = k + 1) {
+            l += countQuotes(str, j, k);
+
+            if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) == 0) {
+                sb.append(parseATAV(trim(str.substring(i, k)), toXml) + "+");
 
-            if ((k > 0) && (_DN.charAt(k - 1) != '\\') && (l % 2) != 1) {
-               sb.append(parseRDN(_DN.substring(i, k).trim()) + ",");
+                i = k + 1;
+                l = 0;
+            }
+        }
 
-               i = k + 1;
-               l = 0;
-            }
-         }
+        sb.append(parseATAV(trim(str.substring(i)), toXml));
+
+        return sb.toString();
+    }
 
-         sb.append(parseRDN(trim(_DN.substring(i))));
-
-         return sb.toString();
-      } catch (IOException ex) {
-         return dn;
-      }
-   }
+    /**
+     * Method parseATAV
+     *
+     * @param str
+     * @param toXml
+     * @return normalized string
+     * @throws IOException
+     */
+    static String parseATAV(String str, boolean toXml) throws IOException {
+        int i = str.indexOf('=');
 
-   /**
-    * Method parseRDN
-    *
-    * @param str
-    * @return normalized string
-    * @throws IOException
-    */
-   static String parseRDN(String str) throws IOException {
+        if ((i == -1) || ((i > 0) && (str.charAt(i - 1) == '\\'))) {
+            return str;
+        }
+        String attrType = normalizeAT(str.substring(0, i));
+        // only normalize if value is a String
+        String attrValue = null;
+        if (attrType.charAt(0) >= '0' && attrType.charAt(0) <= '9') {
+            attrValue = str.substring(i + 1);
+        } else {
+            attrValue = normalizeV(str.substring(i + 1), toXml);
+        }
+
+        return attrType + "=" + attrValue;
 
-      StringBuffer sb = new StringBuffer();
-      int i = 0;
-      int l = 0;
-      int k;
+    }
 
-      for (int j = 0; (k = str.indexOf("+", j)) >= 0; j = k + 1) {
-         l += countQuotes(str, j, k);
+    /**
+     * Method normalizeAT
+     *
+     * @param str
+     * @return normalized string
+     */
+    static String normalizeAT(String str) {
 
-         if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) != 1) {
-            sb.append(parseATAV(trim(str.substring(i, k))) + "+");
+        String at = str.toUpperCase().trim();
+
+        if (at.startsWith("OID")) {
+            at = at.substring(3);
+        }
 
-            i = k + 1;
-            l = 0;
-         }
-      }
+        return at;
+    }
 
-      sb.append(parseATAV(trim(str.substring(i))));
-
-      return sb.toString();
-   }
+    /**
+     * Method normalizeV
+     *
+     * @param str
+     * @param toXml
+     * @return normalized string
+     * @throws IOException
+     */
+    static String normalizeV(String str, boolean toXml) throws IOException {
+        String value = trim(str);
 
-   /**
-    * Method parseATAV
-    *
-    * @param str
-    * @return normalized string
-    * @throws IOException
-    */
-   static String parseATAV(String str) throws IOException {
+        if (value.startsWith("\"")) {
+            StringBuilder sb = new StringBuilder();
+            StringReader sr = new StringReader(value.substring(1, value.length() - 1));
+            int i = 0;
+            char c;
+
+            while ((i = sr.read()) > -1) {
+                c = (char) i;
 
-      int i = str.indexOf("=");
+                //the following char is defined at 4.Relationship with RFC1779 and LDAPv2 inrfc2253
+                if ((c == ',') || (c == '=') || (c == '+') || (c == '<')
+                    || (c == '>') || (c == '#') || (c == ';')) {
+                    sb.append('\\');
+                }
+
+                sb.append(c);
+            }
 
-      if ((i == -1) || ((i > 0) && (str.charAt(i - 1) == '\\'))) {
-         return str;
-      }
-      String attrType = normalizeAT(str.substring(0, i));
-      // only normalize if value is a String
-      String attrValue = null;
-      if (attrType.charAt(0) >= '0' && attrType.charAt(0) <= '9') {
-          attrValue = str.substring(i + 1);
-      } else {
-          attrValue = normalizeV(str.substring(i + 1));
-      }
+            value = trim(sb.toString());
+        }
+
+        if (toXml) {
+            if (value.startsWith("#")) {
+                value = '\\' + value;
+            }
+        } else {
+            if (value.startsWith("\\#")) {
+                value = value.substring(1);
+            }
+        }
 
-      return attrType + "=" + attrValue;
-
-   }
+        return value;
+    }
 
-   /**
-    * Method normalizeAT
-    *
-    * @param str
-    * @return normalized string
-    */
-   static String normalizeAT(String str) {
-
-      String at = str.toUpperCase().trim();
+    /**
+     * Method rfctoXML
+     *
+     * @param string
+     * @return normalized string
+     */
+    static String rfctoXML(String string) {
+        try {
+            String s = changeLess32toXML(string);
 
-      if (at.startsWith("OID")) {
-         at = at.substring(3);
-      }
+            return changeWStoXML(s);
+        } catch (Exception e) {
+            return string;
+        }
+    }
 
-      return at;
-   }
+    /**
+     * Method xmltoRFC
+     *
+     * @param string
+     * @return normalized string
+     */
+    static String xmltoRFC(String string) {
+        try {
+            String s = changeLess32toRFC(string);
 
-   /**
-    * Method normalizeV
-    *
-    * @param str
-    * @return normalized string
-    * @throws IOException
-    */
-   static String normalizeV(String str) throws IOException {
+            return changeWStoRFC(s);
+        } catch (Exception e) {
+            return string;
+        }
+    }
 
-      String value = trim(str);
+    /**
+     * Method changeLess32toRFC
+     *
+     * @param string
+     * @return normalized string
+     * @throws IOException
+     */
+    static String changeLess32toRFC(String string) throws IOException {
+        StringBuilder sb = new StringBuilder();
+        StringReader sr = new StringReader(string);
+        int i = 0;
+        char c;
 
-      if (value.startsWith("\"")) {
-         StringBuffer sb = new StringBuffer();
-         StringReader sr = new StringReader(value.substring(1,
-                              value.length() - 1));
-         int i = 0;
-         char c;
-
-         for (; (i = sr.read()) > -1; ) {
+        while ((i = sr.read()) > -1) {
             c = (char) i;
 
-            //the following char is defined at 4.Relationship with RFC1779 and LDAPv2 inrfc2253
-            if ((c == ',') || (c == '=') || (c == '+') || (c == '<')
-                    || (c == '>') || (c == '#') || (c == ';')) {
-               sb.append('\\');
-            }
-
-            sb.append(c);
-         }
-
-         value = trim(sb.toString());
-      }
-
-      if (_TOXML == true) {
-         if (value.startsWith("#")) {
-            value = '\\' + value;
-         }
-      } else {
-         if (value.startsWith("\\#")) {
-            value = value.substring(1);
-         }
-      }
-
-      return value;
-   }
-
-   /**
-    * Method rfctoXML
-    *
-    * @param string
-    * @return normalized string
-    */
-   static String rfctoXML(String string) {
-
-      try {
-         String s = changeLess32toXML(string);
-
-         return changeWStoXML(s);
-      } catch (Exception e) {
-         return string;
-      }
-   }
+            if (c == '\\') {
+                sb.append(c);
 
-   /**
-    * Method xmltoRFC
-    *
-    * @param string
-    * @return normalized string
-    */
-   static String xmltoRFC(String string) {
-
-      try {
-         String s = changeLess32toRFC(string);
-
-         return changeWStoRFC(s);
-      } catch (Exception e) {
-         return string;
-      }
-   }
+                char c1 = (char) sr.read();
+                char c2 = (char) sr.read();
 
-   /**
-    * Method changeLess32toRFC
-    *
-    * @param string
-    * @return normalized string
-    * @throws IOException
-    */
-   static String changeLess32toRFC(String string) throws IOException {
-
-      StringBuffer sb = new StringBuffer();
-      StringReader sr = new StringReader(string);
-      int i = 0;
-      char c;
-
-      for (; (i = sr.read()) > -1; ) {
-         c = (char) i;
-
-         if (c == '\\') {
-            sb.append(c);
-
-            char c1 = (char) sr.read();
-            char c2 = (char) sr.read();
-
-            //65 (A) 97 (a)
-            if ((((c1 >= 48) && (c1 <= 57)) || ((c1 >= 65) && (c1 <= 70)) || ((c1 >= 97) && (c1 <= 102)))
+                //65 (A) 97 (a)
+                if ((((c1 >= 48) && (c1 <= 57)) || ((c1 >= 65) && (c1 <= 70)) || ((c1 >= 97) && (c1 <= 102)))
                     && (((c2 >= 48) && (c2 <= 57))
                         || ((c2 >= 65) && (c2 <= 70))
                         || ((c2 >= 97) && (c2 <= 102)))) {
-               char ch = (char) Byte.parseByte("" + c1 + c2, 16);
-
-               sb.append(ch);
-            } else {
-               sb.append(c1);
-               sb.append(c2);
-            }
-         } else {
-            sb.append(c);
-         }
-      }
+                    char ch = (char) Byte.parseByte("" + c1 + c2, 16);
 
-      return sb.toString();
-   }
+                    sb.append(ch);
+                } else {
+                    sb.append(c1);
+                    sb.append(c2);
+                }
+            } else {
+                sb.append(c);
+            }
+        }
 
-   /**
-    * Method changeLess32toXML
-    *
-    * @param string
-    * @return normalized string
-    * @throws IOException
-    */
-   static String changeLess32toXML(String string) throws IOException {
-
-      StringBuffer sb = new StringBuffer();
-      StringReader sr = new StringReader(string);
-      int i = 0;
+        return sb.toString();
+    }
 
-      for (; (i = sr.read()) > -1; ) {
-         if (i < 32) {
-            sb.append('\\');
-            sb.append(Integer.toHexString(i));
-         } else {
-            sb.append((char) i);
-         }
-      }
-
-      return sb.toString();
-   }
+    /**
+     * Method changeLess32toXML
+     *
+     * @param string
+     * @return normalized string
+     * @throws IOException
+     */
+    static String changeLess32toXML(String string) throws IOException {
+        StringBuilder sb = new StringBuilder();
+        StringReader sr = new StringReader(string);
+        int i = 0;
 
-   /**
-    * Method changeWStoXML
-    *
-    * @param string
-    * @return normalized string
-    * @throws IOException
-    */
-   static String changeWStoXML(String string) throws IOException {
-
-      StringBuffer sb = new StringBuffer();
-      StringReader sr = new StringReader(string);
-      int i = 0;
-      char c;
-
-      for (; (i = sr.read()) > -1; ) {
-         c = (char) i;
-
-         if (c == '\\') {
-            char c1 = (char) sr.read();
-
-            if (c1 == ' ') {
-               sb.append('\\');
-
-               String s = "20";
-
-               sb.append(s);
+        while ((i = sr.read()) > -1) {
+            if (i < 32) {
+                sb.append('\\');
+                sb.append(Integer.toHexString(i));
             } else {
-               sb.append('\\');
-               sb.append(c1);
+                sb.append((char) i);
             }
-         } else {
-            sb.append(c);
-         }
-      }
+        }
 
-      return sb.toString();
-   }
+        return sb.toString();
+    }
 
-   /**
-    * Method changeWStoRFC
-    *
-    * @param string
-    * @return normalized string
-    */
-   static String changeWStoRFC(String string) {
+    /**
+     * Method changeWStoXML
+     *
+     * @param string
+     * @return normalized string
+     * @throws IOException
+     */
+    static String changeWStoXML(String string) throws IOException {
+        StringBuilder sb = new StringBuilder();
+        StringReader sr = new StringReader(string);
+        int i = 0;
+        char c;
 
-      StringBuffer sb = new StringBuffer();
-      int i = 0;
-      int k;
-
-      for (int j = 0; (k = string.indexOf("\\20", j)) >= 0; j = k + 3) {
-         sb.append(trim(string.substring(i, k)) + "\\ ");
+        while ((i = sr.read()) > -1) {
+            c = (char) i;
 
-         i = k + 3;
-      }
+            if (c == '\\') {
+                char c1 = (char) sr.read();
 
-      sb.append(string.substring(i));
+                if (c1 == ' ') {
+                    sb.append('\\');
 
-      return sb.toString();
-   }
+                    String s = "20";
 
-   /**
-    * Method semicolonToComma
-    *
-    * @param str
-    * @return normalized string
-    */
-   static String semicolonToComma(String str) {
-      return removeWSandReplace(str, ";", ",");
-   }
+                    sb.append(s);
+                } else {
+                    sb.append('\\');
+                    sb.append(c1);
+                }
+            } else {
+                sb.append(c);
+            }
+        }
+
+        return sb.toString();
+    }
 
-   /**
-    * Method removeWhiteSpace
-    *
-    * @param str
-    * @param symbol
-    * @return normalized string
-    */
-   static String removeWhiteSpace(String str, String symbol) {
-      return removeWSandReplace(str, symbol, symbol);
-   }
+    /**
+     * Method changeWStoRFC
+     *
+     * @param string
+     * @return normalized string
+     */
+    static String changeWStoRFC(String string) {
+        StringBuilder sb = new StringBuilder();
+        int i = 0;
+        int k;
 
-   /**
-    * Method removeWSandReplace
-    *
-    * @param str
-    * @param symbol
-    * @param replace
-    * @return normalized string
-    */
-   static String removeWSandReplace(String str, String symbol, String replace) {
+        for (int j = 0; (k = string.indexOf("\\20", j)) >= 0; j = k + 3) {
+            sb.append(trim(string.substring(i, k)) + "\\ ");
 
-      StringBuffer sb = new StringBuffer();
-      int i = 0;
-      int l = 0;
-      int k;
+            i = k + 3;
+        }
+
+        sb.append(string.substring(i));
 
-      for (int j = 0; (k = str.indexOf(symbol, j)) >= 0; j = k + 1) {
-         l += countQuotes(str, j, k);
-
-         if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) != 1) {
-            sb.append(trim(str.substring(i, k)) + replace);
-
-            i = k + 1;
-            l = 0;
-         }
-      }
-
-      sb.append(trim(str.substring(i)));
-
-      return sb.toString();
-   }
+        return sb.toString();
+    }
 
-   /**
-    * Returns the number of Quotation from i to j
-    *
-    * @param s
-    * @param i
-    * @param j
-    * @return number of quotes
-    */
-   private static int countQuotes(String s, int i, int j) {
-
-      int k = 0;
-
-      for (int l = i; l < j; l++) {
-         if (s.charAt(l) == '"') {
-            k++;
-         }
-      }
+    /**
+     * Method semicolonToComma
+     *
+     * @param str
+     * @return normalized string
+     */
+    static String semicolonToComma(String str) {
+        return removeWSandReplace(str, ";", ",");
+    }
 
-      return k;
-   }
-
-   //only for the end of a space character occurring at the end of the string from rfc2253
-
-   /**
-    * Method trim
-    *
-    * @param str
-    * @return the string
-    */
-   static String trim(String str) {
-
-      String trimed = str.trim();
-      int i = str.indexOf(trimed) + trimed.length();
+    /**
+     * Method removeWhiteSpace
+     *
+     * @param str
+     * @param symbol
+     * @return normalized string
+     */
+    static String removeWhiteSpace(String str, String symbol) {
+        return removeWSandReplace(str, symbol, symbol);
+    }
 
-      if ((str.length() > i) && trimed.endsWith("\\")
-              &&!trimed.endsWith("\\\\")) {
-         if (str.charAt(i) == ' ') {
-            trimed = trimed + " ";
-         }
-      }
+    /**
+     * Method removeWSandReplace
+     *
+     * @param str
+     * @param symbol
+     * @param replace
+     * @return normalized string
+     */
+    static String removeWSandReplace(String str, String symbol, String replace) {
+        StringBuilder sb = new StringBuilder();
+        int i = 0;
+        int l = 0;
+        int k;
 
-      return trimed;
-   }
+        for (int j = 0; (k = str.indexOf(symbol, j)) >= 0; j = k + 1) {
+            l += countQuotes(str, j, k);
 
-   /**
-    * Method main
-    *
-    * @param args
-    * @throws Exception
-    */
-   public static void main(String[] args) throws Exception {
+            if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) == 0) {
+                sb.append(trim(str.substring(i, k)) + replace);
 
-      testToXML("CN=\"Steve, Kille\",  O=Isode Limited, C=GB");
-      testToXML("CN=Steve Kille    ,   O=Isode Limited,C=GB");
-      testToXML("\\ OU=Sales+CN=J. Smith,O=Widget Inc.,C=US\\ \\ ");
-      testToXML("CN=L. Eagle,O=Sue\\, Grabbit and Runn,C=GB");
-      testToXML("CN=Before\\0DAfter,O=Test,C=GB");
-      testToXML("CN=\"L. Eagle,O=Sue, = + < > # ;Grabbit and Runn\",C=GB");
-      testToXML("1.3.6.1.4.1.1466.0=#04024869,O=Test,C=GB");
+                i = k + 1;
+                l = 0;
+            }
+        }
 
-      {
-         StringBuffer sb = new StringBuffer();
+        sb.append(trim(str.substring(i)));
+
+        return sb.toString();
+    }
 
-         sb.append('L');
-         sb.append('u');
-         sb.append('\uc48d');
-         sb.append('i');
-         sb.append('\uc487');
-
-         String test7 = "SN=" + sb.toString();
-
-         testToXML(test7);
-      }
-
-      testToRFC("CN=\"Steve, Kille\",  O=Isode Limited, C=GB");
-      testToRFC("CN=Steve Kille    ,   O=Isode Limited,C=GB");
-      testToRFC("\\20OU=Sales+CN=J. Smith,O=Widget Inc.,C=US\\20\\20 ");
-      testToRFC("CN=L. Eagle,O=Sue\\, Grabbit and Runn,C=GB");
-      testToRFC("CN=Before\\12After,O=Test,C=GB");
-      testToRFC("CN=\"L. Eagle,O=Sue, = + < > # ;Grabbit and Runn\",C=GB");
-      testToRFC("1.3.6.1.4.1.1466.0=\\#04024869,O=Test,C=GB");
-
-      {
-         StringBuffer sb = new StringBuffer();
+    /**
+     * Returns the number of Quotation from i to j
+     *
+     * @param s
+     * @param i
+     * @param j
+     * @return number of quotes
+     */
+    private static int countQuotes(String s, int i, int j) {
+        int k = 0;
 
-         sb.append('L');
-         sb.append('u');
-         sb.append('\uc48d');
-         sb.append('i');
-         sb.append('\uc487');
+        for (int l = i; l < j; l++) {
+            if (s.charAt(l) == '"') {
+                k++;
+            }
+        }
 
-         String test7 = "SN=" + sb.toString();
+        return k;
+    }
 
-         testToRFC(test7);
-      }
-   }
-
-   /** Field i */
-   static int counter = 0;
+    //only for the end of a space character occurring at the end of the string from rfc2253
 
-   /**
-    * Method test
-    *
-    * @param st
-    */
-   static void testToXML(String st) {
-
-      System.out.println("start " + counter++ + ": " + st);
-      System.out.println("         " + rfc2253toXMLdsig(st));
-      System.out.println("");
-   }
+    /**
+     * Method trim
+     *
+     * @param str
+     * @return the string
+     */
+    static String trim(String str) {
 
-   /**
-    * Method testToRFC
-    *
-    * @param st
-    */
-   static void testToRFC(String st) {
+        String trimed = str.trim();
+        int i = str.indexOf(trimed) + trimed.length();
 
-      System.out.println("start " + counter++ + ": " + st);
-      System.out.println("         " + xmldsigtoRFC2253(st));
-      System.out.println("");
-   }
+        if ((str.length() > i) && trimed.endsWith("\\")
+            && !trimed.endsWith("\\\\") && (str.charAt(i) == ' ')) {
+            trimed = trimed + " ";
+        }
+
+        return trimed;
+    }
+
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,70 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.utils;
+
+import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * Class SignatureElementProxy
+ *
+ * @author Brent Putman (putmanb@georgetown.edu)
+ */
+public abstract class Signature11ElementProxy extends ElementProxy {
+
+    protected Signature11ElementProxy() {
+    };
+
+    /**
+     * Constructor Signature11ElementProxy
+     *
+     * @param doc
+     */
+    public Signature11ElementProxy(Document doc) {
+        if (doc == null) {
+            throw new RuntimeException("Document is null");
+        }
+
+        this.doc = doc;
+        this.constructionElement =
+            XMLUtils.createElementInSignature11Space(this.doc, this.getBaseLocalName());
+    }
+
+    /**
+     * Constructor Signature11ElementProxy
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public Signature11ElementProxy(Element element, String BaseURI) throws XMLSecurityException {
+        super(element, BaseURI);
+
+    }
+
+    /** @inheritDoc */
+    public String getBaseNamespace() {
+        return Constants.SignatureSpec11NS;
+    }
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,70 +2,69 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
-
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-
 /**
  * Class SignatureElementProxy
  *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
+ * @author $Author: coheigea $
  */
 public abstract class SignatureElementProxy extends ElementProxy {
-        protected SignatureElementProxy() {
-        };
-   /**
-    * Constructor SignatureElementProxy
-    *
-    * @param doc
-    */
-   public SignatureElementProxy(Document doc) {
-              if (doc == null) {
-                 throw new RuntimeException("Document is null");
-              }
+
+    protected SignatureElementProxy() {
+    };
 
-              this._doc = doc;
-              this._constructionElement =  XMLUtils.createElementInSignatureSpace(this._doc,
-                           this.getBaseLocalName());
-   }
+    /**
+     * Constructor SignatureElementProxy
+     *
+     * @param doc
+     */
+    public SignatureElementProxy(Document doc) {
+        if (doc == null) {
+            throw new RuntimeException("Document is null");
+        }
 
-   /**
-    * Constructor SignatureElementProxy
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public SignatureElementProxy(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
+        this.doc = doc;
+        this.constructionElement =
+            XMLUtils.createElementInSignatureSpace(this.doc, this.getBaseLocalName());
+    }
 
-   }
+    /**
+     * Constructor SignatureElementProxy
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public SignatureElementProxy(Element element, String BaseURI) throws XMLSecurityException {
+        super(element, BaseURI);
 
-   /** @inheritDoc */
-   public String getBaseNamespace() {
-      return Constants.SignatureSpecNS;
-   }
+    }
+
+    /** @inheritDoc */
+    public String getBaseNamespace() {
+        return Constants.SignatureSpecNS;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 1999-2008 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
@@ -30,53 +32,50 @@
  *
  */
 public class SignerOutputStream extends ByteArrayOutputStream {
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(SignerOutputStream.class.getName());
+
     final SignatureAlgorithm sa;
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger
-        (SignerOutputStream.class.getName());
 
     /**
      * @param sa
      */
     public SignerOutputStream(SignatureAlgorithm sa) {
-        this.sa=sa;
+        this.sa = sa;
     }
 
     /** @inheritDoc */
     public void write(byte[] arg0)  {
-        super.write(arg0, 0, arg0.length);
         try {
             sa.update(arg0);
         } catch (XMLSignatureException e) {
-            throw new RuntimeException(""+e);
+            throw new RuntimeException("" + e);
         }
     }
 
     /** @inheritDoc */
     public void write(int arg0) {
-        super.write(arg0);
         try {
             sa.update((byte)arg0);
         } catch (XMLSignatureException e) {
-            throw new RuntimeException(""+e);
+            throw new RuntimeException("" + e);
         }
     }
 
     /** @inheritDoc */
     public void write(byte[] arg0, int arg1, int arg2) {
-        super.write(arg0, arg1, arg2);
         if (log.isLoggable(java.util.logging.Level.FINE)) {
             log.log(java.util.logging.Level.FINE, "Canonicalized SignedInfo:");
-            StringBuffer sb = new StringBuffer(arg2);
-            for (int i=arg1; i<(arg1+arg2); i++) {
-                sb.append((char) arg0[i]);
+            StringBuilder sb = new StringBuilder(arg2);
+            for (int i = arg1; i < (arg1 + arg2); i++) {
+                sb.append((char)arg0[i]);
             }
             log.log(java.util.logging.Level.FINE, sb.toString());
         }
         try {
-            sa.update(arg0,arg1,arg2);
+            sa.update(arg0, arg1, arg2);
         } catch (XMLSignatureException e) {
-            throw new RuntimeException(""+e);
+            throw new RuntimeException("" + e);
         }
     }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 1999-2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
@@ -24,75 +26,73 @@
 import java.io.OutputStream;
 
 /**
- * A class that buffers writte without synchronize its methods
+ * A class that buffers without synchronizing its methods
  * @author raul
- *
  */
 public class UnsyncBufferedOutputStream extends OutputStream {
-        final OutputStream out;
+    static final int size = 8*1024;
+
+    private int pointer = 0;
+    private final OutputStream out;
+
+    private final byte[] buf;
 
-        final byte[] buf;
-        static final int size=8*1024;
-        private static ThreadLocal<byte[]> bufCahce = new ThreadLocal<byte[]>() {
-        protected synchronized byte[] initialValue() {
-            return new byte[size];
-        }
-    };
-        int pointer=0;
-        /**
-         * Creates a buffered output stream without synchronization
-         * @param out the outputstream to buffer
-         */
-        public UnsyncBufferedOutputStream(OutputStream out) {
-                buf=bufCahce.get();
-                this.out=out;
-        }
+    /**
+     * Creates a buffered output stream without synchronization
+     * @param out the outputstream to buffer
+     */
+    public UnsyncBufferedOutputStream(OutputStream out) {
+        buf = new byte[size];
+        this.out = out;
+    }
 
-        /** @inheritDoc */
-        public void write(byte[] arg0) throws IOException {
-                write(arg0,0,arg0.length);
-        }
+    /** @inheritDoc */
+    public void write(byte[] arg0) throws IOException {
+        write(arg0, 0, arg0.length);
+    }
 
-        /** @inheritDoc */
-        public void write(byte[] arg0, int arg1, int len) throws IOException {
-                int newLen=pointer+len;
-                if (newLen> size) {
-                        flushBuffer();
-                        if (len>size) {
-                                out.write(arg0,arg1,len);
-                                return;
-                        }
-                        newLen=len;
-                }
-                System.arraycopy(arg0,arg1,buf,pointer,len);
-                pointer=newLen;
+    /** @inheritDoc */
+    public void write(byte[] arg0, int arg1, int len) throws IOException {
+        int newLen = pointer+len;
+        if (newLen > size) {
+            flushBuffer();
+            if (len > size) {
+                out.write(arg0, arg1,len);
+                return;
+            }
+            newLen = len;
         }
+        System.arraycopy(arg0, arg1, buf, pointer, len);
+        pointer = newLen;
+    }
 
-        private final void flushBuffer() throws IOException {
-                if (pointer>0)
-                        out.write(buf,0,pointer);
-                pointer=0;
-
+    private void flushBuffer() throws IOException {
+        if (pointer > 0) {
+            out.write(buf, 0, pointer);
         }
+        pointer = 0;
 
-        /** @inheritDoc */
-        public void write(int arg0) throws IOException {
-                if (pointer>= size) {
-                        flushBuffer();
-                }
-                buf[pointer++]=(byte)arg0;
+    }
 
+    /** @inheritDoc */
+    public void write(int arg0) throws IOException {
+        if (pointer >= size) {
+            flushBuffer();
         }
+        buf[pointer++] = (byte)arg0;
 
-        /** @inheritDoc */
-        public void flush() throws IOException {
-                flushBuffer();
-                out.flush();
-        }
+    }
 
-        /** @inheritDoc */
-        public void close() throws IOException {
-                flush();
-        }
+    /** @inheritDoc */
+    public void flush() throws IOException {
+        flushBuffer();
+        out.flush();
+    }
+
+    /** @inheritDoc */
+    public void close() throws IOException {
+        flush();
+        out.close();
+    }
 
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 1999-2010 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
@@ -28,22 +30,21 @@
  *
  */
 public class UnsyncByteArrayOutputStream extends OutputStream  {
+
     private static final int INITIAL_SIZE = 8192;
-    private static ThreadLocal<byte[]> bufCache = new ThreadLocal<byte[]>() {
-        protected synchronized byte[] initialValue() {
-            return new byte[INITIAL_SIZE];
-        }
-    };
 
     private byte[] buf;
     private int size = INITIAL_SIZE;
     private int pos = 0;
 
     public UnsyncByteArrayOutputStream() {
-        buf = bufCache.get();
+        buf = new byte[INITIAL_SIZE];
     }
 
     public void write(byte[] arg0) {
+        if ((Integer.MAX_VALUE - pos) < arg0.length) {
+            throw new OutOfMemoryError();
+        }
         int newPos = pos + arg0.length;
         if (newPos > size) {
             expandSize(newPos);
@@ -53,6 +54,9 @@
     }
 
     public void write(byte[] arg0, int arg1, int arg2) {
+        if ((Integer.MAX_VALUE - pos) < arg2) {
+            throw new OutOfMemoryError();
+        }
         int newPos = pos + arg2;
         if (newPos > size) {
             expandSize(newPos);
@@ -62,6 +66,9 @@
     }
 
     public void write(int arg0) {
+        if ((Integer.MAX_VALUE - pos) == 0) {
+            throw new OutOfMemoryError();
+        }
         int newPos = pos + 1;
         if (newPos > size) {
             expandSize(newPos);
@@ -82,7 +89,11 @@
     private void expandSize(int newPos) {
         int newSize = size;
         while (newPos > newSize) {
-            newSize = newSize<<2;
+            newSize = newSize << 1;
+            // Deal with overflow
+            if (newSize < 0) {
+                newSize = Integer.MAX_VALUE;
+            }
         }
         byte newBuf[] = new byte[newSize];
         System.arraycopy(buf, 0, newBuf, 0, pos);
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,35 +2,34 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
-
 import java.io.IOException;
 import java.io.OutputStream;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 import java.util.ArrayList;
-import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
-import java.util.Map;
 import java.util.Set;
 
 import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
@@ -42,10 +41,9 @@
 import org.w3c.dom.NamedNodeMap;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
+import org.w3c.dom.ProcessingInstruction;
 import org.w3c.dom.Text;
 
-
-
 /**
  * DOM and XML accessibility and comfort functions.
  *
@@ -53,28 +51,31 @@
  */
 public class XMLUtils {
 
-   private static boolean ignoreLineBreaks =
-      AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
-         public Boolean run() {
-            return Boolean.getBoolean
-               ("com.sun.org.apache.xml.internal.security.ignoreLineBreaks");
-         }
-      });
+    private static boolean ignoreLineBreaks =
+        AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
+            public Boolean run() {
+                return Boolean.valueOf(Boolean.getBoolean
+                    ("com.sun.org.apache.xml.internal.security.ignoreLineBreaks"));
+            }
+        }).booleanValue();
 
     private static volatile String dsPrefix = "ds";
+    private static volatile String ds11Prefix = "dsig11";
     private static volatile String xencPrefix = "xenc";
+    private static volatile String xenc11Prefix = "xenc11";
 
-   private static final java.util.logging.Logger log =
-       java.util.logging.Logger.getLogger(XMLUtils.class.getName());
+    /** {@link org.apache.commons.logging} logging facility */
+    private static final java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(XMLUtils.class.getName());
 
-   /**
-    * Constructor XMLUtils
-    *
-    */
-   private XMLUtils() {
 
-      // we don't allow instantiation
-   }
+    /**
+     * Constructor XMLUtils
+     *
+     */
+    private XMLUtils() {
+        // we don't allow instantiation
+    }
 
     /**
      * Set the prefix for the digital signature namespace
@@ -85,6 +86,14 @@
     }
 
     /**
+     * Set the prefix for the digital signature 1.1 namespace
+     * @param prefix the new prefix for the digital signature 1.1 namespace
+     */
+    public static void setDs11Prefix(String prefix) {
+        ds11Prefix = prefix;
+    }
+
+    /**
      * Set the prefix for the encryption namespace
      * @param prefix the new prefix for the encryption namespace
      */
@@ -92,197 +101,256 @@
         xencPrefix = prefix;
     }
 
-   public static Element getNextElement(Node el) {
-           while ((el!=null) && (el.getNodeType()!=Node.ELEMENT_NODE)) {
-                   el=el.getNextSibling();
-           }
-           return (Element)el;
-
-   }
+    /**
+     * Set the prefix for the encryption namespace 1.1
+     * @param prefix the new prefix for the encryption namespace 1.1
+     */
+    public static void setXenc11Prefix(String prefix) {
+        xenc11Prefix = prefix;
+    }
 
-   /**
-    * @param rootNode
-    * @param result
-    * @param exclude
-    * @param com wheather comments or not
-    */
-   public static void getSet(Node rootNode,Set<Node> result,Node exclude ,boolean com) {
-          if ((exclude!=null) && isDescendantOrSelf(exclude,rootNode)){
-                return;
-      }
-      getSetRec(rootNode,result,exclude,com);
-   }
+    public static Element getNextElement(Node el) {
+        Node node = el;
+        while ((node != null) && (node.getNodeType() != Node.ELEMENT_NODE)) {
+            node = node.getNextSibling();
+        }
+        return (Element)node;
+    }
+
+    /**
+     * @param rootNode
+     * @param result
+     * @param exclude
+     * @param com whether comments or not
+     */
+    public static void getSet(Node rootNode, Set<Node> result, Node exclude, boolean com) {
+        if ((exclude != null) && isDescendantOrSelf(exclude, rootNode)) {
+            return;
+        }
+        getSetRec(rootNode, result, exclude, com);
+    }
 
-   @SuppressWarnings("fallthrough")
-   static final void getSetRec(final Node rootNode,final Set<Node> result,
-        final Node exclude ,final boolean com) {
-           //Set result = new HashSet();
-       if (rootNode==exclude) {
-          return;
-       }
-           switch (rootNode.getNodeType()) {
-                case Node.ELEMENT_NODE:
-                                result.add(rootNode);
-                        Element el=(Element)rootNode;
-                if (el.hasAttributes()) {
-                                NamedNodeMap nl = ((Element)rootNode).getAttributes();
-                                for (int i=0;i<nl.getLength();i++) {
-                                        result.add(nl.item(i));
-                                }
+    @SuppressWarnings("fallthrough")
+    private static void getSetRec(final Node rootNode, final Set<Node> result,
+                                final Node exclude, final boolean com) {
+        if (rootNode == exclude) {
+            return;
+        }
+        switch (rootNode.getNodeType()) {
+        case Node.ELEMENT_NODE:
+            result.add(rootNode);
+            Element el = (Element)rootNode;
+            if (el.hasAttributes()) {
+                NamedNodeMap nl = el.getAttributes();
+                for (int i = 0;i < nl.getLength(); i++) {
+                    result.add(nl.item(i));
                 }
-                //no return keep working - ignore fallthrough warning
-                case Node.DOCUMENT_NODE:
-                                for (Node r=rootNode.getFirstChild();r!=null;r=r.getNextSibling()){
-                                        if (r.getNodeType()==Node.TEXT_NODE) {
-                                                result.add(r);
-                                                while ((r!=null) && (r.getNodeType()==Node.TEXT_NODE)) {
-                                                        r=r.getNextSibling();
-                                                }
-                                                if (r==null)
-                                                        return;
-                                        }
-                                        getSetRec(r,result,exclude,com);
-                                }
-                                return;
-                        case Node.COMMENT_NODE:
-                                if (com) {
-                                        result.add(rootNode);
-                                }
-                            return;
-                        case Node.DOCUMENT_TYPE_NODE:
-                                return;
-                        default:
-                                result.add(rootNode);
-           }
-           return;
-   }
+            }
+            //no return keep working
+        case Node.DOCUMENT_NODE:
+            for (Node r = rootNode.getFirstChild(); r != null; r = r.getNextSibling()) {
+                if (r.getNodeType() == Node.TEXT_NODE) {
+                    result.add(r);
+                    while ((r != null) && (r.getNodeType() == Node.TEXT_NODE)) {
+                        r = r.getNextSibling();
+                    }
+                    if (r == null) {
+                        return;
+                    }
+                }
+                getSetRec(r, result, exclude, com);
+            }
+            return;
+        case Node.COMMENT_NODE:
+            if (com) {
+                result.add(rootNode);
+            }
+            return;
+        case Node.DOCUMENT_TYPE_NODE:
+            return;
+        default:
+            result.add(rootNode);
+        }
+    }
 
 
-   /**
-    * Outputs a DOM tree to an {@link OutputStream}.
-    *
-    * @param contextNode root node of the DOM tree
-    * @param os the {@link OutputStream}
-    */
-   public static void outputDOM(Node contextNode, OutputStream os) {
-      XMLUtils.outputDOM(contextNode, os, false);
-   }
+    /**
+     * Outputs a DOM tree to an {@link OutputStream}.
+     *
+     * @param contextNode root node of the DOM tree
+     * @param os the {@link OutputStream}
+     */
+    public static void outputDOM(Node contextNode, OutputStream os) {
+        XMLUtils.outputDOM(contextNode, os, false);
+    }
 
-   /**
-    * Outputs a DOM tree to an {@link OutputStream}. <I>If an Exception is
-    * thrown during execution, it's StackTrace is output to System.out, but the
-    * Exception is not re-thrown.</I>
-    *
-    * @param contextNode root node of the DOM tree
-    * @param os the {@link OutputStream}
-    * @param addPreamble
-    */
-   public static void outputDOM(Node contextNode, OutputStream os,
-                                boolean addPreamble) {
+    /**
+     * Outputs a DOM tree to an {@link OutputStream}. <I>If an Exception is
+     * thrown during execution, it's StackTrace is output to System.out, but the
+     * Exception is not re-thrown.</I>
+     *
+     * @param contextNode root node of the DOM tree
+     * @param os the {@link OutputStream}
+     * @param addPreamble
+     */
+    public static void outputDOM(Node contextNode, OutputStream os, boolean addPreamble) {
+        try {
+            if (addPreamble) {
+                os.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes("UTF-8"));
+            }
 
-      try {
-         if (addPreamble) {
-            os.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes());
-         }
+            os.write(Canonicalizer.getInstance(
+                Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(contextNode)
+            );
+        } catch (IOException ex) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
+            }
+        }
+        catch (InvalidCanonicalizerException ex) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
+            }
+        } catch (CanonicalizationException ex) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
+            }
+        }
+    }
 
-         os.write(
-            Canonicalizer.getInstance(
-               Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(
-               contextNode));
-      } catch (IOException ex) {}
-      catch (InvalidCanonicalizerException ex) {
-         ex.printStackTrace();
-      } catch (CanonicalizationException ex) {
-         ex.printStackTrace();
-      }
-   }
+    /**
+     * Serializes the <CODE>contextNode</CODE> into the OutputStream, <I>but
+     * suppresses all Exceptions</I>.
+     * <BR />
+     * NOTE: <I>This should only be used for debugging purposes,
+     * NOT in a production environment; this method ignores all exceptions,
+     * so you won't notice if something goes wrong. If you're asking what is to
+     * be used in a production environment, simply use the code inside the
+     * <code>try{}</code> statement, but handle the Exceptions appropriately.</I>
+     *
+     * @param contextNode
+     * @param os
+     */
+    public static void outputDOMc14nWithComments(Node contextNode, OutputStream os) {
+        try {
+            os.write(Canonicalizer.getInstance(
+                Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(contextNode)
+            );
+        } catch (IOException ex) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
+            }
+            // throw new RuntimeException(ex.getMessage());
+        } catch (InvalidCanonicalizerException ex) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
+            }
+            // throw new RuntimeException(ex.getMessage());
+        } catch (CanonicalizationException ex) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
+            }
+            // throw new RuntimeException(ex.getMessage());
+        }
+    }
 
-   /**
-    * Serializes the <CODE>contextNode</CODE> into the OutputStream, <I>but
-    * supresses all Exceptions</I>.
-    * <BR />
-    * NOTE: <I>This should only be used for debugging purposes,
-    * NOT in a production environment; this method ignores all exceptions,
-    * so you won't notice if something goes wrong. If you're asking what is to
-    * be used in a production environment, simply use the code inside the
-    * <code>try{}</code> statement, but handle the Exceptions appropriately.</I>
-    *
-    * @param contextNode
-    * @param os
-    */
-   public static void outputDOMc14nWithComments(Node contextNode,
-           OutputStream os) {
-
-      try {
-         os.write(
-            Canonicalizer.getInstance(
-               Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(
-               contextNode));
-      } catch (IOException ex) {
+    /**
+     * Method getFullTextChildrenFromElement
+     *
+     * @param element
+     * @return the string of children
+     */
+    public static String getFullTextChildrenFromElement(Element element) {
+        StringBuilder sb = new StringBuilder();
 
-         // throw new RuntimeException(ex.getMessage());
-      } catch (InvalidCanonicalizerException ex) {
+        Node child = element.getFirstChild();
+        while (child != null) {
+            if (child.getNodeType() == Node.TEXT_NODE) {
+                sb.append(((Text)child).getData());
+            }
+            child = child.getNextSibling();
+        }
 
-         // throw new RuntimeException(ex.getMessage());
-      } catch (CanonicalizationException ex) {
-
-         // throw new RuntimeException(ex.getMessage());
-      }
-   }
-
+        return sb.toString();
+    }
 
-   /**
-    * Method getFullTextChildrenFromElement
-    *
-    * @param element
-    * @return the string of chi;ds
-    */
-   public static String getFullTextChildrenFromElement(Element element) {
+    /**
+     * Creates an Element in the XML Signature specification namespace.
+     *
+     * @param doc the factory Document
+     * @param elementName the local name of the Element
+     * @return the Element
+     */
+    public static Element createElementInSignatureSpace(Document doc, String elementName) {
+        if (doc == null) {
+            throw new RuntimeException("Document is null");
+        }
 
-      StringBuffer sb = new StringBuffer();
-      NodeList children = element.getChildNodes();
-      int iMax = children.getLength();
+        if ((dsPrefix == null) || (dsPrefix.length() == 0)) {
+            return doc.createElementNS(Constants.SignatureSpecNS, elementName);
+        }
+        return doc.createElementNS(Constants.SignatureSpecNS, dsPrefix + ":" + elementName);
+    }
 
-      for (int i = 0; i < iMax; i++) {
-         Node curr = children.item(i);
-
-         if (curr.getNodeType() == Node.TEXT_NODE) {
-            sb.append(((Text) curr).getData());
-         }
-      }
+    /**
+     * Creates an Element in the XML Signature 1.1 specification namespace.
+     *
+     * @param doc the factory Document
+     * @param elementName the local name of the Element
+     * @return the Element
+     */
+    public static Element createElementInSignature11Space(Document doc, String elementName) {
+        if (doc == null) {
+            throw new RuntimeException("Document is null");
+        }
 
-      return sb.toString();
-   }
-
-   static Map<String, String> namePrefixes=new HashMap<String, String>();
+        if ((ds11Prefix == null) || (ds11Prefix.length() == 0)) {
+            return doc.createElementNS(Constants.SignatureSpec11NS, elementName);
+        }
+        return doc.createElementNS(Constants.SignatureSpec11NS, ds11Prefix + ":" + elementName);
+    }
 
-   /**
-    * Creates an Element in the XML Signature specification namespace.
-    *
-    * @param doc the factory Document
-    * @param elementName the local name of the Element
-    * @return the Element
-    */
-   public static Element createElementInSignatureSpace(Document doc,
-           String elementName) {
+    /**
+     * Creates an Element in the XML Encryption specification namespace.
+     *
+     * @param doc the factory Document
+     * @param elementName the local name of the Element
+     * @return the Element
+     */
+    public static Element createElementInEncryptionSpace(Document doc, String elementName) {
+        if (doc == null) {
+            throw new RuntimeException("Document is null");
+        }
 
-      if (doc == null) {
-         throw new RuntimeException("Document is null");
-      }
+        if ((xencPrefix == null) || (xencPrefix.length() == 0)) {
+            return doc.createElementNS(EncryptionConstants.EncryptionSpecNS, elementName);
+        }
+        return
+            doc.createElementNS(
+                EncryptionConstants.EncryptionSpecNS, xencPrefix + ":" + elementName
+            );
+    }
 
-      if ((dsPrefix == null) || (dsPrefix.length() == 0)) {
-         return doc.createElementNS(Constants.SignatureSpecNS, elementName);
-      }
-      String namePrefix= namePrefixes.get(elementName);
-      if (namePrefix==null) {
-          StringBuffer tag=new StringBuffer(dsPrefix);
-          tag.append(':');
-          tag.append(elementName);
-          namePrefix=tag.toString();
-          namePrefixes.put(elementName,namePrefix);
-      }
-      return doc.createElementNS(Constants.SignatureSpecNS, namePrefix);
-   }
+    /**
+     * Creates an Element in the XML Encryption 1.1 specification namespace.
+     *
+     * @param doc the factory Document
+     * @param elementName the local name of the Element
+     * @return the Element
+     */
+    public static Element createElementInEncryption11Space(Document doc, String elementName) {
+        if (doc == null) {
+            throw new RuntimeException("Document is null");
+        }
+
+        if ((xenc11Prefix == null) || (xenc11Prefix.length() == 0)) {
+            return doc.createElementNS(EncryptionConstants.EncryptionSpec11NS, elementName);
+        }
+        return
+            doc.createElementNS(
+                EncryptionConstants.EncryptionSpec11NS, xenc11Prefix + ":" + elementName
+            );
+    }
 
     /**
      * Returns true if the element is in XML Signature namespace and the local
@@ -290,14 +358,33 @@
      *
      * @param element
      * @param localName
-     * @return true if the element is in XML Signature namespace and the local name equals the supplied one
+     * @return true if the element is in XML Signature namespace and the local name equals
+     * the supplied one
      */
     public static boolean elementIsInSignatureSpace(Element element, String localName) {
+        if (element == null){
+            return false;
+        }
+
+        return Constants.SignatureSpecNS.equals(element.getNamespaceURI())
+            && element.getLocalName().equals(localName);
+    }
+
+    /**
+     * Returns true if the element is in XML Signature 1.1 namespace and the local
+     * name equals the supplied one.
+     *
+     * @param element
+     * @param localName
+     * @return true if the element is in XML Signature namespace and the local name equals
+     * the supplied one
+     */
+    public static boolean elementIsInSignature11Space(Element element, String localName) {
         if (element == null) {
             return false;
         }
 
-        return Constants.SignatureSpecNS.equals(element.getNamespaceURI())
+        return Constants.SignatureSpec11NS.equals(element.getNamespaceURI())
             && element.getLocalName().equals(localName);
     }
 
@@ -307,42 +394,58 @@
      *
      * @param element
      * @param localName
-     * @return true if the element is in XML Encryption namespace and the local name equals the supplied one
+     * @return true if the element is in XML Encryption namespace and the local name
+     * equals the supplied one
      */
     public static boolean elementIsInEncryptionSpace(Element element, String localName) {
-        if (element == null) {
+        if (element == null){
             return false;
         }
         return EncryptionConstants.EncryptionSpecNS.equals(element.getNamespaceURI())
             && element.getLocalName().equals(localName);
     }
 
-   /**
-    * This method returns the owner document of a particular node.
-    * This method is necessary because it <I>always</I> returns a
-    * {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE>
-    * if the {@link Node} is a {@link Document}.
-    *
-    * @param node
-    * @return the owner document of the node
-    */
-   public static Document getOwnerDocument(Node node) {
+    /**
+     * Returns true if the element is in XML Encryption 1.1 namespace and the local
+     * name equals the supplied one.
+     *
+     * @param element
+     * @param localName
+     * @return true if the element is in XML Encryption 1.1 namespace and the local name
+     * equals the supplied one
+     */
+    public static boolean elementIsInEncryption11Space(Element element, String localName) {
+        if (element == null){
+            return false;
+        }
+        return EncryptionConstants.EncryptionSpec11NS.equals(element.getNamespaceURI())
+            && element.getLocalName().equals(localName);
+    }
 
-      if (node.getNodeType() == Node.DOCUMENT_NODE) {
-         return (Document) node;
-      }
-         try {
+    /**
+     * This method returns the owner document of a particular node.
+     * This method is necessary because it <I>always</I> returns a
+     * {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE>
+     * if the {@link Node} is a {@link Document}.
+     *
+     * @param node
+     * @return the owner document of the node
+     */
+    public static Document getOwnerDocument(Node node) {
+        if (node.getNodeType() == Node.DOCUMENT_NODE) {
+            return (Document) node;
+        }
+        try {
             return node.getOwnerDocument();
-         } catch (NullPointerException npe) {
+        } catch (NullPointerException npe) {
             throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0")
                                            + " Original message was \""
                                            + npe.getMessage() + "\"");
-         }
-
-   }
+        }
+    }
 
     /**
-     * This method returns the first non-null owner document of the Node's in this Set.
+     * This method returns the first non-null owner document of the Nodes in this Set.
      * This method is necessary because it <I>always</I> returns a
      * {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE>
      * if the {@link Node} is a {@link Document}.
@@ -351,23 +454,23 @@
      * @return the owner document
      */
     public static Document getOwnerDocument(Set<Node> xpathNodeSet) {
-       NullPointerException npe = null;
-       for (Node node : xpathNodeSet) {
-           int nodeType =node.getNodeType();
-           if (nodeType == Node.DOCUMENT_NODE) {
-              return (Document) node;
-           }
-              try {
-                 if (nodeType==Node.ATTRIBUTE_NODE) {
+        NullPointerException npe = null;
+        for (Node node : xpathNodeSet) {
+            int nodeType = node.getNodeType();
+            if (nodeType == Node.DOCUMENT_NODE) {
+                return (Document) node;
+            }
+            try {
+                if (nodeType == Node.ATTRIBUTE_NODE) {
                     return ((Attr)node).getOwnerElement().getOwnerDocument();
-                 }
-                 return node.getOwnerDocument();
-              } catch (NullPointerException e) {
-                  npe = e;
-              }
+                }
+                return node.getOwnerDocument();
+            } catch (NullPointerException e) {
+                npe = e;
+            }
+        }
 
-       }
-       throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0")
+        throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0")
                                        + " Original message was \""
                                        + (npe == null ? "" : npe.getMessage()) + "\"");
     }
@@ -380,165 +483,161 @@
      * @param namespace
      * @return the element.
      */
-    public static Element createDSctx(Document doc, String prefix,
-                                      String namespace) {
+    public static Element createDSctx(Document doc, String prefix, String namespace) {
+        if ((prefix == null) || (prefix.trim().length() == 0)) {
+            throw new IllegalArgumentException("You must supply a prefix");
+        }
+
+        Element ctx = doc.createElementNS(null, "namespaceContext");
+
+        ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(), namespace);
+
+        return ctx;
+    }
 
-       if ((prefix == null) || (prefix.trim().length() == 0)) {
-          throw new IllegalArgumentException("You must supply a prefix");
-       }
+    /**
+     * Method addReturnToElement
+     *
+     * @param e
+     */
+    public static void addReturnToElement(Element e) {
+        if (!ignoreLineBreaks) {
+            Document doc = e.getOwnerDocument();
+            e.appendChild(doc.createTextNode("\n"));
+        }
+    }
 
-       Element ctx = doc.createElementNS(null, "namespaceContext");
+    public static void addReturnToElement(Document doc, HelperNodeList nl) {
+        if (!ignoreLineBreaks) {
+            nl.appendChild(doc.createTextNode("\n"));
+        }
+    }
+
+    public static void addReturnBeforeChild(Element e, Node child) {
+        if (!ignoreLineBreaks) {
+            Document doc = e.getOwnerDocument();
+            e.insertBefore(doc.createTextNode("\n"), child);
+        }
+    }
 
-       ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(),
-                          namespace);
+    /**
+     * Method convertNodelistToSet
+     *
+     * @param xpathNodeSet
+     * @return the set with the nodelist
+     */
+    public static Set<Node> convertNodelistToSet(NodeList xpathNodeSet) {
+        if (xpathNodeSet == null) {
+            return new HashSet<Node>();
+        }
 
-       return ctx;
+        int length = xpathNodeSet.getLength();
+        Set<Node> set = new HashSet<Node>(length);
+
+        for (int i = 0; i < length; i++) {
+            set.add(xpathNodeSet.item(i));
+        }
+
+        return set;
     }
 
-   /**
-    * Method addReturnToElement
-    *
-    * @param e
-    */
-   public static void addReturnToElement(Element e) {
-
-      if (!ignoreLineBreaks) {
-         Document doc = e.getOwnerDocument();
-         e.appendChild(doc.createTextNode("\n"));
-      }
-   }
-
-   public static void addReturnToElement(Document doc, HelperNodeList nl) {
-      if (!ignoreLineBreaks) {
-         nl.appendChild(doc.createTextNode("\n"));
-      }
-   }
-
-   public static void addReturnBeforeChild(Element e, Node child) {
-      if (!ignoreLineBreaks) {
-         Document doc = e.getOwnerDocument();
-         e.insertBefore(doc.createTextNode("\n"), child);
-      }
-   }
-
-   /**
-    * Method convertNodelistToSet
-    *
-    * @param xpathNodeSet
-    * @return the set with the nodelist
-    */
-   public static Set<Node> convertNodelistToSet(NodeList xpathNodeSet) {
+    /**
+     * This method spreads all namespace attributes in a DOM document to their
+     * children. This is needed because the XML Signature XPath transform
+     * must evaluate the XPath against all nodes in the input, even against
+     * XPath namespace nodes. Through a bug in XalanJ2, the namespace nodes are
+     * not fully visible in the Xalan XPath model, so we have to do this by
+     * hand in DOM spaces so that the nodes become visible in XPath space.
+     *
+     * @param doc
+     * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">
+     * Namespace axis resolution is not XPath compliant </A>
+     */
+    public static void circumventBug2650(Document doc) {
 
-      if (xpathNodeSet == null) {
-         return new HashSet<Node>();
-      }
-
-      int length = xpathNodeSet.getLength();
-      Set<Node> set = new HashSet<Node>(length);
+        Element documentElement = doc.getDocumentElement();
 
-      for (int i = 0; i < length; i++) {
-         set.add(xpathNodeSet.item(i));
-      }
-
-      return set;
-   }
-
+        // if the document element has no xmlns definition, we add xmlns=""
+        Attr xmlnsAttr =
+            documentElement.getAttributeNodeNS(Constants.NamespaceSpecNS, "xmlns");
 
-   /**
-    * This method spreads all namespace attributes in a DOM document to their
-    * children. This is needed because the XML Signature XPath transform
-    * must evaluate the XPath against all nodes in the input, even against
-    * XPath namespace nodes. Through a bug in XalanJ2, the namespace nodes are
-    * not fully visible in the Xalan XPath model, so we have to do this by
-    * hand in DOM spaces so that the nodes become visible in XPath space.
-    *
-    * @param doc
-    * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">Namespace axis resolution is not XPath compliant </A>
-    */
-   public static void circumventBug2650(Document doc) {
+        if (xmlnsAttr == null) {
+            documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "");
+        }
 
-      Element documentElement = doc.getDocumentElement();
-
-      // if the document element has no xmlns definition, we add xmlns=""
-      Attr xmlnsAttr =
-         documentElement.getAttributeNodeNS(Constants.NamespaceSpecNS, "xmlns");
+        XMLUtils.circumventBug2650internal(doc);
+    }
 
-      if (xmlnsAttr == null) {
-         documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "");
-      }
-
-      XMLUtils.circumventBug2650internal(doc);
-   }
-
-   /**
-    * This is the work horse for {@link #circumventBug2650}.
-    *
-    * @param node
-    * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">Namespace axis resolution is not XPath compliant </A>
-    */
-   @SuppressWarnings("fallthrough")
-   private static void circumventBug2650internal(Node node) {
-           Node parent=null;
-           Node sibling=null;
-           final String namespaceNs=Constants.NamespaceSpecNS;
-           do {
-         switch (node.getNodeType()) {
-         case Node.ELEMENT_NODE :
-                 Element element = (Element) node;
-             if (!element.hasChildNodes())
-                 break;
-             if (element.hasAttributes()) {
-             NamedNodeMap attributes = element.getAttributes();
-             int attributesLength = attributes.getLength();
-
-             for (Node child = element.getFirstChild(); child!=null;
-                child=child.getNextSibling()) {
-
-                if (child.getNodeType() != Node.ELEMENT_NODE) {
-                        continue;
+    /**
+     * This is the work horse for {@link #circumventBug2650}.
+     *
+     * @param node
+     * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">
+     * Namespace axis resolution is not XPath compliant </A>
+     */
+    @SuppressWarnings("fallthrough")
+    private static void circumventBug2650internal(Node node) {
+        Node parent = null;
+        Node sibling = null;
+        final String namespaceNs = Constants.NamespaceSpecNS;
+        do {
+            switch (node.getNodeType()) {
+            case Node.ELEMENT_NODE :
+                Element element = (Element) node;
+                if (!element.hasChildNodes()) {
+                    break;
                 }
-                Element childElement = (Element) child;
+                if (element.hasAttributes()) {
+                    NamedNodeMap attributes = element.getAttributes();
+                    int attributesLength = attributes.getLength();
+
+                    for (Node child = element.getFirstChild(); child!=null;
+                        child = child.getNextSibling()) {
 
-                for (int i = 0; i < attributesLength; i++) {
-                        Attr currentAttr = (Attr) attributes.item(i);
-                        if (namespaceNs!=currentAttr.getNamespaceURI())
+                        if (child.getNodeType() != Node.ELEMENT_NODE) {
+                            continue;
+                        }
+                        Element childElement = (Element) child;
+
+                        for (int i = 0; i < attributesLength; i++) {
+                            Attr currentAttr = (Attr) attributes.item(i);
+                            if (!namespaceNs.equals(currentAttr.getNamespaceURI())) {
                                 continue;
-                        if (childElement.hasAttributeNS(namespaceNs,
-                                                        currentAttr.getLocalName())) {
-                                        continue;
+                            }
+                            if (childElement.hasAttributeNS(namespaceNs,
+                                                            currentAttr.getLocalName())) {
+                                continue;
+                            }
+                            childElement.setAttributeNS(namespaceNs,
+                                                        currentAttr.getName(),
+                                                        currentAttr.getNodeValue());
                         }
-                        childElement.setAttributeNS(namespaceNs,
-                                                currentAttr.getName(),
-                                                currentAttr.getNodeValue());
-
-
+                    }
                 }
-             }
-             }
-         case Node.ENTITY_REFERENCE_NODE :
-         case Node.DOCUMENT_NODE :
-                 parent=node;
-                 sibling=node.getFirstChild();
-             break;
-         }
-         while ((sibling==null) && (parent!=null)) {
-                         sibling=parent.getNextSibling();
-                         parent=parent.getParentNode();
-                 };
-       if (sibling==null) {
-                         return;
-                 }
+            case Node.ENTITY_REFERENCE_NODE :
+            case Node.DOCUMENT_NODE :
+                parent = node;
+                sibling = node.getFirstChild();
+                break;
+            }
+            while ((sibling == null) && (parent != null)) {
+                sibling = parent.getNextSibling();
+                parent = parent.getParentNode();
+            }
+            if (sibling == null) {
+                return;
+            }
 
-         node=sibling;
-         sibling=node.getNextSibling();
-           } while (true);
-   }
+            node = sibling;
+            sibling = node.getNextSibling();
+        } while (true);
+    }
 
     /**
      * @param sibling
      * @param nodeName
      * @param number
-     * @return nodes with the constrain
+     * @return nodes with the constraint
      */
     public static Element selectDsNode(Node sibling, String nodeName, int number) {
         while (sibling != null) {
@@ -558,6 +657,26 @@
      * @param sibling
      * @param nodeName
      * @param number
+     * @return nodes with the constraint
+     */
+    public static Element selectDs11Node(Node sibling, String nodeName, int number) {
+        while (sibling != null) {
+            if (Constants.SignatureSpec11NS.equals(sibling.getNamespaceURI())
+                && sibling.getLocalName().equals(nodeName)) {
+                if (number == 0){
+                    return (Element)sibling;
+                }
+                number--;
+            }
+            sibling = sibling.getNextSibling();
+        }
+        return null;
+    }
+
+    /**
+     * @param sibling
+     * @param nodeName
+     * @param number
      * @return nodes with the constrain
      */
     public static Element selectXencNode(Node sibling, String nodeName, int number) {
@@ -574,42 +693,61 @@
         return null;
     }
 
-   /**
-    * @param sibling
-    * @param nodeName
-    * @param number
-    * @return nodes with the constrain
-    */
-   public static Text selectDsNodeText(Node sibling, String nodeName, int number) {
-            Node n=selectDsNode(sibling,nodeName,number);
-        if (n==null) {
-                return null;
+
+    /**
+     * @param sibling
+     * @param nodeName
+     * @param number
+     * @return nodes with the constrain
+     */
+    public static Text selectDsNodeText(Node sibling, String nodeName, int number) {
+        Node n = selectDsNode(sibling,nodeName,number);
+        if (n == null) {
+            return null;
         }
-        n=n.getFirstChild();
-        while (n!=null && n.getNodeType()!=Node.TEXT_NODE) {
-                n=n.getNextSibling();
+        n = n.getFirstChild();
+        while (n != null && n.getNodeType() != Node.TEXT_NODE) {
+            n = n.getNextSibling();
         }
         return (Text)n;
-   }
+    }
 
-   /**
-    * @param sibling
-    * @param uri
-    * @param nodeName
-    * @param number
-    * @return nodes with the constrain
-    */
-   public static Text selectNodeText(Node sibling, String uri, String nodeName, int number) {
-        Node n=selectNode(sibling,uri,nodeName,number);
-    if (n==null) {
-        return null;
+    /**
+     * @param sibling
+     * @param nodeName
+     * @param number
+     * @return nodes with the constrain
+     */
+    public static Text selectDs11NodeText(Node sibling, String nodeName, int number) {
+        Node n = selectDs11Node(sibling,nodeName,number);
+        if (n == null) {
+            return null;
+        }
+        n = n.getFirstChild();
+        while (n != null && n.getNodeType() != Node.TEXT_NODE) {
+            n = n.getNextSibling();
+        }
+        return (Text)n;
     }
-    n=n.getFirstChild();
-    while (n!=null && n.getNodeType()!=Node.TEXT_NODE) {
-        n=n.getNextSibling();
+
+    /**
+     * @param sibling
+     * @param uri
+     * @param nodeName
+     * @param number
+     * @return nodes with the constrain
+     */
+    public static Text selectNodeText(Node sibling, String uri, String nodeName, int number) {
+        Node n = selectNode(sibling,uri,nodeName,number);
+        if (n == null) {
+            return null;
+        }
+        n = n.getFirstChild();
+        while (n != null && n.getNodeType() != Node.TEXT_NODE) {
+            n = n.getNextSibling();
+        }
+        return (Text)n;
     }
-    return (Text)n;
-   }
 
     /**
      * @param sibling
@@ -638,16 +776,25 @@
      * @return nodes with the constrain
      */
     public static Element[] selectDsNodes(Node sibling, String nodeName) {
-        return selectNodes(sibling,Constants.SignatureSpecNS, nodeName);
+        return selectNodes(sibling, Constants.SignatureSpecNS, nodeName);
+    }
+
+    /**
+     * @param sibling
+     * @param nodeName
+     * @return nodes with the constrain
+     */
+    public static Element[] selectDs11Nodes(Node sibling, String nodeName) {
+        return selectNodes(sibling, Constants.SignatureSpec11NS, nodeName);
     }
 
     /**
      * @param sibling
      * @param uri
      * @param nodeName
-     * @return nodes with the constrain
+     * @return nodes with the constraint
      */
-     public static Element[] selectNodes(Node sibling, String uri, String nodeName) {
+    public static Element[] selectNodes(Node sibling, String uri, String nodeName) {
         List<Element> list = new ArrayList<Element>();
         while (sibling != null) {
             if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri)
@@ -659,73 +806,117 @@
         return list.toArray(new Element[list.size()]);
     }
 
-   /**
-    * @param signatureElement
-    * @param inputSet
-    * @return nodes with the constrain
-    */
+    /**
+     * @param signatureElement
+     * @param inputSet
+     * @return nodes with the constrain
+     */
     public static Set<Node> excludeNodeFromSet(Node signatureElement, Set<Node> inputSet) {
-          Set<Node> resultSet = new HashSet<Node>();
-          Iterator<Node> iterator = inputSet.iterator();
+        Set<Node> resultSet = new HashSet<Node>();
+        Iterator<Node> iterator = inputSet.iterator();
 
-          while (iterator.hasNext()) {
+        while (iterator.hasNext()) {
             Node inputNode = iterator.next();
 
-            if (!XMLUtils
-                    .isDescendantOrSelf(signatureElement, inputNode)) {
-               resultSet.add(inputNode);
+            if (!XMLUtils.isDescendantOrSelf(signatureElement, inputNode)) {
+                resultSet.add(inputNode);
             }
-         }
-         return resultSet;
-     }
+        }
+        return resultSet;
+    }
 
-   /**
-    * Returns true if the descendantOrSelf is on the descendant-or-self axis
-    * of the context node.
-    *
-    * @param ctx
-    * @param descendantOrSelf
-    * @return true if the node is descendant
-    */
-   static public boolean isDescendantOrSelf(Node ctx, Node descendantOrSelf) {
+    /**
+     * Method getStrFromNode
+     *
+     * @param xpathnode
+     * @return the string for the node.
+     */
+    public static String getStrFromNode(Node xpathnode) {
+        if (xpathnode.getNodeType() == Node.TEXT_NODE) {
+            // we iterate over all siblings of the context node because eventually,
+            // the text is "polluted" with pi's or comments
+            StringBuilder sb = new StringBuilder();
+
+            for (Node currentSibling = xpathnode.getParentNode().getFirstChild();
+                currentSibling != null;
+                currentSibling = currentSibling.getNextSibling()) {
+                if (currentSibling.getNodeType() == Node.TEXT_NODE) {
+                    sb.append(((Text) currentSibling).getData());
+                }
+            }
+
+            return sb.toString();
+        } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) {
+            return ((Attr) xpathnode).getNodeValue();
+        } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
+            return ((ProcessingInstruction) xpathnode).getNodeValue();
+        }
 
-      if (ctx == descendantOrSelf) {
-         return true;
-      }
+        return null;
+    }
 
-      Node parent = descendantOrSelf;
-
-      while (true) {
-         if (parent == null) {
-            return false;
-         }
+    /**
+     * Returns true if the descendantOrSelf is on the descendant-or-self axis
+     * of the context node.
+     *
+     * @param ctx
+     * @param descendantOrSelf
+     * @return true if the node is descendant
+     */
+    public static boolean isDescendantOrSelf(Node ctx, Node descendantOrSelf) {
+        if (ctx == descendantOrSelf) {
+            return true;
+        }
 
-         if (parent == ctx) {
-            return true;
-         }
+        Node parent = descendantOrSelf;
+
+        while (true) {
+            if (parent == null) {
+                return false;
+            }
 
-         if (parent.getNodeType() == Node.ATTRIBUTE_NODE) {
-            parent = ((Attr) parent).getOwnerElement();
-         } else {
-            parent = parent.getParentNode();
-         }
-      }
-   }
+            if (parent == ctx) {
+                return true;
+            }
+
+            if (parent.getNodeType() == Node.ATTRIBUTE_NODE) {
+                parent = ((Attr) parent).getOwnerElement();
+            } else {
+                parent = parent.getParentNode();
+            }
+        }
+    }
 
     public static boolean ignoreLineBreaks() {
         return ignoreLineBreaks;
     }
 
     /**
-     * This method is a tree-search to help prevent against wrapping attacks.
-     * It checks that no two Elements have ID Attributes that match the "value"
-     * argument, if this is the case then "false" is returned. Note that a
-     * return value of "true" does not necessarily mean that a matching Element
-     * has been found, just that no wrapping attack has been detected.
+     * Returns the attribute value for the attribute with the specified name.
+     * Returns null if there is no such attribute, or
+     * the empty string if the attribute value is empty.
+     *
+     * <p>This works around a limitation of the DOM
+     * <code>Element.getAttributeNode</code> method, which does not distinguish
+     * between an unspecified attribute and an attribute with a value of
+     * "" (it returns "" for both cases).
+     *
+     * @param elem the element containing the attribute
+     * @param name the name of the attribute
+     * @return the attribute value (may be null if unspecified)
      */
-    public static boolean protectAgainstWrappingAttack(Node startNode,
-                                                       String value)
-    {
+    public static String getAttributeValue(Element elem, String name) {
+        Attr attr = elem.getAttributeNodeNS(null, name);
+        return (attr == null) ? null : attr.getValue();
+    }
+
+    /**
+     * This method is a tree-search to help prevent against wrapping attacks. It checks that no
+     * two Elements have ID Attributes that match the "value" argument, if this is the case then
+     * "false" is returned. Note that a return value of "true" does not necessarily mean that
+     * a matching Element has been found, just that no wrapping attack has been detected.
+     */
+    public static boolean protectAgainstWrappingAttack(Node startNode, String value) {
         Node startParent = startNode.getParentNode();
         Node processedNode = null;
         Element foundElement = null;
@@ -780,15 +971,13 @@
     }
 
     /**
-     * This method is a tree-search to help prevent against wrapping attacks.
-     * It checks that no other Element than the given "knownElement" argument
-     * has an ID attribute that matches the "value" argument, which is the ID
-     * value of "knownElement". If this is the case then "false" is returned.
+     * This method is a tree-search to help prevent against wrapping attacks. It checks that no other
+     * Element than the given "knownElement" argument has an ID attribute that matches the "value"
+     * argument, which is the ID value of "knownElement". If this is the case then "false" is returned.
      */
-    public static boolean protectAgainstWrappingAttack(Node startNode,
-                                                       Element knownElement,
-                                                       String value)
-    {
+    public static boolean protectAgainstWrappingAttack(
+        Node startNode, Element knownElement, String value
+    ) {
         Node startParent = startNode.getParentNode();
         Node processedNode = null;
 
@@ -805,9 +994,7 @@
                 if (attributes != null) {
                     for (int i = 0; i < attributes.getLength(); i++) {
                         Attr attr = (Attr)attributes.item(i);
-                        if (attr.isId() && id.equals(attr.getValue())
-                            && se != knownElement)
-                        {
+                        if (attr.isId() && id.equals(attr.getValue()) && se != knownElement) {
                             log.log(java.util.logging.Level.FINE, "Multiple elements with the same 'Id' attribute value!");
                             return false;
                         }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathAPI.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,66 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.utils;
+
+import javax.xml.transform.TransformerException;
+
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * An interface to abstract XPath evaluation
+ */
+public interface XPathAPI {
+
+    /**
+     *  Use an XPath string to select a nodelist.
+     *  XPath namespace prefixes are resolved from the namespaceNode.
+     *
+     *  @param contextNode The node to start searching from.
+     *  @param xpathnode
+     *  @param str
+     *  @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
+     *  @return A NodeIterator, should never be null.
+     *
+     * @throws TransformerException
+     */
+    NodeList selectNodeList(
+        Node contextNode, Node xpathnode, String str, Node namespaceNode
+    ) throws TransformerException;
+
+    /**
+     * Evaluate an XPath string and return true if the output is to be included or not.
+     *  @param contextNode The node to start searching from.
+     *  @param xpathnode The XPath node
+     *  @param str The XPath expression
+     *  @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
+     */
+    boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode)
+        throws TransformerException;
+
+    /**
+     * Clear any context information from this object
+     */
+    void clear();
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,71 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.utils;
+
+
+/**
+ * A Factory to return an XPathAPI instance. If Xalan is available it returns XalanXPathAPI. If not, then
+ * it returns JDKXPathAPI.
+ */
+public abstract class XPathFactory {
+
+    private static boolean xalanInstalled;
+
+    static {
+        try {
+            Class<?> funcTableClass =
+                ClassLoaderUtils.loadClass("com.sun.org.apache.xpath.internal.compiler.FunctionTable", XPathFactory.class);
+            if (funcTableClass != null) {
+                xalanInstalled = true;
+            }
+        } catch (Exception e) {
+            //ignore
+        }
+    }
+
+    protected synchronized static boolean isXalanInstalled() {
+        return xalanInstalled;
+    }
+
+    /**
+     * Get a new XPathFactory instance
+     */
+    public static XPathFactory newInstance() {
+        if (!isXalanInstalled()) {
+            return new JDKXPathFactory();
+        }
+        // Xalan is available
+        if (XalanXPathAPI.isInstalled()) {
+            return new XalanXPathFactory();
+        }
+        // Some problem was encountered in fixing up the Xalan FunctionTable so fall back to the
+        // JDK implementation
+        return new JDKXPathFactory();
+    }
+
+    /**
+     * Get a new XPathAPI instance
+     */
+    public abstract XPathAPI newXPathAPI();
+
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java	Thu Jul 18 03:38:49 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,306 +0,0 @@
-/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
- */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- */
-package com.sun.org.apache.xml.internal.security.utils;
-
-
-
-import javax.xml.transform.TransformerException;
-
-import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHereContext;
-import com.sun.org.apache.xml.internal.utils.PrefixResolver;
-import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault;
-import com.sun.org.apache.xpath.internal.XPath;
-import com.sun.org.apache.xpath.internal.objects.XObject;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.w3c.dom.ProcessingInstruction;
-import org.w3c.dom.Text;
-import org.w3c.dom.traversal.NodeIterator;
-
-
-
-
-/**
- * This class does the same as {@link com.sun.org.apache.xpath.internal.XPathAPI} except that the XPath strings
- * are not supplied as Strings but as {@link Text}, {@link Attr}ibute or
- * {ProcessingInstruction} nodes which contain the XPath string. This enables
- * us to use the <CODE>here()</CODE> function.
- * <BR>
- * The methods in this class are convenience methods into the low-level XPath API.
- * These functions tend to be a little slow, since a number of objects must be
- * created for each evaluation.  A faster way is to precompile the
- * XPaths using the low-level API, and then just use the XPaths
- * over and over.
- *
- * @author $Author: mullan $
- * @see <a href="http://www.w3.org/TR/xpath">XPath Specification</a>
- */
-public class XPathFuncHereAPI {
-
-   /**
-    * Use an XPath string to select a single node. XPath namespace
-    * prefixes are resolved from the context node, which may not
-    * be what you want (see the next method).
-    *
-    * @param contextNode The node to start searching from.
-    * @param xpathnode A Node containing a valid XPath string.
-    * @return The first node found that matches the XPath, or null.
-    *
-    * @throws TransformerException
-    */
-   public static Node selectSingleNode(Node contextNode, Node xpathnode)
-           throws TransformerException {
-      return selectSingleNode(contextNode, xpathnode, contextNode);
-   }
-
-   /**
-    * Use an XPath string to select a single node.
-    * XPath namespace prefixes are resolved from the namespaceNode.
-    *
-    * @param contextNode The node to start searching from.
-    * @param xpathnode
-    * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
-    * @return The first node found that matches the XPath, or null.
-    *
-    * @throws TransformerException
-    */
-   public static Node selectSingleNode(
-           Node contextNode, Node xpathnode, Node namespaceNode)
-              throws TransformerException {
-
-      // Have the XObject return its result as a NodeSetDTM.
-      NodeIterator nl = selectNodeIterator(contextNode, xpathnode,
-                                           namespaceNode);
-
-      // Return the first node, or null
-      return nl.nextNode();
-   }
-
-   /**
-    *  Use an XPath string to select a nodelist.
-    *  XPath namespace prefixes are resolved from the contextNode.
-    *
-    *  @param contextNode The node to start searching from.
-    * @param xpathnode
-    *  @return A NodeIterator, should never be null.
-    *
-    * @throws TransformerException
-    */
-   public static NodeIterator selectNodeIterator(
-           Node contextNode, Node xpathnode) throws TransformerException {
-      return selectNodeIterator(contextNode, xpathnode, contextNode);
-   }
-
-   /**
-    *  Use an XPath string to select a nodelist.
-    *  XPath namespace prefixes are resolved from the namespaceNode.
-    *
-    *  @param contextNode The node to start searching from.
-    * @param xpathnode
-    *  @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
-    *  @return A NodeIterator, should never be null.
-    *
-    * @throws TransformerException
-    */
-   public static NodeIterator selectNodeIterator(
-           Node contextNode, Node xpathnode, Node namespaceNode)
-              throws TransformerException {
-
-      // Execute the XPath, and have it return the result
-      XObject list = eval(contextNode, xpathnode, namespaceNode);
-
-      // Have the XObject return its result as a NodeSetDTM.
-      return list.nodeset();
-   }
-
-   /**
-    *  Use an XPath string to select a nodelist.
-    *  XPath namespace prefixes are resolved from the contextNode.
-    *
-    *  @param contextNode The node to start searching from.
-    * @param xpathnode
-    *  @return A NodeIterator, should never be null.
-    *
-    * @throws TransformerException
-    */
-   public static NodeList selectNodeList(Node contextNode, Node xpathnode)
-           throws TransformerException {
-      return selectNodeList(contextNode, xpathnode, contextNode);
-   }
-
-   /**
-    *  Use an XPath string to select a nodelist.
-    *  XPath namespace prefixes are resolved from the namespaceNode.
-    *
-    *  @param contextNode The node to start searching from.
-    * @param xpathnode
-    *  @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
-    *  @return A NodeIterator, should never be null.
-    *
-    * @throws TransformerException
-    */
-   public static NodeList selectNodeList(
-           Node contextNode, Node xpathnode, Node namespaceNode)
-              throws TransformerException {
-
-      // Execute the XPath, and have it return the result
-      XObject list = eval(contextNode, xpathnode, namespaceNode);
-
-      // Return a NodeList.
-      return list.nodelist();
-   }
-
-   /**
-    *  Evaluate XPath string to an XObject.  Using this method,
-    *  XPath namespace prefixes will be resolved from the namespaceNode.
-    *  @param contextNode The node to start searching from.
-    * @param xpathnode
-    *  @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null.
-    *  @see com.sun.org.apache.xpath.internal.objects.XObject
-    *  @see com.sun.org.apache.xpath.internal.objects.XNull
-    *  @see com.sun.org.apache.xpath.internal.objects.XBoolean
-    *  @see com.sun.org.apache.xpath.internal.objects.XNumber
-    *  @see com.sun.org.apache.xpath.internal.objects.XString
-    *  @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag
-    *
-    * @throws TransformerException
-    */
-   public static XObject eval(Node contextNode, Node xpathnode)
-           throws TransformerException {
-      return eval(contextNode, xpathnode, contextNode);
-   }
-
-   /**
-    *  Evaluate XPath string to an XObject.
-    *  XPath namespace prefixes are resolved from the namespaceNode.
-    *  The implementation of this is a little slow, since it creates
-    *  a number of objects each time it is called.  This could be optimized
-    *  to keep the same objects around, but then thread-safety issues would arise.
-    *
-    *  @param contextNode The node to start searching from.
-    * @param xpathnode
-    *  @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
-    *  @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null.
-    *  @see com.sun.org.apache.xpath.internal.objects.XObject
-    *  @see com.sun.org.apache.xpath.internal.objects.XNull
-    *  @see com.sun.org.apache.xpath.internal.objects.XBoolean
-    *  @see com.sun.org.apache.xpath.internal.objects.XNumber
-    *  @see com.sun.org.apache.xpath.internal.objects.XString
-    *  @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag
-    *
-    * @throws TransformerException
-    */
-   public static XObject eval(
-           Node contextNode, Node xpathnode, Node namespaceNode)
-              throws TransformerException {
-
-      // Since we don't have a XML Parser involved here, install some default support
-      // for things like namespaces, etc.
-      // (Changed from: XPathContext xpathSupport = new XPathContext();
-      //    because XPathContext is weak in a number of areas... perhaps
-      //    XPathContext should be done away with.)
-      FuncHereContext xpathSupport = new FuncHereContext(xpathnode);
-
-      // Create an object to resolve namespace prefixes.
-      // XPath namespaces are resolved from the input context node's document element
-      // if it is a root node, or else the current context node (for lack of a better
-      // resolution space, given the simplicity of this sample code).
-      PrefixResolverDefault prefixResolver =
-         new PrefixResolverDefault((namespaceNode.getNodeType()
-                                    == Node.DOCUMENT_NODE)
-                                   ? ((Document) namespaceNode)
-                                      .getDocumentElement()
-                                   : namespaceNode);
-      String str = getStrFromNode(xpathnode);
-
-      // Create the XPath object.
-      XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null);
-
-      // Execute the XPath, and have it return the result
-      // return xpath.execute(xpathSupport, contextNode, prefixResolver);
-      int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode);
-
-      return xpath.execute(xpathSupport, ctxtNode, prefixResolver);
-   }
-
-   /**
-    *   Evaluate XPath string to an XObject.
-    *   XPath namespace prefixes are resolved from the namespaceNode.
-    *   The implementation of this is a little slow, since it creates
-    *   a number of objects each time it is called.  This could be optimized
-    *   to keep the same objects around, but then thread-safety issues would arise.
-    *
-    *   @param contextNode The node to start searching from.
-    * @param xpathnode
-    *   @param prefixResolver Will be called if the parser encounters namespace
-    *                         prefixes, to resolve the prefixes to URLs.
-    *   @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null.
-    *   @see com.sun.org.apache.xpath.internal.objects.XObject
-    *   @see com.sun.org.apache.xpath.internal.objects.XNull
-    *   @see com.sun.org.apache.xpath.internal.objects.XBoolean
-    *   @see com.sun.org.apache.xpath.internal.objects.XNumber
-    *   @see com.sun.org.apache.xpath.internal.objects.XString
-    *   @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag
-    *
-    * @throws TransformerException
-    */
-   public static XObject eval(
-           Node contextNode, Node xpathnode, PrefixResolver prefixResolver)
-              throws TransformerException {
-
-      String str = getStrFromNode(xpathnode);
-
-      // Since we don't have a XML Parser involved here, install some default support
-      // for things like namespaces, etc.
-      // (Changed from: XPathContext xpathSupport = new XPathContext();
-      //    because XPathContext is weak in a number of areas... perhaps
-      //    XPathContext should be done away with.)
-      // Create the XPath object.
-      XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null);
-
-      // Execute the XPath, and have it return the result
-      FuncHereContext xpathSupport = new FuncHereContext(xpathnode);
-      int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode);
-
-      return xpath.execute(xpathSupport, ctxtNode, prefixResolver);
-   }
-
-   /**
-    * Method getStrFromNode
-    *
-    * @param xpathnode
-    * @return the string from the node
-    */
-   private static String getStrFromNode(Node xpathnode) {
-
-      if (xpathnode.getNodeType() == Node.TEXT_NODE) {
-         return ((Text) xpathnode).getData();
-      } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) {
-         return ((Attr) xpathnode).getNodeValue();
-      } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
-         return ((ProcessingInstruction) xpathnode).getNodeValue();
-      }
-
-      return "";
-   }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,210 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.utils;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+
+import javax.xml.transform.ErrorListener;
+import javax.xml.transform.SourceLocator;
+import javax.xml.transform.TransformerException;
+
+import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHere;
+import com.sun.org.apache.xml.internal.utils.PrefixResolver;
+import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault;
+import com.sun.org.apache.xpath.internal.Expression;
+import com.sun.org.apache.xpath.internal.XPath;
+import com.sun.org.apache.xpath.internal.XPathContext;
+import com.sun.org.apache.xpath.internal.compiler.FunctionTable;
+import com.sun.org.apache.xpath.internal.objects.XObject;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * An implementation of XPathAPI using Xalan. This supports the "here()" function defined in the digital
+ * signature spec.
+ */
+public class XalanXPathAPI implements XPathAPI {
+
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(XalanXPathAPI.class.getName());
+
+    private String xpathStr = null;
+
+    private XPath xpath = null;
+
+    private static FunctionTable funcTable = null;
+
+    private static boolean installed;
+
+    private XPathContext context;
+
+    static {
+        fixupFunctionTable();
+    }
+
+
+    /**
+     *  Use an XPath string to select a nodelist.
+     *  XPath namespace prefixes are resolved from the namespaceNode.
+     *
+     *  @param contextNode The node to start searching from.
+     *  @param xpathnode
+     *  @param str
+     *  @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
+     *  @return A NodeIterator, should never be null.
+     *
+     * @throws TransformerException
+     */
+    public NodeList selectNodeList(
+        Node contextNode, Node xpathnode, String str, Node namespaceNode
+    ) throws TransformerException {
+
+        // Execute the XPath, and have it return the result
+        XObject list = eval(contextNode, xpathnode, str, namespaceNode);
+
+        // Return a NodeList.
+        return list.nodelist();
+    }
+
+    /**
+     * Evaluate an XPath string and return true if the output is to be included or not.
+     *  @param contextNode The node to start searching from.
+     *  @param xpathnode The XPath node
+     *  @param str The XPath expression
+     *  @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
+     */
+    public boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode)
+        throws TransformerException {
+        XObject object = eval(contextNode, xpathnode, str, namespaceNode);
+        return object.bool();
+    }
+
+    /**
+     * Clear any context information from this object
+     */
+    public void clear() {
+        xpathStr = null;
+        xpath = null;
+        context = null;
+    }
+
+    public synchronized static boolean isInstalled() {
+        return installed;
+    }
+
+    private XObject eval(Node contextNode, Node xpathnode, String str, Node namespaceNode)
+        throws TransformerException {
+        if (context == null) {
+            context = new XPathContext(xpathnode);
+            context.setSecureProcessing(true);
+        }
+
+        // Create an object to resolve namespace prefixes.
+        // XPath namespaces are resolved from the input context node's document element
+        // if it is a root node, or else the current context node (for lack of a better
+        // resolution space, given the simplicity of this sample code).
+        Node resolverNode =
+            (namespaceNode.getNodeType() == Node.DOCUMENT_NODE)
+                ? ((Document) namespaceNode).getDocumentElement() : namespaceNode;
+        PrefixResolverDefault prefixResolver = new PrefixResolverDefault(resolverNode);
+
+        if (!str.equals(xpathStr)) {
+            if (str.indexOf("here()") > 0) {
+                context.reset();
+            }
+            xpath = createXPath(str, prefixResolver);
+            xpathStr = str;
+        }
+
+        // Execute the XPath, and have it return the result
+        int ctxtNode = context.getDTMHandleFromNode(contextNode);
+
+        return xpath.execute(context, ctxtNode, prefixResolver);
+    }
+
+    private XPath createXPath(String str, PrefixResolver prefixResolver) throws TransformerException {
+        XPath xpath = null;
+        Class<?>[] classes = new Class<?>[]{String.class, SourceLocator.class, PrefixResolver.class, int.class,
+                                      ErrorListener.class, FunctionTable.class};
+        Object[] objects =
+            new Object[]{str, null, prefixResolver, Integer.valueOf(XPath.SELECT), null, funcTable};
+        try {
+            Constructor<?> constructor = XPath.class.getConstructor(classes);
+            xpath = (XPath) constructor.newInstance(objects);
+        } catch (Exception ex) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
+            }
+        }
+        if (xpath == null) {
+            xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null);
+        }
+        return xpath;
+    }
+
+    private synchronized static void fixupFunctionTable() {
+        installed = false;
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Registering Here function");
+        }
+        /**
+         * Try to register our here() implementation as internal function.
+         */
+        try {
+            Class<?>[] args = {String.class, Expression.class};
+            Method installFunction = FunctionTable.class.getMethod("installFunction", args);
+            if ((installFunction.getModifiers() & Modifier.STATIC) != 0) {
+                Object[] params = {"here", new FuncHere()};
+                installFunction.invoke(null, params);
+                installed = true;
+            }
+        } catch (Exception ex) {
+            log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", ex);
+        }
+        if (!installed) {
+            try {
+                funcTable = new FunctionTable();
+                Class<?>[] args = {String.class, Class.class};
+                Method installFunction = FunctionTable.class.getMethod("installFunction", args);
+                Object[] params = {"here", FuncHere.class};
+                installFunction.invoke(funcTable, params);
+                installed = true;
+            } catch (Exception ex) {
+                log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", ex);
+            }
+        }
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            if (installed) {
+                log.log(java.util.logging.Level.FINE, "Registered class " + FuncHere.class.getName()
+                          + " for XPath function 'here()' function in internal table");
+            } else {
+                log.log(java.util.logging.Level.FINE, "Unable to register class " + FuncHere.class.getName()
+                          + " for XPath function 'here()' function in internal table");
+            }
+        }
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathFactory.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,37 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.utils;
+
+
+/**
+ * A Factory to return a XalanXPathAPI instance.
+ */
+public class XalanXPathFactory extends XPathFactory {
+
+    /**
+     * Get a new XPathAPI instance
+     */
+    public XPathAPI newXPathAPI() {
+        return new XalanXPathAPI();
+    }
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java	Mon Jul 22 17:37:15 2013 -0700
@@ -85,8 +85,14 @@
      * @throws ResourceResolverException
      */
     public static final ResourceResolver getInstance(
-        Attr uri, String baseURI, boolean secureValidation
+        Attr uriAttr, String baseURI, boolean secureValidation
     ) throws ResourceResolverException {
+        ResourceResolverContext context = new ResourceResolverContext(uriAttr, baseURI, secureValidation);
+        return internalGetInstance(context);
+    }
+
+    private static <N> ResourceResolver internalGetInstance(ResourceResolverContext context)
+            throws ResourceResolverException {
         synchronized (resolverList) {
             for (ResourceResolver resolver : resolverList) {
                 ResourceResolver resolverTmp = resolver;
@@ -95,9 +101,9 @@
                         resolverTmp =
                             new ResourceResolver(resolver.resolverSpi.getClass().newInstance());
                     } catch (InstantiationException e) {
-                        throw new ResourceResolverException("", e, uri, baseURI);
+                        throw new ResourceResolverException("", e, context.attr, context.baseUri);
                     } catch (IllegalAccessException e) {
-                        throw new ResourceResolverException("", e, uri, baseURI);
+                        throw new ResourceResolverException("", e, context.attr, context.baseUri);
                     }
                 }
 
@@ -107,15 +113,14 @@
                     );
                 }
 
-                resolverTmp.resolverSpi.secureValidation = secureValidation;
-                if ((resolverTmp != null) && resolverTmp.canResolve(uri, baseURI)) {
+                if ((resolverTmp != null) && resolverTmp.canResolve(context)) {
                     // Check to see whether the Resolver is allowed
-                    if (secureValidation
+                    if (context.secureValidation
                         && (resolverTmp.resolverSpi instanceof ResolverLocalFilesystem
                             || resolverTmp.resolverSpi instanceof ResolverDirectHTTP)) {
                         Object exArgs[] = { resolverTmp.resolverSpi.getClass().getName() };
                         throw new ResourceResolverException(
-                            "signature.Reference.ForbiddenResolver", exArgs, uri, baseURI
+                            "signature.Reference.ForbiddenResolver", exArgs, context.attr, context.baseUri
                         );
                     }
                     return resolverTmp;
@@ -123,9 +128,10 @@
             }
         }
 
-        Object exArgs[] = { ((uri != null) ? uri.getNodeValue() : "null"), baseURI };
+        Object exArgs[] = { ((context.uriToResolve != null)
+                ? context.uriToResolve : "null"), context.baseUri };
 
-        throw new ResourceResolverException("utils.resolver.noClass", exArgs, uri, baseURI);
+        throw new ResourceResolverException("utils.resolver.noClass", exArgs, context.attr, context.baseUri);
     }
 
     /**
@@ -165,6 +171,8 @@
             );
         }
 
+        ResourceResolverContext context = new ResourceResolverContext(uri, baseURI, secureValidation);
+
         // first check the individual Resolvers
         if (individualResolvers != null) {
             for (int i = 0; i < individualResolvers.size(); i++) {
@@ -176,15 +184,14 @@
                         log.log(java.util.logging.Level.FINE, "check resolvability by class " + currentClass);
                     }
 
-                    resolver.resolverSpi.secureValidation = secureValidation;
-                    if (resolver.canResolve(uri, baseURI)) {
+                    if (resolver.canResolve(context)) {
                         return resolver;
                     }
                 }
             }
         }
 
-        return getInstance(uri, baseURI, secureValidation);
+        return internalGetInstance(context);
     }
 
     /**
@@ -270,6 +277,15 @@
     }
 
     /**
+     * @deprecated New clients should use {@link #resolve(Attr, String, boolean)}
+     */
+    @Deprecated
+    public XMLSignatureInput resolve(Attr uri, String baseURI)
+        throws ResourceResolverException {
+        return resolve(uri, baseURI, true);
+    }
+
+    /**
      * Method resolve
      *
      * @param uri
@@ -278,9 +294,10 @@
      *
      * @throws ResourceResolverException
      */
-    public XMLSignatureInput resolve(Attr uri, String baseURI)
+    public XMLSignatureInput resolve(Attr uri, String baseURI, boolean secureValidation)
         throws ResourceResolverException {
-        return resolverSpi.engineResolve(uri, baseURI);
+        ResourceResolverContext context = new ResourceResolverContext(uri, baseURI, secureValidation);
+        return resolverSpi.engineResolveURI(context);
     }
 
     /**
@@ -338,7 +355,7 @@
      * @param baseURI
      * @return true if it can resolve the uri
      */
-    private boolean canResolve(Attr uri, String baseURI) {
-        return resolverSpi.engineCanResolve(uri, baseURI);
+    private boolean canResolve(ResourceResolverContext context) {
+        return this.resolverSpi.engineCanResolveURI(context);
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,43 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.utils.resolver;
+
+import org.w3c.dom.Attr;
+
+public class ResourceResolverContext {
+
+    public ResourceResolverContext(Attr attr, String baseUri, boolean secureValidation) {
+        this.attr = attr;
+        this.baseUri = baseUri;
+        this.secureValidation = secureValidation;
+        this.uriToResolve = attr != null ? attr.getValue() : null;
+    }
+
+    public final String uriToResolve;
+
+    public final boolean secureValidation;
+
+    public final String baseUri;
+
+    public final Attr attr;
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,144 +2,137 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils.resolver;
 
-
-
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import org.w3c.dom.Attr;
 
-
 /**
  * This Exception is thrown if something related to the
  * {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver} goes wrong.
  *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  */
 public class ResourceResolverException extends XMLSecurityException {
 
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
-   /**
-    * Constructor ResourceResolverException
-    *
-    * @param _msgID
-    * @param uri
-    * @param BaseURI
-    */
-   public ResourceResolverException(String _msgID, Attr uri, String BaseURI) {
+    private static final long serialVersionUID = 1L;
+
+    private Attr uri = null;
+
+    private String baseURI = null;
 
-      super(_msgID);
+    /**
+     * Constructor ResourceResolverException
+     *
+     * @param msgID
+     * @param uri
+     * @param baseURI
+     */
+    public ResourceResolverException(String msgID, Attr uri, String baseURI) {
+        super(msgID);
 
-      this._uri = uri;
-      this._BaseURI = BaseURI;
-   }
+        this.uri = uri;
+        this.baseURI = baseURI;
+    }
 
-   /**
-    * Constructor ResourceResolverException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param uri
-    * @param BaseURI
-    */
-   public ResourceResolverException(String _msgID, Object exArgs[], Attr uri,
-                                    String BaseURI) {
+    /**
+     * Constructor ResourceResolverException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param uri
+     * @param baseURI
+     */
+    public ResourceResolverException(String msgID, Object exArgs[], Attr uri,
+                                     String baseURI) {
+        super(msgID, exArgs);
 
-      super(_msgID, exArgs);
-
-      this._uri = uri;
-      this._BaseURI = BaseURI;
-   }
+        this.uri = uri;
+        this.baseURI = baseURI;
+    }
 
-   /**
-    * Constructor ResourceResolverException
-    *
-    * @param _msgID
-    * @param _originalException
-    * @param uri
-    * @param BaseURI
-    */
-   public ResourceResolverException(String _msgID, Exception _originalException,
-                                    Attr uri, String BaseURI) {
+    /**
+     * Constructor ResourceResolverException
+     *
+     * @param msgID
+     * @param originalException
+     * @param uri
+     * @param baseURI
+     */
+    public ResourceResolverException(String msgID, Exception originalException,
+                                     Attr uri, String baseURI) {
+        super(msgID, originalException);
 
-      super(_msgID, _originalException);
-
-      this._uri = uri;
-      this._BaseURI = BaseURI;
-   }
+        this.uri = uri;
+        this.baseURI = baseURI;
+    }
 
-   /**
-    * Constructor ResourceResolverException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    * @param uri
-    * @param BaseURI
-    */
-   public ResourceResolverException(String _msgID, Object exArgs[],
-                                    Exception _originalException, Attr uri,
-                                    String BaseURI) {
+    /**
+     * Constructor ResourceResolverException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     * @param uri
+     * @param baseURI
+     */
+    public ResourceResolverException(String msgID, Object exArgs[],
+                                     Exception originalException, Attr uri,
+                                     String baseURI) {
+        super(msgID, exArgs, originalException);
 
-      super(_msgID, exArgs, _originalException);
+        this.uri = uri;
+        this.baseURI = baseURI;
+    }
 
-      this._uri = uri;
-      this._BaseURI = BaseURI;
-   }
+    /**
+     *
+     * @param uri
+     */
+    public void setURI(Attr uri) {
+        this.uri = uri;
+    }
 
-   //J-
-   Attr _uri = null;
-   /**
-    *
-    * @param uri
-    */
-   public void setURI(Attr uri) {
-      this._uri = uri;
-   }
-
-   /**
-    *
-    * @return the uri
-    */
-   public Attr getURI() {
-      return this._uri;
-   }
+    /**
+     *
+     * @return the uri
+     */
+    public Attr getURI() {
+        return this.uri;
+    }
 
-   String _BaseURI;
-
-   /**
-    *
-    * @param BaseURI
-    */
-   public void setBaseURI(String BaseURI) {
-      this._BaseURI = BaseURI;
-   }
+    /**
+     *
+     * @param baseURI
+     */
+    public void setbaseURI(String baseURI) {
+        this.baseURI = baseURI;
+    }
 
-   /**
-    *
-    * @return the basUri
-    */
-   public String getBaseURI() {
-      return this._BaseURI;
-   }
-   //J+
+    /**
+     *
+     * @return the baseURI
+     */
+    public String getbaseURI() {
+        return this.baseURI;
+    }
+
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,192 +2,239 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils.resolver;
 
-
 import java.util.HashMap;
 import java.util.Map;
 
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import org.w3c.dom.Attr;
 
-
 /**
  * During reference validation, we have to retrieve resources from somewhere.
  *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  */
 public abstract class ResourceResolverSpi {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(
-                    ResourceResolverSpi.class.getName());
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(ResourceResolverSpi.class.getName());
+
+    /** Field properties */
+    protected java.util.Map<String, String> properties = null;
 
-   /** Field _properties */
-   protected java.util.Map<String,String> _properties = null;
-
-   protected boolean secureValidation;
+    /**
+     * Deprecated - used to carry state about whether resolution was being done in a secure fashion,
+     * but was not thread safe, so the resolution information is now passed as parameters to methods.
+     *
+     * @deprecated Secure validation flag is now passed to methods.
+     */
+    @Deprecated
+    protected final boolean secureValidation = true;
 
-   /**
-    * This is the workhorse method used to resolve resources.
-    *
-    * @param uri
-    * @param BaseURI
-    * @return the resource wrapped arround a XMLSignatureInput
-    *
-    * @throws ResourceResolverException
-    */
-   public abstract XMLSignatureInput engineResolve(Attr uri, String BaseURI)
-      throws ResourceResolverException;
+    /**
+     * This is the workhorse method used to resolve resources.
+     *
+     * @param uri
+     * @param BaseURI
+     * @return the resource wrapped around a XMLSignatureInput
+     *
+     * @throws ResourceResolverException
+     *
+     * @deprecated New clients should override {@link #engineResolveURI(ResourceResolverContext)}
+     */
+    @Deprecated
+    public XMLSignatureInput engineResolve(Attr uri, String BaseURI)
+        throws ResourceResolverException {
+        throw new UnsupportedOperationException();
+    }
 
-   /**
-    * Method engineSetProperty
-    *
-    * @param key
-    * @param value
-    */
-   public void engineSetProperty(String key, String value) {
-          if (_properties==null) {
-                  _properties=new HashMap<String,String>();
-          }
-      this._properties.put(key, value);
-   }
+    /**
+     * This is the workhorse method used to resolve resources.
+     * @param context Context to use to resolve resources.
+     *
+     * @return the resource wrapped around a XMLSignatureInput
+     *
+     * @throws ResourceResolverException
+     */
+    public XMLSignatureInput engineResolveURI(ResourceResolverContext context)
+        throws ResourceResolverException {
+        // The default implementation, to preserve backwards compatibility in the
+        // test cases, calls the old resolver API.
+        return engineResolve(context.attr, context.baseUri);
+    }
 
-   /**
-    * Method engineGetProperty
-    *
-    * @param key
-    * @return the value of the property
-    */
-   public String engineGetProperty(String key) {
-          if (_properties==null) {
-                        return null;
-          }
-      return this._properties.get(key);
-   }
+    /**
+     * Method engineSetProperty
+     *
+     * @param key
+     * @param value
+     */
+    public void engineSetProperty(String key, String value) {
+        if (properties == null) {
+            properties = new HashMap<String, String>();
+        }
+        properties.put(key, value);
+    }
+
+    /**
+     * Method engineGetProperty
+     *
+     * @param key
+     * @return the value of the property
+     */
+    public String engineGetProperty(String key) {
+        if (properties == null) {
+            return null;
+        }
+        return properties.get(key);
+    }
 
-   /**
-    *
-    * @param properties
-    */
-   public void engineAddProperies(Map<String,String> properties) {
-          if (properties!=null) {
-                  if (_properties==null) {
-                          _properties=new HashMap<String,String>();
-                  }
-                  this._properties.putAll(properties);
-          }
-   }
-   /**
-    * Tells if the implementation does can be reused by several threads safely.
-    * It normally means that the implemantation does not have any member, or there is
-    * member change betwen engineCanResolve & engineResolve invocations. Or it mantians all
-    * member info in ThreadLocal methods.
-    */
-   public boolean engineIsThreadSafe() {
-           return false;
-   }
-   /**
-    * This method helps the {@link ResourceResolver} to decide whether a
-    * {@link ResourceResolverSpi} is able to perform the requested action.
-    *
-    * @param uri
-    * @param BaseURI
-    * @return true if the engine can resolve the uri
-    */
-   public abstract boolean engineCanResolve(Attr uri, String BaseURI);
+    /**
+     *
+     * @param newProperties
+     */
+    public void engineAddProperies(Map<String, String> newProperties) {
+        if (newProperties != null && !newProperties.isEmpty()) {
+            if (properties == null) {
+                properties = new HashMap<String, String>();
+            }
+            properties.putAll(newProperties);
+        }
+    }
+
+    /**
+     * Tells if the implementation does can be reused by several threads safely.
+     * It normally means that the implementation does not have any member, or there is
+     * member change between engineCanResolve & engineResolve invocations. Or it maintains all
+     * member info in ThreadLocal methods.
+     */
+    public boolean engineIsThreadSafe() {
+        return false;
+    }
+
+    /**
+     * This method helps the {@link ResourceResolver} to decide whether a
+     * {@link ResourceResolverSpi} is able to perform the requested action.
+     *
+     * @param uri
+     * @param BaseURI
+     * @return true if the engine can resolve the uri
+     *
+     * @deprecated See {@link #engineCanResolveURI(ResourceResolverContext)}
+     */
+    @Deprecated
+    public boolean engineCanResolve(Attr uri, String BaseURI) {
+        // This method used to be abstract, so any calls to "super" are bogus.
+        throw new UnsupportedOperationException();
+    }
 
-   /**
-    * Method engineGetPropertyKeys
-    *
-    * @return the property keys
-    */
-   public String[] engineGetPropertyKeys() {
-      return new String[0];
-   }
+    /**
+     * This method helps the {@link ResourceResolver} to decide whether a
+     * {@link ResourceResolverSpi} is able to perform the requested action.
+     *
+     * <p>New clients should override this method, and not override {@link #engineCanResolve(Attr, String)}
+     * </p>
+     * @param context Context in which to do resolution.
+     * @return true if the engine can resolve the uri
+     */
+    public boolean engineCanResolveURI(ResourceResolverContext context) {
+        // To preserve backward compatibility with existing resolvers that might override the old method,
+        // call the old deprecated API.
+        return engineCanResolve( context.attr, context.baseUri );
+    }
 
-   /**
-    * Method understandsProperty
-    *
-    * @param propertyToTest
-    * @return true if understands the property
-    */
-   public boolean understandsProperty(String propertyToTest) {
-
-      String[] understood = this.engineGetPropertyKeys();
+    /**
+     * Method engineGetPropertyKeys
+     *
+     * @return the property keys
+     */
+    public String[] engineGetPropertyKeys() {
+        return new String[0];
+    }
 
-      if (understood != null) {
-         for (int i = 0; i < understood.length; i++) {
-            if (understood[i].equals(propertyToTest)) {
-               return true;
+    /**
+     * Method understandsProperty
+     *
+     * @param propertyToTest
+     * @return true if understands the property
+     */
+    public boolean understandsProperty(String propertyToTest) {
+        String[] understood = this.engineGetPropertyKeys();
+
+        if (understood != null) {
+            for (int i = 0; i < understood.length; i++) {
+                if (understood[i].equals(propertyToTest)) {
+                    return true;
+                }
             }
-         }
-      }
+        }
 
-      return false;
-   }
+        return false;
+    }
 
 
-   /**
-    * Fixes a platform dependent filename to standard URI form.
-    *
-    * @param str The string to fix.
-    *
-    * @return Returns the fixed URI string.
-    */
-   public static String fixURI(String str) {
+    /**
+     * Fixes a platform dependent filename to standard URI form.
+     *
+     * @param str The string to fix.
+     *
+     * @return Returns the fixed URI string.
+     */
+    public static String fixURI(String str) {
 
-      // handle platform dependent strings
-      str = str.replace(java.io.File.separatorChar, '/');
+        // handle platform dependent strings
+        str = str.replace(java.io.File.separatorChar, '/');
 
-      if (str.length() >= 4) {
+        if (str.length() >= 4) {
 
-         // str =~ /^\W:\/([^/])/ # to speak perl ;-))
-         char ch0 = Character.toUpperCase(str.charAt(0));
-         char ch1 = str.charAt(1);
-         char ch2 = str.charAt(2);
-         char ch3 = str.charAt(3);
-         boolean isDosFilename = ((('A' <= ch0) && (ch0 <= 'Z'))
-                                  && (ch1 == ':') && (ch2 == '/')
-                                  && (ch3 != '/'));
+            // str =~ /^\W:\/([^/])/ # to speak perl ;-))
+            char ch0 = Character.toUpperCase(str.charAt(0));
+            char ch1 = str.charAt(1);
+            char ch2 = str.charAt(2);
+            char ch3 = str.charAt(3);
+            boolean isDosFilename = ((('A' <= ch0) && (ch0 <= 'Z'))
+                && (ch1 == ':') && (ch2 == '/')
+                && (ch3 != '/'));
 
-         if (isDosFilename) {
-            if (log.isLoggable(java.util.logging.Level.FINE))
+            if (isDosFilename && log.isLoggable(java.util.logging.Level.FINE)) {
                 log.log(java.util.logging.Level.FINE, "Found DOS filename: " + str);
-         }
-      }
+            }
+        }
 
-      // Windows fix
-      if (str.length() >= 2) {
-         char ch1 = str.charAt(1);
+        // Windows fix
+        if (str.length() >= 2) {
+            char ch1 = str.charAt(1);
 
-         if (ch1 == ':') {
-            char ch0 = Character.toUpperCase(str.charAt(0));
+            if (ch1 == ':') {
+                char ch0 = Character.toUpperCase(str.charAt(0));
 
-            if (('A' <= ch0) && (ch0 <= 'Z')) {
-               str = "/" + str;
+                if (('A' <= ch0) && (ch0 <= 'Z')) {
+                    str = "/" + str;
+                }
             }
-         }
-      }
+        }
 
-      // done
-      return str;
-   }
+        // done
+        return str;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 
 package com.sun.org.apache.xml.internal.security.utils.resolver.implementations;
@@ -27,51 +29,56 @@
 import java.io.InputStream;
 
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
+import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
-import org.w3c.dom.Attr;
 
 /**
- *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  */
-
 public class ResolverAnonymous extends ResourceResolverSpi {
 
-   private XMLSignatureInput _input = null;
+    private InputStream inStream = null;
 
-   /**
-    * @param filename
+    @Override
+    public boolean engineIsThreadSafe() {
+        return true;
+    }
+
+    /**
+     * @param filename
      * @throws FileNotFoundException
      * @throws IOException
      */
-   public ResolverAnonymous(String filename) throws FileNotFoundException, IOException {
-      this._input = new XMLSignatureInput(new FileInputStream(filename));
-   }
+    public ResolverAnonymous(String filename) throws FileNotFoundException, IOException {
+        inStream = new FileInputStream(filename);
+    }
 
-   /**
-    * @param is
+    /**
+     * @param is
      */
-   public ResolverAnonymous(InputStream is) {
-      this._input = new XMLSignatureInput(is);
-   }
+    public ResolverAnonymous(InputStream is) {
+        inStream = is;
+    }
 
-   /** @inheritDoc */
-   public XMLSignatureInput engineResolve(Attr uri, String BaseURI) {
-      return this._input;
-   }
+    /** @inheritDoc */
+    @Override
+    public XMLSignatureInput engineResolveURI(ResourceResolverContext context) {
+        return new XMLSignatureInput(inStream);
+    }
 
-   /**
-    * @inheritDoc
-    */
-   public boolean engineCanResolve(Attr uri, String BaseURI) {
-      if (uri == null) {
-         return true;
-      }
-      return false;
-   }
+    /**
+     * @inheritDoc
+     */
+    @Override
+    public boolean engineCanResolveURI(ResourceResolverContext context) {
+        if (context.uriToResolve == null) {
+            return true;
+        }
+        return false;
+    }
 
-   /** @inheritDoc */
-   public String[] engineGetPropertyKeys() {
-      return new String[0];
-   }
+    /** @inheritDoc */
+    public String[] engineGetPropertyKeys() {
+        return new String[0];
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,38 +2,42 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils.resolver.implementations;
 
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.net.InetSocketAddress;
 import java.net.MalformedURLException;
+import java.net.Proxy;
+import java.net.URISyntaxException;
+import java.net.URI;
 import java.net.URL;
 import java.net.URLConnection;
 
-import com.sun.org.apache.xml.internal.utils.URI;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import com.sun.org.apache.xml.internal.security.utils.Base64;
+import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
-import org.w3c.dom.Attr;
-
 
 /**
  * A simple ResourceResolver for HTTP requests. This class handles only 'pure'
@@ -51,253 +55,219 @@
  * resourceResolver.setProperty("http.proxy.password", "secretca");
  * </PRE>
  *
- *
- * @author $Author: mullan $
  * @see <A HREF="http://www.javaworld.com/javaworld/javatips/jw-javatip42_p.html">Java Tip 42: Write Java apps that work with proxy-based firewalls</A>
  * @see <A HREF="http://java.sun.com/j2se/1.4/docs/guide/net/properties.html">SUN J2SE docs for network properties</A>
  * @see <A HREF="http://metalab.unc.edu/javafaq/javafaq.html#proxy">The JAVA FAQ Question 9.5: How do I make Java work with a proxy server?</A>
- * $todo$ the proxy behaviour seems not to work; if a on-existing proxy is set, it works ?!?
  */
 public class ResolverDirectHTTP extends ResourceResolverSpi {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(
-                            ResolverDirectHTTP.class.getName());
-
-   /** Field properties[] */
-   private static final String properties[] =
-        { "http.proxy.host", "http.proxy.port",
-          "http.proxy.username",
-          "http.proxy.password",
-          "http.basic.username",
-          "http.basic.password" };
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(ResolverDirectHTTP.class.getName());
 
-   /** Field HttpProxyHost */
-   private static final int HttpProxyHost = 0;
-
-   /** Field HttpProxyPort */
-   private static final int HttpProxyPort = 1;
-
-   /** Field HttpProxyUser */
-   private static final int HttpProxyUser = 2;
-
-   /** Field HttpProxyPass */
-   private static final int HttpProxyPass = 3;
-
-   /** Field HttpProxyUser */
-   private static final int HttpBasicUser = 4;
+    /** Field properties[] */
+    private static final String properties[] = {
+                                                 "http.proxy.host", "http.proxy.port",
+                                                 "http.proxy.username", "http.proxy.password",
+                                                 "http.basic.username", "http.basic.password"
+                                               };
 
-   /** Field HttpProxyPass */
-   private static final int HttpBasicPass = 5;
+    /** Field HttpProxyHost */
+    private static final int HttpProxyHost = 0;
+
+    /** Field HttpProxyPort */
+    private static final int HttpProxyPort = 1;
 
-   public boolean engineIsThreadSafe() {
-           return true;
-   }
-   /**
-    * Method resolve
-    *
-    * @param uri
-    * @param BaseURI
-    *
-    * @throws ResourceResolverException
-    * @return
-    * $todo$ calculate the correct URI from the attribute and the BaseURI
-    */
-   public XMLSignatureInput engineResolve(Attr uri, String BaseURI)
-           throws ResourceResolverException {
+    /** Field HttpProxyUser */
+    private static final int HttpProxyUser = 2;
 
-      try {
-         boolean useProxy = false;
-         String proxyHost =
-            engineGetProperty(ResolverDirectHTTP
-               .properties[ResolverDirectHTTP.HttpProxyHost]);
-         String proxyPort =
-            engineGetProperty(ResolverDirectHTTP
-               .properties[ResolverDirectHTTP.HttpProxyPort]);
+    /** Field HttpProxyPass */
+    private static final int HttpProxyPass = 3;
+
+    /** Field HttpProxyUser */
+    private static final int HttpBasicUser = 4;
 
-         if ((proxyHost != null) && (proxyPort != null)) {
-            useProxy = true;
-         }
+    /** Field HttpProxyPass */
+    private static final int HttpBasicPass = 5;
 
-         String oldProxySet = null;
-         String oldProxyHost = null;
-         String oldProxyPort = null;
-         // switch on proxy usage
-         if (useProxy) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Use of HTTP proxy enabled: " + proxyHost + ":"
-                      + proxyPort);
-            }
-            oldProxySet = System.getProperty("http.proxySet");
-            oldProxyHost = System.getProperty("http.proxyHost");
-            oldProxyPort = System.getProperty("http.proxyPort");
-            System.setProperty("http.proxySet", "true");
-            System.setProperty("http.proxyHost", proxyHost);
-            System.setProperty("http.proxyPort", proxyPort);
-         }
-
-         boolean switchBackProxy = ((oldProxySet != null)
-                                    && (oldProxyHost != null)
-                                    && (oldProxyPort != null));
-
-         // calculate new URI
-         URI uriNew = getNewURI(uri.getNodeValue(), BaseURI);
+    @Override
+    public boolean engineIsThreadSafe() {
+        return true;
+    }
 
-         // if the URI contains a fragment, ignore it
-         URI uriNewNoFrag = new URI(uriNew);
-
-         uriNewNoFrag.setFragment(null);
-
-         URL url = new URL(uriNewNoFrag.toString());
-         URLConnection urlConnection = url.openConnection();
-
-         {
+    /**
+     * Method resolve
+     *
+     * @param uri
+     * @param baseURI
+     *
+     * @throws ResourceResolverException
+     * @return
+     * $todo$ calculate the correct URI from the attribute and the baseURI
+     */
+    @Override
+    public XMLSignatureInput engineResolveURI(ResourceResolverContext context)
+        throws ResourceResolverException {
+        try {
 
-            // set proxy pass
-            String proxyUser =
-               engineGetProperty(ResolverDirectHTTP
-                  .properties[ResolverDirectHTTP.HttpProxyUser]);
-            String proxyPass =
-               engineGetProperty(ResolverDirectHTTP
-                  .properties[ResolverDirectHTTP.HttpProxyPass]);
-
-            if ((proxyUser != null) && (proxyPass != null)) {
-               String password = proxyUser + ":" + proxyPass;
-               String encodedPassword = Base64.encode(password.getBytes());
-
-               // or was it Proxy-Authenticate ?
-               urlConnection.setRequestProperty("Proxy-Authorization",
-                                                encodedPassword);
-            }
-         }
-
-         {
+            // calculate new URI
+            URI uriNew = getNewURI(context.uriToResolve, context.baseUri);
+            URL url = uriNew.toURL();
+            URLConnection urlConnection;
+            urlConnection = openConnection(url);
 
             // check if Basic authentication is required
             String auth = urlConnection.getHeaderField("WWW-Authenticate");
 
-            if (auth != null) {
+            if (auth != null && auth.startsWith("Basic")) {
+                // do http basic authentication
+                String user =
+                    engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpBasicUser]);
+                String pass =
+                    engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpBasicPass]);
 
-               // do http basic authentication
-               if (auth.startsWith("Basic")) {
-                  String user =
-                     engineGetProperty(ResolverDirectHTTP
-                        .properties[ResolverDirectHTTP.HttpBasicUser]);
-                  String pass =
-                     engineGetProperty(ResolverDirectHTTP
-                        .properties[ResolverDirectHTTP.HttpBasicPass]);
+                if ((user != null) && (pass != null)) {
+                    urlConnection = openConnection(url);
+
+                    String password = user + ":" + pass;
+                    String encodedPassword = Base64.encode(password.getBytes("ISO-8859-1"));
 
-                  if ((user != null) && (pass != null)) {
-                     urlConnection = url.openConnection();
-
-                     String password = user + ":" + pass;
-                     String encodedPassword =
-                        Base64.encode(password.getBytes());
+                    // set authentication property in the http header
+                    urlConnection.setRequestProperty("Authorization",
+                                                     "Basic " + encodedPassword);
+                }
+            }
 
-                     // set authentication property in the http header
-                     urlConnection.setRequestProperty("Authorization",
-                                                      "Basic "
-                                                      + encodedPassword);
-                  }
-               }
+            String mimeType = urlConnection.getHeaderField("Content-Type");
+            InputStream inputStream = urlConnection.getInputStream();
+            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+            byte buf[] = new byte[4096];
+            int read = 0;
+            int summarized = 0;
+
+            while ((read = inputStream.read(buf)) >= 0) {
+                baos.write(buf, 0, read);
+                summarized += read;
             }
-         }
+
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "Fetched " + summarized + " bytes from URI " + uriNew.toString());
+            }
 
-         String mimeType = urlConnection.getHeaderField("Content-Type");
-         InputStream inputStream = urlConnection.getInputStream();
-         ByteArrayOutputStream baos = new ByteArrayOutputStream();
-         byte buf[] = new byte[4096];
-         int read = 0;
-         int summarized = 0;
+            XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray());
+
+            result.setSourceURI(uriNew.toString());
+            result.setMIMEType(mimeType);
 
-         while ((read = inputStream.read(buf)) >= 0) {
-            baos.write(buf, 0, read);
+            return result;
+        } catch (URISyntaxException ex) {
+            throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri);
+        } catch (MalformedURLException ex) {
+            throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri);
+        } catch (IOException ex) {
+            throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri);
+        } catch (IllegalArgumentException e) {
+            throw new ResourceResolverException("generic.EmptyMessage", e, context.attr, context.baseUri);
+        }
+    }
 
-            summarized += read;
-         }
+    private URLConnection openConnection(URL url) throws IOException {
 
-         log.log(java.util.logging.Level.FINE, "Fetched " + summarized + " bytes from URI "
-                   + uriNew.toString());
-
-         XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray());
+        String proxyHostProp =
+                engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyHost]);
+        String proxyPortProp =
+                engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyPort]);
+        String proxyUser =
+                engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyUser]);
+        String proxyPass =
+                engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyPass]);
 
-         // XMLSignatureInput result = new XMLSignatureInput(inputStream);
-         result.setSourceURI(uriNew.toString());
-         result.setMIMEType(mimeType);
+        Proxy proxy = null;
+        if ((proxyHostProp != null) && (proxyPortProp != null)) {
+            int port = Integer.parseInt(proxyPortProp);
+            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostProp, port));
+        }
 
-         // switch off proxy usage
-         if (useProxy && switchBackProxy) {
-            System.setProperty("http.proxySet", oldProxySet);
-            System.setProperty("http.proxyHost", oldProxyHost);
-            System.setProperty("http.proxyPort", oldProxyPort);
-         }
+        URLConnection urlConnection;
+        if (proxy != null) {
+            urlConnection = url.openConnection(proxy);
 
-         return result;
-      } catch (MalformedURLException ex) {
-         throw new ResourceResolverException("generic.EmptyMessage", ex, uri,
-                                             BaseURI);
-      } catch (IOException ex) {
-         throw new ResourceResolverException("generic.EmptyMessage", ex, uri,
-                                             BaseURI);
-      }
-   }
+            if ((proxyUser != null) && (proxyPass != null)) {
+                String password = proxyUser + ":" + proxyPass;
+                String authString = "Basic " + Base64.encode(password.getBytes("ISO-8859-1"));
+
+                urlConnection.setRequestProperty("Proxy-Authorization", authString);
+            }
+        } else {
+            urlConnection = url.openConnection();
+        }
+
+        return urlConnection;
+    }
 
-   /**
-    * We resolve http URIs <I>without</I> fragment...
-    *
-    * @param uri
-    * @param BaseURI
-    *  @return true if can be resolved
-    */
-   public boolean engineCanResolve(Attr uri, String BaseURI) {
-      if (uri == null) {
-         log.log(java.util.logging.Level.FINE, "quick fail, uri == null");
+    /**
+     * We resolve http URIs <I>without</I> fragment...
+     *
+     * @param uri
+     * @param baseURI
+     * @return true if can be resolved
+     */
+    public boolean engineCanResolveURI(ResourceResolverContext context) {
+        if (context.uriToResolve == null) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "quick fail, uri == null");
+            }
+            return false;
+        }
 
-         return false;
-      }
-
-      String uriNodeValue = uri.getNodeValue();
+        if (context.uriToResolve.equals("") || (context.uriToResolve.charAt(0)=='#')) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "quick fail for empty URIs and local ones");
+            }
+            return false;
+        }
 
-      if (uriNodeValue.equals("") || (uriNodeValue.charAt(0)=='#')) {
-         log.log(java.util.logging.Level.FINE, "quick fail for empty URIs and local ones");
-
-         return false;
-      }
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + context.uriToResolve);
+        }
 
-      if (log.isLoggable(java.util.logging.Level.FINE)) {
-         log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + uriNodeValue);
-      }
+        if (context.uriToResolve.startsWith("http:") ||
+            (context.baseUri != null && context.baseUri.startsWith("http:") )) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "I state that I can resolve " + context.uriToResolve);
+            }
+            return true;
+        }
 
-      if ( uriNodeValue.startsWith("http:") ||
-                                (BaseURI!=null && BaseURI.startsWith("http:") )) {
-         if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "I state that I can resolve " + uriNodeValue);
-         }
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "I state that I can't resolve " + context.uriToResolve);
+        }
 
-         return true;
-      }
-
-      if (log.isLoggable(java.util.logging.Level.FINE)) {
-         log.log(java.util.logging.Level.FINE, "I state that I can't resolve " + uriNodeValue);
-      }
+        return false;
+    }
 
-      return false;
-   }
-
-   /**
-    * @inheritDoc
-    */
-   public String[] engineGetPropertyKeys() {
-      return ResolverDirectHTTP.properties.clone();
-   }
+    /**
+     * @inheritDoc
+     */
+    public String[] engineGetPropertyKeys() {
+        return ResolverDirectHTTP.properties.clone();
+    }
 
-   private URI getNewURI(String uri, String BaseURI)
-           throws URI.MalformedURIException {
+    private static URI getNewURI(String uri, String baseURI) throws URISyntaxException {
+        URI newUri = null;
+        if (baseURI == null || "".equals(baseURI)) {
+            newUri = new URI(uri);
+        } else {
+            newUri = new URI(baseURI).resolve(uri);
+        }
 
-      if ((BaseURI == null) || "".equals(BaseURI)) {
-         return new URI(uri);
-      }
-      return new URI(new URI(BaseURI), uri);
-   }
+        // if the URI contains a fragment, ignore it
+        if (newUri.getFragment() != null) {
+            URI uriNewNoFrag =
+                new URI(newUri.getScheme(), newUri.getSchemeSpecificPart(), null);
+            return uriNewNoFrag;
+        }
+        return newUri;
+    }
+
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,148 +2,148 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils.resolver.implementations;
 
-
-
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
+import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
-import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
-
 /**
  * This resolver is used for resolving same-document URIs like URI="" of URI="#id".
  *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#sec-ReferenceProcessingModel">The Reference processing model in the XML Signature spec</A>
  * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#sec-Same-Document">Same-Document URI-References in the XML Signature spec</A>
  * @see <A HREF="http://www.ietf.org/rfc/rfc2396.txt">Section 4.2 of RFC 2396</A>
  */
 public class ResolverFragment extends ResourceResolverSpi {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(
-                            ResolverFragment.class.getName());
-   public boolean engineIsThreadSafe() {
-           return true;
-   }
-   /**
-    * Method engineResolve
-    *
-    * @inheritDoc
-    * @param uri
-    * @param baseURI
-    */
-   public XMLSignatureInput engineResolve(Attr uri, String baseURI)
-       throws ResourceResolverException
-   {
-        String uriNodeValue = uri.getNodeValue();
-        Document doc = uri.getOwnerElement().getOwnerDocument();
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(ResolverFragment.class.getName());
+
+    @Override
+    public boolean engineIsThreadSafe() {
+        return true;
+    }
+
+    /**
+     * Method engineResolve
+     *
+     * @inheritDoc
+     * @param uri
+     * @param baseURI
+     */
+    public XMLSignatureInput engineResolveURI(ResourceResolverContext context)
+        throws ResourceResolverException {
+
+        Document doc = context.attr.getOwnerElement().getOwnerDocument();
 
         Node selectedElem = null;
-        if (uriNodeValue.equals("")) {
-
-           /*
-            * Identifies the node-set (minus any comment nodes) of the XML
-            * resource containing the signature
-            */
-
-            log.log(java.util.logging.Level.FINE, "ResolverFragment with empty URI (means complete document)");
+        if (context.uriToResolve.equals("")) {
+            /*
+             * Identifies the node-set (minus any comment nodes) of the XML
+             * resource containing the signature
+             */
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "ResolverFragment with empty URI (means complete document)");
+            }
             selectedElem = doc;
         } else {
-
             /*
              * URI="#chapter1"
              * Identifies a node-set containing the element with ID attribute
              * value 'chapter1' of the XML resource containing the signature.
              * XML Signature (and its applications) modify this node-set to
-             * include the element plus all descendents including namespaces and
+             * include the element plus all descendants including namespaces and
              * attributes -- but not comments.
              */
-            String id = uriNodeValue.substring(1);
+            String id = context.uriToResolve.substring(1);
 
             selectedElem = doc.getElementById(id);
             if (selectedElem == null) {
                 Object exArgs[] = { id };
                 throw new ResourceResolverException(
-                    "signature.Verification.MissingID", exArgs, uri, baseURI);
+                    "signature.Verification.MissingID", exArgs, context.attr, context.baseUri
+                );
             }
-            if (secureValidation) {
-                Element start = uri.getOwnerDocument().getDocumentElement();
+            if (context.secureValidation) {
+                Element start = context.attr.getOwnerDocument().getDocumentElement();
                 if (!XMLUtils.protectAgainstWrappingAttack(start, id)) {
                     Object exArgs[] = { id };
                     throw new ResourceResolverException(
-                        "signature.Verification.MultipleIDs", exArgs,
-                        uri, baseURI);
+                        "signature.Verification.MultipleIDs", exArgs, context.attr, context.baseUri
+                    );
                 }
             }
-            if (log.isLoggable(java.util.logging.Level.FINE))
-                log.log(java.util.logging.Level.FINE, "Try to catch an Element with ID " + id + " and Element was " + selectedElem);
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE,
+                    "Try to catch an Element with ID " + id + " and Element was " + selectedElem
+                );
+            }
         }
 
         XMLSignatureInput result = new XMLSignatureInput(selectedElem);
         result.setExcludeComments(true);
 
         result.setMIMEType("text/xml");
-        if (baseURI != null && baseURI.length() > 0) {
-            result.setSourceURI(baseURI.concat(uri.getNodeValue()));
+        if (context.baseUri != null && context.baseUri.length() > 0) {
+            result.setSourceURI(context.baseUri.concat(context.uriToResolve));
         } else {
-            result.setSourceURI(uri.getNodeValue());
+            result.setSourceURI(context.uriToResolve);
         }
         return result;
     }
 
-   /**
-    * Method engineCanResolve
-    * @inheritDoc
-    * @param uri
-    * @param BaseURI
-    *
-    */
-   public boolean engineCanResolve(Attr uri, String BaseURI) {
-
-      if (uri == null) {
-         log.log(java.util.logging.Level.FINE, "Quick fail for null uri");
-         return false;
-      }
+    /**
+     * Method engineCanResolve
+     * @inheritDoc
+     * @param uri
+     * @param baseURI
+     */
+    public boolean engineCanResolveURI(ResourceResolverContext context) {
+        if (context.uriToResolve == null) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "Quick fail for null uri");
+            }
+            return false;
+        }
 
-      String uriNodeValue = uri.getNodeValue();
-
-      if  (uriNodeValue.equals("") ||
-             (
-            (uriNodeValue.charAt(0)=='#')
-              && !((uriNodeValue.charAt(1)=='x') && uriNodeValue.startsWith("#xpointer("))
-              )
-           ){
-         if (log.isLoggable(java.util.logging.Level.FINE))
-                log.log(java.util.logging.Level.FINE, "State I can resolve reference: \"" + uriNodeValue + "\"");
-         return true;
-      }
-      if (log.isLoggable(java.util.logging.Level.FINE))
-        log.log(java.util.logging.Level.FINE, "Do not seem to be able to resolve reference: \"" + uriNodeValue + "\"");
-      return false;
-   }
+        if (context.uriToResolve.equals("") ||
+            ((context.uriToResolve.charAt(0) == '#') && !context.uriToResolve.startsWith("#xpointer("))
+        ) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "State I can resolve reference: \"" + context.uriToResolve + "\"");
+            }
+            return true;
+        }
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Do not seem to be able to resolve reference: \"" + context.uriToResolve + "\"");
+        }
+        return false;
+    }
 
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,156 +2,160 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils.resolver.implementations;
 
 import java.io.FileInputStream;
+import java.net.URI;
+import java.net.URISyntaxException;
 
-import com.sun.org.apache.xml.internal.utils.URI;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
+import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
-import org.w3c.dom.Attr;
 
 /**
  * A simple ResourceResolver for requests into the local filesystem.
- *
- * @author $Author: mullan $
  */
 public class ResolverLocalFilesystem extends ResourceResolverSpi {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(
-                    ResolverLocalFilesystem.class.getName());
+    private static final int FILE_URI_LENGTH = "file:/".length();
 
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(ResolverLocalFilesystem.class.getName());
+
+    @Override
     public boolean engineIsThreadSafe() {
-           return true;
-   }
-   /**
-    * @inheritDoc
-    */
-   public XMLSignatureInput engineResolve(Attr uri, String BaseURI)
-           throws ResourceResolverException {
+        return true;
+    }
+
+    /**
+     * @inheritDoc
+     */
+    @Override
+    public XMLSignatureInput engineResolveURI(ResourceResolverContext context)
+        throws ResourceResolverException {
+        try {
+            // calculate new URI
+            URI uriNew = getNewURI(context.uriToResolve, context.baseUri);
+
+            String fileName =
+                ResolverLocalFilesystem.translateUriToFilename(uriNew.toString());
+            FileInputStream inputStream = new FileInputStream(fileName);
+            XMLSignatureInput result = new XMLSignatureInput(inputStream);
+
+            result.setSourceURI(uriNew.toString());
+
+            return result;
+        } catch (Exception e) {
+            throw new ResourceResolverException("generic.EmptyMessage", e, context.attr, context.baseUri);
+        }
+    }
+
+    /**
+     * Method translateUriToFilename
+     *
+     * @param uri
+     * @return the string of the filename
+     */
+    private static String translateUriToFilename(String uri) {
+
+        String subStr = uri.substring(FILE_URI_LENGTH);
+
+        if (subStr.indexOf("%20") > -1) {
+            int offset = 0;
+            int index = 0;
+            StringBuilder temp = new StringBuilder(subStr.length());
+            do {
+                index = subStr.indexOf("%20",offset);
+                if (index == -1) {
+                    temp.append(subStr.substring(offset));
+                } else {
+                    temp.append(subStr.substring(offset, index));
+                    temp.append(' ');
+                    offset = index + 3;
+                }
+            } while(index != -1);
+            subStr = temp.toString();
+        }
 
-     try {
-        URI uriNew = getNewURI(uri.getNodeValue(), BaseURI);
+        if (subStr.charAt(1) == ':') {
+            // we're running M$ Windows, so this works fine
+            return subStr;
+        }
+        // we're running some UNIX, so we have to prepend a slash
+        return "/" + subStr;
+    }
+
+    /**
+     * @inheritDoc
+     */
+    public boolean engineCanResolveURI(ResourceResolverContext context) {
+        if (context.uriToResolve == null) {
+            return false;
+        }
+
+        if (context.uriToResolve.equals("") || (context.uriToResolve.charAt(0)=='#') ||
+            context.uriToResolve.startsWith("http:")) {
+            return false;
+        }
+
+        try {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + context.uriToResolve);
+            }
+
+            if (context.uriToResolve.startsWith("file:") || context.baseUri.startsWith("file:")) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "I state that I can resolve " + context.uriToResolve);
+                }
+                return true;
+            }
+        } catch (Exception e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+            }
+        }
+
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "But I can't");
+        }
+
+        return false;
+    }
+
+    private static URI getNewURI(String uri, String baseURI) throws URISyntaxException {
+        URI newUri = null;
+        if (baseURI == null || "".equals(baseURI)) {
+            newUri = new URI(uri);
+        } else {
+            newUri = new URI(baseURI).resolve(uri);
+        }
 
         // if the URI contains a fragment, ignore it
-        URI uriNewNoFrag = new URI(uriNew);
-
-        uriNewNoFrag.setFragment(null);
-
-        String fileName =
-           ResolverLocalFilesystem
-              .translateUriToFilename(uriNewNoFrag.toString());
-        FileInputStream inputStream = new FileInputStream(fileName);
-        XMLSignatureInput result = new XMLSignatureInput(inputStream);
-
-        result.setSourceURI(uriNew.toString());
-
-        return result;
-     } catch (Exception e) {
-        throw new ResourceResolverException("generic.EmptyMessage", e, uri,
-                                            BaseURI);
-      }
-   }
-
-   private static int FILE_URI_LENGTH="file:/".length();
-   /**
-    * Method translateUriToFilename
-    *
-    * @param uri
-    * @return the string of the filename
-    */
-   private static String translateUriToFilename(String uri) {
-
-      String subStr = uri.substring(FILE_URI_LENGTH);
-
-      if (subStr.indexOf("%20") > -1)
-      {
-        int offset = 0;
-        int index = 0;
-        StringBuffer temp = new StringBuffer(subStr.length());
-        do
-        {
-          index = subStr.indexOf("%20",offset);
-          if (index == -1) temp.append(subStr.substring(offset));
-          else
-          {
-            temp.append(subStr.substring(offset,index));
-            temp.append(' ');
-            offset = index+3;
-          }
+        if (newUri.getFragment() != null) {
+            URI uriNewNoFrag =
+                new URI(newUri.getScheme(), newUri.getSchemeSpecificPart(), null);
+            return uriNewNoFrag;
         }
-        while(index != -1);
-        subStr = temp.toString();
-      }
-
-      if (subStr.charAt(1) == ':') {
-         // we're running M$ Windows, so this works fine
-         return subStr;
-      }
-      // we're running some UNIX, so we have to prepend a slash
-      return "/" + subStr;
-   }
-
-   /**
-    * @inheritDoc
-    */
-   public boolean engineCanResolve(Attr uri, String BaseURI) {
-
-      if (uri == null) {
-         return false;
-      }
-
-      String uriNodeValue = uri.getNodeValue();
-
-      if (uriNodeValue.equals("") || (uriNodeValue.charAt(0)=='#') ||
-          uriNodeValue.startsWith("http:")) {
-         return false;
-      }
-
-      try {
-                 //URI uriNew = new URI(new URI(BaseURI), uri.getNodeValue());
-                 if (log.isLoggable(java.util.logging.Level.FINE))
-                        log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + uriNodeValue/*uriNew.toString()*/);
-
-                 if ( uriNodeValue.startsWith("file:") ||
-                                         BaseURI.startsWith("file:")/*uriNew.getScheme().equals("file")*/) {
-                    if (log.isLoggable(java.util.logging.Level.FINE))
-                        log.log(java.util.logging.Level.FINE, "I state that I can resolve " + uriNodeValue/*uriNew.toString()*/);
-
-                    return true;
-                 }
-      } catch (Exception e) {}
-
-      log.log(java.util.logging.Level.FINE, "But I can't");
-
-      return false;
-   }
-
-   private static URI getNewURI(String uri, String BaseURI)
-           throws URI.MalformedURIException {
-
-      if ((BaseURI == null) || "".equals(BaseURI)) {
-         return new URI(uri);
-      }
-      return new URI(new URI(BaseURI), uri);
-   }
+        return newUri;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,36 +2,35 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils.resolver.implementations;
 
-
-
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
+import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
-import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
-
 /**
  * Handles barename XPointer Reference URIs.
  * <BR />
@@ -45,15 +44,18 @@
  * nodes of the parse tree (all descendants, plus all attributes,
  * plus all namespaces nodes).
  *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
  */
 public class ResolverXPointer extends ResourceResolverSpi {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(
-                            ResolverXPointer.class.getName());
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(ResolverXPointer.class.getName());
 
+    private static final String XP = "#xpointer(id(";
+    private static final int XP_LENGTH = XP.length();
+
+    @Override
     public boolean engineIsThreadSafe() {
         return true;
     }
@@ -61,139 +63,118 @@
     /**
      * @inheritDoc
      */
-    public XMLSignatureInput engineResolve(Attr uri, String baseURI)
-           throws ResourceResolverException {
+    @Override
+    public XMLSignatureInput engineResolveURI(ResourceResolverContext context)
+        throws ResourceResolverException {
 
         Node resultNode = null;
-        Document doc = uri.getOwnerElement().getOwnerDocument();
+        Document doc = context.attr.getOwnerElement().getOwnerDocument();
 
-        String uriStr = uri.getNodeValue();
-        if (isXPointerSlash(uriStr)) {
+        if (isXPointerSlash(context.uriToResolve)) {
             resultNode = doc;
-
-        } else if (isXPointerId(uriStr)) {
-            String id = getXPointerId(uriStr);
+        } else if (isXPointerId(context.uriToResolve)) {
+            String id = getXPointerId(context.uriToResolve);
             resultNode = doc.getElementById(id);
 
-            if (secureValidation) {
-                Element start = uri.getOwnerDocument().getDocumentElement();
+            if (context.secureValidation) {
+                Element start = context.attr.getOwnerDocument().getDocumentElement();
                 if (!XMLUtils.protectAgainstWrappingAttack(start, id)) {
                     Object exArgs[] = { id };
                     throw new ResourceResolverException(
-                        "signature.Verification.MultipleIDs", exArgs,
-                        uri, baseURI);
+                        "signature.Verification.MultipleIDs", exArgs, context.attr, context.baseUri
+                    );
                 }
             }
 
             if (resultNode == null) {
-               Object exArgs[] = { id };
+                Object exArgs[] = { id };
 
-               throw new ResourceResolverException(
-                  "signature.Verification.MissingID", exArgs, uri, baseURI);
+                throw new ResourceResolverException(
+                    "signature.Verification.MissingID", exArgs, context.attr, context.baseUri
+                );
             }
         }
 
         XMLSignatureInput result = new XMLSignatureInput(resultNode);
 
         result.setMIMEType("text/xml");
-        if (baseURI != null && baseURI.length() > 0) {
-            result.setSourceURI(baseURI.concat(uri.getNodeValue()));
+        if (context.baseUri != null && context.baseUri.length() > 0) {
+            result.setSourceURI(context.baseUri.concat(context.uriToResolve));
         } else {
-            result.setSourceURI(uri.getNodeValue());
+            result.setSourceURI(context.uriToResolve);
         }
 
         return result;
     }
 
-   /**
-    * @inheritDoc
-    */
-   public boolean engineCanResolve(Attr uri, String BaseURI) {
+    /**
+     * @inheritDoc
+     */
+    public boolean engineCanResolveURI(ResourceResolverContext context) {
+        if (context.uriToResolve == null) {
+            return false;
+        }
+        if (isXPointerSlash(context.uriToResolve) || isXPointerId(context.uriToResolve)) {
+            return true;
+        }
 
-      if (uri == null) {
-         return false;
-      }
-          String uriStr =uri.getNodeValue();
-      if (isXPointerSlash(uriStr) || isXPointerId(uriStr)) {
-         return true;
-      }
-
-      return false;
-   }
+        return false;
+    }
 
-   /**
-    * Method isXPointerSlash
-    *
-    * @param uri
-    * @return true if begins with xpointer
-    */
-   private static boolean isXPointerSlash(String uri) {
-
-      if (uri.equals("#xpointer(/)")) {
-         return true;
-      }
+    /**
+     * Method isXPointerSlash
+     *
+     * @param uri
+     * @return true if begins with xpointer
+     */
+    private static boolean isXPointerSlash(String uri) {
+        if (uri.equals("#xpointer(/)")) {
+            return true;
+        }
 
-      return false;
-   }
-
-
-   private static final String XP="#xpointer(id(";
-   private static final int XP_LENGTH=XP.length();
-   /**
-    * Method isXPointerId
-    *
-    * @param uri
-    * @return it it has an xpointer id
-    *
-    */
-   private static boolean isXPointerId(String uri) {
-
+        return false;
+    }
 
-      if (uri.startsWith(XP)
-              && uri.endsWith("))")) {
-         String idPlusDelim = uri.substring(XP_LENGTH,
-                                                     uri.length()
-                                                     - 2);
+    /**
+     * Method isXPointerId
+     *
+     * @param uri
+     * @return whether it has an xpointer id
+     */
+    private static boolean isXPointerId(String uri) {
+        if (uri.startsWith(XP) && uri.endsWith("))")) {
+            String idPlusDelim = uri.substring(XP_LENGTH, uri.length() - 2);
 
-         // log.log(java.util.logging.Level.FINE, "idPlusDelim=" + idPlusDelim);
-                 int idLen=idPlusDelim.length() -1;
-         if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim
-                 .charAt(idLen) == '"')) || ((idPlusDelim
-                 .charAt(0) == '\'') && (idPlusDelim
-                 .charAt(idLen) == '\''))) {
-            if (log.isLoggable(java.util.logging.Level.FINE))
-                log.log(java.util.logging.Level.FINE, "Id="
-                      + idPlusDelim.substring(1, idLen));
-
-            return true;
-         }
-      }
-
-      return false;
-   }
+            int idLen = idPlusDelim.length() -1;
+            if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim.charAt(idLen) == '"'))
+                || ((idPlusDelim.charAt(0) == '\'') && (idPlusDelim.charAt(idLen) == '\''))) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "Id = " + idPlusDelim.substring(1, idLen));
+                }
+                return true;
+            }
+        }
 
-   /**
-    * Method getXPointerId
-    *
-    * @param uri
-    * @return xpointerId to search.
-    */
-   private static String getXPointerId(String uri) {
-
+        return false;
+    }
 
-      if (uri.startsWith(XP)
-              && uri.endsWith("))")) {
-         String idPlusDelim = uri.substring(XP_LENGTH,uri.length()
-                                                     - 2);
-                 int idLen=idPlusDelim.length() -1;
-         if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim
-                 .charAt(idLen) == '"')) || ((idPlusDelim
-                 .charAt(0) == '\'') && (idPlusDelim
-                 .charAt(idLen) == '\''))) {
-            return idPlusDelim.substring(1, idLen);
-         }
-      }
+    /**
+     * Method getXPointerId
+     *
+     * @param uri
+     * @return xpointerId to search.
+     */
+    private static String getXPointerId(String uri) {
+        if (uri.startsWith(XP) && uri.endsWith("))")) {
+            String idPlusDelim = uri.substring(XP_LENGTH,uri.length() - 2);
 
-      return null;
-   }
+            int idLen = idPlusDelim.length() -1;
+            if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim.charAt(idLen) == '"'))
+                || ((idPlusDelim.charAt(0) == '\'') && (idPlusDelim.charAt(idLen) == '\''))) {
+                return idPlusDelim.substring(1, idLen);
+            }
+        }
+
+        return null;
+    }
 }
--- a/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java	Mon Jul 22 17:37:15 2013 -0700
@@ -252,13 +252,12 @@
 
 
     /**
-     * Outputs a byte array and converts
+     * Outputs a byte array. Can be null.
      */
     protected static final void traceOutput(String srcClass, String srcMethod,
         String traceTag, byte[] output) {
-        if (output != null) {
-            traceOutput(srcClass, srcMethod, traceTag, output, 0, output.length);
-        }
+        traceOutput(srcClass, srcMethod, traceTag, output, 0,
+                output == null ? 0 : output.length);
     }
 
     protected static final void traceOutput(String srcClass, String srcMethod,
@@ -274,13 +273,20 @@
                 lev = Level.FINEST;
             }
 
-            ByteArrayOutputStream out = new ByteArrayOutputStream(len);
-            new HexDumpEncoder().encodeBuffer(
-                new ByteArrayInputStream(output, offset, len), out);
+            String content;
+
+            if (output != null) {
+                ByteArrayOutputStream out = new ByteArrayOutputStream(len);
+                new HexDumpEncoder().encodeBuffer(
+                    new ByteArrayInputStream(output, offset, len), out);
+                content = out.toString();
+            } else {
+                content = "NULL";
+            }
 
             // Message id supplied by caller as part of traceTag
             logger.logp(lev, srcClass, srcMethod, "{0} ( {1} ): {2}",
-                new Object[] {traceTag, new Integer(origlen), out.toString()});
+                new Object[] {traceTag, new Integer(origlen), content});
         } catch (Exception e) {
             logger.logp(Level.WARNING, srcClass, srcMethod,
                 "SASLIMPL09:Error generating trace output: {0}", e);
--- a/src/share/classes/java/awt/GraphicsDevice.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/awt/GraphicsDevice.java	Mon Jul 22 17:37:15 2013 -0700
@@ -296,6 +296,12 @@
                                     bgColor.getBlue(), 255);
                 w.setBackground(bgColor);
             }
+            // Check if this window is in fullscreen mode on another device.
+            final GraphicsConfiguration gc = w.getGraphicsConfiguration();
+            if (gc != null && gc.getDevice() != this
+                    && gc.getDevice().getFullScreenWindow() == w) {
+                gc.getDevice().setFullScreenWindow(null);
+            }
         }
         if (fullScreenWindow != null && windowedModeBounds != null) {
             // if the window went into fs mode before it was realized it may
--- a/src/share/classes/java/beans/Introspector.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/beans/Introspector.java	Mon Jul 22 17:37:15 2013 -0700
@@ -652,11 +652,12 @@
                     }
                 } else {
                     if (pd.getReadMethod() != null) {
+                        String pdName = pd.getReadMethod().getName();
                         if (gpd != null) {
                             // Don't replace the existing read
                             // method if it starts with "is"
-                            Method method = gpd.getReadMethod();
-                            if (!method.getName().startsWith(IS_PREFIX)) {
+                            String gpdName = gpd.getReadMethod().getName();
+                            if (gpdName.equals(pdName) || !gpdName.startsWith(IS_PREFIX)) {
                                 gpd = new PropertyDescriptor(gpd, pd);
                             }
                         } else {
--- a/src/share/classes/java/io/BufferedReader.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/io/BufferedReader.java	Mon Jul 22 17:37:15 2013 -0700
@@ -587,6 +587,6 @@
                 }
             }
         };
-        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iter, Spliterator.ORDERED));
+        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iter, Spliterator.ORDERED), false);
     }
 }
--- a/src/share/classes/java/io/DataInput.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/io/DataInput.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -66,10 +66,10 @@
  *          summary="Bit values and bytes">
  *     <tr>
  *       <td></td>
- *       <th id="bit">Bit Values</th>
+ *       <th id="bit_a">Bit Values</th>
  *     </tr>
  *     <tr>
- *       <th id="byte1">Byte 1</th>
+ *       <th id="byte1_a">Byte 1</th>
  *       <td>
  *         <table border="1" cellspacing="0" width="100%">
  *           <tr>
@@ -92,10 +92,10 @@
  *          summary="Bit values and bytes">
  *     <tr>
  *       <td></td>
- *       <th id="bit">Bit Values</th>
+ *       <th id="bit_b">Bit Values</th>
  *     </tr>
  *     <tr>
- *       <th id="byte1">Byte 1</th>
+ *       <th id="byte1_b">Byte 1</th>
  *       <td>
  *         <table border="1" cellspacing="0" width="100%">
  *           <tr>
@@ -108,7 +108,7 @@
  *       </td>
  *     </tr>
  *     <tr>
- *       <th id="byte2">Byte 2</th>
+ *       <th id="byte2_a">Byte 2</th>
  *       <td>
  *         <table border="1" cellspacing="0" width="100%">
  *           <tr>
@@ -131,10 +131,10 @@
  *          summary="Bit values and bytes">
  *     <tr>
  *       <td></td>
- *       <th id="bit">Bit Values</th>
+ *       <th id="bit_c">Bit Values</th>
  *     </tr>
  *     <tr>
- *       <th id="byte1">Byte 1</th>
+ *       <th id="byte1_c">Byte 1</th>
  *       <td>
  *         <table border="1" cellspacing="0" width="100%">
  *           <tr>
@@ -148,7 +148,7 @@
  *       </td>
  *     </tr>
  *     <tr>
- *       <th id="byte2">Byte 2</th>
+ *       <th id="byte2_b">Byte 2</th>
  *       <td>
  *         <table border="1" cellspacing="0" width="100%">
  *           <tr>
--- a/src/share/classes/java/io/File.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/io/File.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1910,7 +1910,7 @@
             }
             String name = prefix + Long.toString(n) + suffix;
             File f = new File(dir, name);
-            if (!name.equals(f.getName()))
+            if (!name.equals(f.getName()) || f.isInvalid())
                 throw new IOException("Unable to create temporary file");
             return f;
         }
@@ -1996,19 +1996,26 @@
 
         File tmpdir = (directory != null) ? directory
                                           : TempDirectory.location();
+        SecurityManager sm = System.getSecurityManager();
         File f;
-        try {
-            do {
-                f = TempDirectory.generateFile(prefix, suffix, tmpdir);
-            } while (f.exists());
-            if (!f.createNewFile())
-                throw new IOException("Unable to create temporary file");
-        } catch (SecurityException se) {
-            // don't reveal temporary directory location
-            if (directory == null)
-                throw new SecurityException("Unable to create temporary file");
-            throw se;
-        }
+        do {
+            f = TempDirectory.generateFile(prefix, suffix, tmpdir);
+
+            if (sm != null) {
+                try {
+                    sm.checkWrite(f.getPath());
+                } catch (SecurityException se) {
+                    // don't reveal temporary directory location
+                    if (directory == null)
+                        throw new SecurityException("Unable to create temporary file");
+                    throw se;
+                }
+            }
+        } while ((fs.getBooleanAttributes(f) & FileSystem.BA_EXISTS) != 0);
+
+        if (!fs.createFileExclusively(f.getPath()))
+            throw new IOException("Unable to create temporary file");
+
         return f;
     }
 
--- a/src/share/classes/java/io/FileInputStream.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/io/FileInputStream.java	Mon Jul 22 17:37:15 2013 -0700
@@ -331,7 +331,7 @@
      * object associated with this file input stream.
      *
      * <p> The initial {@link java.nio.channels.FileChannel#position()
-     * </code>position<code>} of the returned channel will be equal to the
+     * position} of the returned channel will be equal to the
      * number of bytes read from the file so far.  Reading bytes from this
      * stream will increment the channel's position.  Changing the channel's
      * position, either explicitly or by reading, will change this stream's
--- a/src/share/classes/java/io/FileOutputStream.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/io/FileOutputStream.java	Mon Jul 22 17:37:15 2013 -0700
@@ -358,10 +358,10 @@
 
     /**
      * Returns the unique {@link java.nio.channels.FileChannel FileChannel}
-     * object associated with this file output stream. </p>
+     * object associated with this file output stream.
      *
      * <p> The initial {@link java.nio.channels.FileChannel#position()
-     * </code>position<code>} of the returned channel will be equal to the
+     * position} of the returned channel will be equal to the
      * number of bytes written to the file so far unless this stream is in
      * append mode, in which case it will be equal to the size of the file.
      * Writing bytes to this stream will increment the channel's position
--- a/src/share/classes/java/io/InputStreamReader.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/io/InputStreamReader.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,7 +33,7 @@
 /**
  * An InputStreamReader is a bridge from byte streams to character streams: It
  * reads bytes and decodes them into characters using a specified {@link
- * java.nio.charset.Charset <code>charset</code>}.  The charset that it uses
+ * java.nio.charset.Charset charset}.  The charset that it uses
  * may be specified by name or may be given explicitly, or the platform's
  * default charset may be accepted.
  *
@@ -101,7 +101,7 @@
     }
 
     /**
-     * Creates an InputStreamReader that uses the given charset. </p>
+     * Creates an InputStreamReader that uses the given charset.
      *
      * @param  in       An InputStream
      * @param  cs       A charset
@@ -117,7 +117,7 @@
     }
 
     /**
-     * Creates an InputStreamReader that uses the given charset decoder.  </p>
+     * Creates an InputStreamReader that uses the given charset decoder.
      *
      * @param  in       An InputStream
      * @param  dec      A charset decoder
--- a/src/share/classes/java/io/OutputStreamWriter.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/io/OutputStreamWriter.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,7 +33,7 @@
 /**
  * An OutputStreamWriter is a bridge from character streams to byte streams:
  * Characters written to it are encoded into bytes using a specified {@link
- * java.nio.charset.Charset <code>charset</code>}.  The charset that it uses
+ * java.nio.charset.Charset charset}.  The charset that it uses
  * may be specified by name or may be given explicitly, or the platform's
  * default charset may be accepted.
  *
@@ -86,7 +86,7 @@
      *
      * @param  charsetName
      *         The name of a supported
-     *         {@link java.nio.charset.Charset </code>charset<code>}
+     *         {@link java.nio.charset.Charset charset}
      *
      * @exception  UnsupportedEncodingException
      *             If the named encoding is not supported
@@ -115,7 +115,7 @@
     }
 
     /**
-     * Creates an OutputStreamWriter that uses the given charset. </p>
+     * Creates an OutputStreamWriter that uses the given charset.
      *
      * @param  out
      *         An OutputStream
@@ -134,7 +134,7 @@
     }
 
     /**
-     * Creates an OutputStreamWriter that uses the given charset encoder.  </p>
+     * Creates an OutputStreamWriter that uses the given charset encoder.
      *
      * @param  out
      *         An OutputStream
--- a/src/share/classes/java/io/PipedInputStream.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/io/PipedInputStream.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -39,7 +39,7 @@
  * The piped input stream contains a buffer,
  * decoupling read operations from write operations,
  * within limits.
- * A pipe is said to be <a name=BROKEN> <i>broken</i> </a> if a
+ * A pipe is said to be <a name="BROKEN"> <i>broken</i> </a> if a
  * thread that was providing data bytes to the connected
  * piped output stream is no longer alive.
  *
@@ -193,7 +193,7 @@
      * Receives a byte of data.  This method will block if no input is
      * available.
      * @param b the byte being received
-     * @exception IOException If the pipe is <a href=#BROKEN> <code>broken</code></a>,
+     * @exception IOException If the pipe is <a href="#BROKEN"> <code>broken</code></a>,
      *          {@link #connect(java.io.PipedOutputStream) unconnected},
      *          closed, or if an I/O error occurs.
      * @since     JDK1.1
@@ -219,7 +219,7 @@
      * @param b the buffer into which the data is received
      * @param off the start offset of the data
      * @param len the maximum number of bytes received
-     * @exception IOException If the pipe is <a href=#BROKEN> broken</a>,
+     * @exception IOException If the pipe is <a href="#BROKEN"> broken</a>,
      *           {@link #connect(java.io.PipedOutputStream) unconnected},
      *           closed,or if an I/O error occurs.
      */
@@ -298,7 +298,7 @@
      *             stream is reached.
      * @exception  IOException  if the pipe is
      *           {@link #connect(java.io.PipedOutputStream) unconnected},
-     *           <a href=#BROKEN> <code>broken</code></a>, closed,
+     *           <a href="#BROKEN"> <code>broken</code></a>, closed,
      *           or if an I/O error occurs.
      */
     public synchronized int read()  throws IOException {
@@ -361,7 +361,7 @@
      * @exception  IndexOutOfBoundsException If <code>off</code> is negative,
      * <code>len</code> is negative, or <code>len</code> is greater than
      * <code>b.length - off</code>
-     * @exception  IOException if the pipe is <a href=#BROKEN> <code>broken</code></a>,
+     * @exception  IOException if the pipe is <a href="#BROKEN"> <code>broken</code></a>,
      *           {@link #connect(java.io.PipedOutputStream) unconnected},
      *           closed, or if an I/O error occurs.
      */
@@ -419,7 +419,7 @@
      *         without blocking, or {@code 0} if this input stream has been
      *         closed by invoking its {@link #close()} method, or if the pipe
      *         is {@link #connect(java.io.PipedOutputStream) unconnected}, or
-     *          <a href=#BROKEN> <code>broken</code></a>.
+     *          <a href="#BROKEN"> <code>broken</code></a>.
      *
      * @exception  IOException  if an I/O error occurs.
      * @since   JDK1.0.2
--- a/src/share/classes/java/io/RandomAccessFile.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/io/RandomAccessFile.java	Mon Jul 22 17:37:15 2013 -0700
@@ -123,11 +123,11 @@
      * write to, the file specified by the {@link File} argument.  A new {@link
      * FileDescriptor} object is created to represent this file connection.
      *
-     * <a name="mode"><p> The <tt>mode</tt> argument specifies the access mode
+     * <p>The <a name="mode"><tt>mode</tt></a> argument specifies the access mode
      * in which the file is to be opened.  The permitted values and their
      * meanings are:
      *
-     * <blockquote><table summary="Access mode permitted values and meanings">
+     * <table summary="Access mode permitted values and meanings">
      * <tr><th><p align="left">Value</p></th><th><p align="left">Meaning</p></th></tr>
      * <tr><td valign="top"><tt>"r"</tt></td>
      *     <td> Open for reading only.  Invoking any of the <tt>write</tt>
@@ -144,7 +144,7 @@
      *     <td> Open for reading and writing, as with <tt>"rw"</tt>, and also
      *     require that every update to the file's content be written
      *     synchronously to the underlying storage device. </td></tr>
-     * </table></blockquote>
+     * </table>
      *
      * The <tt>"rws"</tt> and <tt>"rwd"</tt> modes work much like the {@link
      * java.nio.channels.FileChannel#force(boolean) force(boolean)} method of
@@ -158,13 +158,13 @@
      * event of a system crash.  If the file does not reside on a local device
      * then no such guarantee is made.
      *
-     * <p> The <tt>"rwd"</tt> mode can be used to reduce the number of I/O
+     * <p>The <tt>"rwd"</tt> mode can be used to reduce the number of I/O
      * operations performed.  Using <tt>"rwd"</tt> only requires updates to the
      * file's content to be written to storage; using <tt>"rws"</tt> requires
      * updates to both the file's content and its metadata to be written, which
      * generally requires at least one more low-level I/O operation.
      *
-     * <p> If there is a security manager, its {@code checkRead} method is
+     * <p>If there is a security manager, its {@code checkRead} method is
      * called with the pathname of the {@code file} argument as its
      * argument to see if read access to the file is allowed.  If the mode
      * allows writing, the security manager's {@code checkWrite} method is
@@ -238,7 +238,7 @@
 
     /**
      * Returns the opaque file descriptor object associated with this
-     * stream. </p>
+     * stream.
      *
      * @return     the file descriptor object associated with this stream.
      * @exception  IOException  if an I/O error occurs.
--- a/src/share/classes/java/lang/CharSequence.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/CharSequence.java	Mon Jul 22 17:37:15 2013 -0700
@@ -60,7 +60,7 @@
 
     /**
      * Returns the length of this character sequence.  The length is the number
-     * of 16-bit <code>char</code>s in the sequence.</p>
+     * of 16-bit <code>char</code>s in the sequence.
      *
      * @return  the number of <code>char</code>s in this sequence
      */
@@ -70,7 +70,7 @@
      * Returns the <code>char</code> value at the specified index.  An index ranges from zero
      * to <tt>length() - 1</tt>.  The first <code>char</code> value of the sequence is at
      * index zero, the next at index one, and so on, as for array
-     * indexing. </p>
+     * indexing.
      *
      * <p>If the <code>char</code> value specified by the index is a
      * <a href="{@docRoot}/java/lang/Character.html#unicode">surrogate</a>, the surrogate
@@ -92,7 +92,7 @@
      * ends with the <code>char</code> value at index <tt>end - 1</tt>.  The length
      * (in <code>char</code>s) of the
      * returned sequence is <tt>end - start</tt>, so if <tt>start == end</tt>
-     * then an empty sequence is returned. </p>
+     * then an empty sequence is returned.
      *
      * @param   start   the start index, inclusive
      * @param   end     the end index, exclusive
@@ -109,7 +109,7 @@
     /**
      * Returns a string containing the characters in this sequence in the same
      * order as this sequence.  The length of the string will be the length of
-     * this sequence. </p>
+     * this sequence.
      *
      * @return  a string consisting of exactly this sequence of characters
      */
@@ -156,7 +156,8 @@
                         new CharIterator(),
                         length(),
                         Spliterator.ORDERED),
-                Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED);
+                Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED,
+                false);
     }
 
     /**
@@ -227,6 +228,7 @@
                 Spliterators.spliteratorUnknownSize(
                         new CodePointIterator(),
                         Spliterator.ORDERED),
-                Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED);
+                Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED,
+                false);
     }
 }
--- a/src/share/classes/java/lang/Character.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/Character.java	Mon Jul 22 17:37:15 2013 -0700
@@ -54,7 +54,7 @@
  * <li><a href="http://www.unicode.org">http://www.unicode.org</a>
  * </ul>
  *
- * <h4><a name="unicode">Unicode Character Representations</a></h4>
+ * <h3><a name="unicode">Unicode Character Representations</a></h3>
  *
  * <p>The {@code char} data type (and therefore the value that a
  * {@code Character} object encapsulates) are based on the
@@ -68,7 +68,7 @@
  * definition</i></a> of the U+<i>n</i> notation in the Unicode
  * Standard.)
  *
- * <p><a name="BMP">The set of characters from U+0000 to U+FFFF is
+ * <p><a name="BMP">The set of characters from U+0000 to U+FFFF</a> is
  * sometimes referred to as the <em>Basic Multilingual Plane (BMP)</em>.
  * <a name="supplementary">Characters</a> whose code points are greater
  * than U+FFFF are called <em>supplementary character</em>s.  The Java
@@ -4599,6 +4599,7 @@
      *
      * @since 1.8
      *
+     * @param value The {@code char} for which to return a hash code.
      * @return a hash code value for a {@code char} value.
      */
     public static int hashCode(char value) {
@@ -6637,7 +6638,7 @@
      * Determines if the specified character is ISO-LATIN-1 white space.
      * This method returns {@code true} for the following five
      * characters only:
-     * <table>
+     * <table summary="truechars">
      * <tr><td>{@code '\t'}</td>            <td>{@code U+0009}</td>
      *     <td>{@code HORIZONTAL TABULATION}</td></tr>
      * <tr><td>{@code '\n'}</td>            <td>{@code U+000A}</td>
@@ -7174,6 +7175,7 @@
      * Returns the value obtained by reversing the order of the bytes in the
      * specified <tt>char</tt> value.
      *
+     * @param ch The {@code char} of which to reverse the byte order.
      * @return the value obtained by reversing (or, equivalently, swapping)
      *     the bytes in the specified <tt>char</tt> value.
      * @since 1.5
--- a/src/share/classes/java/lang/Class.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/Class.java	Mon Jul 22 17:37:15 2013 -0700
@@ -360,36 +360,24 @@
      * any exception thrown by the constructor in a (checked) {@link
      * java.lang.reflect.InvocationTargetException}.
      *
-     * @return     a newly allocated instance of the class represented by this
-     *             object.
-     * @exception  IllegalAccessException  if the class or its nullary
-     *               constructor is not accessible.
-     * @exception  InstantiationException
-     *               if this {@code Class} represents an abstract class,
-     *               an interface, an array class, a primitive type, or void;
-     *               or if the class has no nullary constructor;
-     *               or if the instantiation fails for some other reason.
-     * @exception  ExceptionInInitializerError if the initialization
-     *               provoked by this method fails.
-     * @exception  SecurityException
-     *             If a security manager, <i>s</i>, is present and any of the
-     *             following conditions is met:
-     *
-     *             <ul>
-     *
-     *             <li> invocation of
-     *             {@link SecurityManager#checkMemberAccess
-     *             s.checkMemberAccess(this, Member.PUBLIC)} denies
-     *             creation of new instances of this class
-     *
-     *             <li> the caller's class loader is not the same as or an
-     *             ancestor of the class loader for the current class and
-     *             invocation of {@link SecurityManager#checkPackageAccess
-     *             s.checkPackageAccess()} denies access to the package
-     *             of this class
-     *
-     *             </ul>
-     *
+     * @return  a newly allocated instance of the class represented by this
+     *          object.
+     * @throws  IllegalAccessException  if the class or its nullary
+     *          constructor is not accessible.
+     * @throws  InstantiationException
+     *          if this {@code Class} represents an abstract class,
+     *          an interface, an array class, a primitive type, or void;
+     *          or if the class has no nullary constructor;
+     *          or if the instantiation fails for some other reason.
+     * @throws  ExceptionInInitializerError if the initialization
+     *          provoked by this method fails.
+     * @throws  SecurityException
+     *          If a security manager, <i>s</i>, is present and
+     *          the caller's class loader is not the same as or an
+     *          ancestor of the class loader for the current class and
+     *          invocation of {@link SecurityManager#checkPackageAccess
+     *          s.checkPackageAccess()} denies access to the package
+     *          of this class.
      */
     @CallerSensitive
     public T newInstance()
@@ -981,24 +969,27 @@
      *
      * @return the immediately enclosing method of the underlying class, if
      *     that class is a local or anonymous class; otherwise {@code null}.
-     * @exception  SecurityException
-     *             If a security manager, <i>s</i>, is present and any of the
-     *             following conditions is met:
      *
-     *             <ul>
+     * @throws SecurityException
+     *         If a security manager, <i>s</i>, is present and any of the
+     *         following conditions is met:
+     *
+     *         <ul>
      *
-     *             <li> invocation of
-     *             {@link SecurityManager#checkMemberAccess
-     *             s.checkMemberAccess(enclosingClass, Member.DECLARED)} denies
-     *             access to the methods within the enclosing class
+     *         <li> the caller's class loader is not the same as the
+     *         class loader of the enclosing class and invocation of
+     *         {@link SecurityManager#checkPermission
+     *         s.checkPermission} method with
+     *         {@code RuntimePermission("accessDeclaredMembers")}
+     *         denies access to the methods within the enclosing class
      *
-     *             <li> the caller's class loader is not the same as or an
-     *             ancestor of the class loader for the enclosing class and
-     *             invocation of {@link SecurityManager#checkPackageAccess
-     *             s.checkPackageAccess()} denies access to the package
-     *             of the enclosing class
+     *         <li> the caller's class loader is not the same as or an
+     *         ancestor of the class loader for the enclosing class and
+     *         invocation of {@link SecurityManager#checkPackageAccess
+     *         s.checkPackageAccess()} denies access to the package
+     *         of the enclosing class
      *
-     *             </ul>
+     *         </ul>
      * @since 1.5
      */
     @CallerSensitive
@@ -1025,11 +1016,6 @@
 
             // Perform access check
             Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
-            // be very careful not to change the stack depth of this
-            // checkMemberAccess call for security reasons
-            // see java.lang.SecurityManager.checkMemberAccess
-            //
-            // Note that we need to do this on the enclosing class
             enclosingCandidate.checkMemberAccess(Member.DECLARED,
                                                  Reflection.getCallerClass(), true);
             /*
@@ -1137,24 +1123,26 @@
      *
      * @return the immediately enclosing constructor of the underlying class, if
      *     that class is a local or anonymous class; otherwise {@code null}.
-     * @exception  SecurityException
-     *             If a security manager, <i>s</i>, is present and any of the
-     *             following conditions is met:
+     * @throws SecurityException
+     *         If a security manager, <i>s</i>, is present and any of the
+     *         following conditions is met:
      *
-     *             <ul>
+     *         <ul>
      *
-     *             <li> invocation of
-     *             {@link SecurityManager#checkMemberAccess
-     *             s.checkMemberAccess(enclosingClass, Member.DECLARED)} denies
-     *             access to the constructors within the enclosing class
+     *         <li> the caller's class loader is not the same as the
+     *         class loader of the enclosing class and invocation of
+     *         {@link SecurityManager#checkPermission
+     *         s.checkPermission} method with
+     *         {@code RuntimePermission("accessDeclaredMembers")}
+     *         denies access to the constructors within the enclosing class
      *
-     *             <li> the caller's class loader is not the same as or an
-     *             ancestor of the class loader for the enclosing class and
-     *             invocation of {@link SecurityManager#checkPackageAccess
-     *             s.checkPackageAccess()} denies access to the package
-     *             of the enclosing class
+     *         <li> the caller's class loader is not the same as or an
+     *         ancestor of the class loader for the enclosing class and
+     *         invocation of {@link SecurityManager#checkPackageAccess
+     *         s.checkPackageAccess()} denies access to the package
+     *         of the enclosing class
      *
-     *             </ul>
+     *         </ul>
      * @since 1.5
      */
     @CallerSensitive
@@ -1180,11 +1168,6 @@
 
             // Perform access check
             Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
-            // be very careful not to change the stack depth of this
-            // checkMemberAccess call for security reasons
-            // see java.lang.SecurityManager.checkMemberAccess
-            //
-            // Note that we need to do this on the enclosing class
             enclosingCandidate.checkMemberAccess(Member.DECLARED,
                                                  Reflection.getCallerClass(), true);
             /*
@@ -1457,25 +1440,14 @@
      * class, or void.
      *
      * @return the array of {@code Class} objects representing the public
-     * members of this class
-     * @exception  SecurityException
-     *             If a security manager, <i>s</i>, is present and any of the
-     *             following conditions is met:
-     *
-     *             <ul>
-     *
-     *             <li> invocation of
-     *             {@link SecurityManager#checkMemberAccess
-     *             s.checkMemberAccess(this, Member.PUBLIC)} method
-     *             denies access to the classes within this class
-     *
-     *             <li> the caller's class loader is not the same as or an
-     *             ancestor of the class loader for the current class and
-     *             invocation of {@link SecurityManager#checkPackageAccess
-     *             s.checkPackageAccess()} denies access to the package
-     *             of this class
-     *
-     *             </ul>
+     *         members of this class
+     * @throws SecurityException
+     *         If a security manager, <i>s</i>, is present and
+     *         the caller's class loader is not the same as or an
+     *         ancestor of the class loader for the current class and
+     *         invocation of {@link SecurityManager#checkPackageAccess
+     *         s.checkPackageAccess()} denies access to the package
+     *         of this class.
      *
      * @since JDK1.1
      */
@@ -1530,25 +1502,14 @@
      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
      *
      * @return the array of {@code Field} objects representing the
-     * public fields
-     * @exception  SecurityException
-     *             If a security manager, <i>s</i>, is present and any of the
-     *             following conditions is met:
-     *
-     *             <ul>
-     *
-     *             <li> invocation of
-     *             {@link SecurityManager#checkMemberAccess
-     *             s.checkMemberAccess(this, Member.PUBLIC)} denies
-     *             access to the fields within this class
-     *
-     *             <li> the caller's class loader is not the same as or an
-     *             ancestor of the class loader for the current class and
-     *             invocation of {@link SecurityManager#checkPackageAccess
-     *             s.checkPackageAccess()} denies access to the package
-     *             of this class
-     *
-     *             </ul>
+     *         public fields
+     * @throws SecurityException
+     *         If a security manager, <i>s</i>, is present and
+     *         the caller's class loader is not the same as or an
+     *         ancestor of the class loader for the current class and
+     *         invocation of {@link SecurityManager#checkPackageAccess
+     *         s.checkPackageAccess()} denies access to the package
+     *         of this class.
      *
      * @since JDK1.1
      */
@@ -1579,25 +1540,14 @@
      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
      *
      * @return the array of {@code Method} objects representing the
-     * public methods of this class
-     * @exception  SecurityException
-     *             If a security manager, <i>s</i>, is present and any of the
-     *             following conditions is met:
-     *
-     *             <ul>
-     *
-     *             <li> invocation of
-     *             {@link SecurityManager#checkMemberAccess
-     *             s.checkMemberAccess(this, Member.PUBLIC)} denies
-     *             access to the methods within this class
-     *
-     *             <li> the caller's class loader is not the same as or an
-     *             ancestor of the class loader for the current class and
-     *             invocation of {@link SecurityManager#checkPackageAccess
-     *             s.checkPackageAccess()} denies access to the package
-     *             of this class
-     *
-     *             </ul>
+     *         public methods of this class
+     * @throws SecurityException
+     *         If a security manager, <i>s</i>, is present and
+     *         the caller's class loader is not the same as or an
+     *         ancestor of the class loader for the current class and
+     *         invocation of {@link SecurityManager#checkPackageAccess
+     *         s.checkPackageAccess()} denies access to the package
+     *         of this class.
      *
      * @since JDK1.1
      */
@@ -1626,25 +1576,14 @@
      * {@code Constructor<T>[]}.
      *
      * @return the array of {@code Constructor} objects representing the
-     *  public constructors of this class
-     * @exception  SecurityException
-     *             If a security manager, <i>s</i>, is present and any of the
-     *             following conditions is met:
-     *
-     *             <ul>
-     *
-     *             <li> invocation of
-     *             {@link SecurityManager#checkMemberAccess
-     *             s.checkMemberAccess(this, Member.PUBLIC)} denies
-     *             access to the constructors within this class
-     *
-     *             <li> the caller's class loader is not the same as or an
-     *             ancestor of the class loader for the current class and
-     *             invocation of {@link SecurityManager#checkPackageAccess
-     *             s.checkPackageAccess()} denies access to the package
-     *             of this class
-     *
-     *             </ul>
+     *         public constructors of this class
+     * @throws SecurityException
+     *         If a security manager, <i>s</i>, is present and
+     *         the caller's class loader is not the same as or an
+     *         ancestor of the class loader for the current class and
+     *         invocation of {@link SecurityManager#checkPackageAccess
+     *         s.checkPackageAccess()} denies access to the package
+     *         of this class.
      *
      * @since JDK1.1
      */
@@ -1678,29 +1617,18 @@
      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
      *
      * @param name the field name
-     * @return  the {@code Field} object of this class specified by
-     * {@code name}
-     * @exception NoSuchFieldException if a field with the specified name is
-     *              not found.
-     * @exception NullPointerException if {@code name} is {@code null}
-     * @exception  SecurityException
-     *             If a security manager, <i>s</i>, is present and any of the
-     *             following conditions is met:
-     *
-     *             <ul>
-     *
-     *             <li> invocation of
-     *             {@link SecurityManager#checkMemberAccess
-     *             s.checkMemberAccess(this, Member.PUBLIC)} denies
-     *             access to the field
-     *
-     *             <li> the caller's class loader is not the same as or an
-     *             ancestor of the class loader for the current class and
-     *             invocation of {@link SecurityManager#checkPackageAccess
-     *             s.checkPackageAccess()} denies access to the package
-     *             of this class
-     *
-     *             </ul>
+     * @return the {@code Field} object of this class specified by
+     *         {@code name}
+     * @throws NoSuchFieldException if a field with the specified name is
+     *         not found.
+     * @throws NullPointerException if {@code name} is {@code null}
+     * @throws SecurityException
+     *         If a security manager, <i>s</i>, is present and
+     *         the caller's class loader is not the same as or an
+     *         ancestor of the class loader for the current class and
+     *         invocation of {@link SecurityManager#checkPackageAccess
+     *         s.checkPackageAccess()} denies access to the package
+     *         of this class.
      *
      * @since JDK1.1
      */
@@ -1762,28 +1690,17 @@
      * @param name the name of the method
      * @param parameterTypes the list of parameters
      * @return the {@code Method} object that matches the specified
-     * {@code name} and {@code parameterTypes}
-     * @exception NoSuchMethodException if a matching method is not found
-     *            or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
-     * @exception NullPointerException if {@code name} is {@code null}
-     * @exception  SecurityException
-     *             If a security manager, <i>s</i>, is present and any of the
-     *             following conditions is met:
-     *
-     *             <ul>
-     *
-     *             <li> invocation of
-     *             {@link SecurityManager#checkMemberAccess
-     *             s.checkMemberAccess(this, Member.PUBLIC)} denies
-     *             access to the method
-     *
-     *             <li> the caller's class loader is not the same as or an
-     *             ancestor of the class loader for the current class and
-     *             invocation of {@link SecurityManager#checkPackageAccess
-     *             s.checkPackageAccess()} denies access to the package
-     *             of this class
-     *
-     *             </ul>
+     *         {@code name} and {@code parameterTypes}
+     * @throws NoSuchMethodException if a matching method is not found
+     *         or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
+     * @throws NullPointerException if {@code name} is {@code null}
+     * @throws SecurityException
+     *         If a security manager, <i>s</i>, is present and
+     *         the caller's class loader is not the same as or an
+     *         ancestor of the class loader for the current class and
+     *         invocation of {@link SecurityManager#checkPackageAccess
+     *         s.checkPackageAccess()} denies access to the package
+     *         of this class.
      *
      * @since JDK1.1
      */
@@ -1816,26 +1733,15 @@
      *
      * @param parameterTypes the parameter array
      * @return the {@code Constructor} object of the public constructor that
-     * matches the specified {@code parameterTypes}
-     * @exception NoSuchMethodException if a matching method is not found.
-     * @exception  SecurityException
-     *             If a security manager, <i>s</i>, is present and any of the
-     *             following conditions is met:
-     *
-     *             <ul>
-     *
-     *             <li> invocation of
-     *             {@link SecurityManager#checkMemberAccess
-     *             s.checkMemberAccess(this, Member.PUBLIC)} denies
-     *             access to the constructor
-     *
-     *             <li> the caller's class loader is not the same as or an
-     *             ancestor of the class loader for the current class and
-     *             invocation of {@link SecurityManager#checkPackageAccess
-     *             s.checkPackageAccess()} denies access to the package
-     *             of this class
-     *
-     *             </ul>
+     *         matches the specified {@code parameterTypes}
+     * @throws NoSuchMethodException if a matching method is not found.
+     * @throws SecurityException
+     *         If a security manager, <i>s</i>, is present and
+     *         the caller's class loader is not the same as or an
+     *         ancestor of the class loader for the current class and
+     *         invocation of {@link SecurityManager#checkPackageAccess
+     *         s.checkPackageAccess()} denies access to the package
+     *         of this class.
      *
      * @since JDK1.1
      */
@@ -1858,25 +1764,27 @@
      * primitive type, an array class, or void.
      *
      * @return the array of {@code Class} objects representing all the
-     * declared members of this class
-     * @exception  SecurityException
-     *             If a security manager, <i>s</i>, is present and any of the
-     *             following conditions is met:
+     *         declared members of this class
+     * @throws SecurityException
+     *         If a security manager, <i>s</i>, is present and any of the
+     *         following conditions is met:
      *
-     *             <ul>
+     *         <ul>
      *
-     *             <li> invocation of
-     *             {@link SecurityManager#checkMemberAccess
-     *             s.checkMemberAccess(this, Member.DECLARED)} denies
-     *             access to the declared classes within this class
+     *         <li> the caller's class loader is not the same as the
+     *         class loader of this class and invocation of
+     *         {@link SecurityManager#checkPermission
+     *         s.checkPermission} method with
+     *         {@code RuntimePermission("accessDeclaredMembers")}
+     *         denies access to the declared classes within this class
      *
-     *             <li> the caller's class loader is not the same as or an
-     *             ancestor of the class loader for the current class and
-     *             invocation of {@link SecurityManager#checkPackageAccess
-     *             s.checkPackageAccess()} denies access to the package
-     *             of this class
+     *         <li> the caller's class loader is not the same as or an
+     *         ancestor of the class loader for the current class and
+     *         invocation of {@link SecurityManager#checkPackageAccess
+     *         s.checkPackageAccess()} denies access to the package
+     *         of this class
      *
-     *             </ul>
+     *         </ul>
      *
      * @since JDK1.1
      */
@@ -1899,26 +1807,28 @@
      *
      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
      *
-     * @return    the array of {@code Field} objects representing all the
-     * declared fields of this class
-     * @exception  SecurityException
-     *             If a security manager, <i>s</i>, is present and any of the
-     *             following conditions is met:
+     * @return  the array of {@code Field} objects representing all the
+     *          declared fields of this class
+     * @throws  SecurityException
+     *          If a security manager, <i>s</i>, is present and any of the
+     *          following conditions is met:
      *
-     *             <ul>
+     *          <ul>
      *
-     *             <li> invocation of
-     *             {@link SecurityManager#checkMemberAccess
-     *             s.checkMemberAccess(this, Member.DECLARED)} denies
-     *             access to the declared fields within this class
+     *          <li> the caller's class loader is not the same as the
+     *          class loader of this class and invocation of
+     *          {@link SecurityManager#checkPermission
+     *          s.checkPermission} method with
+     *          {@code RuntimePermission("accessDeclaredMembers")}
+     *          denies access to the declared fields within this class
      *
-     *             <li> the caller's class loader is not the same as or an
-     *             ancestor of the class loader for the current class and
-     *             invocation of {@link SecurityManager#checkPackageAccess
-     *             s.checkPackageAccess()} denies access to the package
-     *             of this class
+     *          <li> the caller's class loader is not the same as or an
+     *          ancestor of the class loader for the current class and
+     *          invocation of {@link SecurityManager#checkPackageAccess
+     *          s.checkPackageAccess()} denies access to the package
+     *          of this class
      *
-     *             </ul>
+     *          </ul>
      *
      * @since JDK1.1
      */
@@ -1945,26 +1855,28 @@
      *
      * <p> See <em>The Java Language Specification</em>, section 8.2.
      *
-     * @return    the array of {@code Method} objects representing all the
-     * declared methods of this class
-     * @exception  SecurityException
-     *             If a security manager, <i>s</i>, is present and any of the
-     *             following conditions is met:
+     * @return  the array of {@code Method} objects representing all the
+     *          declared methods of this class
+     * @throws  SecurityException
+     *          If a security manager, <i>s</i>, is present and any of the
+     *          following conditions is met:
      *
-     *             <ul>
+     *          <ul>
      *
-     *             <li> invocation of
-     *             {@link SecurityManager#checkMemberAccess
-     *             s.checkMemberAccess(this, Member.DECLARED)} denies
-     *             access to the declared methods within this class
+     *          <li> the caller's class loader is not the same as the
+     *          class loader of this class and invocation of
+     *          {@link SecurityManager#checkPermission
+     *          s.checkPermission} method with
+     *          {@code RuntimePermission("accessDeclaredMembers")}
+     *          denies access to the declared methods within this class
      *
-     *             <li> the caller's class loader is not the same as or an
-     *             ancestor of the class loader for the current class and
-     *             invocation of {@link SecurityManager#checkPackageAccess
-     *             s.checkPackageAccess()} denies access to the package
-     *             of this class
+     *          <li> the caller's class loader is not the same as or an
+     *          ancestor of the class loader for the current class and
+     *          invocation of {@link SecurityManager#checkPackageAccess
+     *          s.checkPackageAccess()} denies access to the package
+     *          of this class
      *
-     *             </ul>
+     *          </ul>
      *
      * @since JDK1.1
      */
@@ -1988,26 +1900,28 @@
      *
      * <p> See <em>The Java Language Specification</em>, section 8.2.
      *
-     * @return    the array of {@code Constructor} objects representing all the
-     * declared constructors of this class
-     * @exception  SecurityException
-     *             If a security manager, <i>s</i>, is present and any of the
-     *             following conditions is met:
+     * @return  the array of {@code Constructor} objects representing all the
+     *          declared constructors of this class
+     * @throws  SecurityException
+     *          If a security manager, <i>s</i>, is present and any of the
+     *          following conditions is met:
      *
-     *             <ul>
+     *          <ul>
      *
-     *             <li> invocation of
-     *             {@link SecurityManager#checkMemberAccess
-     *             s.checkMemberAccess(this, Member.DECLARED)} denies
-     *             access to the declared constructors within this class
+     *          <li> the caller's class loader is not the same as the
+     *          class loader of this class and invocation of
+     *          {@link SecurityManager#checkPermission
+     *          s.checkPermission} method with
+     *          {@code RuntimePermission("accessDeclaredMembers")}
+     *          denies access to the declared constructors within this class
      *
-     *             <li> the caller's class loader is not the same as or an
-     *             ancestor of the class loader for the current class and
-     *             invocation of {@link SecurityManager#checkPackageAccess
-     *             s.checkPackageAccess()} denies access to the package
-     *             of this class
+     *          <li> the caller's class loader is not the same as or an
+     *          ancestor of the class loader for the current class and
+     *          invocation of {@link SecurityManager#checkPackageAccess
+     *          s.checkPackageAccess()} denies access to the package
+     *          of this class
      *
-     *             </ul>
+     *          </ul>
      *
      * @since JDK1.1
      */
@@ -2026,29 +1940,31 @@
      * will not reflect the {@code length} field of an array class.
      *
      * @param name the name of the field
-     * @return the {@code Field} object for the specified field in this
-     * class
-     * @exception NoSuchFieldException if a field with the specified name is
-     *              not found.
-     * @exception NullPointerException if {@code name} is {@code null}
-     * @exception  SecurityException
-     *             If a security manager, <i>s</i>, is present and any of the
-     *             following conditions is met:
+     * @return  the {@code Field} object for the specified field in this
+     *          class
+     * @throws  NoSuchFieldException if a field with the specified name is
+     *          not found.
+     * @throws  NullPointerException if {@code name} is {@code null}
+     * @throws  SecurityException
+     *          If a security manager, <i>s</i>, is present and any of the
+     *          following conditions is met:
      *
-     *             <ul>
+     *          <ul>
      *
-     *             <li> invocation of
-     *             {@link SecurityManager#checkMemberAccess
-     *             s.checkMemberAccess(this, Member.DECLARED)} denies
-     *             access to the declared field
+     *          <li> the caller's class loader is not the same as the
+     *          class loader of this class and invocation of
+     *          {@link SecurityManager#checkPermission
+     *          s.checkPermission} method with
+     *          {@code RuntimePermission("accessDeclaredMembers")}
+     *          denies access to the declared field
      *
-     *             <li> the caller's class loader is not the same as or an
-     *             ancestor of the class loader for the current class and
-     *             invocation of {@link SecurityManager#checkPackageAccess
-     *             s.checkPackageAccess()} denies access to the package
-     *             of this class
+     *          <li> the caller's class loader is not the same as or an
+     *          ancestor of the class loader for the current class and
+     *          invocation of {@link SecurityManager#checkPackageAccess
+     *          s.checkPackageAccess()} denies access to the package
+     *          of this class
      *
-     *             </ul>
+     *          </ul>
      *
      * @since JDK1.1
      */
@@ -2080,28 +1996,30 @@
      *
      * @param name the name of the method
      * @param parameterTypes the parameter array
-     * @return    the {@code Method} object for the method of this class
-     * matching the specified name and parameters
-     * @exception NoSuchMethodException if a matching method is not found.
-     * @exception NullPointerException if {@code name} is {@code null}
-     * @exception  SecurityException
-     *             If a security manager, <i>s</i>, is present and any of the
-     *             following conditions is met:
+     * @return  the {@code Method} object for the method of this class
+     *          matching the specified name and parameters
+     * @throws  NoSuchMethodException if a matching method is not found.
+     * @throws  NullPointerException if {@code name} is {@code null}
+     * @throws  SecurityException
+     *          If a security manager, <i>s</i>, is present and any of the
+     *          following conditions is met:
      *
-     *             <ul>
+     *          <ul>
      *
-     *             <li> invocation of
-     *             {@link SecurityManager#checkMemberAccess
-     *             s.checkMemberAccess(this, Member.DECLARED)} denies
-     *             access to the declared method
+     *          <li> the caller's class loader is not the same as the
+     *          class loader of this class and invocation of
+     *          {@link SecurityManager#checkPermission
+     *          s.checkPermission} method with
+     *          {@code RuntimePermission("accessDeclaredMembers")}
+     *          denies access to the declared method
      *
-     *             <li> the caller's class loader is not the same as or an
-     *             ancestor of the class loader for the current class and
-     *             invocation of {@link SecurityManager#checkPackageAccess
-     *             s.checkPackageAccess()} denies access to the package
-     *             of this class
+     *          <li> the caller's class loader is not the same as or an
+     *          ancestor of the class loader for the current class and
+     *          invocation of {@link SecurityManager#checkPackageAccess
+     *          s.checkPackageAccess()} denies access to the package
+     *          of this class
      *
-     *             </ul>
+     *          </ul>
      *
      * @since JDK1.1
      */
@@ -2129,27 +2047,29 @@
      * include the explicit enclosing instance as the first parameter.
      *
      * @param parameterTypes the parameter array
-     * @return    The {@code Constructor} object for the constructor with the
-     * specified parameter list
-     * @exception NoSuchMethodException if a matching method is not found.
-     * @exception  SecurityException
-     *             If a security manager, <i>s</i>, is present and any of the
-     *             following conditions is met:
+     * @return  The {@code Constructor} object for the constructor with the
+     *          specified parameter list
+     * @throws  NoSuchMethodException if a matching method is not found.
+     * @throws  SecurityException
+     *          If a security manager, <i>s</i>, is present and any of the
+     *          following conditions is met:
      *
-     *             <ul>
+     *          <ul>
      *
-     *             <li> invocation of
-     *             {@link SecurityManager#checkMemberAccess
-     *             s.checkMemberAccess(this, Member.DECLARED)} denies
-     *             access to the declared constructor
+     *          <li> the caller's class loader is not the same as the
+     *          class loader of this class and invocation of
+     *          {@link SecurityManager#checkPermission
+     *          s.checkPermission} method with
+     *          {@code RuntimePermission("accessDeclaredMembers")}
+     *          denies access to the declared constructor
      *
-     *             <li> the caller's class loader is not the same as or an
-     *             ancestor of the class loader for the current class and
-     *             invocation of {@link SecurityManager#checkPackageAccess
-     *             s.checkPackageAccess()} denies access to the package
-     *             of this class
+     *          <li> the caller's class loader is not the same as or an
+     *          ancestor of the class loader for the current class and
+     *          invocation of {@link SecurityManager#checkPackageAccess
+     *          s.checkPackageAccess()} denies access to the package
+     *          of this class
      *
-     *             </ul>
+     *          </ul>
      *
      * @since JDK1.1
      */
@@ -2306,14 +2226,6 @@
      */
     static native Class<?> getPrimitiveClass(String name);
 
-    private static boolean isCheckMemberAccessOverridden(SecurityManager smgr) {
-        if (smgr.getClass() == SecurityManager.class) return false;
-
-        Class<?>[] paramTypes = new Class<?>[] {Class.class, int.class};
-        return smgr.getClass().getMethod0("checkMemberAccess", paramTypes).
-                getDeclaringClass() != SecurityManager.class;
-    }
-
     /*
      * Check if client is allowed to access members.  If access is denied,
      * throw a SecurityException.
@@ -2326,19 +2238,17 @@
     private void checkMemberAccess(int which, Class<?> caller, boolean checkProxyInterfaces) {
         final SecurityManager s = System.getSecurityManager();
         if (s != null) {
+            /* Default policy allows access to all {@link Member#PUBLIC} members,
+             * as well as access to classes that have the same class loader as the caller.
+             * In all other cases, it requires RuntimePermission("accessDeclaredMembers")
+             * permission.
+             */
             final ClassLoader ccl = ClassLoader.getClassLoader(caller);
             final ClassLoader cl = getClassLoader0();
-            if (!isCheckMemberAccessOverridden(s)) {
-                // Inlined SecurityManager.checkMemberAccess
-                if (which != Member.PUBLIC) {
-                    if (ccl != cl) {
-                        s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
-                    }
+            if (which != Member.PUBLIC) {
+                if (ccl != cl) {
+                    s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
                 }
-            } else {
-                // Don't refactor; otherwise break the stack depth for
-                // checkMemberAccess of subclasses of SecurityManager as specified.
-                s.checkMemberAccess(this, which);
             }
             this.checkPackageAccess(ccl, checkProxyInterfaces);
         }
@@ -2398,6 +2308,45 @@
     }
 
     /**
+     * Atomic operations support.
+     */
+    private static class Atomic {
+        // initialize Unsafe machinery here, since we need to call Class.class instance method
+        // and have to avoid calling it in the static initializer of the Class class...
+        private static final Unsafe unsafe = Unsafe.getUnsafe();
+        // offset of Class.reflectionData instance field
+        private static final long reflectionDataOffset;
+        // offset of Class.annotationType instance field
+        private static final long annotationTypeOffset;
+
+        static {
+            Field[] fields = Class.class.getDeclaredFields0(false); // bypass caches
+            reflectionDataOffset = objectFieldOffset(fields, "reflectionData");
+            annotationTypeOffset = objectFieldOffset(fields, "annotationType");
+        }
+
+        private static long objectFieldOffset(Field[] fields, String fieldName) {
+            Field field = searchFields(fields, fieldName);
+            if (field == null) {
+                throw new Error("No " + fieldName + " field found in java.lang.Class");
+            }
+            return unsafe.objectFieldOffset(field);
+        }
+
+        static <T> boolean casReflectionData(Class<?> clazz,
+                                             SoftReference<ReflectionData<T>> oldData,
+                                             SoftReference<ReflectionData<T>> newData) {
+            return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData);
+        }
+
+        static <T> boolean casAnnotationType(Class<?> clazz,
+                                             AnnotationType oldType,
+                                             AnnotationType newType) {
+            return unsafe.compareAndSwapObject(clazz, annotationTypeOffset, oldType, newType);
+        }
+    }
+
+    /**
      * Reflection support.
      */
 
@@ -2423,29 +2372,6 @@
         ReflectionData(int redefinedCount) {
             this.redefinedCount = redefinedCount;
         }
-
-        // initialize Unsafe machinery here, since we need to call Class.class instance method
-        // and have to avoid calling it in the static initializer of the Class class...
-        private static final Unsafe unsafe;
-        // offset of Class.reflectionData instance field
-        private static final long reflectionDataOffset;
-
-        static {
-            unsafe = Unsafe.getUnsafe();
-            // bypass caches
-            Field reflectionDataField = searchFields(Class.class.getDeclaredFields0(false),
-                                                     "reflectionData");
-            if (reflectionDataField == null) {
-                throw new Error("No reflectionData field found in java.lang.Class");
-            }
-            reflectionDataOffset = unsafe.objectFieldOffset(reflectionDataField);
-        }
-
-        static <T> boolean compareAndSwap(Class<?> clazz,
-                                          SoftReference<ReflectionData<T>> oldData,
-                                          SoftReference<ReflectionData<T>> newData) {
-            return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData);
-        }
     }
 
     private volatile transient SoftReference<ReflectionData<T>> reflectionData;
@@ -2477,7 +2403,7 @@
         while (true) {
             ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
             // try to CAS it...
-            if (ReflectionData.compareAndSwap(this, oldReflectionData, new SoftReference<>(rd))) {
+            if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {
                 return rd;
             }
             // else retry
@@ -2520,7 +2446,7 @@
     }
 
     // Annotations handling
-    private native byte[] getRawAnnotations();
+    native byte[] getRawAnnotations();
     // Since 1.8
     native byte[] getRawTypeAnnotations();
     static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
@@ -3380,10 +3306,11 @@
 
     // Annotation types cache their internal (AnnotationType) form
 
-    private AnnotationType annotationType;
+    @SuppressWarnings("UnusedDeclaration")
+    private volatile transient AnnotationType annotationType;
 
-    void setAnnotationType(AnnotationType type) {
-        annotationType = type;
+    boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {
+        return Atomic.casAnnotationType(this, oldType, newType);
     }
 
     AnnotationType getAnnotationType() {
--- a/src/share/classes/java/lang/ClassLoader.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/ClassLoader.java	Mon Jul 22 17:37:15 2013 -0700
@@ -157,7 +157,7 @@
  *     }
  * </pre></blockquote>
  *
- * <h4> <a name="name">Binary names</a> </h4>
+ * <h3> <a name="name">Binary names</a> </h3>
  *
  * <p> Any class name provided as a {@link String} parameter to methods in
  * <tt>ClassLoader</tt> must be a binary name as defined by
@@ -342,7 +342,7 @@
      * #loadClass(String, boolean)} method.  It is invoked by the Java virtual
      * machine to resolve class references.  Invoking this method is equivalent
      * to invoking {@link #loadClass(String, boolean) <tt>loadClass(name,
-     * false)</tt>}.  </p>
+     * false)</tt>}.
      *
      * @param  name
      *         The <a href="#name">binary name</a> of the class
@@ -441,7 +441,7 @@
      * behaves as follows. If this ClassLoader object is registered as
      * parallel capable, the method returns a dedicated object associated
      * with the specified class name. Otherwise, the method returns this
-     * ClassLoader object. </p>
+     * ClassLoader object.
      *
      * @param  className
      *         The name of the to-be-loaded class
@@ -506,7 +506,7 @@
      * follow the delegation model for loading classes, and will be invoked by
      * the {@link #loadClass <tt>loadClass</tt>} method after checking the
      * parent class loader for the requested class.  The default implementation
-     * throws a <tt>ClassNotFoundException</tt>.  </p>
+     * throws a <tt>ClassNotFoundException</tt>.
      *
      * @param  name
      *         The <a href="#name">binary name</a> of the class
@@ -772,16 +772,16 @@
      * <i>bBuffer</i><tt>,</tt> <i>pd</i><tt>)</tt> yields exactly the same
      * result as the statements
      *
-     * <blockquote><tt>
+     *<p> <tt>
      * ...<br>
-     * byte[] temp = new byte[</tt><i>bBuffer</i><tt>.{@link
+     * byte[] temp = new byte[bBuffer.{@link
      * java.nio.ByteBuffer#remaining remaining}()];<br>
-     *     </tt><i>bBuffer</i><tt>.{@link java.nio.ByteBuffer#get(byte[])
+     *     bBuffer.{@link java.nio.ByteBuffer#get(byte[])
      * get}(temp);<br>
      *     return {@link #defineClass(String, byte[], int, int, ProtectionDomain)
-     * </tt><i>cl</i><tt>.defineClass}(</tt><i>name</i><tt>, temp, 0,
-     * temp.length, </tt><i>pd</i><tt>);<br>
-     * </tt></blockquote>
+     * cl.defineClass}(name, temp, 0,
+     * temp.length, pd);<br>
+     * </tt></p>
      *
      * @param  name
      *         The expected <a href="#name">binary name</a>. of the class, or
@@ -940,7 +940,6 @@
      * already been linked, then this method simply returns. Otherwise, the
      * class is linked as described in the "Execution" chapter of
      * <cite>The Java&trade; Language Specification</cite>.
-     * </p>
      *
      * @param  c
      *         The class to link
@@ -1012,7 +1011,7 @@
      * Returns the class with the given <a href="#name">binary name</a> if this
      * loader has been recorded by the Java virtual machine as an initiating
      * loader of a class with that <a href="#name">binary name</a>.  Otherwise
-     * <tt>null</tt> is returned.  </p>
+     * <tt>null</tt> is returned.
      *
      * @param  name
      *         The <a href="#name">binary name</a> of the class
@@ -1032,7 +1031,7 @@
 
     /**
      * Sets the signers of a class.  This should be invoked after defining a
-     * class.  </p>
+     * class.
      *
      * @param  c
      *         The <tt>Class</tt> object
@@ -1125,7 +1124,7 @@
 
     /**
      * Finds the resource with the given name. Class loader implementations
-     * should override this method to specify where to find resources.  </p>
+     * should override this method to specify where to find resources.
      *
      * @param  name
      *         The resource name
@@ -1143,7 +1142,7 @@
      * Returns an enumeration of {@link java.net.URL <tt>URL</tt>} objects
      * representing all the resources with the given name. Class loader
      * implementations should override this method to specify where to load
-     * resources from.  </p>
+     * resources from.
      *
      * @param  name
      *         The resource name
@@ -1161,14 +1160,16 @@
     }
 
     /**
-     * Registers the caller as parallel capable.</p>
+     * Registers the caller as parallel capable.
      * The registration succeeds if and only if all of the following
-     * conditions are met: <br>
-     * 1. no instance of the caller has been created</p>
-     * 2. all of the super classes (except class Object) of the caller are
-     * registered as parallel capable</p>
-     * Note that once a class loader is registered as parallel capable, there
-     * is no way to change it back. </p>
+     * conditions are met:
+     * <ol>
+     * <li> no instance of the caller has been created</li>
+     * <li> all of the super classes (except class Object) of the caller are
+     * registered as parallel capable</li>
+     * </ol>
+     * <p>Note that once a class loader is registered as parallel capable, there
+     * is no way to change it back.</p>
      *
      * @return  true if the caller is successfully registered as
      *          parallel capable and false if otherwise.
@@ -1185,7 +1186,7 @@
     /**
      * Find a resource of the specified name from the search path used to load
      * classes.  This method locates the resource through the system class
-     * loader (see {@link #getSystemClassLoader()}).  </p>
+     * loader (see {@link #getSystemClassLoader()}).
      *
      * @param  name
      *         The resource name
@@ -1292,7 +1293,7 @@
     /**
      * Open for reading, a resource of the specified name from the search path
      * used to load classes.  This method locates the resource through the
-     * system class loader (see {@link #getSystemClassLoader()}).  </p>
+     * system class loader (see {@link #getSystemClassLoader()}).
      *
      * @param  name
      *         The resource name
@@ -1515,7 +1516,7 @@
      * class loaders to define the packages for their classes. Packages must
      * be created before the class is defined, and package names must be
      * unique within a class loader and cannot be redefined or changed once
-     * created.  </p>
+     * created.
      *
      * @param  name
      *         The package name
@@ -1572,7 +1573,7 @@
 
     /**
      * Returns a <tt>Package</tt> that has been defined by this class loader
-     * or any of its ancestors.  </p>
+     * or any of its ancestors.
      *
      * @param  name
      *         The package name
@@ -1609,7 +1610,7 @@
 
     /**
      * Returns all of the <tt>Packages</tt> defined by this class loader and
-     * its ancestors.  </p>
+     * its ancestors.
      *
      * @return  The array of <tt>Package</tt> objects defined by this
      *          <tt>ClassLoader</tt>
@@ -1646,7 +1647,7 @@
      * method to locate the native libraries that belong to classes loaded with
      * this class loader. If this method returns <tt>null</tt>, the VM
      * searches the library along the path specified as the
-     * "<tt>java.library.path</tt>" property.  </p>
+     * "<tt>java.library.path</tt>" property.
      *
      * @param  libname
      *         The library name
@@ -1966,7 +1967,7 @@
      * in the future will have assertions enabled or disabled by default.
      * This setting may be overridden on a per-package or per-class basis by
      * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link
-     * #setClassAssertionStatus(String, boolean)}.  </p>
+     * #setClassAssertionStatus(String, boolean)}.
      *
      * @param  enabled
      *         <tt>true</tt> if classes loaded by this class loader will
@@ -2068,7 +2069,6 @@
      * status settings associated with the class loader.  This method is
      * provided so that class loaders can be made to ignore any command line or
      * persistent assertion status settings and "start with a clean slate."
-     * </p>
      *
      * @since  1.4
      */
--- a/src/share/classes/java/lang/Double.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/Double.java	Mon Jul 22 17:37:15 2013 -0700
@@ -256,7 +256,7 @@
      * </ul>
      *
      * <table border>
-     * <caption><h3>Examples</h3></caption>
+     * <caption>Examples</caption>
      * <tr><th>Floating-point Value</th><th>Hexadecimal String</th>
      * <tr><td>{@code 1.0}</td> <td>{@code 0x1.0p0}</td>
      * <tr><td>{@code -1.0}</td>        <td>{@code -0x1.0p0}</td>
--- a/src/share/classes/java/lang/Float.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/Float.java	Mon Jul 22 17:37:15 2013 -0700
@@ -258,7 +258,7 @@
      * </ul>
      *
      * <table border>
-     * <caption><h3>Examples</h3></caption>
+     * <caption>Examples</caption>
      * <tr><th>Floating-point Value</th><th>Hexadecimal String</th>
      * <tr><td>{@code 1.0}</td> <td>{@code 0x1.0p0}</td>
      * <tr><td>{@code -1.0}</td>        <td>{@code -0x1.0p0}</td>
--- a/src/share/classes/java/lang/Iterable.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/Iterable.java	Mon Jul 22 17:37:15 2013 -0700
@@ -26,6 +26,8 @@
 
 import java.util.Iterator;
 import java.util.Objects;
+import java.util.Spliterator;
+import java.util.Spliterators;
 import java.util.function.Consumer;
 
 /**
@@ -72,5 +74,30 @@
             action.accept(t);
         }
     }
+
+    /**
+     * Creates a {@link Spliterator} over the elements described by this
+     * {@code Iterable}.
+     *
+     * @implSpec
+     * The default implementation creates an
+     * <em><a href="Spliterator.html#binding">early-binding</a></em>
+     * spliterator from the iterable's {@code Iterator}.  The spliterator
+     * inherits the <em>fail-fast</em> properties of the iterable's iterator.
+     *
+     * @implNote
+     * The default implementation should usually be overridden.  The
+     * spliterator returned by the default implementation has poor splitting
+     * capabilities, is unsized, and does not report any spliterator
+     * characteristics. Implementing classes can nearly always provide a
+     * better implementation.
+     *
+     * @return a {@code Spliterator} over the elements described by this
+     * {@code Iterable}.
+     * @since 1.8
+     */
+    default Spliterator<T> spliterator() {
+        return Spliterators.spliteratorUnknownSize(iterator(), 0);
+    }
 }
 
--- a/src/share/classes/java/lang/ProcessBuilder.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/ProcessBuilder.java	Mon Jul 22 17:37:15 2013 -0700
@@ -65,7 +65,7 @@
  * working directory of the current process, usually the directory
  * named by the system property {@code user.dir}.
  *
- * <li><a name="redirect-input">a source of <i>standard input</i>.
+ * <li><a name="redirect-input">a source of <i>standard input</i></a>.
  * By default, the subprocess reads input from a pipe.  Java code
  * can access this pipe via the output stream returned by
  * {@link Process#getOutputStream()}.  However, standard input may
@@ -81,7 +81,7 @@
  * </ul>
  *
  * <li><a name="redirect-output">a destination for <i>standard output</i>
- * and <i>standard error</i>.  By default, the subprocess writes standard
+ * and <i>standard error</i></a>.  By default, the subprocess writes standard
  * output and standard error to pipes.  Java code can access these pipes
  * via the input streams returned by {@link Process#getInputStream()} and
  * {@link Process#getErrorStream()}.  However, standard output and
@@ -554,6 +554,7 @@
          * Redirect.from(file).type() == Redirect.Type.READ
          * }</pre>
          *
+         * @param file The {@code File} for the {@code Redirect}.
          * @throws NullPointerException if the specified file is null
          * @return a redirect to read from the specified file
          */
@@ -580,6 +581,7 @@
          * Redirect.to(file).type() == Redirect.Type.WRITE
          * }</pre>
          *
+         * @param file The {@code File} for the {@code Redirect}.
          * @throws NullPointerException if the specified file is null
          * @return a redirect to write to the specified file
          */
@@ -610,6 +612,7 @@
          * Redirect.appendTo(file).type() == Redirect.Type.APPEND
          * }</pre>
          *
+         * @param file The {@code File} for the {@code Redirect}.
          * @throws NullPointerException if the specified file is null
          * @return a redirect to append to the specified file
          */
--- a/src/share/classes/java/lang/Runtime.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/Runtime.java	Mon Jul 22 17:37:15 2013 -0700
@@ -661,7 +661,7 @@
     /**
      * Returns the maximum amount of memory that the Java virtual machine will
      * attempt to use.  If there is no inherent limit then the value {@link
-     * java.lang.Long#MAX_VALUE} will be returned. </p>
+     * java.lang.Long#MAX_VALUE} will be returned.
      *
      * @return  the maximum amount of memory that the virtual machine will
      *          attempt to use, measured in bytes
--- a/src/share/classes/java/lang/SecurityManager.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/SecurityManager.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1675,10 +1675,18 @@
      *             permission to access members.
      * @exception  NullPointerException if the <code>clazz</code> argument is
      *             <code>null</code>.
+     *
+     * @deprecated This method relies on the caller being at a stack depth
+     *             of 4 which is error-prone and cannot be enforced by the runtime.
+     *             Users of this method should instead invoke {@link #checkPermission}
+     *             directly.  This method will be changed in a future release
+     *             to check the permission {@code java.security.AllPermission}.
+     *
      * @see java.lang.reflect.Member
      * @since JDK1.1
      * @see        #checkPermission(java.security.Permission) checkPermission
      */
+    @Deprecated
     @CallerSensitive
     public void checkMemberAccess(Class<?> clazz, int which) {
         if (clazz == null) {
--- a/src/share/classes/java/lang/System.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/System.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1220,12 +1220,15 @@
             public sun.reflect.ConstantPool getConstantPool(Class<?> klass) {
                 return klass.getConstantPool();
             }
-            public void setAnnotationType(Class<?> klass, AnnotationType type) {
-                klass.setAnnotationType(type);
+            public boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType) {
+                return klass.casAnnotationType(oldType, newType);
             }
             public AnnotationType getAnnotationType(Class<?> klass) {
                 return klass.getAnnotationType();
             }
+            public byte[] getRawClassAnnotations(Class<?> klass) {
+                return klass.getRawAnnotations();
+            }
             public byte[] getRawClassTypeAnnotations(Class<?> klass) {
                 return klass.getRawTypeAnnotations();
             }
--- a/src/share/classes/java/lang/Thread.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/Thread.java	Mon Jul 22 17:37:15 2013 -0700
@@ -865,8 +865,8 @@
      * will receive an {@link InterruptedException}.
      *
      * <p> If this thread is blocked in an I/O operation upon an {@link
-     * java.nio.channels.InterruptibleChannel </code>interruptible
-     * channel<code>} then the channel will be closed, the thread's interrupt
+     * java.nio.channels.InterruptibleChannel InterruptibleChannel}
+     * then the channel will be closed, the thread's interrupt
      * status will be set, and the thread will receive a {@link
      * java.nio.channels.ClosedByInterruptException}.
      *
@@ -1883,6 +1883,7 @@
      * there is no default.
      * @since 1.5
      * @see #setDefaultUncaughtExceptionHandler
+     * @return the default uncaught exception handler for all threads
      */
     public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){
         return defaultUncaughtExceptionHandler;
@@ -1895,6 +1896,7 @@
      * <tt>ThreadGroup</tt> object is returned, unless this thread
      * has terminated, in which case <tt>null</tt> is returned.
      * @since 1.5
+     * @return the uncaught exception handler for this thread
      */
     public UncaughtExceptionHandler getUncaughtExceptionHandler() {
         return uncaughtExceptionHandler != null ?
--- a/src/share/classes/java/lang/ThreadLocal.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/ThreadLocal.java	Mon Jul 22 17:37:15 2013 -0700
@@ -131,12 +131,13 @@
      * Creates a thread local variable. The initial value of the variable is
      * determined by invoking the {@code get} method on the {@code Supplier}.
      *
+     * @param <S> the type of the thread local's value
      * @param supplier the supplier to be used to determine the initial value
      * @return a new thread local variable
      * @throws NullPointerException if the specified supplier is null
      * @since 1.8
      */
-    public static <T> ThreadLocal<T> withInitial(Supplier<? extends T> supplier) {
+    public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
         return new SuppliedThreadLocal<>(supplier);
     }
 
--- a/src/share/classes/java/lang/invoke/MethodHandleImpl.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/invoke/MethodHandleImpl.java	Mon Jul 22 17:37:15 2013 -0700
@@ -747,7 +747,8 @@
             GuardWithCatch gguard = new GuardWithCatch(gtarget, exType, gcatcher);
             if (gtarget == null || gcatcher == null)  throw new InternalError();
             MethodHandle ginvoker = GuardWithCatch.VARARGS_INVOKE.bindReceiver(gguard);
-            return makeCollectArguments(ginvoker, ValueConversions.varargsArray(nargs), 0, false);
+            MethodHandle gcollect = makeCollectArguments(ginvoker, ValueConversions.varargsArray(nargs), 0, false);
+            return makePairwiseConvert(gcollect, type, 2);
         }
     }
 
--- a/src/share/classes/java/lang/invoke/MethodHandles.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/invoke/MethodHandles.java	Mon Jul 22 17:37:15 2013 -0700
@@ -41,6 +41,7 @@
 import sun.security.util.SecurityConstants;
 import static java.lang.invoke.MethodHandleStatics.*;
 import static java.lang.invoke.MethodHandleNatives.Constants.*;
+import sun.security.util.SecurityConstants;
 
 /**
  * This class consists exclusively of static methods that operate on or return
@@ -305,36 +306,30 @@
      * <a name="secmgr"></a>
      * If a security manager is present, member lookups are subject to
      * additional checks.
-     * From one to four calls are made to the security manager.
+     * From one to three calls are made to the security manager.
      * Any of these calls can refuse access by throwing a
      * {@link java.lang.SecurityException SecurityException}.
      * Define {@code smgr} as the security manager,
+     * {@code lookc} as the lookup class of the current lookup object,
      * {@code refc} as the containing class in which the member
      * is being sought, and {@code defc} as the class in which the
      * member is actually defined.
+     * The value {@code lookc} is defined as <em>not present</em>
+     * if the current lookup object does not have
+     * {@linkplain java.lang.invoke.MethodHandles.Lookup#PRIVATE private access}.
      * The calls are made according to the following rules:
      * <ul>
-     * <li>In all cases, {@link SecurityManager#checkMemberAccess
-     *     smgr.checkMemberAccess(refc, Member.PUBLIC)} is called.
-     * <li>If the class loader of the lookup class is not
+     * <li>If {@code lookc} is not present, or if its class loader is not
      *     the same as or an ancestor of the class loader of {@code refc},
      *     then {@link SecurityManager#checkPackageAccess
      *     smgr.checkPackageAccess(refcPkg)} is called,
      *     where {@code refcPkg} is the package of {@code refc}.
+     * <li>If the retrieved member is not public and
+     *     {@code lookc} is not present, then
+     *     {@link SecurityManager#checkPermission smgr.checkPermission}
+     *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
      * <li>If the retrieved member is not public,
-     *     {@link SecurityManager#checkMemberAccess
-     *     smgr.checkMemberAccess(defc, Member.DECLARED)} is called.
-     *     (Note that {@code defc} might be the same as {@code refc}.)
-     *     The default implementation of this security manager method
-     *     inspects the stack to determine the original caller of
-     *     the reflective request (such as {@code findStatic}),
-     *     and performs additional permission checks if the
-     *     class loader of {@code defc} differs from the class
-     *     loader of the class from which the reflective request came.
-     * <li>If the retrieved member is not public,
-     *     and if {@code defc} and {@code refc} are in different class loaders,
-     *     and if the class loader of the lookup class is not
-     *     the same as or an ancestor of the class loader of {@code defc},
+     *     and if {@code defc} and {@code refc} are different,
      *     then {@link SecurityManager#checkPackageAccess
      *     smgr.checkPackageAccess(defcPkg)} is called,
      *     where {@code defcPkg} is the package of {@code defc}.
@@ -1054,22 +1049,6 @@
         }
 
         /**
-         * Determine whether a security manager has an overridden
-         * SecurityManager.checkMemberAccess method.
-         */
-        private boolean isCheckMemberAccessOverridden(SecurityManager sm) {
-            final Class<? extends SecurityManager> cls = sm.getClass();
-            if (cls == SecurityManager.class) return false;
-
-            try {
-                return cls.getMethod("checkMemberAccess", Class.class, int.class).
-                    getDeclaringClass() != SecurityManager.class;
-            } catch (NoSuchMethodException e) {
-                throw new InternalError("should not reach here");
-            }
-        }
-
-        /**
          * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
          * Determines a trustable caller class to compare with refc, the symbolic reference class.
          * If this lookup object has private access, then the caller class is the lookupClass.
@@ -1079,45 +1058,22 @@
             if (smgr == null)  return;
             if (allowedModes == TRUSTED)  return;
 
-            final boolean overridden = isCheckMemberAccessOverridden(smgr);
             // Step 1:
-            {
-                // Default policy is to allow Member.PUBLIC; no need to check
-                // permission if SecurityManager is the default implementation
-                final int which = Member.PUBLIC;
-                final Class<?> clazz = refc;
-                if (overridden) {
-                    // Don't refactor; otherwise break the stack depth for
-                    // checkMemberAccess of subclasses of SecurityManager as specified.
-                    smgr.checkMemberAccess(clazz, which);
-                }
-            }
-
-            // Step 2:
             if (!isFullPowerLookup() ||
                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
                 ReflectUtil.checkPackageAccess(refc);
             }
 
-            // Step 3:
+            // Step 2:
             if (m.isPublic()) return;
             Class<?> defc = m.getDeclaringClass();
             {
-                // Inline SecurityManager.checkMemberAccess
-                final int which = Member.DECLARED;
-                final Class<?> clazz = defc;
-                if (!overridden) {
-                    if (!isFullPowerLookup()) {
-                        smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
-                    }
-                } else {
-                    // Don't refactor; otherwise break the stack depth for
-                    // checkMemberAccess of subclasses of SecurityManager as specified.
-                    smgr.checkMemberAccess(clazz, which);
+                if (!isFullPowerLookup()) {
+                    smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
                 }
             }
 
-            // Step 4:
+            // Step 3:
             if (defc != refc) {
                 ReflectUtil.checkPackageAccess(defc);
             }
--- a/src/share/classes/java/lang/management/LockInfo.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/management/LockInfo.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,7 +42,7 @@
  * {@link ReentrantReadWriteLock ReentrantReadWriteLock} are
  * two examples of ownable synchronizers provided by the platform.
  *
- * <h4><a name="MappedType">MXBean Mapping</a></h4>
+ * <h3><a name="MappedType">MXBean Mapping</a></h3>
  * <tt>LockInfo</tt> is mapped to a {@link CompositeData CompositeData}
  * as specified in the {@link #from from} method.
  *
@@ -105,7 +105,7 @@
      * given {@code CompositeData}.
      * The given {@code CompositeData} must contain the following attributes:
      * <blockquote>
-     * <table border>
+     * <table border summary="The attributes and the types the given CompositeData contains">
      * <tr>
      *   <th align=left>Attribute Name</th>
      *   <th align=left>Type</th>
--- a/src/share/classes/java/lang/management/ManagementFactory.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/management/ManagementFactory.java	Mon Jul 22 17:37:15 2013 -0700
@@ -61,7 +61,7 @@
  * the management interface of a component of the Java virtual
  * machine.
  * <p>
- * <h4><a name="MXBean">Platform MXBeans</a></h4>
+ * <h3><a name="MXBean">Platform MXBeans</a></h3>
  * <p>
  * A platform MXBean is a <i>managed bean</i> that
  * conforms to the <a href="../../../javax/management/package-summary.html">JMX</a>
@@ -87,7 +87,7 @@
  *
  * <p>
  * An application can access a platform MXBean in the following ways:
- * <h5>1. Direct access to an MXBean interface</h5>
+ * <h4>1. Direct access to an MXBean interface</h4>
  * <blockquote>
  * <ul>
  *     <li>Get an MXBean instance by calling the
@@ -107,7 +107,7 @@
  *         an MXBean of another running virtual machine.
  *         </li>
  * </ul>
- * <h5>2. Indirect access to an MXBean interface via MBeanServer</h5>
+ * <h4>2. Indirect access to an MXBean interface via MBeanServer</h4>
  * <ul>
  *     <li>Go through the platform {@code MBeanServer} to access MXBeans
  *         locally or a specific <tt>MBeanServerConnection</tt> to access
@@ -135,7 +135,7 @@
  * interfaces:
  *
  * <blockquote>
- * <table border>
+ * <table border summary="The list of Management Interfaces and their single instances">
  * <tr>
  * <th>Management Interface</th>
  * <th>ObjectName</th>
@@ -178,7 +178,7 @@
  * the following management interfaces.
  *
  * <blockquote>
- * <table border>
+ * <table border summary="The list of Management Interfaces and their single instances">
  * <tr>
  * <th>Management Interface</th>
  * <th>ObjectName</th>
@@ -195,7 +195,7 @@
  * A Java virtual machine may have one or more instances of the following
  * management interfaces.
  * <blockquote>
- * <table border>
+ * <table border summary="The list of Management Interfaces and their single instances">
  * <tr>
  * <th>Management Interface</th>
  * <th>ObjectName</th>
@@ -561,6 +561,12 @@
      * in the format of {@link ObjectName ObjectName}.
      * @param mxbeanInterface the MXBean interface to be implemented
      * by the proxy.
+     * @param <T> an {@code mxbeanInterface} type parameter
+     *
+     * @return a proxy for a platform MXBean interface of a
+     * given <a href="#MXBeanNames">MXBean name</a>
+     * that forwards its method calls through the given
+     * <tt>MBeanServerConnection</tt>, or {@code null} if not exist.
      *
      * @throws IllegalArgumentException if
      * <ul>
@@ -635,6 +641,7 @@
      * @param mxbeanInterface a management interface for a platform
      *     MXBean with one single instance in the Java virtual machine
      *     if implemented.
+     * @param <T> an {@code mxbeanInterface} type parameter
      *
      * @return the platform MXBean that implements
      * {@code mxbeanInterface}, or {@code null} if not exist.
@@ -670,6 +677,7 @@
      *
      * @param mxbeanInterface a management interface for a platform
      *                        MXBean
+     * @param <T> an {@code mxbeanInterface} type parameter
      *
      * @return the list of platform MXBeans that implement
      * {@code mxbeanInterface}.
@@ -707,6 +715,7 @@
      * @param mxbeanInterface a management interface for a platform
      *     MXBean with one single instance in the Java virtual machine
      *     being monitored, if implemented.
+     * @param <T> an {@code mxbeanInterface} type parameter
      *
      * @return the platform MXBean proxy for
      * forwarding the method calls of the {@code mxbeanInterface}
@@ -750,6 +759,7 @@
      * @param connection the {@code MBeanServerConnection} to forward to.
      * @param mxbeanInterface a management interface for a platform
      *                        MXBean
+     * @param <T> an {@code mxbeanInterface} type parameter
      *
      * @return the list of platform MXBean proxies for
      * forwarding the method calls of the {@code mxbeanInterface}
--- a/src/share/classes/java/lang/management/MemoryMXBean.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/management/MemoryMXBean.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,11 +49,11 @@
  * It can be obtained by calling the
  * {@link PlatformManagedObject#getObjectName} method.
  *
- * <h4> Memory </h4>
+ * <h3> Memory </h3>
  * The memory system of the Java virtual machine manages
  * the following kinds of memory:
  *
- * <h4> 1. Heap </h4>
+ * <h3> 1. Heap </h3>
  * The Java virtual machine has a <i>heap</i> that is the runtime
  * data area from which memory for all class instances and arrays
  * are allocated.  It is created at the Java virtual machine start-up.
@@ -63,7 +63,7 @@
  * <p>The heap may be of a fixed size or may be expanded and shrunk.
  * The memory for the heap does not need to be contiguous.
  *
- * <h4> 2. Non-Heap Memory</h4>
+ * <h3> 2. Non-Heap Memory</h3>
  * The Java virtual machine manages memory other than the heap
  * (referred as <i>non-heap memory</i>).
  *
@@ -87,7 +87,7 @@
  * machine code translated from the Java virtual machine code for
  * high performance.
  *
- * <h4>Memory Pools and Memory Managers</h4>
+ * <h3>Memory Pools and Memory Managers</h3>
  * {@link MemoryPoolMXBean Memory pools} and
  * {@link MemoryManagerMXBean memory managers} are the abstract entities
  * that monitor and manage the memory system
@@ -105,7 +105,7 @@
  * add or remove memory managers during execution.
  * A memory pool can be managed by more than one memory manager.
  *
- * <h4>Memory Usage Monitoring</h4>
+ * <h3>Memory Usage Monitoring</h3>
  *
  * Memory usage is a very important monitoring attribute for the memory system.
  * The memory usage, for example, could indicate:
@@ -131,7 +131,7 @@
  * certain threshold. It is not intended for an application to detect
  * and recover from a low memory condition.
  *
- * <h4>Notifications</h4>
+ * <h3>Notifications</h3>
  *
  * <p>This <tt>MemoryMXBean</tt> is a
  * {@link javax.management.NotificationEmitter NotificationEmitter}
@@ -169,7 +169,7 @@
  * MemoryNotificationInfo}.
  *
  * <hr>
- * <h4>NotificationEmitter</h4>
+ * <h3>NotificationEmitter</h3>
  * The <tt>MemoryMXBean</tt> object returned by
  * {@link ManagementFactory#getMemoryMXBean} implements
  * the {@link javax.management.NotificationEmitter NotificationEmitter}
--- a/src/share/classes/java/lang/management/MemoryNotificationInfo.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/management/MemoryNotificationInfo.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -212,7 +212,7 @@
      * The given <tt>CompositeData</tt> must contain
      * the following attributes:
      * <blockquote>
-     * <table border>
+     * <table border summary="The attributes and the types the given CompositeData contains">
      * <tr>
      *   <th align=left>Attribute Name</th>
      *   <th align=left>Type</th>
--- a/src/share/classes/java/lang/management/MemoryPoolMXBean.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/management/MemoryPoolMXBean.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,7 +49,7 @@
  * It can be obtained by calling the
  * {@link PlatformManagedObject#getObjectName} method.
  *
- * <h4>Memory Type</h4>
+ * <h3>Memory Type</h3>
  * <p>The Java virtual machine has a heap for object allocation and also
  * maintains non-heap memory for the method area and the Java virtual
  * machine execution.  The Java virtual machine can have one or more
@@ -60,7 +60,7 @@
  *   <li>{@link MemoryType#NON_HEAP non-heap}</li>
  * </ul>
  *
- * <h4>Memory Usage Monitoring</h4>
+ * <h3>Memory Usage Monitoring</h3>
  *
  * A memory pool has the following attributes:
  * <ul>
@@ -71,7 +71,7 @@
  *       (only supported by some <em>garbage-collected</em> memory pools)</li>
  * </ul>
  *
- * <h4><a name="Usage">1. Memory Usage</a></h4>
+ * <h3><a name="Usage">1. Memory Usage</a></h3>
  *
  * The {@link #getUsage} method provides an estimate
  * of the current usage of a memory pool.
@@ -86,14 +86,14 @@
  * the current memory usage.  An implementation should document when
  * this is the case.
  *
- * <h4><a name="PeakUsage">2. Peak Memory Usage</a></h4>
+ * <h3><a name="PeakUsage">2. Peak Memory Usage</a></h3>
  *
  * The Java virtual machine maintains the peak memory usage of a memory
  * pool since the virtual machine was started or the peak was reset.
  * The peak memory usage is returned by the {@link #getPeakUsage} method
  * and reset by calling the {@link #resetPeakUsage} method.
  *
- * <h4><a name="UsageThreshold">3. Usage Threshold</a></h4>
+ * <h3><a name="UsageThreshold">3. Usage Threshold</a></h3>
  *
  * Each memory pool has a manageable attribute
  * called the <i>usage threshold</i> which has a default value supplied
@@ -304,7 +304,7 @@
  *   </li>
  * </ol>
  *
- * <h4><a name="CollectionThreshold">4. Collection Usage Threshold</a></h4>
+ * <h3><a name="CollectionThreshold">4. Collection Usage Threshold</a></h3>
  *
  * Collection usage threshold is a manageable attribute only applicable
  * to some garbage-collected memory pools.
--- a/src/share/classes/java/lang/management/MemoryUsage.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/management/MemoryUsage.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,8 +36,7 @@
  * the heap or non-heap memory of the Java virtual machine as a whole.
  *
  * <p> A <tt>MemoryUsage</tt> object contains four values:
- * <ul>
- * <table>
+ * <table summary="Describes the MemoryUsage object content">
  * <tr>
  * <td valign=top> <tt>init</tt> </td>
  * <td valign=top> represents the initial amount of memory (in bytes) that
@@ -78,7 +77,6 @@
  * </td>
  * </tr>
  * </table>
- * </ul>
  *
  * Below is a picture showing an example of a memory pool:
  * <p>
@@ -98,7 +96,7 @@
  *                            max
  * </pre>
  *
- * <h4>MXBean Mapping</h4>
+ * <h3>MXBean Mapping</h3>
  * <tt>MemoryUsage</tt> is mapped to a {@link CompositeData CompositeData}
  * with attributes as specified in the {@link #from from} method.
  *
@@ -254,7 +252,7 @@
      * must contain the following attributes:
      * <p>
      * <blockquote>
-     * <table border>
+     * <table border summary="The attributes and the types the given CompositeData contains">
      * <tr>
      *   <th align=left>Attribute Name</th>
      *   <th align=left>Type</th>
--- a/src/share/classes/java/lang/management/MonitorInfo.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/management/MonitorInfo.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,7 +32,7 @@
  * Information about an object monitor lock.  An object monitor is locked
  * when entering a synchronization block or method on that object.
  *
- * <h4>MXBean Mapping</h4>
+ * <h3>MXBean Mapping</h3>
  * <tt>MonitorInfo</tt> is mapped to a {@link CompositeData CompositeData}
  * with attributes as specified in
  * the {@link #from from} method.
@@ -106,7 +106,7 @@
      * <a href="LockInfo.html#MappedType">
      * mapped type</a> for the {@link LockInfo} class:
      * <blockquote>
-     * <table border>
+     * <table border summary="The attributes and their types the given CompositeData contains">
      * <tr>
      *   <th align=left>Attribute Name</th>
      *   <th align=left>Type</th>
--- a/src/share/classes/java/lang/management/RuntimeMXBean.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/management/RuntimeMXBean.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -272,7 +272,7 @@
      *
      * <p>
      * <b>MBeanServer access</b>:<br>
-     * The mapped type of <tt>List<String></tt> is <tt>String[]</tt>.
+     * The mapped type of {@code List<String>} is <tt>String[]</tt>.
      *
      * @return a list of <tt>String</tt> objects; each element
      * is an argument passed to the Java virtual machine.
@@ -312,7 +312,7 @@
      * {@link javax.management.openmbean.TabularData TabularData}
      * with two items in each row as follows:
      * <blockquote>
-     * <table border>
+     * <table border summary="Name and Type for each item">
      * <tr>
      *   <th>Item Name</th>
      *   <th>Item Type</th>
--- a/src/share/classes/java/lang/management/ThreadInfo.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/management/ThreadInfo.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,13 +33,13 @@
 /**
  * Thread information. <tt>ThreadInfo</tt> contains the information
  * about a thread including:
- * <h4>General thread information</h4>
+ * <h3>General thread information</h3>
  * <ul>
  *   <li>Thread ID.</li>
  *   <li>Name of the thread.</li>
  * </ul>
  *
- * <h4>Execution information</h4>
+ * <h3>Execution information</h3>
  * <ul>
  *   <li>Thread state.</li>
  *   <li>The object upon which the thread is blocked due to:
@@ -652,7 +652,7 @@
      * The given <tt>CompositeData</tt> must contain the following attributes
      * unless otherwise specified below:
      * <blockquote>
-     * <table border>
+     * <table border summary="The attributes and their types the given CompositeData contains">
      * <tr>
      *   <th align=left>Attribute Name</th>
      *   <th align=left>Type</th>
@@ -722,7 +722,7 @@
      *       Each element is a <tt>CompositeData</tt> representing
      *       StackTraceElement containing the following attributes:
      *       <blockquote>
-     *       <table cellspacing=1 cellpadding=0>
+     *       <table cellspacing=1 cellpadding=0 summary="The attributes and their types the given CompositeData contains">
      *       <tr>
      *         <th align=left>Attribute Name</th>
      *         <th align=left>Type</th>
--- a/src/share/classes/java/lang/management/ThreadMXBean.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/management/ThreadMXBean.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,7 +49,7 @@
  * It can be obtained by calling the
  * {@link PlatformManagedObject#getObjectName} method.
  *
- * <h4>Thread ID</h4>
+ * <h3>Thread ID</h3>
  * Thread ID is a positive long value returned by calling the
  * {@link java.lang.Thread#getId} method for a thread.
  * The thread ID is unique during its lifetime.  When a thread
@@ -58,7 +58,7 @@
  * <p> Some methods in this interface take a thread ID or an array
  * of thread IDs as the input parameter and return per-thread information.
  *
- * <h4>Thread CPU time</h4>
+ * <h3>Thread CPU time</h3>
  * A Java virtual machine implementation may support measuring
  * the CPU time for the current thread, for any thread, or for no threads.
  *
@@ -83,7 +83,7 @@
  * Enabling thread CPU measurement could be expensive in some
  * Java virtual machine implementations.
  *
- * <h4>Thread Contention Monitoring</h4>
+ * <h3>Thread Contention Monitoring</h3>
  * Some Java virtual machines may support thread contention monitoring.
  * When thread contention monitoring is enabled, the accumulated elapsed
  * time that the thread has blocked for synchronization or waited for
@@ -96,7 +96,7 @@
  * {@link #setThreadContentionMonitoringEnabled} method can be used to enable
  * thread contention monitoring.
  *
- * <h4>Synchronization Information and Deadlock Detection</h4>
+ * <h3>Synchronization Information and Deadlock Detection</h3>
  * Some Java virtual machines may support monitoring of
  * {@linkplain #isObjectMonitorUsageSupported object monitor usage} and
  * {@linkplain #isSynchronizerUsageSupported ownable synchronizer usage}.
--- a/src/share/classes/java/lang/ref/Reference.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/ref/Reference.java	Mon Jul 22 17:37:15 2013 -0700
@@ -89,7 +89,7 @@
 
     private T referent;         /* Treated specially by GC */
 
-    ReferenceQueue<? super T> queue;
+    volatile ReferenceQueue<? super T> queue;
 
     /* When active:   NULL
      *     pending:   this
@@ -225,9 +225,7 @@
      *           been enqueued
      */
     public boolean isEnqueued() {
-        synchronized (this) {
-            return (this.next != null && this.queue == ReferenceQueue.ENQUEUED);
-        }
+        return (this.queue == ReferenceQueue.ENQUEUED);
     }
 
     /**
--- a/src/share/classes/java/lang/ref/ReferenceQueue.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/ref/ReferenceQueue.java	Mon Jul 22 17:37:15 2013 -0700
@@ -55,25 +55,29 @@
     private long queueLength = 0;
 
     boolean enqueue(Reference<? extends T> r) { /* Called only by Reference class */
-        synchronized (r) {
-            if (r.queue == ENQUEUED) return false;
-            synchronized (lock) {
-                r.queue = ENQUEUED;
-                r.next = (head == null) ? r : head;
-                head = r;
-                queueLength++;
-                if (r instanceof FinalReference) {
-                    sun.misc.VM.addFinalRefCount(1);
-                }
-                lock.notifyAll();
-                return true;
+        synchronized (lock) {
+            // Check that since getting the lock this reference hasn't already been
+            // enqueued (and even then removed)
+            ReferenceQueue queue = r.queue;
+            if ((queue == NULL) || (queue == ENQUEUED)) {
+                return false;
             }
+            assert queue == this;
+            r.queue = ENQUEUED;
+            r.next = (head == null) ? r : head;
+            head = r;
+            queueLength++;
+            if (r instanceof FinalReference) {
+                sun.misc.VM.addFinalRefCount(1);
+            }
+            lock.notifyAll();
+            return true;
         }
     }
 
     private Reference<? extends T> reallyPoll() {       /* Must hold lock */
-        if (head != null) {
-            Reference<? extends T> r = head;
+        Reference<? extends T> r = head;
+        if (r != null) {
             head = (r.next == r) ? null : r.next;
             r.queue = NULL;
             r.next = r;
--- a/src/share/classes/java/lang/reflect/AnnotatedElement.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/reflect/AnnotatedElement.java	Mon Jul 22 17:37:15 2013 -0700
@@ -32,49 +32,101 @@
  * Represents an annotated element of the program currently running in this
  * VM.  This interface allows annotations to be read reflectively.  All
  * annotations returned by methods in this interface are immutable and
- * serializable.  It is permissible for the caller to modify the
- * arrays returned by accessors for array-valued enum members; it will
- * have no affect on the arrays returned to other callers.
+ * serializable. The arrays returned by methods of this interface may be modified
+ * by callers without affecting the arrays returned to other callers.
  *
  * <p>The {@link #getAnnotationsByType(Class)} and {@link
  * #getDeclaredAnnotationsByType(Class)} methods support multiple
- * annotations of the same type on an element. If the argument to either method
- * is a repeatable annotation type (JLS 9.6), then the method will "look
- * through" a container annotation (JLS 9.7) which was generated at
- * compile-time to wrap multiple annotations of the argument type.
+ * annotations of the same type on an element. If the argument to
+ * either method is a repeatable annotation type (JLS 9.6), then the
+ * method will "look through" a container annotation (JLS 9.7), if
+ * present, and return any annotations inside the container. Container
+ * annotations may be generated at compile-time to wrap multiple
+ * annotations of the argument type.
  *
- * <p>The terms <em>directly present</em> and <em>present</em> are used
- * throughout this interface to describe precisely which annotations are
- * returned by methods:
- *
- * <ul>
- * <li>An annotation A is <em>directly present</em> on an element E if E is
- * associated with a RuntimeVisibleAnnotations or
- * RuntimeVisibleParameterAnnotations attribute, and:
+ * <p>The terms <em>directly present</em>, <em>indirectly present</em>,
+ * <em>present</em>, and <em>associated</em> are used throughout this
+ * interface to describe precisely which annotations are returned by
+ * methods:
  *
  * <ul>
- * <li>for an invocation of {@code get[Declared]Annotation(Class<T>)} or
- * {@code get[Declared]Annotations()}, the attribute contains A.
+ *
+ * <li> An annotation <i>A</i> is <em>directly present</em> on an
+ * element <i>E</i> if <i>E</i> has a {@code
+ * RuntimeVisibleAnnotations} or {@code
+ * RuntimeVisibleParameterAnnotations} or {@code
+ * RuntimeVisibleTypeAnnotations} attribute, and the attribute
+ * contains <i>A</i>.
  *
- * <li>for an invocation of {@code get[Declared]AnnotationsByType(Class<T>)}, the
- * attribute either contains A or, if the type of A is repeatable, contains
- * exactly one annotation whose value element contains A and whose type is the
- * containing annotation type of A's type (JLS 9.6).
+ * <li>An annotation <i>A</i> is <em>indirectly present</em> on an
+ * element <i>E</i> if <i>E</i> has a {@code RuntimeVisibleAnnotations} or
+ * {@code RuntimeVisibleParameterAnnotations} or {@code RuntimeVisibleTypeAnnotations}
+ * attribute, and <i>A</i> 's type is repeatable, and the attribute contains
+ * exactly one annotation whose value element contains <i>A</i> and whose
+ * type is the containing annotation type of <i>A</i> 's type.
+ *
+ * <li>An annotation <i>A</i> is present on an element <i>E</i> if either:
+ *
+ * <ul>
+ *
+ * <li><i>A</i> is directly present on <i>E</i>; or
+ *
+ * <li>No annotation of <i>A</i> 's type is directly present on
+ * <i>E</i>, and <i>E</i> is a class, and <i>A</i> 's type is
+ * inheritable, and <i>A</i> is present on the superclass of <i>E</i>.
+ *
  * </ul>
  *
- * <p>
- * <li>An annotation A is <em>present</em> on an element E if either:
+ * <li>An annotation <i>A</i> is <em>associated</em> with an element <i>E</i>
+ * if either:
  *
  * <ul>
- * <li>A is <em>directly present</em> on E; or
+ *
+ * <li><i>A</i> is directly or indirectly present on <i>E</i>; or
  *
- * <li>A is not <em>directly present</em> on E, and E is a class, and A's type
- * is inheritable (JLS 9.6.3.3), and A is <em>present</em> on the superclass of
- * E.
+ * <li>No annotation of <i>A</i> 's type is directly or indirectly
+ * present on <i>E</i>, and <i>E</i> is a class, and <i>A</i>'s type
+ * is inheritable, and <i>A</i> is associated with the superclass of
+ * <i>E</i>.
+ *
  * </ul>
  *
  * </ul>
  *
+ * <p>The table below summarizes which kind of annotation presence
+ * different methods in this interface examine.
+ *
+ * <table border>
+ * <caption>Overview of kind of presence detected by different AnnotatedElement methods</caption>
+ * <tr><th colspan=2></th><th colspan=4>Kind of Presence</th>
+ * <tr><th colspan=2>Method</th><th>Directly Present</th><th>Indirectly Present</th><th>Present</th><th>Associated</th>
+ * <tr><td align=right>{@code T}</td><td>{@link #getAnnotation(Class) getAnnotation(Class&lt;T&gt;)}
+ * <td></td><td></td><td>X</td><td></td>
+ * </tr>
+ * <tr><td align=right>{@code Annotation[]}</td><td>{@link #getAnnotations getAnnotations()}
+ * <td></td><td></td><td>X</td><td></td>
+ * </tr>
+ * <tr><td align=right>{@code T[]}</td><td>{@link #getAnnotationsByType(Class) getAnnotationsByType(Class&lt;T&gt;)}
+ * <td></td><td></td><td></td><td>X</td>
+ * </tr>
+ * <tr><td align=right>{@code T}</td><td>{@link #getDeclaredAnnotation(Class) getDeclaredAnnotation(Class&lt;T&gt;)}
+ * <td>X</td><td></td><td></td><td></td>
+ * </tr>
+ * <tr><td align=right>{@code Annotation[]}</td><td>{@link #getDeclaredAnnotations getDeclaredAnnotations()}
+ * <td>X</td><td></td><td></td><td></td>
+ * </tr>
+ * <tr><td align=right>{@code T[]}</td><td>{@link #getDeclaredAnnotationsByType(Class) getDeclaredAnnotationsByType(Class&lt;T&gt;)}
+ * <td>X</td><td>X</td><td></td><td></td>
+ * </tr>
+ * </table>
+ *
+ * <p>For an invocation of {@code get[Declared]AnnotationsByType( Class <
+ * T >)}, the order of annotations which are directly or indirectly
+ * present on an element <i>E</i> is computed as if indirectly present
+ * annotations on <i>E</i> are directly present on <i>E</i> in place
+ * of their container annotation, in the order in which they appear in
+ * the value element of the container annotation.
+
  * <p>If an annotation returned by a method in this interface contains
  * (directly or indirectly) a {@link Class}-valued member referring to
  * a class that is not accessible in this VM, attempting to read the class
@@ -85,10 +137,11 @@
  * a {@link EnumConstantNotPresentException} if the enum constant in the
  * annotation is no longer present in the enum type.
  *
- * <p>Attempting to read annotations of a repeatable annotation type T
- * that are contained in an annotation whose type is not, in fact, the
- * containing annotation type of T, will result in an {@link
- * AnnotationFormatError}.
+ * <p>If an annotation type <i>T</i> is (meta-)annotated with an
+ * {@code @Repeatable} annotation whose value element indicates a type
+ * <i>TC</i>, but <i>TC</i> does not declare a {@code value()} method
+ * with a return type of <i>T</i>{@code []}, then an exception of type
+ * {@link java.lang.annotation.AnnotationFormatError} is thrown.
  *
  * <p>Finally, attempting to read a member whose definition has evolved
  * incompatibly will result in a {@link
@@ -106,7 +159,7 @@
 public interface AnnotatedElement {
     /**
      * Returns true if an annotation for the specified type
-     * is present on this element, else false.  This method
+     * is <em>present</em> on this element, else false.  This method
      * is designed primarily for convenient access to marker annotations.
      *
      * <p>The truth value returned by this method is equivalent to:
@@ -128,7 +181,7 @@
 
    /**
      * Returns this element's annotation for the specified type if
-     * such an annotation is present, else null.
+     * such an annotation is <em>present</em>, else null.
      *
      * @param <T> the type of the annotation to query for and return if present
      * @param annotationClass the Class object corresponding to the
@@ -146,6 +199,20 @@
      * If there are no annotations <em>present</em> on this element, the return
      * value is an array of length 0.
      *
+     * The caller of this method is free to modify the returned array; it will
+     * have no effect on the arrays returned to other callers.
+     *
+     * @return annotations present on this element
+     * @since 1.5
+     */
+    Annotation[] getAnnotations();
+
+    /**
+     * Returns annotations that are <em>associated</em> with this element.
+     *
+     * If there are no annotations <em>associated</em> with this element, the return
+     * value is an array of length 0.
+     *
      * The difference between this method and {@link #getAnnotation(Class)}
      * is that this method detects if its argument is a <em>repeatable
      * annotation type</em> (JLS 9.6), and if so, attempts to find one or
@@ -159,65 +226,54 @@
      * @param annotationClass the Class object corresponding to the
      *        annotation type
      * @return all this element's annotations for the specified annotation type if
-     *     present on this element, else an array of length zero
+     *     associated with this element, else an array of length zero
      * @throws NullPointerException if the given annotation class is null
      * @since 1.8
      */
     <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass);
 
     /**
-     * Returns annotations that are <em>present</em> on this element.
-     *
-     * If there are no annotations <em>present</em> on this element, the return
-     * value is an array of length 0.
-     *
-     * The caller of this method is free to modify the returned array; it will
-     * have no effect on the arrays returned to other callers.
-     *
-     * @return annotations present on this element
-     * @since 1.5
-     */
-    Annotation[] getAnnotations();
-
-    /**
      * Returns this element's annotation for the specified type if
-     * such an annotation is present, else null.
+     * such an annotation is <em>directly present</em>, else null.
      *
      * This method ignores inherited annotations. (Returns null if no
      * annotations are directly present on this element.)
      *
-     * @param <T> the type of the annotation to query for and return if present
+     * @param <T> the type of the annotation to query for and return if directly present
      * @param annotationClass the Class object corresponding to the
      *        annotation type
      * @return this element's annotation for the specified annotation type if
-     *     present on this element, else null
+     *     directly present on this element, else null
      * @throws NullPointerException if the given annotation class is null
      * @since 1.8
      */
     <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass);
 
     /**
-     * Returns annotations that are <em>directly present</em> on this element.
-     * This method ignores inherited annotations.
+     * Returns this element's annotation(s) for the specified type if
+     * such annotations are either <em>directly present</em> or
+     * <em>indirectly present</em>. This method ignores inherited
+     * annotations.
      *
-     * If there are no annotations <em>directly present</em> on this element,
-     * the return value is an array of length 0.
+     * If there are no specified annotations directly or indirectly
+     * present on this element, the return value is an array of length
+     * 0.
      *
      * The difference between this method and {@link
      * #getDeclaredAnnotation(Class)} is that this method detects if its
      * argument is a <em>repeatable annotation type</em> (JLS 9.6), and if so,
      * attempts to find one or more annotations of that type by "looking
-     * through" a container annotation.
+     * through" a container annotation if one is present.
      *
      * The caller of this method is free to modify the returned array; it will
      * have no effect on the arrays returned to other callers.
      *
      * @param <T> the type of the annotation to query for and return
-     * if directly present
+     * if directly or indirectly present
      * @param annotationClass the Class object corresponding to the
      *        annotation type
      * @return all this element's annotations for the specified annotation type if
-     *     present on this element, else an array of length zero
+     *     directly or indirectly present on this element, else an array of length zero
      * @throws NullPointerException if the given annotation class is null
      * @since 1.8
      */
--- a/src/share/classes/java/lang/reflect/Executable.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/reflect/Executable.java	Mon Jul 22 17:37:15 2013 -0700
@@ -326,8 +326,12 @@
             tmp = getParameters0();
 
             // If we get back nothing, then synthesize parameters
-            if (tmp == null)
+            if (tmp == null) {
+                hasRealParameterData = false;
                 tmp = synthesizeAllParams();
+            } else {
+                hasRealParameterData = true;
+            }
 
             parameters = tmp;
         }
@@ -335,6 +339,16 @@
         return tmp;
     }
 
+    boolean hasRealParameterData() {
+        // If this somehow gets called before parameters gets
+        // initialized, force it into existence.
+        if (parameters == null) {
+            privateGetParameters();
+        }
+        return hasRealParameterData;
+    }
+
+    private transient volatile boolean hasRealParameterData;
     private transient volatile Parameter[] parameters;
 
     private native Parameter[] getParameters0();
--- a/src/share/classes/java/lang/reflect/Member.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/reflect/Member.java	Mon Jul 22 17:37:15 2013 -0700
@@ -42,14 +42,12 @@
     /**
      * Identifies the set of all public members of a class or interface,
      * including inherited members.
-     * @see java.lang.SecurityManager#checkMemberAccess
      */
     public static final int PUBLIC = 0;
 
     /**
      * Identifies the set of declared members of a class or interface.
      * Inherited members are not included.
-     * @see java.lang.SecurityManager#checkMemberAccess
      */
     public static final int DECLARED = 1;
 
--- a/src/share/classes/java/lang/reflect/Parameter.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/lang/reflect/Parameter.java	Mon Jul 22 17:37:15 2013 -0700
@@ -95,6 +95,19 @@
     }
 
     /**
+     * Returns true if the parameter has a name according to the class
+     * file; returns false otherwise. Whether a parameter has a name
+     * is determined by the {@literal MethodParameters} attribute of
+     * the method which declares the parameter.
+     *
+     * @return true if and only if the parameter has a name according
+     * to the class file.
+     */
+    public boolean isNamePresent() {
+        return executable.hasRealParameterData();
+    }
+
+    /**
      * Returns a string describing this parameter.  The format is the
      * modifiers for the parameter, if any, in canonical order as
      * recommended by <cite>The Java&trade; Language
@@ -149,11 +162,15 @@
 
     /**
      * Returns the name of the parameter.  If the parameter's name is
-     * defined in a class file, then that name will be returned by
-     * this method.  Otherwise, this method will synthesize a name of
-     * the form argN, where N is the index of the parameter.
+     * {@linkplain isNamePresent() present}, then this method returns
+     * the name provided by the class file. Otherwise, this method
+     * synthesizes a name of the form argN, where N is the index of
+     * the parameter in the descriptor of the method which declares
+     * the parameter.
      *
-     * @return the name of the parameter
+     * @return The name of the parameter, either provided by the class
+     *         file or synthesized if the class file does not provide
+     *         a name.
      */
     public String getName() {
         // Note: empty strings as paramete names are now outlawed.
--- a/src/share/classes/java/math/BigDecimal.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/math/BigDecimal.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2592,14 +2592,18 @@
      * the {@code BigDecimal} value {@code 600.0}, which has
      * [{@code BigInteger}, {@code scale}] components equals to
      * [6000, 1], yields {@code 6E2} with [{@code BigInteger},
-     * {@code scale}] components equals to [6, -2]
+     * {@code scale}] components equals to [6, -2].  If
+     * this BigDecimal is numerically equal to zero, then
+     * {@code BigDecimal.ZERO} is returned.
      *
      * @return a numerically equal {@code BigDecimal} with any
      * trailing zeros removed.
      * @since 1.5
      */
     public BigDecimal stripTrailingZeros() {
-        if(intCompact!=INFLATED) {
+        if (intCompact == 0 || (intVal != null && intVal.signum() == 0)) {
+            return BigDecimal.ZERO;
+        } else if (intCompact != INFLATED) {
             return createAndStripZerosToMatchScale(intCompact, scale, Long.MIN_VALUE);
         } else {
             return createAndStripZerosToMatchScale(intVal, scale, Long.MIN_VALUE);
--- a/src/share/classes/java/net/CookieStore.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/net/CookieStore.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -75,6 +75,8 @@
      * @return          an immutable list of HttpCookie,
      *                  return empty list if no cookies match the given URI
      *
+     * @param uri       the uri associated with the cookies to be returned
+     *
      * @throws NullPointerException if <tt>uri</tt> is <tt>null</tt>
      *
      * @see #add
--- a/src/share/classes/java/net/HttpURLPermission.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/net/HttpURLPermission.java	Mon Jul 22 17:37:15 2013 -0700
@@ -47,6 +47,7 @@
  * in {@link java.io.FilePermission}. There are three different ways
  * as the following examples show:
  * <table border>
+ * <caption>URL Examples</caption>
  * <tr><th>Example url</th><th>Description</th></tr>
  * <tr><td style="white-space:nowrap;">http://www.oracle.com/a/b/c.html</td>
  *   <td>A url which identifies a specific (single) resource</td>
@@ -57,7 +58,7 @@
  *       which only differ in the final path component, represented by the '*'.
  *   </td>
  * </tr>
- * <tr><td>http://www.oracle.com/a/b/-</li>
+ * <tr><td>http://www.oracle.com/a/b/-</td>
  *   <td>The '-' character refers to all resources recursively below the
  *       preceding path (eg. http://www.oracle.com/a/b/c/d/e.html matches this
  *       example).
@@ -164,6 +165,8 @@
      * methods and request headers by invoking the two argument
      * constructor as follows: HttpURLPermission(url, "*:*")
      *
+     * @param url the url string
+     *
      * @throws    IllegalArgumentException if url does not result in a valid {@link URI}
      */
     public HttpURLPermission(String url) {
@@ -204,11 +207,10 @@
      * <li>if the path or paths specified by p's url are contained in the
      *     set of paths specified by this's url, then return true
      * <li>otherwise, return false</li>
-     * </ol>
-     * <p>
-     * Some examples of how paths are matched are shown below:
-     * <p>
-     * <table border>
+     * </ul>
+     * <p>Some examples of how paths are matched are shown below:
+     * <p><table border>
+     * <caption>Examples of Path Matching</caption>
      * <tr><th>this's path</th><th>p's path</th><th>match</th></tr>
      * <tr><td>/a/b</td><td>/a/b</td><td>yes</td></tr>
      * <tr><td>/a/b/*</td><td>/a/b/c</td><td>yes</td></tr>
--- a/src/share/classes/java/net/Inet4Address.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/net/Inet4Address.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,7 +36,7 @@
  * and <a href="http://www.ietf.org/rfc/rfc2365.txt"><i>RFC&nbsp;2365:
  * Administratively Scoped IP Multicast</i></a>
  *
- * <h4> <A NAME="format">Textual representation of IP addresses</a> </h4>
+ * <h3> <A NAME="format">Textual representation of IP addresses</a> </h3>
  *
  * Textual representation of IPv4 address used as input to methods
  * takes one of the following forms:
--- a/src/share/classes/java/net/Inet6Address.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/net/Inet6Address.java	Mon Jul 22 17:37:15 2013 -0700
@@ -35,7 +35,7 @@
  * Defined by <a href="http://www.ietf.org/rfc/rfc2373.txt">
  * <i>RFC&nbsp;2373: IP Version 6 Addressing Architecture</i></a>.
  *
- * <h4> <A NAME="format">Textual representation of IP addresses</a> </h4>
+ * <h3> <A NAME="format">Textual representation of IP addresses</a> </h3>
  *
  * Textual representation of IPv6 address used as input to methods
  * takes one of the following forms:
@@ -156,7 +156,7 @@
  * system. Usually, the numeric values can be determined through administration
  * tools on the system. Each interface may have multiple values, one for each
  * scope. If the scope is unspecified, then the default value used is zero.</li>
- * <p><li><i>As a string.</i> This must be the exact string that is returned by
+ * <li><i>As a string.</i> This must be the exact string that is returned by
  * {@link java.net.NetworkInterface#getName()} for the particular interface in
  * question. When an Inet6Address is created in this way, the numeric scope-id
  * is determined at the time the object is created by querying the relevant
--- a/src/share/classes/java/net/InetAddress.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/net/InetAddress.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -65,7 +65,7 @@
  * with a host name or whether it has already done reverse host name
  * resolution).
  *
- * <h4> Address types </h4>
+ * <h3> Address types </h3>
  *
  * <blockquote><table cellspacing=2 summary="Description of unicast and multicast address types">
  *   <tr><th valign=top><i>unicast</i></th>
@@ -165,7 +165,6 @@
  * <p>
  * A value of -1 indicates "cache forever".
  * </dd>
- * <p>
  * <dt><b>networkaddress.cache.negative.ttl</b> (default: 10)</dt>
  * <dd>Indicates the caching policy for un-successful name lookups
  * from the name service. The value is specified as as integer to
--- a/src/share/classes/java/net/ProtocolFamily.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/net/ProtocolFamily.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,6 +34,8 @@
 public interface ProtocolFamily {
     /**
      * Returns the name of the protocol family.
+     *
+     * @return the name of the protocol family
      */
     String name();
 }
--- a/src/share/classes/java/net/SocketOption.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/net/SocketOption.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -45,11 +45,15 @@
 
     /**
      * Returns the name of the socket option.
+     *
+     * @return the name of the socket option
      */
     String name();
 
     /**
      * Returns the type of the socket option value.
+     *
+     * @return the type of the socket option value
      */
     Class<T> type();
 }
--- a/src/share/classes/java/net/URI.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/net/URI.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -61,13 +61,13 @@
  * and relativizing URI instances.  Instances of this class are immutable.
  *
  *
- * <h4> URI syntax and components </h4>
+ * <h3> URI syntax and components </h3>
  *
  * At the highest level a URI reference (hereinafter simply "URI") in string
  * form has the syntax
  *
  * <blockquote>
- * [<i>scheme</i><tt><b>:</b></tt><i></i>]<i>scheme-specific-part</i>[<tt><b>#</b></tt><i>fragment</i>]
+ * [<i>scheme</i><tt><b>:</b></tt>]<i>scheme-specific-part</i>[<tt><b>#</b></tt><i>fragment</i>]
  * </blockquote>
  *
  * where square brackets [...] delineate optional components and the characters
@@ -334,14 +334,14 @@
  *
  * <ul>
  *
- *   <li><p> The {@link #URI(java.lang.String) <code>single-argument
- *   constructor</code>} requires any illegal characters in its argument to be
+ *   <li><p> The {@linkplain #URI(java.lang.String) single-argument
+ *   constructor} requires any illegal characters in its argument to be
  *   quoted and preserves any escaped octets and <i>other</i> characters that
  *   are present.  </p></li>
  *
- *   <li><p> The {@link
+ *   <li><p> The {@linkplain
  *   #URI(java.lang.String,java.lang.String,java.lang.String,int,java.lang.String,java.lang.String,java.lang.String)
- *   <code>multi-argument constructors</code>} quote illegal characters as
+ *   multi-argument constructors} quote illegal characters as
  *   required by the components in which they appear.  The percent character
  *   (<tt>'%'</tt>) is always quoted by these constructors.  Any <i>other</i>
  *   characters are preserved.  </p></li>
--- a/src/share/classes/java/nio/X-Buffer.java.template	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/nio/X-Buffer.java.template	Mon Jul 22 17:37:15 2013 -0700
@@ -1495,7 +1495,7 @@
 #end[char]
     public $Streamtype$Stream $type$s() {
         return StreamSupport.$streamtype$Stream(() -> new $Type$BufferSpliterator(this),
-            Buffer.SPLITERATOR_CHARACTERISTICS);
+            Buffer.SPLITERATOR_CHARACTERISTICS, false);
     }
 
 #end[streamableType]
--- a/src/share/classes/java/nio/file/Files.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/nio/file/Files.java	Mon Jul 22 17:37:15 2013 -0700
@@ -3269,9 +3269,10 @@
             }
         };
 
-        return new DelegatingCloseableStream<>(ds,
-            StreamSupport.stream(Spliterators.spliteratorUnknownSize(it,
-                                                                     Spliterator.DISTINCT)));
+        Stream<Path> s = StreamSupport.stream(
+                Spliterators.spliteratorUnknownSize(it, Spliterator.DISTINCT),
+                false);
+        return new DelegatingCloseableStream<>(ds, s);
     }
 
     /**
@@ -3358,9 +3359,12 @@
         throws IOException
     {
         FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options);
-        return new DelegatingCloseableStream<>(iterator,
-            StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT))
-                   .map(entry -> entry.file()));
+
+        Stream<Path> s = StreamSupport.stream(
+                Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT),
+                false).
+                map(entry -> entry.file());
+        return new DelegatingCloseableStream<>(iterator, s);
     }
 
     /**
@@ -3455,10 +3459,13 @@
         throws IOException
     {
         FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options);
-        return new DelegatingCloseableStream<>(iterator,
-            StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT))
-                   .filter(entry -> matcher.test(entry.file(), entry.attributes()))
-                   .map(entry -> entry.file()));
+
+        Stream<Path> s = StreamSupport.stream(
+                Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT),
+                false).
+                filter(entry -> matcher.test(entry.file(), entry.attributes())).
+                map(entry -> entry.file());
+        return new DelegatingCloseableStream<>(iterator, s);
     }
 
     /**
--- a/src/share/classes/java/security/AuthProvider.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/security/AuthProvider.java	Mon Jul 22 17:37:15 2013 -0700
@@ -41,6 +41,8 @@
  */
 public abstract class AuthProvider extends Provider {
 
+    private static final long serialVersionUID = 4197859053084546461L;
+
     /**
      * Constructs a provider with the specified name, version number,
      * and information.
--- a/src/share/classes/java/util/AbstractMap.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/AbstractMap.java	Mon Jul 22 17:37:15 2013 -0700
@@ -543,6 +543,8 @@
     /**
      * Utility method for SimpleEntry and SimpleImmutableEntry.
      * Test for equality, checking for nulls.
+     *
+     * NB: Do not replace with Object.equals until JDK-8015417 is resolved.
      */
     private static boolean eq(Object o1, Object o2) {
         return o1 == null ? o2 == null : o1.equals(o2);
--- a/src/share/classes/java/util/ArrayList.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/ArrayList.java	Mon Jul 22 17:37:15 2013 -0700
@@ -70,9 +70,9 @@
  * unsynchronized access to the list:<pre>
  *   List list = Collections.synchronizedList(new ArrayList(...));</pre>
  *
- * <p><a name="fail-fast"/>
+ * <p><a name="fail-fast">
  * The iterators returned by this class's {@link #iterator() iterator} and
- * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:
+ * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:</a>
  * if the list is structurally modified at any time after the iterator is
  * created, in any way except through the iterator's own
  * {@link ListIterator#remove() remove} or
--- a/src/share/classes/java/util/Arrays.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/Arrays.java	Mon Jul 22 17:37:15 2013 -0700
@@ -984,6 +984,7 @@
      * {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to
      * execute any parallel tasks.
      *
+     * @param <T> the class of the objects to be sorted
      * @param a the array to be sorted
      *
      * @throws ClassCastException if the array contains elements that are not
@@ -1035,6 +1036,7 @@
      * array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is
      * used to execute any parallel tasks.
      *
+     * @param <T> the class of the objects to be sorted
      * @param a the array to be sorted
      * @param fromIndex the index of the first element (inclusive) to be
      *        sorted
@@ -1087,6 +1089,7 @@
      * {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to
      * execute any parallel tasks.
      *
+     * @param <T> the class of the objects to be sorted
      * @param a the array to be sorted
      * @param cmp the comparator to determine the order of the array.  A
      *        {@code null} value indicates that the elements'
@@ -1138,6 +1141,7 @@
      * array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is
      * used to execute any parallel tasks.
      *
+     * @param <T> the class of the objects to be sorted
      * @param a the array to be sorted
      * @param fromIndex the index of the first element (inclusive) to be
      *        sorted
@@ -1412,6 +1416,7 @@
      * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
      * January 1993.
      *
+     * @param <T> the class of the objects to be sorted
      * @param a the array to be sorted
      * @param c the comparator to determine the order of the array.  A
      *        {@code null} value indicates that the elements'
@@ -1475,6 +1480,7 @@
      * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
      * January 1993.
      *
+     * @param <T> the class of the objects to be sorted
      * @param a the array to be sorted
      * @param fromIndex the index of the first element (inclusive) to be
      *        sorted
@@ -1569,6 +1575,7 @@
      * Parallel prefix computation is usually more efficient than
      * sequential loops for large arrays.
      *
+     * @param <T> the class of the objects in the array
      * @param array the array, which is modified in-place by this method
      * @param op a side-effect-free, associative function to perform the
      * cumulation
@@ -1585,6 +1592,7 @@
      * Performs {@link #parallelPrefix(Object[], BinaryOperator)}
      * for the given subrange of the array.
      *
+     * @param <T> the class of the objects in the array
      * @param array the array
      * @param fromIndex the index of the first element, inclusive
      * @param toIndex the index of the last element, exclusive
@@ -2437,6 +2445,7 @@
      * elements equal to the specified object, there is no guarantee which one
      * will be found.
      *
+     * @param <T> the class of the objects in the array
      * @param a the array to be searched
      * @param key the value to be searched for
      * @param c the comparator by which the array is ordered.  A
@@ -2472,6 +2481,7 @@
      * If the range contains multiple elements equal to the specified object,
      * there is no guarantee which one will be found.
      *
+     * @param <T> the class of the objects in the array
      * @param a the array to be searched
      * @param fromIndex the index of the first element (inclusive) to be
      *          searched
@@ -3143,6 +3153,7 @@
      * is greater than that of the original array.
      * The resulting array is of exactly the same class as the original array.
      *
+     * @param <T> the class of the objects in the array
      * @param original the array to be copied
      * @param newLength the length of the copy to be returned
      * @return a copy of the original array, truncated or padded with nulls
@@ -3166,6 +3177,8 @@
      * is greater than that of the original array.
      * The resulting array is of the class <tt>newType</tt>.
      *
+     * @param <U> the class of the objects in the original array
+     * @param <T> the class of the objects in the returned array
      * @param original the array to be copied
      * @param newLength the length of the copy to be returned
      * @param newType the class of the copy to be returned
@@ -3396,6 +3409,7 @@
      * <p>
      * The resulting array is of exactly the same class as the original array.
      *
+     * @param <T> the class of the objects in the array
      * @param original the array from which a range is to be copied
      * @param from the initial index of the range to be copied, inclusive
      * @param to the final index of the range to be copied, exclusive.
@@ -3428,6 +3442,8 @@
      * of the returned array will be <tt>to - from</tt>.
      * The resulting array is of the class <tt>newType</tt>.
      *
+     * @param <U> the class of the objects in the original array
+     * @param <T> the class of the objects in the returned array
      * @param original the array from which a range is to be copied
      * @param from the initial index of the range to be copied, inclusive
      * @param to the final index of the range to be copied, exclusive.
@@ -3760,6 +3776,7 @@
      *     List&lt;String&gt; stooges = Arrays.asList("Larry", "Moe", "Curly");
      * </pre>
      *
+     * @param <T> the class of the objects in the array
      * @param a the array by which the list will be backed
      * @return a list view of the specified array
      */
@@ -4966,7 +4983,7 @@
      * @since 1.8
      */
     public static <T> Stream<T> stream(T[] array, int startInclusive, int endExclusive) {
-        return StreamSupport.stream(spliterator(array, startInclusive, endExclusive));
+        return StreamSupport.stream(spliterator(array, startInclusive, endExclusive), false);
     }
 
     /**
@@ -4996,7 +5013,7 @@
      * @since 1.8
      */
     public static IntStream stream(int[] array, int startInclusive, int endExclusive) {
-        return StreamSupport.intStream(spliterator(array, startInclusive, endExclusive));
+        return StreamSupport.intStream(spliterator(array, startInclusive, endExclusive), false);
     }
 
     /**
@@ -5026,7 +5043,7 @@
      * @since 1.8
      */
     public static LongStream stream(long[] array, int startInclusive, int endExclusive) {
-        return StreamSupport.longStream(spliterator(array, startInclusive, endExclusive));
+        return StreamSupport.longStream(spliterator(array, startInclusive, endExclusive), false);
     }
 
     /**
@@ -5056,6 +5073,6 @@
      * @since 1.8
      */
     public static DoubleStream stream(double[] array, int startInclusive, int endExclusive) {
-        return StreamSupport.doubleStream(spliterator(array, startInclusive, endExclusive));
+        return StreamSupport.doubleStream(spliterator(array, startInclusive, endExclusive), false);
     }
 }
--- a/src/share/classes/java/util/Base64.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/Base64.java	Mon Jul 22 17:37:15 2013 -0700
@@ -42,24 +42,21 @@
  *
  * <p>
  * <ul>
- * <a name="basic">
- * <li><b>Basic</b>
+ * <li><a name="basic"><b>Basic</b></a>
  * <p> Uses "The Base64 Alphabet" as specified in Table 1 of
  *     RFC 4648 and RFC 2045 for encoding and decoding operation.
  *     The encoder does not add any line feed (line separator)
  *     character. The decoder rejects data that contains characters
  *     outside the base64 alphabet.</p></li>
  *
- * <a name="url">
- * <li><b>URL and Filename safe</b>
+ * <li><a name="url"><b>URL and Filename safe</b></a>
  * <p> Uses the "URL and Filename safe Base64 Alphabet" as specified
  *     in Table 2 of RFC 4648 for encoding and decoding. The
  *     encoder does not add any line feed (line separator) character.
  *     The decoder rejects data that contains characters outside the
  *     base64 alphabet.</p></li>
  *
- * <a name="mime">
- * <li><b>MIME</b>
+ * <li><a name="mime"><b>MIME</b></a>
  * <p> Uses the "The Base64 Alphabet" as specified in Table 1 of
  *     RFC 2045 for encoding and decoding operation. The encoded output
  *     must be represented in lines of no more than 76 characters each
--- a/src/share/classes/java/util/BitSet.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/BitSet.java	Mon Jul 22 17:37:15 2013 -0700
@@ -189,6 +189,7 @@
      * @param longs a long array containing a little-endian representation
      *        of a sequence of bits to be used as the initial bits of the
      *        new bit set
+     * @return a {@code BitSet} containing all the bits in the long array
      * @since 1.7
      */
     public static BitSet valueOf(long[] longs) {
@@ -212,6 +213,8 @@
      * @param lb a long buffer containing a little-endian representation
      *        of a sequence of bits between its position and limit, to be
      *        used as the initial bits of the new bit set
+     * @return a {@code BitSet} containing all the bits in the buffer in the
+     *         specified range
      * @since 1.7
      */
     public static BitSet valueOf(LongBuffer lb) {
@@ -237,6 +240,7 @@
      * @param bytes a byte array containing a little-endian
      *        representation of a sequence of bits to be used as the
      *        initial bits of the new bit set
+     * @return a {@code BitSet} containing all the bits in the byte array
      * @since 1.7
      */
     public static BitSet valueOf(byte[] bytes) {
@@ -257,6 +261,8 @@
      * @param bb a byte buffer containing a little-endian representation
      *        of a sequence of bits between its position and limit, to be
      *        used as the initial bits of the new bit set
+     * @return a {@code BitSet} containing all the bits in the buffer in the
+     *         specified range
      * @since 1.7
      */
     public static BitSet valueOf(ByteBuffer bb) {
@@ -1231,6 +1237,7 @@
                         new BitSetIterator(), cardinality(),
                         Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED),
                 Spliterator.SIZED | Spliterator.SUBSIZED |
-                        Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED);
+                        Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED,
+                false);
     }
 }
--- a/src/share/classes/java/util/Calendar.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/Calendar.java	Mon Jul 22 17:37:15 2013 -0700
@@ -96,7 +96,7 @@
  * concrete subclass, such as <code>ERA</code>.  See individual field
  * documentation and subclass documentation for details.
  *
- * <h4>Getting and Setting Calendar Field Values</h4>
+ * <h3>Getting and Setting Calendar Field Values</h3>
  *
  * <p>The calendar field values can be set by calling the <code>set</code>
  * methods. Any field values set in a <code>Calendar</code> will not be
@@ -207,7 +207,7 @@
  * <h4>Field Manipulation</h4>
  *
  * The calendar fields can be changed using three methods:
- * <code>set()</code>, <code>add()</code>, and <code>roll()</code>.</p>
+ * <code>set()</code>, <code>add()</code>, and <code>roll()</code>.
  *
  * <p><strong><code>set(f, value)</code></strong> changes calendar field
  * <code>f</code> to <code>value</code>.  In addition, it sets an
@@ -2024,6 +2024,7 @@
      * including cases that the value has been set by internal fields
      * calculations triggered by a <code>get</code> method call.
      *
+     * @param field the calendar field to test
      * @return <code>true</code> if the given calendar field has a value set;
      * <code>false</code> otherwise.
      */
--- a/src/share/classes/java/util/Collection.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/Collection.java	Mon Jul 22 17:37:15 2013 -0700
@@ -64,9 +64,9 @@
  * but is not required to, throw the exception if the collection to be added
  * is empty.
  *
- * <p><a name="optional-restrictions"/>
+ * <p><a name="optional-restrictions">
  * Some collection implementations have restrictions on the elements that
- * they may contain.  For example, some implementations prohibit null elements,
+ * they may contain.</a>  For example, some implementations prohibit null elements,
  * and some have restrictions on the types of their elements.  Attempting to
  * add an ineligible element throws an unchecked exception, typically
  * <tt>NullPointerException</tt> or <tt>ClassCastException</tt>.  Attempting
@@ -232,6 +232,7 @@
      * Note that <tt>toArray(new Object[0])</tt> is identical in function to
      * <tt>toArray()</tt>.
      *
+     * @param <T> the runtime type of the array to contain the collection
      * @param a the array into which the elements of this collection are to be
      *        stored, if it is big enough; otherwise, a new array of the same
      *        runtime type is allocated for this purpose.
@@ -557,7 +558,7 @@
      * @since 1.8
      */
     default Stream<E> stream() {
-        return StreamSupport.stream(spliterator());
+        return StreamSupport.stream(spliterator(), false);
     }
 
     /**
@@ -578,6 +579,6 @@
      * @since 1.8
      */
     default Stream<E> parallelStream() {
-        return StreamSupport.parallelStream(spliterator());
+        return StreamSupport.stream(spliterator(), true);
     }
 }
--- a/src/share/classes/java/util/Collections.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/Collections.java	Mon Jul 22 17:37:15 2013 -0700
@@ -27,6 +27,7 @@
 import java.io.Serializable;
 import java.io.ObjectOutputStream;
 import java.io.IOException;
+import java.io.InvalidObjectException;
 import java.lang.reflect.Array;
 import java.util.function.BiConsumer;
 import java.util.function.BiFunction;
@@ -34,6 +35,8 @@
 import java.util.function.Function;
 import java.util.function.Predicate;
 import java.util.function.UnaryOperator;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
 
 /**
  * This class consists exclusively of static methods that operate on or return
@@ -136,7 +139,7 @@
      *
      * <p>The implementation was adapted from Tim Peters's list sort for Python
      * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
-     * TimSort</a>).  It uses techiques from Peter McIlroy's "Optimistic
+     * TimSort</a>).  It uses techniques from Peter McIlroy's "Optimistic
      * Sorting and Information Theoretic Complexity", in Proceedings of the
      * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
      * January 1993.
@@ -147,6 +150,7 @@
      * n<sup>2</sup> log(n) performance that would result from attempting
      * to sort a linked list in place.
      *
+     * @param  <T> the class of the objects in the list
      * @param  list the list to be sorted.
      * @throws ClassCastException if the list contains elements that are not
      *         <i>mutually comparable</i> (for example, strings and integers).
@@ -197,7 +201,7 @@
      *
      * <p>The implementation was adapted from Tim Peters's list sort for Python
      * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
-     * TimSort</a>).  It uses techiques from Peter McIlroy's "Optimistic
+     * TimSort</a>).  It uses techniques from Peter McIlroy's "Optimistic
      * Sorting and Information Theoretic Complexity", in Proceedings of the
      * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
      * January 1993.
@@ -208,6 +212,7 @@
      * n<sup>2</sup> log(n) performance that would result from attempting
      * to sort a linked list in place.
      *
+     * @param  <T> the class of the objects in the list
      * @param  list the list to be sorted.
      * @param  c the comparator to determine the order of the list.  A
      *        {@code null} value indicates that the elements' <i>natural
@@ -246,6 +251,7 @@
      * this method will do an iterator-based binary search that performs
      * O(n) link traversals and O(log n) element comparisons.
      *
+     * @param  <T> the class of the objects in the list
      * @param  list the list to be searched.
      * @param  key the key to be searched for.
      * @return the index of the search key, if it is contained in the list;
@@ -346,6 +352,7 @@
      * this method will do an iterator-based binary search that performs
      * O(n) link traversals and O(log n) element comparisons.
      *
+     * @param  <T> the class of the objects in the list
      * @param  list the list to be searched.
      * @param  key the key to be searched for.
      * @param  c the comparator by which the list is ordered.
@@ -565,6 +572,7 @@
      *
      * This method runs in linear time.
      *
+     * @param  <T> the class of the objects in the list
      * @param  list the list to be filled with the specified element.
      * @param  obj The element with which to fill the specified list.
      * @throws UnsupportedOperationException if the specified list or its
@@ -594,6 +602,7 @@
      *
      * This method runs in linear time.
      *
+     * @param  <T> the class of the objects in the lists
      * @param  dest The destination list.
      * @param  src The source list.
      * @throws IndexOutOfBoundsException if the destination list is too small
@@ -632,6 +641,7 @@
      * This method iterates over the entire collection, hence it requires
      * time proportional to the size of the collection.
      *
+     * @param  <T> the class of the objects in the collection
      * @param  coll the collection whose minimum element is to be determined.
      * @return the minimum element of the given collection, according
      *         to the <i>natural ordering</i> of its elements.
@@ -664,6 +674,7 @@
      * This method iterates over the entire collection, hence it requires
      * time proportional to the size of the collection.
      *
+     * @param  <T> the class of the objects in the collection
      * @param  coll the collection whose minimum element is to be determined.
      * @param  comp the comparator with which to determine the minimum element.
      *         A <tt>null</tt> value indicates that the elements' <i>natural
@@ -703,6 +714,7 @@
      * This method iterates over the entire collection, hence it requires
      * time proportional to the size of the collection.
      *
+     * @param  <T> the class of the objects in the collection
      * @param  coll the collection whose maximum element is to be determined.
      * @return the maximum element of the given collection, according
      *         to the <i>natural ordering</i> of its elements.
@@ -735,6 +747,7 @@
      * This method iterates over the entire collection, hence it requires
      * time proportional to the size of the collection.
      *
+     * @param  <T> the class of the objects in the collection
      * @param  coll the collection whose maximum element is to be determined.
      * @param  comp the comparator with which to determine the maximum element.
      *         A <tt>null</tt> value indicates that the elements' <i>natural
@@ -869,6 +882,7 @@
      * <tt>(oldVal==null ? e==null : oldVal.equals(e))</tt>.
      * (This method has no effect on the size of the list.)
      *
+     * @param  <T> the class of the objects in the list
      * @param list the list in which replacement is to occur.
      * @param oldVal the old value to be replaced.
      * @param newVal the new value with which <tt>oldVal</tt> is to be
@@ -1050,6 +1064,7 @@
      * The returned collection will be serializable if the specified collection
      * is serializable.
      *
+     * @param  <T> the class of the objects in the collection
      * @param  c the collection for which an unmodifiable view is to be
      *         returned.
      * @return an unmodifiable view of the specified collection.
@@ -1145,6 +1160,7 @@
      * The returned set will be serializable if the specified set
      * is serializable.
      *
+     * @param  <T> the class of the objects in the set
      * @param  s the set for which an unmodifiable view is to be returned.
      * @return an unmodifiable view of the specified set.
      */
@@ -1176,6 +1192,7 @@
      * The returned sorted set will be serializable if the specified sorted set
      * is serializable.
      *
+     * @param  <T> the class of the objects in the set
      * @param s the sorted set for which an unmodifiable view is to be
      *        returned.
      * @return an unmodifiable view of the specified sorted set.
@@ -1212,6 +1229,95 @@
     }
 
     /**
+     * Returns an unmodifiable view of the specified navigable set.  This method
+     * allows modules to provide users with "read-only" access to internal
+     * navigable sets.  Query operations on the returned navigable set "read
+     * through" to the specified navigable set.  Attempts to modify the returned
+     * navigable set, whether direct, via its iterator, or via its
+     * {@code subSet}, {@code headSet}, or {@code tailSet} views, result in
+     * an {@code UnsupportedOperationException}.<p>
+     *
+     * The returned navigable set will be serializable if the specified
+     * navigable set is serializable.
+     *
+     * @param  <T> the class of the objects in the set
+     * @param s the navigable set for which an unmodifiable view is to be
+     *        returned
+     * @return an unmodifiable view of the specified navigable set
+     * @since 1.8
+     */
+    public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s) {
+        return new UnmodifiableNavigableSet<>(s);
+    }
+
+    /**
+     * Wraps a navigable set and disables all of the mutative operations.
+     *
+     * @param <E> type of elements
+     * @serial include
+     */
+    static class UnmodifiableNavigableSet<E>
+                             extends UnmodifiableSortedSet<E>
+                             implements NavigableSet<E>, Serializable {
+
+        private static final long serialVersionUID = -6027448201786391929L;
+
+        /**
+         * A singleton empty unmodifiable navigable set used for
+         * {@link #emptyNavigableSet()}.
+         *
+         * @param <E> type of elements, if there were any, and bounds
+         */
+        private static class EmptyNavigableSet<E> extends UnmodifiableNavigableSet<E>
+            implements Serializable {
+            private static final long serialVersionUID = -6291252904449939134L;
+
+            public EmptyNavigableSet() {
+                super(new TreeSet<E>());
+            }
+
+            private Object readResolve()        { return EMPTY_NAVIGABLE_SET; }
+        }
+
+        @SuppressWarnings("rawtypes")
+        private static final NavigableSet<?> EMPTY_NAVIGABLE_SET =
+                new EmptyNavigableSet<>();
+
+        /**
+         * The instance we are protecting.
+         */
+        private final NavigableSet<E> ns;
+
+        UnmodifiableNavigableSet(NavigableSet<E> s)         {super(s); ns = s;}
+
+        public E lower(E e)                             { return ns.lower(e); }
+        public E floor(E e)                             { return ns.floor(e); }
+        public E ceiling(E e)                         { return ns.ceiling(e); }
+        public E higher(E e)                           { return ns.higher(e); }
+        public E pollFirst()     { throw new UnsupportedOperationException(); }
+        public E pollLast()      { throw new UnsupportedOperationException(); }
+        public NavigableSet<E> descendingSet()
+                 { return new UnmodifiableNavigableSet<>(ns.descendingSet()); }
+        public Iterator<E> descendingIterator()
+                                         { return descendingSet().iterator(); }
+
+        public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
+            return new UnmodifiableNavigableSet<>(
+                ns.subSet(fromElement, fromInclusive, toElement, toInclusive));
+        }
+
+        public NavigableSet<E> headSet(E toElement, boolean inclusive) {
+            return new UnmodifiableNavigableSet<>(
+                ns.headSet(toElement, inclusive));
+        }
+
+        public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
+            return new UnmodifiableNavigableSet<>(
+                ns.tailSet(fromElement, inclusive));
+        }
+    }
+
+    /**
      * Returns an unmodifiable view of the specified list.  This method allows
      * modules to provide users with "read-only" access to internal
      * lists.  Query operations on the returned list "read through" to the
@@ -1223,6 +1329,7 @@
      * is serializable. Similarly, the returned list will implement
      * {@link RandomAccess} if the specified list does.
      *
+     * @param  <T> the class of the objects in the list
      * @param  list the list for which an unmodifiable view is to be returned.
      * @return an unmodifiable view of the specified list.
      */
@@ -1238,6 +1345,7 @@
     static class UnmodifiableList<E> extends UnmodifiableCollection<E>
                                   implements List<E> {
         private static final long serialVersionUID = -283967356065247728L;
+
         final List<? extends E> list;
 
         UnmodifiableList(List<? extends E> list) {
@@ -1366,6 +1474,8 @@
      * The returned map will be serializable if the specified map
      * is serializable.
      *
+     * @param <K> the class of the map keys
+     * @param <V> the class of the map values
      * @param  m the map for which an unmodifiable view is to be returned.
      * @return an unmodifiable view of the specified map.
      */
@@ -1510,6 +1620,86 @@
                 // Need to cast to raw in order to work around a limitation in the type system
                 super((Set)s);
             }
+
+            static <K, V> Consumer<Map.Entry<K, V>> entryConsumer(Consumer<? super Entry<K, V>> action) {
+                return e -> action.accept(new UnmodifiableEntry<>(e));
+            }
+
+            public void forEach(Consumer<? super Entry<K, V>> action) {
+                Objects.requireNonNull(action);
+                c.forEach(entryConsumer(action));
+            }
+
+            static final class UnmodifiableEntrySetSpliterator<K, V>
+                    implements Spliterator<Entry<K,V>> {
+                final Spliterator<Map.Entry<K, V>> s;
+
+                UnmodifiableEntrySetSpliterator(Spliterator<Entry<K, V>> s) {
+                    this.s = s;
+                }
+
+                @Override
+                public boolean tryAdvance(Consumer<? super Entry<K, V>> action) {
+                    Objects.requireNonNull(action);
+                    return s.tryAdvance(entryConsumer(action));
+                }
+
+                @Override
+                public void forEachRemaining(Consumer<? super Entry<K, V>> action) {
+                    Objects.requireNonNull(action);
+                    s.forEachRemaining(entryConsumer(action));
+                }
+
+                @Override
+                public Spliterator<Entry<K, V>> trySplit() {
+                    Spliterator<Entry<K, V>> split = s.trySplit();
+                    return split == null
+                           ? null
+                           : new UnmodifiableEntrySetSpliterator<>(split);
+                }
+
+                @Override
+                public long estimateSize() {
+                    return s.estimateSize();
+                }
+
+                @Override
+                public long getExactSizeIfKnown() {
+                    return s.getExactSizeIfKnown();
+                }
+
+                @Override
+                public int characteristics() {
+                    return s.characteristics();
+                }
+
+                @Override
+                public boolean hasCharacteristics(int characteristics) {
+                    return s.hasCharacteristics(characteristics);
+                }
+
+                @Override
+                public Comparator<? super Entry<K, V>> getComparator() {
+                    return s.getComparator();
+                }
+            }
+
+            @SuppressWarnings("unchecked")
+            public Spliterator<Entry<K,V>> spliterator() {
+                return new UnmodifiableEntrySetSpliterator<>(
+                        (Spliterator<Map.Entry<K, V>>) c.spliterator());
+            }
+
+            @Override
+            public Stream<Entry<K,V>> stream() {
+                return StreamSupport.stream(spliterator(), false);
+            }
+
+            @Override
+            public Stream<Entry<K,V>> parallelStream() {
+                return StreamSupport.stream(spliterator(), true);
+            }
+
             public Iterator<Map.Entry<K,V>> iterator() {
                 return new Iterator<Map.Entry<K,V>>() {
                     private final Iterator<? extends Map.Entry<? extends K, ? extends V>> i = c.iterator();
@@ -1600,7 +1790,8 @@
             private static class UnmodifiableEntry<K,V> implements Map.Entry<K,V> {
                 private Map.Entry<? extends K, ? extends V> e;
 
-                UnmodifiableEntry(Map.Entry<? extends K, ? extends V> e) {this.e = e;}
+                UnmodifiableEntry(Map.Entry<? extends K, ? extends V> e)
+                        {this.e = Objects.requireNonNull(e);}
 
                 public K getKey()        {return e.getKey();}
                 public V getValue()      {return e.getValue();}
@@ -1634,6 +1825,8 @@
      * The returned sorted map will be serializable if the specified sorted map
      * is serializable.
      *
+     * @param <K> the class of the map keys
+     * @param <V> the class of the map values
      * @param m the sorted map for which an unmodifiable view is to be
      *        returned.
      * @return an unmodifiable view of the specified sorted map.
@@ -1652,24 +1845,153 @@
 
         private final SortedMap<K, ? extends V> sm;
 
-        UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m;}
-
-        public Comparator<? super K> comparator() {return sm.comparator();}
-
-        public SortedMap<K,V> subMap(K fromKey, K toKey) {
-            return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey));
-        }
-        public SortedMap<K,V> headMap(K toKey) {
-            return new UnmodifiableSortedMap<>(sm.headMap(toKey));
-        }
-        public SortedMap<K,V> tailMap(K fromKey) {
-            return new UnmodifiableSortedMap<>(sm.tailMap(fromKey));
-        }
-
-        public K firstKey()           {return sm.firstKey();}
-        public K lastKey()            {return sm.lastKey();}
+        UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m; }
+        public Comparator<? super K> comparator()   { return sm.comparator(); }
+        public SortedMap<K,V> subMap(K fromKey, K toKey)
+             { return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey)); }
+        public SortedMap<K,V> headMap(K toKey)
+                     { return new UnmodifiableSortedMap<>(sm.headMap(toKey)); }
+        public SortedMap<K,V> tailMap(K fromKey)
+                   { return new UnmodifiableSortedMap<>(sm.tailMap(fromKey)); }
+        public K firstKey()                           { return sm.firstKey(); }
+        public K lastKey()                             { return sm.lastKey(); }
+    }
+
+    /**
+     * Returns an unmodifiable view of the specified navigable map.  This method
+     * allows modules to provide users with "read-only" access to internal
+     * navigable maps.  Query operations on the returned navigable map "read
+     * through" to the specified navigable map.  Attempts to modify the returned
+     * navigable map, whether direct, via its collection views, or via its
+     * {@code subMap}, {@code headMap}, or {@code tailMap} views, result in
+     * an {@code UnsupportedOperationException}.<p>
+     *
+     * The returned navigable map will be serializable if the specified
+     * navigable map is serializable.
+     *
+     * @param <K> the class of the map keys
+     * @param <V> the class of the map values
+     * @param m the navigable map for which an unmodifiable view is to be
+     *        returned
+     * @return an unmodifiable view of the specified navigable map
+     * @since 1.8
+     */
+    public static <K,V> NavigableMap<K,V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> m) {
+        return new UnmodifiableNavigableMap<>(m);
     }
 
+    /**
+     * @serial include
+     */
+    static class UnmodifiableNavigableMap<K,V>
+          extends UnmodifiableSortedMap<K,V>
+          implements NavigableMap<K,V>, Serializable {
+        private static final long serialVersionUID = -4858195264774772197L;
+
+        /**
+         * A class for the {@link EMPTY_NAVIGABLE_MAP} which needs readResolve
+         * to preserve singleton property.
+         *
+         * @param <K> type of keys, if there were any, and of bounds
+         * @param <V> type of values, if there were any
+         */
+        private static class EmptyNavigableMap<K,V> extends UnmodifiableNavigableMap<K,V>
+            implements Serializable {
+
+            private static final long serialVersionUID = -2239321462712562324L;
+
+            EmptyNavigableMap()                       { super(new TreeMap()); }
+
+            @Override
+            public NavigableSet<K> navigableKeySet()
+                                                { return emptyNavigableSet(); }
+
+            private Object readResolve()        { return EMPTY_NAVIGABLE_MAP; }
+        }
+
+        /**
+         * Singleton for {@link emptyNavigableMap()} which is also immutable.
+         */
+        private static final EmptyNavigableMap<?,?> EMPTY_NAVIGABLE_MAP =
+            new EmptyNavigableMap<>();
+
+        /**
+         * The instance we wrap and protect.
+         */
+        private final NavigableMap<K, ? extends V> nm;
+
+        UnmodifiableNavigableMap(NavigableMap<K, ? extends V> m)
+                                                            {super(m); nm = m;}
+
+        public K lowerKey(K key)                   { return nm.lowerKey(key); }
+        public K floorKey(K key)                   { return nm.floorKey(key); }
+        public K ceilingKey(K key)               { return nm.ceilingKey(key); }
+        public K higherKey(K key)                 { return nm.higherKey(key); }
+
+        public Entry<K, V> lowerEntry(K key) {
+            Entry<K,V> lower = (Entry<K, V>) nm.lowerEntry(key);
+            return (null != lower)
+                ? new UnmodifiableEntrySet.UnmodifiableEntry(lower)
+                : null;
+        }
+
+        public Entry<K, V> floorEntry(K key) {
+            Entry<K,V> floor = (Entry<K, V>) nm.floorEntry(key);
+            return (null != floor)
+                ? new UnmodifiableEntrySet.UnmodifiableEntry(floor)
+                : null;
+        }
+
+        public Entry<K, V> ceilingEntry(K key) {
+            Entry<K,V> ceiling = (Entry<K, V>) nm.ceilingEntry(key);
+            return (null != ceiling)
+                ? new UnmodifiableEntrySet.UnmodifiableEntry(ceiling)
+                : null;
+        }
+
+
+        public Entry<K, V> higherEntry(K key) {
+            Entry<K,V> higher = (Entry<K, V>) nm.higherEntry(key);
+            return (null != higher)
+                ? new UnmodifiableEntrySet.UnmodifiableEntry(higher)
+                : null;
+        }
+
+        public Entry<K, V> firstEntry() {
+            Entry<K,V> first = (Entry<K, V>) nm.firstEntry();
+            return (null != first)
+                ? new UnmodifiableEntrySet.UnmodifiableEntry(first)
+                : null;
+        }
+
+        public Entry<K, V> lastEntry() {
+            Entry<K,V> last = (Entry<K, V>) nm.lastEntry();
+            return (null != last)
+                ? new UnmodifiableEntrySet.UnmodifiableEntry(last)
+                : null;
+        }
+
+        public Entry<K, V> pollFirstEntry()
+                                 { throw new UnsupportedOperationException(); }
+        public Entry<K, V> pollLastEntry()
+                                 { throw new UnsupportedOperationException(); }
+        public NavigableMap<K, V> descendingMap()
+                       { return unmodifiableNavigableMap(nm.descendingMap()); }
+        public NavigableSet<K> navigableKeySet()
+                     { return unmodifiableNavigableSet(nm.navigableKeySet()); }
+        public NavigableSet<K> descendingKeySet()
+                    { return unmodifiableNavigableSet(nm.descendingKeySet()); }
+
+        public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
+            return unmodifiableNavigableMap(
+                nm.subMap(fromKey, fromInclusive, toKey, toInclusive));
+        }
+
+        public NavigableMap<K, V> headMap(K toKey, boolean inclusive)
+             { return unmodifiableNavigableMap(nm.headMap(toKey, inclusive)); }
+        public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive)
+           { return unmodifiableNavigableMap(nm.tailMap(fromKey, inclusive)); }
+    }
 
     // Synch Wrappers
 
@@ -1702,6 +2024,7 @@
      * The returned collection will be serializable if the specified collection
      * is serializable.
      *
+     * @param  <T> the class of the objects in the collection
      * @param  c the collection to be "wrapped" in a synchronized collection.
      * @return a synchronized view of the specified collection.
      */
@@ -1723,14 +2046,13 @@
         final Object mutex;     // Object on which to synchronize
 
         SynchronizedCollection(Collection<E> c) {
-            if (c==null)
-                throw new NullPointerException();
-            this.c = c;
+            this.c = Objects.requireNonNull(c);
             mutex = this;
         }
+
         SynchronizedCollection(Collection<E> c, Object mutex) {
-            this.c = c;
-            this.mutex = mutex;
+            this.c = Objects.requireNonNull(c);
+            this.mutex = Objects.requireNonNull(mutex);
         }
 
         public int size() {
@@ -1818,6 +2140,7 @@
      * <p>The returned set will be serializable if the specified set is
      * serializable.
      *
+     * @param  <T> the class of the objects in the set
      * @param  s the set to be "wrapped" in a synchronized set.
      * @return a synchronized view of the specified set.
      */
@@ -1888,6 +2211,7 @@
      * <p>The returned sorted set will be serializable if the specified
      * sorted set is serializable.
      *
+     * @param  <T> the class of the objects in the set
      * @param  s the sorted set to be "wrapped" in a synchronized sorted set.
      * @return a synchronized view of the specified sorted set.
      */
@@ -1945,6 +2269,121 @@
     }
 
     /**
+     * Returns a synchronized (thread-safe) navigable set backed by the
+     * specified navigable set.  In order to guarantee serial access, it is
+     * critical that <strong>all</strong> access to the backing navigable set is
+     * accomplished through the returned navigable set (or its views).<p>
+     *
+     * It is imperative that the user manually synchronize on the returned
+     * navigable set when iterating over it or any of its {@code subSet},
+     * {@code headSet}, or {@code tailSet} views.
+     * <pre>
+     *  NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet());
+     *      ...
+     *  synchronized (s) {
+     *      Iterator i = s.iterator(); // Must be in the synchronized block
+     *      while (i.hasNext())
+     *          foo(i.next());
+     *  }
+     * </pre>
+     * or:
+     * <pre>
+     *  NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet());
+     *  NavigableSet s2 = s.headSet(foo, true);
+     *      ...
+     *  synchronized (s) {  // Note: s, not s2!!!
+     *      Iterator i = s2.iterator(); // Must be in the synchronized block
+     *      while (i.hasNext())
+     *          foo(i.next());
+     *  }
+     * </pre>
+     * Failure to follow this advice may result in non-deterministic behavior.
+     *
+     * <p>The returned navigable set will be serializable if the specified
+     * navigable set is serializable.
+     *
+     * @param  <T> the class of the objects in the set
+     * @param  s the navigable set to be "wrapped" in a synchronized navigable
+     * set
+     * @return a synchronized view of the specified navigable set
+     * @since 1.8
+     */
+    public static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s) {
+        return new SynchronizedNavigableSet<>(s);
+    }
+
+    /**
+     * @serial include
+     */
+    static class SynchronizedNavigableSet<E>
+        extends SynchronizedSortedSet<E>
+        implements NavigableSet<E>
+    {
+        private static final long serialVersionUID = -5505529816273629798L;
+
+        private final NavigableSet<E> ns;
+
+        SynchronizedNavigableSet(NavigableSet<E> s) {
+            super(s);
+            ns = s;
+        }
+
+        SynchronizedNavigableSet(NavigableSet<E> s, Object mutex) {
+            super(s, mutex);
+            ns = s;
+        }
+        public E lower(E e)      { synchronized (mutex) {return ns.lower(e);} }
+        public E floor(E e)      { synchronized (mutex) {return ns.floor(e);} }
+        public E ceiling(E e)  { synchronized (mutex) {return ns.ceiling(e);} }
+        public E higher(E e)    { synchronized (mutex) {return ns.higher(e);} }
+        public E pollFirst()  { synchronized (mutex) {return ns.pollFirst();} }
+        public E pollLast()    { synchronized (mutex) {return ns.pollLast();} }
+
+        public NavigableSet<E> descendingSet() {
+            synchronized (mutex) {
+                return new SynchronizedNavigableSet<>(ns.descendingSet(), mutex);
+            }
+        }
+
+        public Iterator<E> descendingIterator()
+                 { synchronized (mutex) { return descendingSet().iterator(); } }
+
+        public NavigableSet<E> subSet(E fromElement, E toElement) {
+            synchronized (mutex) {
+                return new SynchronizedNavigableSet<>(ns.subSet(fromElement, true, toElement, false), mutex);
+            }
+        }
+        public NavigableSet<E> headSet(E toElement) {
+            synchronized (mutex) {
+                return new SynchronizedNavigableSet<>(ns.headSet(toElement, false), mutex);
+            }
+        }
+        public NavigableSet<E> tailSet(E fromElement) {
+            synchronized (mutex) {
+                return new SynchronizedNavigableSet(ns.tailSet(fromElement, true), mutex);
+            }
+        }
+
+        public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
+            synchronized (mutex) {
+                return new SynchronizedNavigableSet<>(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), mutex);
+            }
+        }
+
+        public NavigableSet<E> headSet(E toElement, boolean inclusive) {
+            synchronized (mutex) {
+                return new SynchronizedNavigableSet<>(ns.headSet(toElement, inclusive), mutex);
+            }
+        }
+
+        public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
+            synchronized (mutex) {
+                return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, inclusive));
+            }
+        }
+    }
+
+    /**
      * Returns a synchronized (thread-safe) list backed by the specified
      * list.  In order to guarantee serial access, it is critical that
      * <strong>all</strong> access to the backing list is accomplished
@@ -1966,6 +2405,7 @@
      * <p>The returned list will be serializable if the specified list is
      * serializable.
      *
+     * @param  <T> the class of the objects in the list
      * @param  list the list to be "wrapped" in a synchronized list.
      * @return a synchronized view of the specified list.
      */
@@ -2135,6 +2575,8 @@
      * <p>The returned map will be serializable if the specified map is
      * serializable.
      *
+     * @param <K> the class of the map keys
+     * @param <V> the class of the map values
      * @param  m the map to be "wrapped" in a synchronized map.
      * @return a synchronized view of the specified map.
      */
@@ -2153,9 +2595,7 @@
         final Object      mutex;        // Object on which to synchronize
 
         SynchronizedMap(Map<K,V> m) {
-            if (m==null)
-                throw new NullPointerException();
-            this.m = m;
+            this.m = Objects.requireNonNull(m);
             mutex = this;
         }
 
@@ -2327,6 +2767,8 @@
      * <p>The returned sorted map will be serializable if the specified
      * sorted map is serializable.
      *
+     * @param <K> the class of the map keys
+     * @param <V> the class of the map values
      * @param  m the sorted map to be "wrapped" in a synchronized sorted map.
      * @return a synchronized view of the specified sorted map.
      */
@@ -2334,7 +2776,6 @@
         return new SynchronizedSortedMap<>(m);
     }
 
-
     /**
      * @serial include
      */
@@ -2384,6 +2825,166 @@
         }
     }
 
+    /**
+     * Returns a synchronized (thread-safe) navigable map backed by the
+     * specified navigable map.  In order to guarantee serial access, it is
+     * critical that <strong>all</strong> access to the backing navigable map is
+     * accomplished through the returned navigable map (or its views).<p>
+     *
+     * It is imperative that the user manually synchronize on the returned
+     * navigable map when iterating over any of its collection views, or the
+     * collections views of any of its {@code subMap}, {@code headMap} or
+     * {@code tailMap} views.
+     * <pre>
+     *  NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap());
+     *      ...
+     *  Set s = m.keySet();  // Needn't be in synchronized block
+     *      ...
+     *  synchronized (m) {  // Synchronizing on m, not s!
+     *      Iterator i = s.iterator(); // Must be in synchronized block
+     *      while (i.hasNext())
+     *          foo(i.next());
+     *  }
+     * </pre>
+     * or:
+     * <pre>
+     *  NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap());
+     *  NavigableMap m2 = m.subMap(foo, true, bar, false);
+     *      ...
+     *  Set s2 = m2.keySet();  // Needn't be in synchronized block
+     *      ...
+     *  synchronized (m) {  // Synchronizing on m, not m2 or s2!
+     *      Iterator i = s.iterator(); // Must be in synchronized block
+     *      while (i.hasNext())
+     *          foo(i.next());
+     *  }
+     * </pre>
+     * Failure to follow this advice may result in non-deterministic behavior.
+     *
+     * <p>The returned navigable map will be serializable if the specified
+     * navigable map is serializable.
+     *
+     * @param <K> the class of the map keys
+     * @param <V> the class of the map values
+     * @param  m the navigable map to be "wrapped" in a synchronized navigable
+     *              map
+     * @return a synchronized view of the specified navigable map.
+     * @since 1.8
+     */
+    public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m) {
+        return new SynchronizedNavigableMap<>(m);
+    }
+
+    /**
+     * A synchronized NavigableMap.
+     *
+     * @serial include
+     */
+    static class SynchronizedNavigableMap<K,V>
+        extends SynchronizedSortedMap<K,V>
+        implements NavigableMap<K,V>
+    {
+        private static final long serialVersionUID = 699392247599746807L;
+
+        private final NavigableMap<K,V> nm;
+
+        SynchronizedNavigableMap(NavigableMap<K,V> m) {
+            super(m);
+            nm = m;
+        }
+        SynchronizedNavigableMap(NavigableMap<K,V> m, Object mutex) {
+            super(m, mutex);
+            nm = m;
+        }
+
+        public Entry<K, V> lowerEntry(K key)
+                        { synchronized (mutex) { return nm.lowerEntry(key); } }
+        public K lowerKey(K key)
+                          { synchronized (mutex) { return nm.lowerKey(key); } }
+        public Entry<K, V> floorEntry(K key)
+                        { synchronized (mutex) { return nm.floorEntry(key); } }
+        public K floorKey(K key)
+                          { synchronized (mutex) { return nm.floorKey(key); } }
+        public Entry<K, V> ceilingEntry(K key)
+                      { synchronized (mutex) { return nm.ceilingEntry(key); } }
+        public K ceilingKey(K key)
+                        { synchronized (mutex) { return nm.ceilingKey(key); } }
+        public Entry<K, V> higherEntry(K key)
+                       { synchronized (mutex) { return nm.higherEntry(key); } }
+        public K higherKey(K key)
+                         { synchronized (mutex) { return nm.higherKey(key); } }
+        public Entry<K, V> firstEntry()
+                           { synchronized (mutex) { return nm.firstEntry(); } }
+        public Entry<K, V> lastEntry()
+                            { synchronized (mutex) { return nm.lastEntry(); } }
+        public Entry<K, V> pollFirstEntry()
+                       { synchronized (mutex) { return nm.pollFirstEntry(); } }
+        public Entry<K, V> pollLastEntry()
+                        { synchronized (mutex) { return nm.pollLastEntry(); } }
+
+        public NavigableMap<K, V> descendingMap() {
+            synchronized (mutex) {
+                return
+                    new SynchronizedNavigableMap(nm.descendingMap(), mutex);
+            }
+        }
+
+        public NavigableSet<K> keySet() {
+            return navigableKeySet();
+        }
+
+        public NavigableSet<K> navigableKeySet() {
+            synchronized (mutex) {
+                return new SynchronizedNavigableSet(nm.navigableKeySet(), mutex);
+            }
+        }
+
+        public NavigableSet<K> descendingKeySet() {
+            synchronized (mutex) {
+                return new SynchronizedNavigableSet(nm.descendingKeySet(), mutex);
+            }
+        }
+
+
+        public SortedMap<K,V> subMap(K fromKey, K toKey) {
+            synchronized (mutex) {
+                return new SynchronizedNavigableMap<>(
+                    nm.subMap(fromKey, true, toKey, false), mutex);
+            }
+        }
+        public SortedMap<K,V> headMap(K toKey) {
+            synchronized (mutex) {
+                return new SynchronizedNavigableMap<>(nm.headMap(toKey, false), mutex);
+            }
+        }
+        public SortedMap<K,V> tailMap(K fromKey) {
+            synchronized (mutex) {
+               return new SynchronizedNavigableMap<>(nm.tailMap(fromKey, true),mutex);
+            }
+        }
+
+        public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
+            synchronized (mutex) {
+                return new SynchronizedNavigableMap(
+                    nm.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex);
+            }
+        }
+
+        public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
+            synchronized (mutex) {
+                return new SynchronizedNavigableMap(
+                        nm.headMap(toKey, inclusive), mutex);
+            }
+        }
+
+        public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
+            synchronized (mutex) {
+                return new SynchronizedNavigableMap(
+                    nm.tailMap(fromKey, inclusive), mutex);
+            }
+        }
+    }
+
     // Dynamically typesafe collection wrappers
 
     /**
@@ -2415,12 +3016,12 @@
      * program to wrap the collection with a dynamically typesafe view.
      * For example, this declaration:
      *  <pre> {@code
-     *     Collection<String> c = new HashSet<String>();
+     *     Collection<String> c = new HashSet<>();
      * }</pre>
      * may be replaced temporarily by this one:
      *  <pre> {@code
      *     Collection<String> c = Collections.checkedCollection(
-     *         new HashSet<String>(), String.class);
+     *         new HashSet<>(), String.class);
      * }</pre>
      * Running the program again will cause it to fail at the point where
      * an incorrectly typed element is inserted into the collection, clearly
@@ -2440,6 +3041,7 @@
      * type, the returned collection permits insertion of null elements
      * whenever the backing collection does.
      *
+     * @param <E> the class of the objects in the collection
      * @param c the collection for which a dynamically typesafe view is to be
      *          returned
      * @param type the type of element that {@code c} is permitted to hold
@@ -2585,6 +3187,7 @@
      * type, the returned queue permits insertion of {@code null} elements
      * whenever the backing queue does.
      *
+     * @param <E> the class of the objects in the queue
      * @param queue the queue for which a dynamically typesafe view is to be
      *             returned
      * @param type the type of element that {@code queue} is permitted to hold
@@ -2643,6 +3246,7 @@
      * type, the returned set permits insertion of null elements whenever
      * the backing set does.
      *
+     * @param <E> the class of the objects in the set
      * @param s the set for which a dynamically typesafe view is to be
      *          returned
      * @param type the type of element that {@code s} is permitted to hold
@@ -2688,6 +3292,7 @@
      * type, the returned sorted set permits insertion of null elements
      * whenever the backing sorted set does.
      *
+     * @param <E> the class of the objects in the set
      * @param s the sorted set for which a dynamically typesafe view is to be
      *          returned
      * @param type the type of element that {@code s} is permitted to hold
@@ -2706,6 +3311,7 @@
         implements SortedSet<E>, Serializable
     {
         private static final long serialVersionUID = 1599911165492914959L;
+
         private final SortedSet<E> ss;
 
         CheckedSortedSet(SortedSet<E> s, Class<E> type) {
@@ -2728,6 +3334,88 @@
         }
     }
 
+/**
+     * Returns a dynamically typesafe view of the specified navigable set.
+     * Any attempt to insert an element of the wrong type will result in an
+     * immediate {@link ClassCastException}.  Assuming a navigable set
+     * contains no incorrectly typed elements prior to the time a
+     * dynamically typesafe view is generated, and that all subsequent
+     * access to the navigable set takes place through the view, it is
+     * <em>guaranteed</em> that the navigable set cannot contain an incorrectly
+     * typed element.
+     *
+     * <p>A discussion of the use of dynamically typesafe views may be
+     * found in the documentation for the {@link #checkedCollection
+     * checkedCollection} method.
+     *
+     * <p>The returned navigable set will be serializable if the specified
+     * navigable set is serializable.
+     *
+     * <p>Since {@code null} is considered to be a value of any reference
+     * type, the returned navigable set permits insertion of null elements
+     * whenever the backing sorted set does.
+     *
+     * @param <E> the class of the objects in the set
+     * @param s the navigable set for which a dynamically typesafe view is to be
+     *          returned
+     * @param type the type of element that {@code s} is permitted to hold
+     * @return a dynamically typesafe view of the specified navigable set
+     * @since 1.8
+     */
+    public static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s,
+                                                    Class<E> type) {
+        return new CheckedNavigableSet<>(s, type);
+    }
+
+    /**
+     * @serial include
+     */
+    static class CheckedNavigableSet<E> extends CheckedSortedSet<E>
+        implements NavigableSet<E>, Serializable
+    {
+        private static final long serialVersionUID = -5429120189805438922L;
+
+        private final NavigableSet<E> ns;
+
+        CheckedNavigableSet(NavigableSet<E> s, Class<E> type) {
+            super(s, type);
+            ns = s;
+        }
+
+        public E lower(E e)                             { return ns.lower(e); }
+        public E floor(E e)                             { return ns.floor(e); }
+        public E ceiling(E e)                         { return ns.ceiling(e); }
+        public E higher(E e)                           { return ns.higher(e); }
+        public E pollFirst()                         { return ns.pollFirst(); }
+        public E pollLast()                            {return ns.pollLast(); }
+        public NavigableSet<E> descendingSet()
+                      { return checkedNavigableSet(ns.descendingSet(), type); }
+        public Iterator<E> descendingIterator()
+            {return checkedNavigableSet(ns.descendingSet(), type).iterator(); }
+
+        public NavigableSet<E> subSet(E fromElement, E toElement) {
+            return checkedNavigableSet(ns.subSet(fromElement, true, toElement, false), type);
+        }
+        public NavigableSet<E> headSet(E toElement) {
+            return checkedNavigableSet(ns.headSet(toElement, false), type);
+        }
+        public NavigableSet<E> tailSet(E fromElement) {
+            return checkedNavigableSet(ns.tailSet(fromElement, true), type);
+        }
+
+        public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
+            return checkedNavigableSet(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), type);
+        }
+
+        public NavigableSet<E> headSet(E toElement, boolean inclusive) {
+            return checkedNavigableSet(ns.headSet(toElement, inclusive), type);
+        }
+
+        public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
+            return checkedNavigableSet(ns.tailSet(fromElement, inclusive), type);
+        }
+    }
+
     /**
      * Returns a dynamically typesafe view of the specified list.
      * Any attempt to insert an element of the wrong type will result in
@@ -2748,6 +3436,7 @@
      * type, the returned list permits insertion of null elements whenever
      * the backing list does.
      *
+     * @param <E> the class of the objects in the list
      * @param list the list for which a dynamically typesafe view is to be
      *             returned
      * @param type the type of element that {@code list} is permitted to hold
@@ -2885,6 +3574,8 @@
      * type, the returned map permits insertion of null keys or values
      * whenever the backing map does.
      *
+     * @param <K> the class of the map keys
+     * @param <V> the class of the map values
      * @param m the map for which a dynamically typesafe view is to be
      *          returned
      * @param keyType the type of key that {@code m} is permitted to hold
@@ -2940,11 +3631,9 @@
         }
 
         CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) {
-            if (m == null || keyType == null || valueType == null)
-                throw new NullPointerException();
-            this.m = m;
-            this.keyType = keyType;
-            this.valueType = valueType;
+            this.m = Objects.requireNonNull(m);
+            this.keyType = Objects.requireNonNull(keyType);
+            this.valueType = Objects.requireNonNull(valueType);
         }
 
         public int size()                      { return m.size(); }
@@ -3221,8 +3910,8 @@
                 private final Class<T> valueType;
 
                 CheckedEntry(Map.Entry<K, V> e, Class<T> valueType) {
-                    this.e = e;
-                    this.valueType = valueType;
+                    this.e = Objects.requireNonNull(e);
+                    this.valueType = Objects.requireNonNull(valueType);
                 }
 
                 public K getKey()        { return e.getKey(); }
@@ -3280,6 +3969,8 @@
      * type, the returned map permits insertion of null keys or values
      * whenever the backing map does.
      *
+     * @param <K> the class of the map keys
+     * @param <V> the class of the map values
      * @param m the map for which a dynamically typesafe view is to be
      *          returned
      * @param keyType the type of key that {@code m} is permitted to hold
@@ -3325,27 +4016,195 @@
         }
     }
 
+    /**
+     * Returns a dynamically typesafe view of the specified navigable map.
+     * Any attempt to insert a mapping whose key or value have the wrong
+     * type will result in an immediate {@link ClassCastException}.
+     * Similarly, any attempt to modify the value currently associated with
+     * a key will result in an immediate {@link ClassCastException},
+     * whether the modification is attempted directly through the map
+     * itself, or through a {@link Map.Entry} instance obtained from the
+     * map's {@link Map#entrySet() entry set} view.
+     *
+     * <p>Assuming a map contains no incorrectly typed keys or values
+     * prior to the time a dynamically typesafe view is generated, and
+     * that all subsequent access to the map takes place through the view
+     * (or one of its collection views), it is <em>guaranteed</em> that the
+     * map cannot contain an incorrectly typed key or value.
+     *
+     * <p>A discussion of the use of dynamically typesafe views may be
+     * found in the documentation for the {@link #checkedCollection
+     * checkedCollection} method.
+     *
+     * <p>The returned map will be serializable if the specified map is
+     * serializable.
+     *
+     * <p>Since {@code null} is considered to be a value of any reference
+     * type, the returned map permits insertion of null keys or values
+     * whenever the backing map does.
+     *
+     * @param <K> type of map keys
+     * @param <V> type of map values
+     * @param m the map for which a dynamically typesafe view is to be
+     *          returned
+     * @param keyType the type of key that {@code m} is permitted to hold
+     * @param valueType the type of value that {@code m} is permitted to hold
+     * @return a dynamically typesafe view of the specified map
+     * @since 1.8
+     */
+    public static <K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K, V> m,
+                                                        Class<K> keyType,
+                                                        Class<V> valueType) {
+        return new CheckedNavigableMap<>(m, keyType, valueType);
+    }
+
+    /**
+     * @serial include
+     */
+    static class CheckedNavigableMap<K,V> extends CheckedSortedMap<K,V>
+        implements NavigableMap<K,V>, Serializable
+    {
+        private static final long serialVersionUID = -4852462692372534096L;
+
+        private final NavigableMap<K, V> nm;
+
+        CheckedNavigableMap(NavigableMap<K, V> m,
+                         Class<K> keyType, Class<V> valueType) {
+            super(m, keyType, valueType);
+            nm = m;
+        }
+
+        public Comparator<? super K> comparator()   { return nm.comparator(); }
+        public K firstKey()                           { return nm.firstKey(); }
+        public K lastKey()                             { return nm.lastKey(); }
+
+        public Entry<K, V> lowerEntry(K key) {
+            Entry<K,V> lower = nm.lowerEntry(key);
+            return (null != lower)
+                ? new CheckedMap.CheckedEntrySet.CheckedEntry(lower, valueType)
+                : null;
+        }
+
+        public K lowerKey(K key)                   { return nm.lowerKey(key); }
+
+        public Entry<K, V> floorEntry(K key) {
+            Entry<K,V> floor = nm.floorEntry(key);
+            return (null != floor)
+                ? new CheckedMap.CheckedEntrySet.CheckedEntry(floor, valueType)
+                : null;
+        }
+
+        public K floorKey(K key)                   { return nm.floorKey(key); }
+
+        public Entry<K, V> ceilingEntry(K key) {
+            Entry<K,V> ceiling = nm.ceilingEntry(key);
+            return (null != ceiling)
+                ? new CheckedMap.CheckedEntrySet.CheckedEntry(ceiling, valueType)
+                : null;
+        }
+
+        public K ceilingKey(K key)               { return nm.ceilingKey(key); }
+
+        public Entry<K, V> higherEntry(K key) {
+            Entry<K,V> higher = nm.higherEntry(key);
+            return (null != higher)
+                ? new CheckedMap.CheckedEntrySet.CheckedEntry(higher, valueType)
+                : null;
+        }
+
+        public K higherKey(K key)                 { return nm.higherKey(key); }
+
+        public Entry<K, V> firstEntry() {
+            Entry<K,V> first = nm.firstEntry();
+            return (null != first)
+                ? new CheckedMap.CheckedEntrySet.CheckedEntry(first, valueType)
+                : null;
+        }
+
+        public Entry<K, V> lastEntry() {
+            Entry<K,V> last = nm.lastEntry();
+            return (null != last)
+                ? new CheckedMap.CheckedEntrySet.CheckedEntry(last, valueType)
+                : null;
+        }
+
+        public Entry<K, V> pollFirstEntry() {
+            Entry<K,V> entry = nm.pollFirstEntry();
+            return (null == entry)
+                ? null
+                : new CheckedMap.CheckedEntrySet.CheckedEntry(entry, valueType);
+        }
+
+        public Entry<K, V> pollLastEntry() {
+            Entry<K,V> entry = nm.pollLastEntry();
+            return (null == entry)
+                ? null
+                : new CheckedMap.CheckedEntrySet.CheckedEntry(entry, valueType);
+        }
+
+        public NavigableMap<K, V> descendingMap() {
+            return checkedNavigableMap(nm.descendingMap(), keyType, valueType);
+        }
+
+        public NavigableSet<K> keySet() {
+            return navigableKeySet();
+        }
+
+        public NavigableSet<K> navigableKeySet() {
+            return checkedNavigableSet(nm.navigableKeySet(), keyType);
+        }
+
+        public NavigableSet<K> descendingKeySet() {
+            return checkedNavigableSet(nm.descendingKeySet(), keyType);
+        }
+
+        @Override
+        public NavigableMap<K,V> subMap(K fromKey, K toKey) {
+            return checkedNavigableMap(nm.subMap(fromKey, true, toKey, false),
+                                    keyType, valueType);
+        }
+
+        @Override
+        public NavigableMap<K,V> headMap(K toKey) {
+            return checkedNavigableMap(nm.headMap(toKey, false), keyType, valueType);
+        }
+
+        @Override
+        public NavigableMap<K,V> tailMap(K fromKey) {
+            return checkedNavigableMap(nm.tailMap(fromKey, true), keyType, valueType);
+        }
+
+        public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
+            return checkedNavigableMap(nm.subMap(fromKey, fromInclusive, toKey, toInclusive), keyType, valueType);
+        }
+
+        public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
+            return checkedNavigableMap(nm.headMap(toKey, inclusive), keyType, valueType);
+        }
+
+        public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
+            return checkedNavigableMap(nm.tailMap(fromKey, inclusive), keyType, valueType);
+        }
+    }
+
     // Empty collections
 
     /**
      * Returns an iterator that has no elements.  More precisely,
      *
-     * <ul compact>
-     *
+     * <ul>
      * <li>{@link Iterator#hasNext hasNext} always returns {@code
-     * false}.
-     *
+     * false}.</li>
      * <li>{@link Iterator#next next} always throws {@link
-     * NoSuchElementException}.
-     *
+     * NoSuchElementException}.</li>
      * <li>{@link Iterator#remove remove} always throws {@link
-     * IllegalStateException}.
-     *
+     * IllegalStateException}.</li>
      * </ul>
      *
      * <p>Implementations of this method are permitted, but not
      * required, to return the same object from multiple invocations.
      *
+     * @param <T> type of elements, if there were any, in the iterator
      * @return an empty iterator
      * @since 1.7
      */
@@ -3370,32 +4229,26 @@
     /**
      * Returns a list iterator that has no elements.  More precisely,
      *
-     * <ul compact>
-     *
+     * <ul>
      * <li>{@link Iterator#hasNext hasNext} and {@link
      * ListIterator#hasPrevious hasPrevious} always return {@code
-     * false}.
-     *
+     * false}.</li>
      * <li>{@link Iterator#next next} and {@link ListIterator#previous
-     * previous} always throw {@link NoSuchElementException}.
-     *
+     * previous} always throw {@link NoSuchElementException}.</li>
      * <li>{@link Iterator#remove remove} and {@link ListIterator#set
-     * set} always throw {@link IllegalStateException}.
-     *
+     * set} always throw {@link IllegalStateException}.</li>
      * <li>{@link ListIterator#add add} always throws {@link
-     * UnsupportedOperationException}.
-     *
+     * UnsupportedOperationException}.</li>
      * <li>{@link ListIterator#nextIndex nextIndex} always returns
-     * {@code 0} .
-     *
+     * {@code 0}.</li>
      * <li>{@link ListIterator#previousIndex previousIndex} always
-     * returns {@code -1}.
-     *
+     * returns {@code -1}.</li>
      * </ul>
      *
      * <p>Implementations of this method are permitted, but not
      * required, to return the same object from multiple invocations.
      *
+     * @param <T> type of elements, if there were any, in the iterator
      * @return an empty list iterator
      * @since 1.7
      */
@@ -3422,19 +4275,17 @@
     /**
      * Returns an enumeration that has no elements.  More precisely,
      *
-     * <ul compact>
-     *
+     * <ul>
      * <li>{@link Enumeration#hasMoreElements hasMoreElements} always
-     * returns {@code false}.
-     *
+     * returns {@code false}.</li>
      * <li> {@link Enumeration#nextElement nextElement} always throws
-     * {@link NoSuchElementException}.
-     *
+     * {@link NoSuchElementException}.</li>
      * </ul>
      *
      * <p>Implementations of this method are permitted, but not
      * required, to return the same object from multiple invocations.
      *
+     * @param  <T> the class of the objects in the enumeration
      * @return an empty enumeration
      * @since 1.7
      */
@@ -3460,17 +4311,20 @@
     public static final Set EMPTY_SET = new EmptySet<>();
 
     /**
-     * Returns the empty set (immutable).  This set is serializable.
+     * Returns an empty set (immutable).  This set is serializable.
      * Unlike the like-named field, this method is parameterized.
      *
      * <p>This example illustrates the type-safe way to obtain an empty set:
      * <pre>
      *     Set&lt;String&gt; s = Collections.emptySet();
      * </pre>
-     * Implementation note:  Implementations of this method need not
-     * create a separate <tt>Set</tt> object for each call.   Using this
-     * method is likely to have comparable cost to using the like-named
-     * field.  (Unlike this method, the field does not provide type safety.)
+     * @implNote Implementations of this method need not create a separate
+     * {@code Set} object for each call.  Using this method is likely to have
+     * comparable cost to using the like-named field.  (Unlike this method, the
+     * field does not provide type safety.)
+     *
+     * @param  <T> the class of the objects in the set
+     * @return the empty set
      *
      * @see #EMPTY_SET
      * @since 1.5
@@ -3525,121 +4379,45 @@
     }
 
     /**
-     * Returns the empty sorted set (immutable).  This set is serializable.
-     *
-     * <p>This example illustrates the type-safe way to obtain an empty sorted
-     * set:
-     * <pre>
-     *     SortedSet&lt;String&gt; s = Collections.emptySortedSet();
-     * </pre>
-     * Implementation note:  Implementations of this method need not
-     * create a separate <tt>SortedSet</tt> object for each call.
-     *
+     * Returns an empty sorted set (immutable).  This set is serializable.
+     *
+     * <p>This example illustrates the type-safe way to obtain an empty
+     * sorted set:
+     * <pre> {@code
+     *     SortedSet<String> s = Collections.emptySortedSet();
+     * }</pre>
+     *
+     * @implNote Implementations of this method need not create a separate
+     * {@code SortedSet} object for each call.
+     *
+     * @param <E> type of elements, if there were any, in the set
+     * @return the empty sorted set
      * @since 1.8
      */
     @SuppressWarnings("unchecked")
-    public static final <E> SortedSet<E> emptySortedSet() {
-        return (SortedSet<E>) new EmptySortedSet<>();
+    public static <E> SortedSet<E> emptySortedSet() {
+        return (SortedSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET;
     }
 
     /**
-     * @serial include
+     * Returns an empty navigable set (immutable).  This set is serializable.
+     *
+     * <p>This example illustrates the type-safe way to obtain an empty
+     * navigable set:
+     * <pre> {@code
+     *     NavigableSet<String> s = Collections.emptyNavigableSet();
+     * }</pre>
+     *
+     * @implNote Implementations of this method need not
+     * create a separate {@code NavigableSet} object for each call.
+     *
+     * @param <E> type of elements, if there were any, in the set
+     * @return the empty navigable set
+     * @since 1.8
      */
-    private static class EmptySortedSet<E>
-        extends AbstractSet<E>
-        implements SortedSet<E>, Serializable
-    {
-        private static final long serialVersionUID = 6316515401502265487L;
-        public Iterator<E> iterator() { return emptyIterator(); }
-        public int size() {return 0;}
-        public boolean isEmpty() {return true;}
-        public boolean contains(Object obj) {return false;}
-        public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
-        public Object[] toArray() { return new Object[0]; }
-
-        public <E> E[] toArray(E[] a) {
-            if (a.length > 0)
-                a[0] = null;
-            return a;
-        }
-
-        // Preserves singleton property
-        private Object readResolve() {
-            return new EmptySortedSet<>();
-        }
-
-        @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);
-
-            if (!(fromElement instanceof Comparable) ||
-                    !(toElement instanceof Comparable))
-            {
-                throw new ClassCastException();
-            }
-
-            if ((((Comparable)fromElement).compareTo(toElement) >= 0) ||
-                    (((Comparable)toElement).compareTo(fromElement) < 0))
-            {
-                throw new IllegalArgumentException();
-            }
-
-            return emptySortedSet();
-        }
-
-        @Override
-        public SortedSet<E> headSet(Object toElement) {
-            Objects.requireNonNull(toElement);
-
-            if (!(toElement instanceof Comparable)) {
-                throw new ClassCastException();
-            }
-
-            return emptySortedSet();
-        }
-
-        @Override
-        public SortedSet<E> tailSet(Object fromElement) {
-            Objects.requireNonNull(fromElement);
-
-            if (!(fromElement instanceof Comparable)) {
-                throw new ClassCastException();
-            }
-
-            return emptySortedSet();
-        }
-
-        @Override
-        public E first() {
-            throw new NoSuchElementException();
-        }
-
-        @Override
-        public E last() {
-            throw new NoSuchElementException();
-        }
-
-        // Override default methods in Collection
-        @Override
-        public void forEach(Consumer<? super E> action) {
-            Objects.requireNonNull(action);
-        }
-
-        @Override
-        public boolean removeIf(Predicate<? super E> filter) {
-            Objects.requireNonNull(filter);
-            return false;
-        }
-
-        @Override
-        public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }
+    @SuppressWarnings("unchecked")
+    public static <E> NavigableSet<E> emptyNavigableSet() {
+        return (NavigableSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET;
     }
 
     /**
@@ -3651,7 +4429,7 @@
     public static final List EMPTY_LIST = new EmptyList<>();
 
     /**
-     * Returns the empty list (immutable).  This list is serializable.
+     * Returns an empty list (immutable).  This list is serializable.
      *
      * <p>This example illustrates the type-safe way to obtain an empty list:
      * <pre>
@@ -3662,6 +4440,9 @@
      * method is likely to have comparable cost to using the like-named
      * field.  (Unlike this method, the field does not provide type safety.)
      *
+     * @param <T> type of elements, if there were any, in the list
+     * @return an empty immutable list
+     *
      * @see #EMPTY_LIST
      * @since 1.5
      */
@@ -3748,17 +4529,20 @@
     public static final Map EMPTY_MAP = new EmptyMap<>();
 
     /**
-     * Returns the empty map (immutable).  This map is serializable.
-     *
-     * <p>This example illustrates the type-safe way to obtain an empty set:
+     * Returns an empty map (immutable).  This map is serializable.
+     *
+     * <p>This example illustrates the type-safe way to obtain an empty map:
      * <pre>
      *     Map&lt;String, Date&gt; s = Collections.emptyMap();
      * </pre>
-     * Implementation note:  Implementations of this method need not
-     * create a separate <tt>Map</tt> object for each call.   Using this
-     * method is likely to have comparable cost to using the like-named
-     * field.  (Unlike this method, the field does not provide type safety.)
-     *
+     * @implNote Implementations of this method need not create a separate
+     * {@code Map} object for each call.  Using this method is likely to have
+     * comparable cost to using the like-named field.  (Unlike this method, the
+     * field does not provide type safety.)
+     *
+     * @param <K> the class of the map keys
+     * @param <V> the class of the map values
+     * @return an empty map
      * @see #EMPTY_MAP
      * @since 1.5
      */
@@ -3768,6 +4552,48 @@
     }
 
     /**
+     * Returns an empty sorted map (immutable).  This map is serializable.
+     *
+     * <p>This example illustrates the type-safe way to obtain an empty map:
+     * <pre> {@code
+     *     SortedMap<String, Date> s = Collections.emptySortedMap();
+     * }</pre>
+     *
+     * @implNote Implementations of this method need not create a separate
+     * {@code SortedMap} object for each call.
+     *
+     * @param <K> the class of the map keys
+     * @param <V> the class of the map values
+     * @return an empty sorted map
+     * @since 1.8
+     */
+    @SuppressWarnings("unchecked")
+    public static final <K,V> SortedMap<K,V> emptySortedMap() {
+        return (SortedMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP;
+    }
+
+    /**
+     * Returns an empty navigable map (immutable).  This map is serializable.
+     *
+     * <p>This example illustrates the type-safe way to obtain an empty map:
+     * <pre> {@code
+     *     NavigableMap<String, Date> s = Collections.emptyNavigableMap();
+     * }</pre>
+     *
+     * @implNote Implementations of this method need not create a separate
+     * {@code NavigableMap} object for each call.
+     *
+     * @param <K> the class of the map keys
+     * @param <V> the class of the map values
+     * @return an empty navigable map
+     * @since 1.8
+     */
+    @SuppressWarnings("unchecked")
+    public static final <K,V> NavigableMap<K,V> emptyNavigableMap() {
+        return (NavigableMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP;
+    }
+
+    /**
      * @serial include
      */
     private static class EmptyMap<K,V>
@@ -3864,6 +4690,7 @@
      * Returns an immutable set containing only the specified object.
      * The returned set is serializable.
      *
+     * @param  <T> the class of the objects in the set
      * @param o the sole object to be stored in the returned set.
      * @return an immutable set containing only the specified object.
      */
@@ -3984,6 +4811,7 @@
      * Returns an immutable list containing only the specified object.
      * The returned list is serializable.
      *
+     * @param  <T> the class of the objects in the list
      * @param o the sole object to be stored in the returned list.
      * @return an immutable list containing only the specified object.
      * @since 1.3
@@ -4045,6 +4873,8 @@
      * Returns an immutable map, mapping only the specified key to the
      * specified value.  The returned map is serializable.
      *
+     * @param <K> the class of the map keys
+     * @param <V> the class of the map values
      * @param key the sole key to be stored in the returned map.
      * @param value the value to which the returned map maps <tt>key</tt>.
      * @return an immutable map containing only the specified key-value
@@ -4071,15 +4901,11 @@
             v = value;
         }
 
-        public int size()                          {return 1;}
-
-        public boolean isEmpty()                   {return false;}
-
-        public boolean containsKey(Object key)     {return eq(key, k);}
-
-        public boolean containsValue(Object value) {return eq(value, v);}
-
-        public V get(Object key)                   {return (eq(key, k) ? v : null);}
+        public int size()                                           {return 1;}
+        public boolean isEmpty()                                {return false;}
+        public boolean containsKey(Object key)             {return eq(key, k);}
+        public boolean containsValue(Object value)       {return eq(value, v);}
+        public V get(Object key)              {return (eq(key, k) ? v : null);}
 
         private transient Set<K> keySet = null;
         private transient Set<Map.Entry<K,V>> entrySet = null;
@@ -4174,6 +5000,8 @@
      * combination with the <tt>List.addAll</tt> method to grow lists.
      * The returned list is serializable.
      *
+     * @param  <T> the class of the object to copy and of the objects
+     *         in the returned list.
      * @param  n the number of elements in the returned list.
      * @param  o the element to appear repeatedly in the returned list.
      * @return an immutable list consisting of <tt>n</tt> copies of the
@@ -4278,6 +5106,7 @@
      *
      * The returned comparator is serializable.
      *
+     * @param  <T> the class of the objects compared by the comparator
      * @return A comparator that imposes the reverse of the <i>natural
      *         ordering</i> on a collection of objects that implement
      *         the <tt>Comparable</tt> interface.
@@ -4321,6 +5150,7 @@
      * <p>The returned comparator is serializable (assuming the specified
      * comparator is also serializable or {@code null}).
      *
+     * @param <T> the class of the objects compared by the comparator
      * @param cmp a comparator who's ordering is to be reversed by the returned
      * comparator or {@code null}
      * @return A comparator that imposes the reverse ordering of the
@@ -4384,6 +5214,7 @@
      * interoperability with legacy APIs that require an enumeration
      * as input.
      *
+     * @param  <T> the class of the objects in the collection
      * @param c the collection for which an enumeration is to be returned.
      * @return an enumeration over the specified collection.
      * @see Enumeration
@@ -4409,6 +5240,7 @@
      * legacy APIs that return enumerations and new APIs that require
      * collections.
      *
+     * @param <T> the class of the objects returned by the enumeration
      * @param e enumeration providing elements for the returned
      *          array list
      * @return an array list containing the elements returned
@@ -4426,6 +5258,8 @@
 
     /**
      * Returns true if the specified arguments are equal, or both null.
+     *
+     * NB: Do not replace with Object.equals until JDK-8015417 is resolved.
      */
     static boolean eq(Object o1, Object o2) {
         return o1==null ? o2==null : o1.equals(o2);
@@ -4440,6 +5274,7 @@
      * @param c the collection in which to determine the frequency
      *     of <tt>o</tt>
      * @param o the object whose frequency is to be determined
+     * @return the number of elements in {@code c} equal to {@code o}
      * @throws NullPointerException if <tt>c</tt> is null
      * @since 1.5
      */
@@ -4560,6 +5395,7 @@
      *     Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");
      * </pre>
      *
+     * @param  <T> the class of the elements to add and of the collection
      * @param c the collection into which <tt>elements</tt> are to be inserted
      * @param elements the elements to insert into <tt>c</tt>
      * @return <tt>true</tt> if the collection changed as a result of the call
@@ -4605,6 +5441,8 @@
      *        new WeakHashMap&lt;Object, Boolean&gt;());
      * </pre>
      *
+     * @param <E> the class of the map keys and of the objects in the
+     *        returned set
      * @param map the backing map
      * @return the set backed by the map
      * @throws IllegalArgumentException if <tt>map</tt> is not empty
@@ -4683,6 +5521,7 @@
      * implemented as a sequence of {@link Deque#addFirst addFirst}
      * invocations on the backing deque.
      *
+     * @param  <T> the class of the objects in the deque
      * @param deque the deque
      * @return the queue
      * @since  1.6
--- a/src/share/classes/java/util/ConcurrentModificationException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/ConcurrentModificationException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -57,6 +57,7 @@
  * @author  Josh Bloch
  * @see     Collection
  * @see     Iterator
+ * @see     Spliterator
  * @see     ListIterator
  * @see     Vector
  * @see     LinkedList
--- a/src/share/classes/java/util/EnumSet.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/EnumSet.java	Mon Jul 22 17:37:15 2013 -0700
@@ -100,8 +100,10 @@
     /**
      * Creates an empty enum set with the specified element type.
      *
+     * @param <E> The class of the elements in the set
      * @param elementType the class object of the element type for this enum
      *     set
+     * @return An empty enum set of the specified type.
      * @throws NullPointerException if <tt>elementType</tt> is null
      */
     public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) {
@@ -119,8 +121,10 @@
      * Creates an enum set containing all of the elements in the specified
      * element type.
      *
+     * @param <E> The class of the elements in the set
      * @param elementType the class object of the element type for this enum
      *     set
+     * @return An enum set containing all the elements in the specified type.
      * @throws NullPointerException if <tt>elementType</tt> is null
      */
     public static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType) {
@@ -139,7 +143,9 @@
      * Creates an enum set with the same element type as the specified enum
      * set, initially containing the same elements (if any).
      *
+     * @param <E> The class of the elements in the set
      * @param s the enum set from which to initialize this enum set
+     * @return A copy of the specified enum set.
      * @throws NullPointerException if <tt>s</tt> is null
      */
     public static <E extends Enum<E>> EnumSet<E> copyOf(EnumSet<E> s) {
@@ -153,7 +159,9 @@
      * Otherwise, the specified collection must contain at least one element
      * (in order to determine the new enum set's element type).
      *
+     * @param <E> The class of the elements in the collection
      * @param c the collection from which to initialize this enum set
+     * @return An enum set initialized from the given collection.
      * @throws IllegalArgumentException if <tt>c</tt> is not an
      *     <tt>EnumSet</tt> instance and contains no elements
      * @throws NullPointerException if <tt>c</tt> is null
@@ -178,7 +186,9 @@
      * set, initially containing all the elements of this type that are
      * <i>not</i> contained in the specified set.
      *
+     * @param <E> The class of the elements in the enum set
      * @param s the enum set from whose complement to initialize this enum set
+     * @return The complement of the specified set in this set
      * @throws NullPointerException if <tt>s</tt> is null
      */
     public static <E extends Enum<E>> EnumSet<E> complementOf(EnumSet<E> s) {
@@ -196,6 +206,7 @@
      * an enum set initially containing an arbitrary number of elements, but
      * is likely to run slower than the overloadings that do not use varargs.
      *
+     * @param <E> The class of the specified element and of the set
      * @param e the element that this set is to contain initially
      * @throws NullPointerException if <tt>e</tt> is null
      * @return an enum set initially containing the specified element
@@ -215,6 +226,7 @@
      * an enum set initially containing an arbitrary number of elements, but
      * is likely to run slower than the overloadings that do not use varargs.
      *
+     * @param <E> The class of the parameter elements and of the set
      * @param e1 an element that this set is to contain initially
      * @param e2 another element that this set is to contain initially
      * @throws NullPointerException if any parameters are null
@@ -236,6 +248,7 @@
      * an enum set initially containing an arbitrary number of elements, but
      * is likely to run slower than the overloadings that do not use varargs.
      *
+     * @param <E> The class of the parameter elements and of the set
      * @param e1 an element that this set is to contain initially
      * @param e2 another element that this set is to contain initially
      * @param e3 another element that this set is to contain initially
@@ -259,6 +272,7 @@
      * an enum set initially containing an arbitrary number of elements, but
      * is likely to run slower than the overloadings that do not use varargs.
      *
+     * @param <E> The class of the parameter elements and of the set
      * @param e1 an element that this set is to contain initially
      * @param e2 another element that this set is to contain initially
      * @param e3 another element that this set is to contain initially
@@ -284,6 +298,7 @@
      * an enum set initially containing an arbitrary number of elements, but
      * is likely to run slower than the overloadings that do not use varargs.
      *
+     * @param <E> The class of the parameter elements and of the set
      * @param e1 an element that this set is to contain initially
      * @param e2 another element that this set is to contain initially
      * @param e3 another element that this set is to contain initially
@@ -311,6 +326,7 @@
      * number of elements, but it is likely to run slower than the overloadings
      * that do not use varargs.
      *
+     * @param <E> The class of the parameter elements and of the set
      * @param first an element that the set is to contain initially
      * @param rest the remaining elements the set is to contain initially
      * @throws NullPointerException if any of the specified elements are null,
@@ -332,6 +348,7 @@
      * contain the endpoints themselves, which may be identical but must not
      * be out of order.
      *
+     * @param <E> The class of the parameter elements and of the set
      * @param from the first element in the range
      * @param to the last element in the range
      * @throws NullPointerException if {@code from} or {@code to} are null
--- a/src/share/classes/java/util/Formattable.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/Formattable.java	Mon Jul 22 17:37:15 2013 -0700
@@ -36,7 +36,7 @@
  * For example, the following class prints out different representations of a
  * stock's name depending on the flags and length constraints:
  *
- * <blockquote><pre>
+ * {@code
  *   import java.nio.CharBuffer;
  *   import java.util.Formatter;
  *   import java.util.Formattable;
@@ -89,12 +89,12 @@
  *           return String.format("%s - %s", symbol, companyName);
  *       }
  *   }
- * </pre></blockquote>
+ * }
  *
  * <p> When used in conjunction with the {@link java.util.Formatter}, the above
  * class produces the following output for various format strings.
  *
- * <blockquote><pre>
+ * {@code
  *   Formatter fmt = new Formatter();
  *   StockName sn = new StockName("HUGE", "Huge Fruit, Inc.",
  *                                "Fruit Titanesque, Inc.");
@@ -104,7 +104,7 @@
  *   fmt.format("%-10.8s", sn);              //   -> "HUGE      "
  *   fmt.format("%.12s", sn);                //   -> "Huge Fruit,*"
  *   fmt.format(Locale.FRANCE, "%25s", sn);  //   -> "   Fruit Titanesque, Inc."
- * </pre></blockquote>
+ * }
  *
  * <p> Formattables are not necessarily safe for multithreaded access.  Thread
  * safety is optional and may be enforced by classes that extend and implement
--- a/src/share/classes/java/util/Formatter.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/Formatter.java	Mon Jul 22 17:37:15 2013 -0700
@@ -190,7 +190,7 @@
  * <p> The optional <i>flags</i> is a set of characters that modify the output
  * format.  The set of valid flags depends on the conversion.
  *
- * <p> The optional <i>width</i> is a non-negative decimal integer indicating
+ * <p> The optional <i>width</i> is a positive decimal integer indicating
  * the minimum number of characters to be written to the output.
  *
  * <p> The optional <i>precision</i> is a non-negative decimal integer usually
@@ -841,7 +841,7 @@
  *
  * <p> Numeric types will be formatted according to the following algorithm:
  *
- * <p><b><a name="l10n algorithm"> Number Localization Algorithm</a></b>
+ * <p><b><a name="L10nAlgorithm"> Number Localization Algorithm</a></b>
  *
  * <p> After digits are obtained for the integer part, fractional part, and
  * exponent (as appropriate for the data type), the following transformation
@@ -860,7 +860,7 @@
  * substituted.
  *
  * <li> If the {@code ','} (<tt>'&#92;u002c'</tt>)
- * <a name="l10n group">flag</a> is given, then the locale-specific {@linkplain
+ * <a name="L10nGroup">flag</a> is given, then the locale-specific {@linkplain
  * java.text.DecimalFormatSymbols#getGroupingSeparator grouping separator} is
  * inserted by scanning the integer part of the string from least significant
  * to most significant digits and inserting a separator at intervals defined by
@@ -902,7 +902,7 @@
  * <tr><td valign="top"> {@code 'd'}
  *     <td valign="top"> <tt>'&#92;u0054'</tt>
  *     <td> Formats the argument as a decimal integer. The <a
- *     href="#l10n algorithm">localization algorithm</a> is applied.
+ *     href="#L10nAlgorithm">localization algorithm</a> is applied.
  *
  *     <p> If the {@code '0'} flag is given and the value is negative, then
  *     the zero padding will occur after the sign.
@@ -1011,7 +1011,7 @@
  *     <td valign="top"> <tt>'&#92;u002c'</tt>
  *     <td> Requires the output to include the locale-specific {@linkplain
  *     java.text.DecimalFormatSymbols#getGroupingSeparator group separators} as
- *     described in the <a href="#l10n group">"group" section</a> of the
+ *     described in the <a href="#L10nGroup">"group" section</a> of the
  *     localization algorithm.
  *
  * <tr><td valign="top"> {@code '('}
@@ -1060,7 +1060,7 @@
  * <tr><td valign="top"> {@code 'd'}
  *     <td valign="top"> <tt>'&#92;u0054'</tt>
  *     <td> Requires the output to be formatted as a decimal integer. The <a
- *     href="#l10n algorithm">localization algorithm</a> is applied.
+ *     href="#L10nAlgorithm">localization algorithm</a> is applied.
  *
  *     <p> If the {@code '#'} flag is given {@link
  *     FormatFlagsConversionMismatchException} will be thrown.
@@ -1155,7 +1155,7 @@
  *     <td valign="top"> <tt>'&#92;u0065'</tt>
  *     <td> Requires the output to be formatted using <a
  *     name="scientific">computerized scientific notation</a>.  The <a
- *     href="#l10n algorithm">localization algorithm</a> is applied.
+ *     href="#L10nAlgorithm">localization algorithm</a> is applied.
  *
  *     <p> The formatting of the magnitude <i>m</i> depends upon its value.
  *
@@ -1168,7 +1168,7 @@
  *
  *     <p> Otherwise, the result is a string that represents the sign and
  *     magnitude (absolute value) of the argument.  The formatting of the sign
- *     is described in the <a href="#l10n algorithm">localization
+ *     is described in the <a href="#L10nAlgorithm">localization
  *     algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its
  *     value.
  *
@@ -1207,7 +1207,7 @@
  * <tr><td valign="top"> {@code 'g'}
  *     <td valign="top"> <tt>'&#92;u0067'</tt>
  *     <td> Requires the output to be formatted in general scientific notation
- *     as described below. The <a href="#l10n algorithm">localization
+ *     as described below. The <a href="#L10nAlgorithm">localization
  *     algorithm</a> is applied.
  *
  *     <p> After rounding for the precision, the formatting of the resulting
@@ -1236,12 +1236,12 @@
  * <tr><td valign="top"> {@code 'f'}
  *     <td valign="top"> <tt>'&#92;u0066'</tt>
  *     <td> Requires the output to be formatted using <a name="decimal">decimal
- *     format</a>.  The <a href="#l10n algorithm">localization algorithm</a> is
+ *     format</a>.  The <a href="#L10nAlgorithm">localization algorithm</a> is
  *     applied.
  *
  *     <p> The result is a string that represents the sign and magnitude
  *     (absolute value) of the argument.  The formatting of the sign is
- *     described in the <a href="#l10n algorithm">localization
+ *     described in the <a href="#L10nAlgorithm">localization
  *     algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its
  *     value.
  *
@@ -1382,7 +1382,7 @@
  *     <td valign="top"> <tt>'&#92;u0065'</tt>
  *     <td> Requires the output to be formatted using <a
  *     name="bscientific">computerized scientific notation</a>.  The <a
- *     href="#l10n algorithm">localization algorithm</a> is applied.
+ *     href="#L10nAlgorithm">localization algorithm</a> is applied.
  *
  *     <p> The formatting of the magnitude <i>m</i> depends upon its value.
  *
@@ -1391,7 +1391,7 @@
  *
  *     <p> Otherwise, the result is a string that represents the sign and
  *     magnitude (absolute value) of the argument.  The formatting of the sign
- *     is described in the <a href="#l10n algorithm">localization
+ *     is described in the <a href="#L10nAlgorithm">localization
  *     algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its
  *     value.
  *
@@ -1428,7 +1428,7 @@
  * <tr><td valign="top"> {@code 'g'}
  *     <td valign="top"> <tt>'&#92;u0067'</tt>
  *     <td> Requires the output to be formatted in general scientific notation
- *     as described below. The <a href="#l10n algorithm">localization
+ *     as described below. The <a href="#L10nAlgorithm">localization
  *     algorithm</a> is applied.
  *
  *     <p> After rounding for the precision, the formatting of the resulting
@@ -1457,12 +1457,12 @@
  * <tr><td valign="top"> {@code 'f'}
  *     <td valign="top"> <tt>'&#92;u0066'</tt>
  *     <td> Requires the output to be formatted using <a name="bdecimal">decimal
- *     format</a>.  The <a href="#l10n algorithm">localization algorithm</a> is
+ *     format</a>.  The <a href="#L10nAlgorithm">localization algorithm</a> is
  *     applied.
  *
  *     <p> The result is a string that represents the sign and magnitude
  *     (absolute value) of the argument.  The formatting of the sign is
- *     described in the <a href="#l10n algorithm">localization
+ *     described in the <a href="#L10nAlgorithm">localization
  *     algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its
  *     value.
  *
@@ -1721,7 +1721,7 @@
  * conversions</a> applies.  If the {@code '#'} flag is given, then a {@link
  * FormatFlagsConversionMismatchException} will be thrown.
  *
- * <p> The <a name="dtWidth">width</a> is the minimum number of characters to
+ * <p> The width is the minimum number of characters to
  * be written to the output.  If the length of the converted value is less than
  * the {@code width} then the output will be padded by spaces
  * (<tt>'&#92;u0020'</tt>) until the total number of characters equals width.
@@ -1741,7 +1741,7 @@
  * <tr><td valign="top">{@code '%'}
  *     <td> The result is a literal {@code '%'} (<tt>'&#92;u0025'</tt>)
  *
- * <p> The <a name="dtWidth">width</a> is the minimum number of characters to
+ * <p> The width is the minimum number of characters to
  * be written to the output including the {@code '%'}.  If the length of the
  * converted value is less than the {@code width} then the output will be
  * padded by spaces (<tt>'&#92;u0020'</tt>) until the total number of
@@ -2590,7 +2590,20 @@
         public String toString() { return s; }
     }
 
-    public enum BigDecimalLayoutForm { SCIENTIFIC, DECIMAL_FLOAT };
+    /**
+     * Enum for {@code BigDecimal} formatting.
+     */
+    public enum BigDecimalLayoutForm {
+        /**
+         * Format the {@code BigDecimal} in computerized scientific notation.
+         */
+        SCIENTIFIC,
+
+        /**
+         * Format the {@code BigDecimal} as a decimal number.
+         */
+        DECIMAL_FLOAT
+    };
 
     private class FormatSpecifier implements FormatString {
         private int index = -1;
--- a/src/share/classes/java/util/GregorianCalendar.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/GregorianCalendar.java	Mon Jul 22 17:37:15 2013 -0700
@@ -94,7 +94,7 @@
  * adjustment may be made if desired for dates that are prior to the Gregorian
  * changeover and which fall between January 1 and March 24.
  *
- * <h4><a name="week_and_year">Week Of Year and Week Year</a></h4>
+ * <h3><a name="week_and_year">Week Of Year and Week Year</a></h3>
  *
  * <p>Values calculated for the {@link Calendar#WEEK_OF_YEAR
  * WEEK_OF_YEAR} field range from 1 to 53. The first week of a
--- a/src/share/classes/java/util/HashMap.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/HashMap.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1013,7 +1013,7 @@
      */
     @SuppressWarnings("unchecked")
     final Entry<K,V> getEntry(Object key) {
-        if (isEmpty()) {
+        if (size == 0) {
             return null;
         }
         if (key == null) {
@@ -1468,7 +1468,7 @@
 
     @Override
     public boolean remove(Object key, Object value) {
-        if (isEmpty()) {
+        if (size == 0) {
             return false;
         }
         if (key == null) {
@@ -1531,7 +1531,7 @@
 
     @Override
     public boolean replace(K key, V oldValue, V newValue) {
-        if (isEmpty()) {
+        if (size == 0) {
             return false;
         }
         if (key == null) {
@@ -1574,7 +1574,7 @@
 
    @Override
     public V replace(K key, V value) {
-        if (isEmpty()) {
+        if (size == 0) {
             return null;
         }
         if (key == null) {
@@ -1694,7 +1694,7 @@
 
     @Override
     public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
-        if (isEmpty()) {
+        if (size == 0) {
             return null;
         }
         if (key == null) {
@@ -1980,7 +1980,7 @@
      * TreeNode in a TreeBin.
      */
     final Entry<K,V> removeEntryForKey(Object key) {
-        if (isEmpty()) {
+        if (size == 0) {
             return null;
         }
         if (key == null) {
@@ -2040,7 +2040,7 @@
      * for matching.
      */
     final Entry<K,V> removeMapping(Object o) {
-        if (isEmpty() || !(o instanceof Map.Entry))
+        if (size == 0 || !(o instanceof Map.Entry))
             return null;
 
         Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
--- a/src/share/classes/java/util/LinkedList.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/LinkedList.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1195,12 +1195,7 @@
                     n = s;
                 if (n > MAX_BATCH)
                     n = MAX_BATCH;
-                Object[] a;
-                try {
-                    a = new Object[n];
-                } catch (OutOfMemoryError oome) {
-                    return null;
-                }
+                Object[] a = new Object[n];
                 int j = 0;
                 do { a[j++] = p.item; } while ((p = p.next) != null && j < n);
                 current = p;
--- a/src/share/classes/java/util/Locale.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/Locale.java	Mon Jul 22 17:37:15 2013 -0700
@@ -84,7 +84,7 @@
  * described below.
  *
  * <dl>
- *   <dt><a name="def_language"/><b>language</b></dt>
+ *   <dt><a name="def_language"><b>language</b></a></dt>
  *
  *   <dd>ISO 639 alpha-2 or alpha-3 language code, or registered
  *   language subtags up to 8 alpha letters (for future enhancements).
@@ -92,51 +92,51 @@
  *   alpha-2 code must be used.  You can find a full list of valid
  *   language codes in the IANA Language Subtag Registry (search for
  *   "Type: language").  The language field is case insensitive, but
- *   <code>Locale</code> always canonicalizes to lower case.</dd><br>
+ *   <code>Locale</code> always canonicalizes to lower case.</dd>
  *
  *   <dd>Well-formed language values have the form
  *   <code>[a-zA-Z]{2,8}</code>.  Note that this is not the the full
  *   BCP47 language production, since it excludes extlang.  They are
  *   not needed since modern three-letter language codes replace
- *   them.</dd><br>
+ *   them.</dd>
  *
- *   <dd>Example: "en" (English), "ja" (Japanese), "kok" (Konkani)</dd><br>
+ *   <dd>Example: "en" (English), "ja" (Japanese), "kok" (Konkani)</dd>
  *
- *   <dt><a name="def_script"/><b>script</b></dt>
+ *   <dt><a name="def_script"><b>script</b></a></dt>
  *
  *   <dd>ISO 15924 alpha-4 script code.  You can find a full list of
  *   valid script codes in the IANA Language Subtag Registry (search
  *   for "Type: script").  The script field is case insensitive, but
  *   <code>Locale</code> always canonicalizes to title case (the first
  *   letter is upper case and the rest of the letters are lower
- *   case).</dd><br>
+ *   case).</dd>
  *
  *   <dd>Well-formed script values have the form
- *   <code>[a-zA-Z]{4}</code></dd><br>
+ *   <code>[a-zA-Z]{4}</code></dd>
  *
- *   <dd>Example: "Latn" (Latin), "Cyrl" (Cyrillic)</dd><br>
+ *   <dd>Example: "Latn" (Latin), "Cyrl" (Cyrillic)</dd>
  *
- *   <dt><a name="def_region"/><b>country (region)</b></dt>
+ *   <dt><a name="def_region"><b>country (region)</b></a></dt>
  *
  *   <dd>ISO 3166 alpha-2 country code or UN M.49 numeric-3 area code.
  *   You can find a full list of valid country and region codes in the
  *   IANA Language Subtag Registry (search for "Type: region").  The
  *   country (region) field is case insensitive, but
- *   <code>Locale</code> always canonicalizes to upper case.</dd><br>
+ *   <code>Locale</code> always canonicalizes to upper case.</dd>
  *
  *   <dd>Well-formed country/region values have
- *   the form <code>[a-zA-Z]{2} | [0-9]{3}</code></dd><br>
+ *   the form <code>[a-zA-Z]{2} | [0-9]{3}</code></dd>
  *
  *   <dd>Example: "US" (United States), "FR" (France), "029"
- *   (Caribbean)</dd><br>
+ *   (Caribbean)</dd>
  *
- *   <dt><a name="def_variant"/><b>variant</b></dt>
+ *   <dt><a name="def_variant"><b>variant</b></a></dt>
  *
  *   <dd>Any arbitrary value used to indicate a variation of a
  *   <code>Locale</code>.  Where there are two or more variant values
  *   each indicating its own semantics, these values should be ordered
  *   by importance, with most important first, separated by
- *   underscore('_').  The variant field is case sensitive.</dd><br>
+ *   underscore('_').  The variant field is case sensitive.</dd>
  *
  *   <dd>Note: IETF BCP 47 places syntactic restrictions on variant
  *   subtags.  Also BCP 47 subtags are strictly used to indicate
@@ -152,16 +152,16 @@
  *   cultural behaviors such as calendar type or number script.  In
  *   BCP 47 this kind of information, which does not identify the
  *   language, is supported by extension subtags or private use
- *   subtags.</dd><br>
+ *   subtags.</dd>
  *
  *   <dd>Well-formed variant values have the form <code>SUBTAG
  *   (('_'|'-') SUBTAG)*</code> where <code>SUBTAG =
  *   [0-9][0-9a-zA-Z]{3} | [0-9a-zA-Z]{5,8}</code>. (Note: BCP 47 only
- *   uses hyphen ('-') as a delimiter, this is more lenient).</dd><br>
+ *   uses hyphen ('-') as a delimiter, this is more lenient).</dd>
  *
- *   <dd>Example: "polyton" (Polytonic Greek), "POSIX"</dd><br>
+ *   <dd>Example: "polyton" (Polytonic Greek), "POSIX"</dd>
  *
- *   <dt><a name="def_extensions"/><b>extensions</b></dt>
+ *   <dt><a name="def_extensions"><b>extensions</b></a></dt>
  *
  *   <dd>A map from single character keys to string values, indicating
  *   extensions apart from language identification.  The extensions in
@@ -169,14 +169,14 @@
  *   extension subtags and private use subtags. The extensions are
  *   case insensitive, but <code>Locale</code> canonicalizes all
  *   extension keys and values to lower case. Note that extensions
- *   cannot have empty values.</dd><br>
+ *   cannot have empty values.</dd>
  *
  *   <dd>Well-formed keys are single characters from the set
  *   <code>[0-9a-zA-Z]</code>.  Well-formed values have the form
  *   <code>SUBTAG ('-' SUBTAG)*</code> where for the key 'x'
  *   <code>SUBTAG = [0-9a-zA-Z]{1,8}</code> and for other keys
  *   <code>SUBTAG = [0-9a-zA-Z]{2,8}</code> (that is, 'x' allows
- *   single-character subtags).</dd><br>
+ *   single-character subtags).</dd>
  *
  *   <dd>Example: key="u"/value="ca-japanese" (Japanese Calendar),
  *   key="x"/value="java-1-7"</dd>
@@ -189,7 +189,7 @@
  * requirement (is well-formed), but does not validate the value
  * itself.  See {@link Builder} for details.
  *
- * <h4><a name="def_locale_extension">Unicode locale/language extension</h4>
+ * <h3><a name="def_locale_extension">Unicode locale/language extension</a></h3>
  *
  * <p>UTS#35, "Unicode Locale Data Markup Language" defines optional
  * attributes and keywords to override or refine the default behavior
@@ -409,7 +409,7 @@
  * Clients desiring a string representation of the complete locale can
  * then always rely on <code>toLanguageTag</code> for this purpose.
  *
- * <h5><a name="special_cases_constructor"/>Special cases</h5>
+ * <h5><a name="special_cases_constructor">Special cases</a></h5>
  *
  * <p>For compatibility reasons, two
  * non-conforming locales are treated as special cases.  These are
@@ -1007,6 +1007,8 @@
      * country (region), such as 3-letter numeric UN M.49 area codes.
      * Therefore, the list returned by this method does not contain ALL valid
      * codes that can be used to create Locales.
+     *
+     * @return An array of ISO 3166 two-letter country codes.
      */
     public static String[] getISOCountries() {
         if (isoCountries == null) {
@@ -1030,6 +1032,8 @@
      * 8 characters in length.  Therefore, the list returned by this method does
      * not contain ALL valid codes that can be used to create Locales.
      * </ul>
+     *
+     * @return Am array of ISO 639 two-letter language codes.
      */
     public static String[] getISOLanguages() {
         if (isoLanguages == null) {
@@ -1268,15 +1272,15 @@
      * fields only.  To represent a Locale as a String for interchange purposes, use
      * {@link #toLanguageTag}.
      *
-     * <p>Examples: <ul><tt>
-     * <li>en
-     * <li>de_DE
-     * <li>_GB
-     * <li>en_US_WIN
-     * <li>de__POSIX
-     * <li>zh_CN_#Hans
-     * <li>zh_TW_#Hant-x-java
-     * <li>th_TH_TH_#u-nu-thai</tt></ul>
+     * <p>Examples: <ul>
+     * <li><tt>en</tt></li>
+     * <li><tt>de_DE</tt></li>
+     * <li><tt>_GB</tt></li>
+     * <li><tt>en_US_WIN</tt></li>
+     * <li><tt>de__POSIX</tt></li>
+     * <li><tt>zh_CN_#Hans</tt></li>
+     * <li><tt>zh_TW_#Hant-x-java</tt></li>
+     * <li><tt>th_TH_TH_#u-nu-thai</tt></li></ul>
      *
      * @return A string representation of the Locale, for debugging.
      * @see #getDisplayName
@@ -1506,7 +1510,7 @@
      *
      * <p>Grandfathered tags with canonical replacements are as follows:
      *
-     * <table>
+     * <table summary="Grandfathered tags with canonical replacements">
      * <tbody align="center">
      * <tr><th>grandfathered tag</th><th>&nbsp;</th><th>modern replacement</th></tr>
      * <tr><td>art-lojban</td><td>&nbsp;</td><td>jbo</td></tr>
@@ -1535,7 +1539,7 @@
      * <p>Grandfathered tags with no modern replacement will be
      * converted as follows:
      *
-     * <table>
+     * <table summary="Grandfathered tags with no modern replacement">
      * <tbody align="center">
      * <tr><th>grandfathered tag</th><th>&nbsp;</th><th>converts to</th></tr>
      * <tr><td>cel-gaulish</td><td>&nbsp;</td><td>xtg-x-cel-gaulish</td></tr>
@@ -1659,6 +1663,8 @@
      * (say, we don't have a Japanese name for Croatian),
      * this function falls back on the English name, and uses the ISO code as a last-resort
      * value.  If the locale doesn't specify a language, this function returns the empty string.
+     *
+     * @return The name of the display language.
      */
     public final String getDisplayLanguage() {
         return getDisplayLanguage(getDefault(Category.DISPLAY));
@@ -1677,6 +1683,8 @@
      * on the ISO code as a last-resort value.  If the locale doesn't specify a language,
      * this function returns the empty string.
      *
+     * @param inLocale The locale for which to retrieve the display language.
+     * @return The name of the display language appropriate to the given locale.
      * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
      */
     public String getDisplayLanguage(Locale inLocale) {
@@ -1703,6 +1711,7 @@
      * localized for the given locale. Returns the empty string if
      * this locale doesn't specify a script code.
      *
+     * @param inLocale The locale for which to retrieve the display script.
      * @return the display name of the script code for the current default
      * {@link Locale.Category#DISPLAY DISPLAY} locale
      * @throws NullPointerException if <code>inLocale</code> is <code>null</code>
@@ -1727,6 +1736,8 @@
      * (say, we don't have a Japanese name for Croatia),
      * this function falls back on the English name, and uses the ISO code as a last-resort
      * value.  If the locale doesn't specify a country, this function returns the empty string.
+     *
+     * @return The name of the country appropriate to the locale.
      */
     public final String getDisplayCountry() {
         return getDisplayCountry(getDefault(Category.DISPLAY));
@@ -1745,6 +1756,8 @@
      * on the ISO code as a last-resort value.  If the locale doesn't specify a country,
      * this function returns the empty string.
      *
+     * @param inLocale The locale for which to retrieve the display country.
+     * @return The name of the country appropriate to the given locale.
      * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
      */
     public String getDisplayCountry(Locale inLocale) {
@@ -1778,6 +1791,8 @@
      * user.  If possible, the name will be localized for the default
      * {@link Locale.Category#DISPLAY DISPLAY} locale.  If the locale
      * doesn't specify a variant code, this function returns the empty string.
+     *
+     * @return The name of the display variant code appropriate to the locale.
      */
     public final String getDisplayVariant() {
         return getDisplayVariant(getDefault(Category.DISPLAY));
@@ -1788,6 +1803,8 @@
      * user.  If possible, the name will be localized for inLocale.  If the locale
      * doesn't specify a variant code, this function returns the empty string.
      *
+     * @param inLocale The locale for which to retrieve the display variant code.
+     * @return The name of the display variant code appropriate to the given locale.
      * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
      */
     public String getDisplayVariant(Locale inLocale) {
@@ -1821,6 +1838,8 @@
      * depending on which fields are specified in the locale.  If the
      * language, sacript, country, and variant fields are all empty,
      * this function returns the empty string.
+     *
+     * @return The name of the locale appropriate to display.
      */
     public final String getDisplayName() {
         return getDisplayName(getDefault(Category.DISPLAY));
@@ -1844,6 +1863,8 @@
      * language, script, country, and variant fields are all empty,
      * this function returns the empty string.
      *
+     * @param inLocale The locale for which to retrieve the display name.
+     * @return The name of the locale appropriate to display.
      * @throws NullPointerException if <code>inLocale</code> is <code>null</code>
      */
     public String getDisplayName(Locale inLocale) {
@@ -2672,7 +2693,7 @@
      *
      * The filtering method will behave as follows:
      *
-     * <table cellpadding=2>
+     * <table cellpadding=2 summary="Filtering method behavior">
      * <tr>
      * <th>Filtering Mode</th>
      * <th>Language Priority List: {@code "de-DE"}</th>
--- a/src/share/classes/java/util/NavigableSet.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/NavigableSet.java	Mon Jul 22 17:37:15 2013 -0700
@@ -303,7 +303,7 @@
      * @throws ClassCastException       {@inheritDoc}
      * @throws NullPointerException     {@inheritDoc}
      * @throws IllegalArgumentException {@inheritDoc}
-na     */
+     */
     SortedSet<E> headSet(E toElement);
 
     /**
--- a/src/share/classes/java/util/Optional.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/Optional.java	Mon Jul 22 17:37:15 2013 -0700
@@ -25,6 +25,8 @@
 package java.util;
 
 import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Predicate;
 import java.util.function.Supplier;
 
 /**
@@ -52,7 +54,7 @@
     private final T value;
 
     /**
-     * Construct an empty instance.
+     * Constructs an empty instance.
      *
      * @implNote Generally only one empty instance, {@link Optional#EMPTY},
      * should exist per VM.
@@ -80,7 +82,7 @@
     }
 
     /**
-     * Construct an instance with the value present.
+     * Constructs an instance with the value present.
      *
      * @param value the non-null value to be present
      */
@@ -89,7 +91,7 @@
     }
 
     /**
-     * Return an {@code Optional} with the specified present value.
+     * Returns an {@code Optional} with the specified present non-null value.
      *
      * @param value the value to be present, which must be non-null
      * @return an {@code Optional} with the value present
@@ -99,6 +101,18 @@
     }
 
     /**
+     * Returns an {@code Optional} describing the specified value, if non-null,
+     * otherwise returns an empty {@code Optional}.
+     *
+     * @param value the possibly-null value to describe
+     * @return an {@code Optional} with a present value if the specified value
+     * is non-null, otherwise an empty {@code Optional}
+     */
+    public static <T> Optional<T> ofNullable(T value) {
+        return value == null ? empty() : of(value);
+    }
+
+    /**
      * If a value is present in this {@code Optional}, returns the value,
      * otherwise throws {@code NoSuchElementException}.
      *
@@ -124,7 +138,7 @@
     }
 
     /**
-     * Have the specified consumer accept the value if a value is present,
+     * If a value is present, invoke the specified consumer with the value,
      * otherwise do nothing.
      *
      * @param consumer block to be executed if a value is present
@@ -137,6 +151,89 @@
     }
 
     /**
+     * If a value is present, and the value matches the given predicate,
+     * return an {@code Optional} describing the value, otherwise return an
+     * empty {@code Optional}.
+     *
+     * @param predicate a predicate to apply to the value, if present
+     * @return an {@code Optional} describing the value of this {@code Optional}
+     * if a value is present and the value matches the given predicate,
+     * otherwise an empty {@code Optional}
+     * @throws NullPointerException if the predicate is null
+     */
+    public Optional<T> filter(Predicate<? super T> predicate) {
+        Objects.requireNonNull(predicate);
+        if (!isPresent())
+            return this;
+        else
+            return predicate.test(value) ? this : empty();
+    }
+
+    /**
+     * If a value is present, apply the provided mapping function to it,
+     * and if the result is non-null, return an {@code Optional} describing the
+     * result.  Otherwise return an empty {@code Optional}.
+     *
+     * @apiNote This method supports post-processing on optional values, without
+     * the need to explicitly check for a return status.  For example, the
+     * following code traverses a stream of file names, selects one that has
+     * not yet been processed, and then opens that file, returning an
+     * {@code Optional<FileInputStream>}:
+     *
+     * <pre>{@code
+     *     Optional<FileInputStream> fis =
+     *         names.stream().filter(name -> !isProcessedYet(name))
+     *                       .findFirst()
+     *                       .map(name -> new FileInputStream(name));
+     * }</pre>
+     *
+     * Here, {@code findFirst} returns an {@code Optional<String>}, and then
+     * {@code map} returns an {@code Optional<FileInputStream>} for the desired
+     * file if one exists.
+     *
+     * @param <U> The type of the result of the mapping function
+     * @param mapper a mapping function to apply to the value, if present
+     * @return an {@code Optional} describing the result of applying a mapping
+     * function to the value of this {@code Optional}, if a value is present,
+     * otherwise an empty {@code Optional}
+     * @throws NullPointerException if the mapping function is null
+     */
+    public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
+        Objects.requireNonNull(mapper);
+        if (!isPresent())
+            return empty();
+        else {
+            return Optional.ofNullable(mapper.apply(value));
+        }
+    }
+
+    /**
+     * If a value is present, apply the provided {@code Optional}-bearing
+     * mapping function to it, return that result, otherwise return an empty
+     * {@code Optional}.  This method is similar to {@link #map(Function)},
+     * but the provided mapper is one whose result is already an {@code Optional},
+     * and if invoked, {@code flatMap} does not wrap it with an additional
+     * {@code Optional}.
+     *
+     * @param <U> The type parameter to the {@code Optional} returned by
+     * @param mapper a mapping function to apply to the value, if present
+     *           the mapping function
+     * @return the result of applying an {@code Optional}-bearing mapping
+     * function to the value of this {@code Optional}, if a value is present,
+     * otherwise an empty {@code Optional}
+     * @throws NullPointerException if the mapping function is null or returns
+     * a null result
+     */
+    public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
+        Objects.requireNonNull(mapper);
+        if (!isPresent())
+            return empty();
+        else {
+            return Objects.requireNonNull(mapper.apply(value));
+        }
+    }
+
+    /**
      * Return the value if present, otherwise return {@code other}.
      *
      * @param other the value to be returned if there is no value present, may
--- a/src/share/classes/java/util/OptionalDouble.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/OptionalDouble.java	Mon Jul 22 17:37:15 2013 -0700
@@ -186,10 +186,10 @@
     }
 
     /**
-     * Indicates whether some other object is "equal to" this Optional. The
+     * Indicates whether some other object is "equal to" this OptionalDouble. The
      * other object is considered equal if:
      * <ul>
-     * <li>it is also an {@code OptionalInt} and;
+     * <li>it is also an {@code OptionalDouble} and;
      * <li>both instances have no value present or;
      * <li>the present values are "equal to" each other via {@code Double.compare() == 0}.
      * </ul>
@@ -226,12 +226,14 @@
     }
 
     /**
-     * Returns a non-empty string representation of this OptionalDouble suitable for
+     * {@inheritDoc}
+     *
+     * Returns a non-empty string representation of this object suitable for
      * debugging. The exact presentation format is unspecified and may vary
      * between implementations and versions.
      *
      * @implSpec If a value is present the result must include its string
-     * representation in the result. Empty and present OptionalDoubless must be
+     * representation in the result. Empty and present instances must be
      * unambiguously differentiable.
      *
      * @return the string representation of this instance
--- a/src/share/classes/java/util/OptionalInt.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/OptionalInt.java	Mon Jul 22 17:37:15 2013 -0700
@@ -186,7 +186,7 @@
     }
 
     /**
-     * Indicates whether some other object is "equal to" this Optional. The
+     * Indicates whether some other object is "equal to" this OptionalInt. The
      * other object is considered equal if:
      * <ul>
      * <li>it is also an {@code OptionalInt} and;
@@ -226,12 +226,14 @@
     }
 
     /**
-     * Returns a non-empty string representation of this OptionalInt suitable for
+     * {@inheritDoc}
+     *
+     * Returns a non-empty string representation of this object suitable for
      * debugging. The exact presentation format is unspecified and may vary
      * between implementations and versions.
      *
      * @implSpec If a value is present the result must include its string
-     * representation in the result. Empty and present OptionalInts must be
+     * representation in the result. Empty and present instances must be
      * unambiguously differentiable.
      *
      * @return the string representation of this instance
--- a/src/share/classes/java/util/OptionalLong.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/OptionalLong.java	Mon Jul 22 17:37:15 2013 -0700
@@ -186,10 +186,10 @@
     }
 
     /**
-     * Indicates whether some other object is "equal to" this Optional. The
+     * Indicates whether some other object is "equal to" this OptionalLong. The
      * other object is considered equal if:
      * <ul>
-     * <li>it is also an {@code OptionalInt} and;
+     * <li>it is also an {@code OptionalLong} and;
      * <li>both instances have no value present or;
      * <li>the present values are "equal to" each other via {@code ==}.
      * </ul>
@@ -226,12 +226,14 @@
     }
 
     /**
-     * Returns a non-empty string representation of this OptionalLong suitable for
+     * {@inheritDoc}
+     *
+     * Returns a non-empty string representation of this object suitable for
      * debugging. The exact presentation format is unspecified and may vary
      * between implementations and versions.
      *
      * @implSpec If a value is present the result must include its string
-     * representation in the result. Empty and present OptionalLongs must be
+     * representation in the result. Empty and present instances must be
      * unambiguously differentiable.
      *
      * @return the string representation of this instance
--- a/src/share/classes/java/util/ResourceBundle.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/ResourceBundle.java	Mon Jul 22 17:37:15 2013 -0700
@@ -74,7 +74,7 @@
  *
  * <p>
  * This allows you to write programs that can:
- * <UL type=SQUARE>
+ * <UL>
  * <LI> be easily localized, or translated, into different languages
  * <LI> handle multiple locales at once
  * <LI> be easily modified later to support even more locales
@@ -184,7 +184,7 @@
  * subclass.  Your subclasses must override two methods: <code>handleGetObject</code>
  * and <code>getKeys()</code>.
  *
- * <h4>ResourceBundle.Control</h4>
+ * <h3>ResourceBundle.Control</h3>
  *
  * The {@link ResourceBundle.Control} class provides information necessary
  * to perform the bundle loading process by the <code>getBundle</code>
@@ -195,7 +195,7 @@
  * {@link #getBundle(String, Locale, ClassLoader, Control) getBundle}
  * factory method for details.
  *
- * <p><a name="modify_default_behavior">For the {@code getBundle} factory
+ * <p><a name="modify_default_behavior">For the {@code getBundle} factory</a>
  * methods that take no {@link Control} instance, their <a
  * href="#default_behavior"> default behavior</a> of resource bundle loading
  * can be modified with <em>installed</em> {@link
@@ -206,7 +206,7 @@
  * more than one service provider installed for supporting the same base name,
  * the first one returned from {@link ServiceLoader} will be used.
  *
- * <h4>Cache Management</h4>
+ * <h3>Cache Management</h3>
  *
  * Resource bundle instances created by the <code>getBundle</code> factory
  * methods are cached by default, and the factory methods return the same
@@ -222,7 +222,7 @@
  * Control#needsReload(String, Locale, String, ClassLoader, ResourceBundle,
  * long) ResourceBundle.Control.needsReload} for details.
  *
- * <h4>Example</h4>
+ * <h3>Example</h3>
  *
  * The following is a very simple example of a <code>ResourceBundle</code>
  * subclass, <code>MyResources</code>, that manages two resources (for a larger number of
@@ -878,8 +878,8 @@
      * description of <a href="#modify_default_behavior">modifying the default
      * behavior</a>.
      *
-     * <p><a name="default_behavior"/>The following describes the default
-     * behavior.
+     * <p><a name="default_behavior">The following describes the default
+     * behavior</a>.
      *
      * <p><code>getBundle</code> uses the base name, the specified locale, and
      * the default locale (obtained from {@link java.util.Locale#getDefault()
@@ -974,8 +974,8 @@
      * <p>If still no result bundle is found, the base name alone is looked up. If
      * this still fails, a <code>MissingResourceException</code> is thrown.
      *
-     * <p><a name="parent_chain"/> Once a result resource bundle has been found,
-     * its <em>parent chain</em> is instantiated.  If the result bundle already
+     * <p><a name="parent_chain"> Once a result resource bundle has been found,
+     * its <em>parent chain</em> is instantiated</a>.  If the result bundle already
      * has a parent (perhaps because it was returned from a cache) the chain is
      * complete.
      *
@@ -1004,8 +1004,8 @@
      * path name (using "/") instead of a fully qualified class name (using
      * ".").
      *
-     * <p><a name="default_behavior_example"/>
-     * <strong>Example:</strong>
+     * <p><a name="default_behavior_example">
+     * <strong>Example:</strong></a>
      * <p>
      * The following class and property files are provided:
      * <pre>
@@ -1026,7 +1026,7 @@
      * <p>Calling <code>getBundle</code> with the locale arguments below will
      * instantiate resource bundles as follows:
      *
-     * <table>
+     * <table summary="getBundle() locale to resource bundle mapping">
      * <tr><td>Locale("fr", "CH")</td><td>MyResources_fr_CH.class, parent MyResources_fr.properties, parent MyResources.class</td></tr>
      * <tr><td>Locale("fr", "FR")</td><td>MyResources_fr.properties, parent MyResources.class</td></tr>
      * <tr><td>Locale("de", "DE")</td><td>MyResources_en.properties, parent MyResources.class</td></tr>
@@ -1106,45 +1106,45 @@
      * <code>control.newBundle</code>.
      *
      * <table style="width: 50%; text-align: left; margin-left: 40px;"
-     *  border="0" cellpadding="2" cellspacing="2">
-     * <tbody><code>
+     *  border="0" cellpadding="2" cellspacing="2" summary="locale-format combinations for newBundle">
+     * <tbody>
      * <tr>
      * <td
-     * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;">Locale<br>
+     * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;"><code>Locale</code><br>
      * </td>
      * <td
-     * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;">format<br>
+     * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;"><code>format</code><br>
      * </td>
      * </tr>
      * <tr>
-     * <td style="vertical-align: top; width: 50%;">Locale("de", "DE")<br>
+     * <td style="vertical-align: top; width: 50%;"><code>Locale("de", "DE")</code><br>
      * </td>
-     * <td style="vertical-align: top; width: 50%;">java.class<br>
+     * <td style="vertical-align: top; width: 50%;"><code>java.class</code><br>
      * </td>
      * </tr>
      * <tr>
-     * <td style="vertical-align: top; width: 50%;">Locale("de", "DE")</td>
-     * <td style="vertical-align: top; width: 50%;">java.properties<br>
+     * <td style="vertical-align: top; width: 50%;"><code>Locale("de", "DE")</code></td>
+     * <td style="vertical-align: top; width: 50%;"><code>java.properties</code><br>
      * </td>
      * </tr>
      * <tr>
-     * <td style="vertical-align: top; width: 50%;">Locale("de")</td>
-     * <td style="vertical-align: top; width: 50%;">java.class</td>
+     * <td style="vertical-align: top; width: 50%;"><code>Locale("de")</code></td>
+     * <td style="vertical-align: top; width: 50%;"><code>java.class</code></td>
      * </tr>
      * <tr>
-     * <td style="vertical-align: top; width: 50%;">Locale("de")</td>
-     * <td style="vertical-align: top; width: 50%;">java.properties</td>
+     * <td style="vertical-align: top; width: 50%;"><code>Locale("de")</code></td>
+     * <td style="vertical-align: top; width: 50%;"><code>java.properties</code></td>
      * </tr>
      * <tr>
-     * <td style="vertical-align: top; width: 50%;">Locale("")<br>
+     * <td style="vertical-align: top; width: 50%;"><code>Locale("")</code><br>
      * </td>
-     * <td style="vertical-align: top; width: 50%;">java.class</td>
+     * <td style="vertical-align: top; width: 50%;"><code>java.class</code></td>
      * </tr>
      * <tr>
-     * <td style="vertical-align: top; width: 50%;">Locale("")</td>
-     * <td style="vertical-align: top; width: 50%;">java.properties</td>
+     * <td style="vertical-align: top; width: 50%;"><code>Locale("")</code></td>
+     * <td style="vertical-align: top; width: 50%;"><code>java.properties</code></td>
      * </tr>
-     * </code></tbody>
+     * </tbody>
      * </table>
      * </li>
      *
@@ -2199,11 +2199,11 @@
          * one by one as below:
          *
          * <ul>
-         * <li> [<em>L</em>, <em>C</em>, <em>V</em>]
-         * <li> [<em>L</em>, <em>C</em>]
-         * <li> [<em>L</em>]
-         * <li> <code>Locale.ROOT</code>
-         * </ul>
+         * <li> [<em>L</em>, <em>C</em>, <em>V</em>] </li>
+         * <li> [<em>L</em>, <em>C</em>] </li>
+         * <li> [<em>L</em>] </li>
+         * <li> <code>Locale.ROOT</code> </li>
+         * </ul></li>
          *
          * <li>For an input <code>Locale</code> with a non-empty script value,
          * append candidate <code>Locale</code>s by omitting the final component
@@ -2211,14 +2211,14 @@
          * <code>Locale</code> with country and variant restored:
          *
          * <ul>
-         * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V</em>]
-         * <li> [<em>L</em>, <em>S</em>, <em>C</em>]
-         * <li> [<em>L</em>, <em>S</em>]
-         * <li> [<em>L</em>, <em>C</em>, <em>V</em>]
-         * <li> [<em>L</em>, <em>C</em>]
-         * <li> [<em>L</em>]
-         * <li> <code>Locale.ROOT</code>
-         * </ul>
+         * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V</em>]</li>
+         * <li> [<em>L</em>, <em>S</em>, <em>C</em>]</li>
+         * <li> [<em>L</em>, <em>S</em>]</li>
+         * <li> [<em>L</em>, <em>C</em>, <em>V</em>]</li>
+         * <li> [<em>L</em>, <em>C</em>]</li>
+         * <li> [<em>L</em>]</li>
+         * <li> <code>Locale.ROOT</code></li>
+         * </ul></li>
          *
          * <li>For an input <code>Locale</code> with a variant value consisting
          * of multiple subtags separated by underscore, generate candidate
@@ -2228,16 +2228,16 @@
          * the variant consists of two subtags <em>V1</em> and <em>V2</em>:
          *
          * <ul>
-         * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V1</em>, <em>V2</em>]
-         * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V1</em>]
-         * <li> [<em>L</em>, <em>S</em>, <em>C</em>]
-         * <li> [<em>L</em>, <em>S</em>]
-         * <li> [<em>L</em>, <em>C</em>, <em>V1</em>, <em>V2</em>]
-         * <li> [<em>L</em>, <em>C</em>, <em>V1</em>]
-         * <li> [<em>L</em>, <em>C</em>]
-         * <li> [<em>L</em>]
-         * <li> <code>Locale.ROOT</code>
-         * </ul>
+         * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V1</em>, <em>V2</em>]</li>
+         * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V1</em>]</li>
+         * <li> [<em>L</em>, <em>S</em>, <em>C</em>]</li>
+         * <li> [<em>L</em>, <em>S</em>]</li>
+         * <li> [<em>L</em>, <em>C</em>, <em>V1</em>, <em>V2</em>]</li>
+         * <li> [<em>L</em>, <em>C</em>, <em>V1</em>]</li>
+         * <li> [<em>L</em>, <em>C</em>]</li>
+         * <li> [<em>L</em>]</li>
+         * <li> <code>Locale.ROOT</code></li>
+         * </ul></li>
          *
          * <li>Special cases for Chinese.  When an input <code>Locale</code> has the
          * language "zh" (Chinese) and an empty script value, either "Hans" (Simplified) or
@@ -2248,21 +2248,21 @@
          * is empty, no script is supplied.  For example, for <code>Locale("zh", "CN")
          * </code>, the candidate list will be:
          * <ul>
-         * <li> [<em>L</em>("zh"), <em>S</em>("Hans"), <em>C</em>("CN")]
-         * <li> [<em>L</em>("zh"), <em>S</em>("Hans")]
-         * <li> [<em>L</em>("zh"), <em>C</em>("CN")]
-         * <li> [<em>L</em>("zh")]
-         * <li> <code>Locale.ROOT</code>
+         * <li> [<em>L</em>("zh"), <em>S</em>("Hans"), <em>C</em>("CN")]</li>
+         * <li> [<em>L</em>("zh"), <em>S</em>("Hans")]</li>
+         * <li> [<em>L</em>("zh"), <em>C</em>("CN")]</li>
+         * <li> [<em>L</em>("zh")]</li>
+         * <li> <code>Locale.ROOT</code></li>
          * </ul>
          *
          * For <code>Locale("zh", "TW")</code>, the candidate list will be:
          * <ul>
-         * <li> [<em>L</em>("zh"), <em>S</em>("Hant"), <em>C</em>("TW")]
-         * <li> [<em>L</em>("zh"), <em>S</em>("Hant")]
-         * <li> [<em>L</em>("zh"), <em>C</em>("TW")]
-         * <li> [<em>L</em>("zh")]
-         * <li> <code>Locale.ROOT</code>
-         * </ul>
+         * <li> [<em>L</em>("zh"), <em>S</em>("Hant"), <em>C</em>("TW")]</li>
+         * <li> [<em>L</em>("zh"), <em>S</em>("Hant")]</li>
+         * <li> [<em>L</em>("zh"), <em>C</em>("TW")]</li>
+         * <li> [<em>L</em>("zh")]</li>
+         * <li> <code>Locale.ROOT</code></li>
+         * </ul></li>
          *
          * <li>Special cases for Norwegian.  Both <code>Locale("no", "NO",
          * "NY")</code> and <code>Locale("nn", "NO")</code> represent Norwegian
@@ -2270,10 +2270,10 @@
          * list is generated up to [<em>L</em>("nn")], and then the following
          * candidates are added:
          *
-         * <ul><li> [<em>L</em>("no"), <em>C</em>("NO"), <em>V</em>("NY")]
-         * <li> [<em>L</em>("no"), <em>C</em>("NO")]
-         * <li> [<em>L</em>("no")]
-         * <li> <code>Locale.ROOT</code>
+         * <ul><li> [<em>L</em>("no"), <em>C</em>("NO"), <em>V</em>("NY")]</li>
+         * <li> [<em>L</em>("no"), <em>C</em>("NO")]</li>
+         * <li> [<em>L</em>("no")]</li>
+         * <li> <code>Locale.ROOT</code></li>
          * </ul>
          *
          * If the locale is exactly <code>Locale("no", "NO", "NY")</code>, it is first
@@ -2290,20 +2290,18 @@
          * candidate list:
          *
          * <ul>
-         * <li> [<em>L</em>("nb"), <em>C</em>("NO"), <em>V</em>("POSIX")]
-         * <li> [<em>L</em>("no"), <em>C</em>("NO"), <em>V</em>("POSIX")]
-         * <li> [<em>L</em>("nb"), <em>C</em>("NO")]
-         * <li> [<em>L</em>("no"), <em>C</em>("NO")]
-         * <li> [<em>L</em>("nb")]
-         * <li> [<em>L</em>("no")]
-         * <li> <code>Locale.ROOT</code>
+         * <li> [<em>L</em>("nb"), <em>C</em>("NO"), <em>V</em>("POSIX")]</li>
+         * <li> [<em>L</em>("no"), <em>C</em>("NO"), <em>V</em>("POSIX")]</li>
+         * <li> [<em>L</em>("nb"), <em>C</em>("NO")]</li>
+         * <li> [<em>L</em>("no"), <em>C</em>("NO")]</li>
+         * <li> [<em>L</em>("nb")]</li>
+         * <li> [<em>L</em>("no")]</li>
+         * <li> <code>Locale.ROOT</code></li>
          * </ul>
          *
          * <code>Locale("no", "NO", "POSIX")</code> would generate the same list
          * except that locales with "no" would appear before the corresponding
          * locales with "nb".</li>
-         *
-         * </li>
          * </ol>
          *
          * <p>The default implementation uses an {@link ArrayList} that
--- a/src/share/classes/java/util/ServiceLoader.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/ServiceLoader.java	Mon Jul 22 17:37:15 2013 -0700
@@ -30,6 +30,9 @@
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.net.URL;
+import java.security.AccessController;
+import java.security.AccessControlContext;
+import java.security.PrivilegedAction;
 import java.util.ArrayList;
 import java.util.Enumeration;
 import java.util.Iterator;
@@ -185,10 +188,13 @@
     private static final String PREFIX = "META-INF/services/";
 
     // The class or interface representing the service being loaded
-    private Class<S> service;
+    private final Class<S> service;
 
     // The class loader used to locate, load, and instantiate providers
-    private ClassLoader loader;
+    private final ClassLoader loader;
+
+    // The access control context taken when the ServiceLoader is created
+    private final AccessControlContext acc;
 
     // Cached providers, in instantiation order
     private LinkedHashMap<String,S> providers = new LinkedHashMap<>();
@@ -215,6 +221,7 @@
     private ServiceLoader(Class<S> svc, ClassLoader cl) {
         service = Objects.requireNonNull(svc, "Service interface cannot be null");
         loader = (cl == null) ? ClassLoader.getSystemClassLoader() : cl;
+        acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null;
         reload();
     }
 
@@ -327,7 +334,7 @@
             this.loader = loader;
         }
 
-        public boolean hasNext() {
+        private boolean hasNextService() {
             if (nextName != null) {
                 return true;
             }
@@ -352,10 +359,9 @@
             return true;
         }
 
-        public S next() {
-            if (!hasNext()) {
+        private S nextService() {
+            if (!hasNextService())
                 throw new NoSuchElementException();
-            }
             String cn = nextName;
             nextName = null;
             Class<?> c = null;
@@ -381,6 +387,28 @@
             throw new Error();          // This cannot happen
         }
 
+        public boolean hasNext() {
+            if (acc == null) {
+                return hasNextService();
+            } else {
+                PrivilegedAction<Boolean> action = new PrivilegedAction<Boolean>() {
+                    public Boolean run() { return hasNextService(); }
+                };
+                return AccessController.doPrivileged(action, acc);
+            }
+        }
+
+        public S next() {
+            if (acc == null) {
+                return nextService();
+            } else {
+                PrivilegedAction<S> action = new PrivilegedAction<S>() {
+                    public S run() { return nextService(); }
+                };
+                return AccessController.doPrivileged(action, acc);
+            }
+        }
+
         public void remove() {
             throw new UnsupportedOperationException();
         }
--- a/src/share/classes/java/util/Spliterator.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/Spliterator.java	Mon Jul 22 17:37:15 2013 -0700
@@ -62,10 +62,10 @@
  * New characteristics may be defined in the future, so implementors should not
  * assign meanings to unlisted values.
  *
- * <p><a name="binding"/>A Spliterator that does not report {@code IMMUTABLE} or
+ * <p><a name="binding">A Spliterator that does not report {@code IMMUTABLE} or
  * {@code CONCURRENT} is expected to have a documented policy concerning:
  * when the spliterator <em>binds</em> to the element source; and detection of
- * structural interference of the element source detected after binding.  A
+ * structural interference of the element source detected after binding.</a>  A
  * <em>late-binding</em> Spliterator binds to the source of elements at the
  * point of first traversal, first split, or first query for estimated size,
  * rather than at the time the Spliterator is created.  A Spliterator that is
@@ -429,6 +429,7 @@
      * The default implementation returns true if the corresponding bits
      * of the given characteristics are set.
      *
+     * @param characteristics the characteristics to check for
      * @return {@code true} if all the specified characteristics are present,
      * else {@code false}
      */
--- a/src/share/classes/java/util/Spliterators.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/Spliterators.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1314,12 +1314,7 @@
                     n = (int) s;
                 if (n > MAX_BATCH)
                     n = MAX_BATCH;
-                Object[] a;
-                try {
-                    a = new Object[n];
-                } catch (OutOfMemoryError oome) {
-                    return null;
-                }
+                Object[] a = new Object[n];
                 int j = 0;
                 do { a[j] = holder.value; } while (++j < n && tryAdvance(holder));
                 batch = j;
@@ -1429,12 +1424,7 @@
                     n = (int) s;
                 if (n > MAX_BATCH)
                     n = MAX_BATCH;
-                int[] a;
-                try {
-                    a = new int[n];
-                } catch (OutOfMemoryError oome) {
-                    return null;
-                }
+                int[] a = new int[n];
                 int j = 0;
                 do { a[j] = holder.value; } while (++j < n && tryAdvance(holder));
                 batch = j;
@@ -1544,12 +1534,7 @@
                     n = (int) s;
                 if (n > MAX_BATCH)
                     n = MAX_BATCH;
-                long[] a;
-                try {
-                    a = new long[n];
-                } catch (OutOfMemoryError oome) {
-                    return null;
-                }
+                long[] a = new long[n];
                 int j = 0;
                 do { a[j] = holder.value; } while (++j < n && tryAdvance(holder));
                 batch = j;
@@ -1659,12 +1644,7 @@
                     n = (int) s;
                 if (n > MAX_BATCH)
                     n = MAX_BATCH;
-                double[] a;
-                try {
-                    a = new double[n];
-                } catch (OutOfMemoryError oome) {
-                    return null;
-                }
+                double[] a = new double[n];
                 int j = 0;
                 do { a[j] = holder.value; } while (++j < n && tryAdvance(holder));
                 batch = j;
@@ -1795,12 +1775,7 @@
                     n = (int) s;
                 if (n > MAX_BATCH)
                     n = MAX_BATCH;
-                Object[] a;
-                try {
-                    a = new Object[n];
-                } catch (OutOfMemoryError oome) {
-                    return null;
-                }
+                Object[] a = new Object[n];
                 int j = 0;
                 do { a[j] = i.next(); } while (++j < n && i.hasNext());
                 batch = j;
@@ -1910,12 +1885,7 @@
                     n = (int) s;
                 if (n > MAX_BATCH)
                     n = MAX_BATCH;
-                int[] a;
-                try {
-                    a = new int[n];
-                } catch (OutOfMemoryError oome) {
-                    return null;
-                }
+                int[] a = new int[n];
                 int j = 0;
                 do { a[j] = i.nextInt(); } while (++j < n && i.hasNext());
                 batch = j;
@@ -2007,12 +1977,7 @@
                     n = (int) s;
                 if (n > MAX_BATCH)
                     n = MAX_BATCH;
-                long[] a;
-                try {
-                    a = new long[n];
-                } catch (OutOfMemoryError oome) {
-                    return null;
-                }
+                long[] a = new long[n];
                 int j = 0;
                 do { a[j] = i.nextLong(); } while (++j < n && i.hasNext());
                 batch = j;
@@ -2104,12 +2069,7 @@
                     n = (int) s;
                 if (n > MAX_BATCH)
                     n = MAX_BATCH;
-                double[] a;
-                try {
-                    a = new double[n];
-                } catch (OutOfMemoryError oome) {
-                    return null;
-                }
+                double[] a = new double[n];
                 int j = 0;
                 do { a[j] = i.nextDouble(); } while (++j < n && i.hasNext());
                 batch = j;
--- a/src/share/classes/java/util/StringJoiner.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/StringJoiner.java	Mon Jul 22 17:37:15 2013 -0700
@@ -114,8 +114,9 @@
      * @throws NullPointerException if {@code prefix}, {@code delimiter}, or
      *         {@code suffix} is {@code null}
      */
-    public StringJoiner(CharSequence delimiter, CharSequence prefix,
-            CharSequence suffix) {
+    public StringJoiner(CharSequence delimiter,
+                        CharSequence prefix,
+                        CharSequence suffix) {
         Objects.requireNonNull(prefix, "The prefix must not be null");
         Objects.requireNonNull(delimiter, "The delimiter must not be null");
         Objects.requireNonNull(suffix, "The suffix must not be null");
@@ -172,7 +173,7 @@
     }
 
     /**
-     * Add the a copy of the supplied {@code CharSequence} value as the next
+     * Adds a copy of the given {@code CharSequence} value as the next
      * element of the {@code StringJoiner} value. If {@code newElement} is
      * {@code null}, then {@code "null"} is added.
      *
@@ -184,6 +185,36 @@
         return this;
     }
 
+    /**
+     * Adds the contents of the given {@code StringJoiner} without prefix and
+     * suffix as the next element if it is non-empty. If the given {@code
+     * StringJoiner} is empty, the call has no effect.
+     *
+     * <p>A {@code StringJoiner} is empty if {@link #add(CharSequence) add()}
+     * has never been called, and if {@code merge()} has never been called
+     * with a non-empty {@code StringJoiner} argument.
+     *
+     * <p>If the other {@code StringJoiner} is using a different delimiter,
+     * then elements from the other {@code StringJoiner} are concatenated with
+     * that delimiter and the result is appended to this {@code StringJoiner}
+     * as a single element.
+     *
+     * @param other The {@code StringJoiner} whose contents should be merged
+     *              into this one
+     * @throws NullPointerException if the other {@code StringJoiner} is null
+     */
+    public StringJoiner merge(StringJoiner other) {
+        Objects.requireNonNull(other);
+        if (other.value != null) {
+            StringBuilder builder = prepareBuilder();
+            StringBuilder otherBuilder = other.value;
+            if (other.prefix.length() < otherBuilder.length()) {
+                builder.append(otherBuilder, other.prefix.length(), otherBuilder.length());
+            }
+        }
+        return this;
+    }
+
     private StringBuilder prepareBuilder() {
         if (value != null) {
             value.append(delimiter);
--- a/src/share/classes/java/util/concurrent/AbstractExecutorService.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/AbstractExecutorService.java	Mon Jul 22 17:37:15 2013 -0700
@@ -38,19 +38,19 @@
 
 /**
  * Provides default implementations of {@link ExecutorService}
- * execution methods. This class implements the <tt>submit</tt>,
- * <tt>invokeAny</tt> and <tt>invokeAll</tt> methods using a
- * {@link RunnableFuture} returned by <tt>newTaskFor</tt>, which defaults
+ * execution methods. This class implements the {@code submit},
+ * {@code invokeAny} and {@code invokeAll} methods using a
+ * {@link RunnableFuture} returned by {@code newTaskFor}, which defaults
  * to the {@link FutureTask} class provided in this package.  For example,
- * the implementation of <tt>submit(Runnable)</tt> creates an
- * associated <tt>RunnableFuture</tt> that is executed and
- * returned. Subclasses may override the <tt>newTaskFor</tt> methods
- * to return <tt>RunnableFuture</tt> implementations other than
- * <tt>FutureTask</tt>.
+ * the implementation of {@code submit(Runnable)} creates an
+ * associated {@code RunnableFuture} that is executed and
+ * returned. Subclasses may override the {@code newTaskFor} methods
+ * to return {@code RunnableFuture} implementations other than
+ * {@code FutureTask}.
  *
- * <p> <b>Extension example</b>. Here is a sketch of a class
+ * <p><b>Extension example</b>. Here is a sketch of a class
  * that customizes {@link ThreadPoolExecutor} to use
- * a <tt>CustomTask</tt> class instead of the default <tt>FutureTask</tt>:
+ * a {@code CustomTask} class instead of the default {@code FutureTask}:
  *  <pre> {@code
  * public class CustomThreadPoolExecutor extends ThreadPoolExecutor {
  *
@@ -71,15 +71,15 @@
 public abstract class AbstractExecutorService implements ExecutorService {
 
     /**
-     * Returns a <tt>RunnableFuture</tt> for the given runnable and default
+     * Returns a {@code RunnableFuture} for the given runnable and default
      * value.
      *
      * @param runnable the runnable task being wrapped
      * @param value the default value for the returned future
-     * @return a <tt>RunnableFuture</tt> which when run will run the
-     * underlying runnable and which, as a <tt>Future</tt>, will yield
+     * @return a {@code RunnableFuture} which, when run, will run the
+     * underlying runnable and which, as a {@code Future}, will yield
      * the given value as its result and provide for cancellation of
-     * the underlying task.
+     * the underlying task
      * @since 1.6
      */
     protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
@@ -87,13 +87,13 @@
     }
 
     /**
-     * Returns a <tt>RunnableFuture</tt> for the given callable task.
+     * Returns a {@code RunnableFuture} for the given callable task.
      *
      * @param callable the callable task being wrapped
-     * @return a <tt>RunnableFuture</tt> which when run will call the
-     * underlying callable and which, as a <tt>Future</tt>, will yield
+     * @return a {@code RunnableFuture} which, when run, will call the
+     * underlying callable and which, as a {@code Future}, will yield
      * the callable's result as its result and provide for
-     * cancellation of the underlying task.
+     * cancellation of the underlying task
      * @since 1.6
      */
     protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
@@ -144,7 +144,7 @@
         int ntasks = tasks.size();
         if (ntasks == 0)
             throw new IllegalArgumentException();
-        List<Future<T>> futures= new ArrayList<Future<T>>(ntasks);
+        ArrayList<Future<T>> futures = new ArrayList<Future<T>>(ntasks);
         ExecutorCompletionService<T> ecs =
             new ExecutorCompletionService<T>(this);
 
@@ -202,8 +202,8 @@
             throw ee;
 
         } finally {
-            for (Future<T> f : futures)
-                f.cancel(true);
+            for (int i = 0, size = futures.size(); i < size; i++)
+                futures.get(i).cancel(true);
         }
     }
 
@@ -227,7 +227,7 @@
         throws InterruptedException {
         if (tasks == null)
             throw new NullPointerException();
-        List<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
+        ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
         boolean done = false;
         try {
             for (Callable<T> t : tasks) {
@@ -235,7 +235,8 @@
                 futures.add(f);
                 execute(f);
             }
-            for (Future<T> f : futures) {
+            for (int i = 0, size = futures.size(); i < size; i++) {
+                Future<T> f = futures.get(i);
                 if (!f.isDone()) {
                     try {
                         f.get();
@@ -248,8 +249,8 @@
             return futures;
         } finally {
             if (!done)
-                for (Future<T> f : futures)
-                    f.cancel(true);
+                for (int i = 0, size = futures.size(); i < size; i++)
+                    futures.get(i).cancel(true);
         }
     }
 
@@ -259,25 +260,26 @@
         if (tasks == null)
             throw new NullPointerException();
         long nanos = unit.toNanos(timeout);
-        List<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
+        ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
         boolean done = false;
         try {
             for (Callable<T> t : tasks)
                 futures.add(newTaskFor(t));
 
             final long deadline = System.nanoTime() + nanos;
+            final int size = futures.size();
 
             // Interleave time checks and calls to execute in case
             // executor doesn't have any/much parallelism.
-            Iterator<Future<T>> it = futures.iterator();
-            while (it.hasNext()) {
-                execute((Runnable)(it.next()));
+            for (int i = 0; i < size; i++) {
+                execute((Runnable)futures.get(i));
                 nanos = deadline - System.nanoTime();
                 if (nanos <= 0L)
                     return futures;
             }
 
-            for (Future<T> f : futures) {
+            for (int i = 0; i < size; i++) {
+                Future<T> f = futures.get(i);
                 if (!f.isDone()) {
                     if (nanos <= 0L)
                         return futures;
@@ -295,8 +297,8 @@
             return futures;
         } finally {
             if (!done)
-                for (Future<T> f : futures)
-                    f.cancel(true);
+                for (int i = 0, size = futures.size(); i < size; i++)
+                    futures.get(i).cancel(true);
         }
     }
 
--- a/src/share/classes/java/util/concurrent/ArrayBlockingQueue.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/ArrayBlockingQueue.java	Mon Jul 22 17:37:15 2013 -0700
@@ -34,8 +34,15 @@
  */
 
 package java.util.concurrent;
-import java.util.concurrent.locks.*;
-import java.util.*;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.AbstractQueue;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.lang.ref.WeakReference;
+import java.util.Spliterators;
+import java.util.Spliterator;
 
 /**
  * A bounded {@linkplain BlockingQueue blocking queue} backed by an
@@ -102,19 +109,21 @@
 
     /** Main lock guarding all access */
     final ReentrantLock lock;
+
     /** Condition for waiting takes */
     private final Condition notEmpty;
+
     /** Condition for waiting puts */
     private final Condition notFull;
 
-    // Internal helper methods
+    /**
+     * Shared state for currently active iterators, or null if there
+     * are known not to be any.  Allows queue operations to update
+     * iterator state.
+     */
+    transient Itrs itrs = null;
 
-    /**
-     * Circularly increment i.
-     */
-    final int inc(int i) {
-        return (++i == items.length) ? 0 : i;
-    }
+    // Internal helper methods
 
     /**
      * Circularly decrement i.
@@ -123,11 +132,6 @@
         return ((i == 0) ? items.length : i) - 1;
     }
 
-    @SuppressWarnings("unchecked")
-    static <E> E cast(Object item) {
-        return (E) item;
-    }
-
     /**
      * Returns item at index i.
      */
@@ -150,10 +154,14 @@
      * Inserts element at current put position, advances, and signals.
      * Call only when holding lock.
      */
-    private void insert(E x) {
+    private void enqueue(E x) {
+        // assert lock.getHoldCount() == 1;
+        // assert items[putIndex] == null;
+        final Object[] items = this.items;
         items[putIndex] = x;
-        putIndex = inc(putIndex);
-        ++count;
+        if (++putIndex == items.length)
+            putIndex = 0;
+        count++;
         notEmpty.signal();
     }
 
@@ -161,43 +169,62 @@
      * Extracts element at current take position, advances, and signals.
      * Call only when holding lock.
      */
-    private E extract() {
+    private E dequeue() {
+        // assert lock.getHoldCount() == 1;
+        // assert items[takeIndex] != null;
         final Object[] items = this.items;
         @SuppressWarnings("unchecked")
         E x = (E) items[takeIndex];
         items[takeIndex] = null;
-        takeIndex = inc(takeIndex);
-        --count;
+        if (++takeIndex == items.length)
+            takeIndex = 0;
+        count--;
+        if (itrs != null)
+            itrs.elementDequeued();
         notFull.signal();
         return x;
     }
 
     /**
-     * Deletes item at position i.
-     * Utility for remove and iterator.remove.
+     * Deletes item at array index removeIndex.
+     * Utility for remove(Object) and iterator.remove.
      * Call only when holding lock.
      */
-    void removeAt(int i) {
+    void removeAt(final int removeIndex) {
+        // assert lock.getHoldCount() == 1;
+        // assert items[removeIndex] != null;
+        // assert removeIndex >= 0 && removeIndex < items.length;
         final Object[] items = this.items;
-        // if removing front item, just advance
-        if (i == takeIndex) {
+        if (removeIndex == takeIndex) {
+            // removing front item; just advance
             items[takeIndex] = null;
-            takeIndex = inc(takeIndex);
+            if (++takeIndex == items.length)
+                takeIndex = 0;
+            count--;
+            if (itrs != null)
+                itrs.elementDequeued();
         } else {
+            // an "interior" remove
+
             // slide over all others up through putIndex.
-            for (;;) {
-                int nexti = inc(i);
-                if (nexti != putIndex) {
-                    items[i] = items[nexti];
-                    i = nexti;
+            final int putIndex = this.putIndex;
+            for (int i = removeIndex;;) {
+                int next = i + 1;
+                if (next == items.length)
+                    next = 0;
+                if (next != putIndex) {
+                    items[i] = items[next];
+                    i = next;
                 } else {
                     items[i] = null;
-                    putIndex = i;
+                    this.putIndex = i;
                     break;
                 }
             }
+            count--;
+            if (itrs != null)
+                itrs.removedAt(removeIndex);
         }
-        --count;
         notFull.signal();
     }
 
@@ -302,7 +329,7 @@
             if (count == items.length)
                 return false;
             else {
-                insert(e);
+                enqueue(e);
                 return true;
             }
         } finally {
@@ -324,7 +351,7 @@
         try {
             while (count == items.length)
                 notFull.await();
-            insert(e);
+            enqueue(e);
         } finally {
             lock.unlock();
         }
@@ -351,7 +378,7 @@
                     return false;
                 nanos = notFull.awaitNanos(nanos);
             }
-            insert(e);
+            enqueue(e);
             return true;
         } finally {
             lock.unlock();
@@ -362,7 +389,7 @@
         final ReentrantLock lock = this.lock;
         lock.lock();
         try {
-            return (count == 0) ? null : extract();
+            return (count == 0) ? null : dequeue();
         } finally {
             lock.unlock();
         }
@@ -374,7 +401,7 @@
         try {
             while (count == 0)
                 notEmpty.await();
-            return extract();
+            return dequeue();
         } finally {
             lock.unlock();
         }
@@ -390,7 +417,7 @@
                     return null;
                 nanos = notEmpty.awaitNanos(nanos);
             }
-            return extract();
+            return dequeue();
         } finally {
             lock.unlock();
         }
@@ -400,7 +427,7 @@
         final ReentrantLock lock = this.lock;
         lock.lock();
         try {
-            return (count == 0) ? null : itemAt(takeIndex);
+            return itemAt(takeIndex); // null when queue is empty
         } finally {
             lock.unlock();
         }
@@ -469,11 +496,17 @@
         final ReentrantLock lock = this.lock;
         lock.lock();
         try {
-            for (int i = takeIndex, k = count; k > 0; i = inc(i), k--) {
-                if (o.equals(items[i])) {
-                    removeAt(i);
-                    return true;
-                }
+            if (count > 0) {
+                final int putIndex = this.putIndex;
+                int i = takeIndex;
+                do {
+                    if (o.equals(items[i])) {
+                        removeAt(i);
+                        return true;
+                    }
+                    if (++i == items.length)
+                        i = 0;
+                } while (i != putIndex);
             }
             return false;
         } finally {
@@ -495,9 +528,16 @@
         final ReentrantLock lock = this.lock;
         lock.lock();
         try {
-            for (int i = takeIndex, k = count; k > 0; i = inc(i), k--)
-                if (o.equals(items[i]))
-                    return true;
+            if (count > 0) {
+                final int putIndex = this.putIndex;
+                int i = takeIndex;
+                do {
+                    if (o.equals(items[i]))
+                        return true;
+                    if (++i == items.length)
+                        i = 0;
+                } while (i != putIndex);
+            }
             return false;
         } finally {
             lock.unlock();
@@ -518,18 +558,23 @@
      * @return an array containing all of the elements in this queue
      */
     public Object[] toArray() {
-        final Object[] items = this.items;
+        Object[] a;
         final ReentrantLock lock = this.lock;
         lock.lock();
         try {
             final int count = this.count;
-            Object[] a = new Object[count];
-            for (int i = takeIndex, k = 0; k < count; i = inc(i), k++)
-                a[k] = items[i];
-            return a;
+            a = new Object[count];
+            int n = items.length - takeIndex;
+            if (count <= n)
+                System.arraycopy(items, takeIndex, a, 0, count);
+            else {
+                System.arraycopy(items, takeIndex, a, 0, n);
+                System.arraycopy(items, 0, a, n, count - n);
+            }
         } finally {
             lock.unlock();
         }
+        return a;
     }
 
     /**
@@ -553,8 +598,7 @@
      * The following code can be used to dump the queue into a newly
      * allocated array of {@code String}:
      *
-     * <pre>
-     *     String[] y = x.toArray(new String[0]);</pre>
+     *  <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
      *
      * Note that {@code toArray(new Object[0])} is identical in function to
      * {@code toArray()}.
@@ -579,14 +623,19 @@
             if (len < count)
                 a = (T[])java.lang.reflect.Array.newInstance(
                     a.getClass().getComponentType(), count);
-            for (int i = takeIndex, k = 0; k < count; i = inc(i), k++)
-                a[k] = (T) items[i];
+            int n = items.length - takeIndex;
+            if (count <= n)
+                System.arraycopy(items, takeIndex, a, 0, count);
+            else {
+                System.arraycopy(items, takeIndex, a, 0, n);
+                System.arraycopy(items, 0, a, n, count - n);
+            }
             if (len > count)
                 a[count] = null;
-            return a;
         } finally {
             lock.unlock();
         }
+        return a;
     }
 
     public String toString() {
@@ -597,14 +646,17 @@
             if (k == 0)
                 return "[]";
 
+            final Object[] items = this.items;
             StringBuilder sb = new StringBuilder();
             sb.append('[');
-            for (int i = takeIndex; ; i = inc(i)) {
+            for (int i = takeIndex; ; ) {
                 Object e = items[i];
                 sb.append(e == this ? "(this Collection)" : e);
                 if (--k == 0)
                     return sb.append(']').toString();
                 sb.append(',').append(' ');
+                if (++i == items.length)
+                    i = 0;
             }
         } finally {
             lock.unlock();
@@ -620,12 +672,22 @@
         final ReentrantLock lock = this.lock;
         lock.lock();
         try {
-            for (int i = takeIndex, k = count; k > 0; i = inc(i), k--)
-                items[i] = null;
-            count = 0;
-            putIndex = 0;
-            takeIndex = 0;
-            notFull.signalAll();
+            int k = count;
+            if (k > 0) {
+                final int putIndex = this.putIndex;
+                int i = takeIndex;
+                do {
+                    items[i] = null;
+                    if (++i == items.length)
+                        i = 0;
+                } while (i != putIndex);
+                takeIndex = putIndex;
+                count = 0;
+                if (itrs != null)
+                    itrs.queueIsEmpty();
+                for (; k > 0 && lock.hasWaiters(notFull); k--)
+                    notFull.signal();
+            }
         } finally {
             lock.unlock();
         }
@@ -638,34 +700,7 @@
      * @throws IllegalArgumentException      {@inheritDoc}
      */
     public int drainTo(Collection<? super E> c) {
-        checkNotNull(c);
-        if (c == this)
-            throw new IllegalArgumentException();
-        final Object[] items = this.items;
-        final ReentrantLock lock = this.lock;
-        lock.lock();
-        try {
-            int i = takeIndex;
-            int n = 0;
-            int max = count;
-            while (n < max) {
-                @SuppressWarnings("unchecked")
-                E x = (E) items[i];
-                c.add(x);
-                items[i] = null;
-                i = inc(i);
-                ++n;
-            }
-            if (n > 0) {
-                count = 0;
-                putIndex = 0;
-                takeIndex = 0;
-                notFull.signalAll();
-            }
-            return n;
-        } finally {
-            lock.unlock();
-        }
+        return drainTo(c, Integer.MAX_VALUE);
     }
 
     /**
@@ -684,23 +719,35 @@
         final ReentrantLock lock = this.lock;
         lock.lock();
         try {
-            int i = takeIndex;
-            int n = 0;
-            int max = (maxElements < count) ? maxElements : count;
-            while (n < max) {
-                @SuppressWarnings("unchecked")
-                E x = (E) items[i];
-                c.add(x);
-                items[i] = null;
-                i = inc(i);
-                ++n;
+            int n = Math.min(maxElements, count);
+            int take = takeIndex;
+            int i = 0;
+            try {
+                while (i < n) {
+                    @SuppressWarnings("unchecked")
+                    E x = (E) items[take];
+                    c.add(x);
+                    items[take] = null;
+                    if (++take == items.length)
+                        take = 0;
+                    i++;
+                }
+                return n;
+            } finally {
+                // Restore invariants even if c.add() threw
+                if (i > 0) {
+                    count -= i;
+                    takeIndex = take;
+                    if (itrs != null) {
+                        if (count == 0)
+                            itrs.queueIsEmpty();
+                        else if (i > take)
+                            itrs.takeIndexWrapped();
+                    }
+                    for (; i > 0 && lock.hasWaiters(notFull); i--)
+                        notFull.signal();
+                }
             }
-            if (n > 0) {
-                count -= n;
-                takeIndex = i;
-                notFull.signalAll();
-            }
-            return n;
         } finally {
             lock.unlock();
         }
@@ -710,12 +757,12 @@
      * Returns an iterator over the elements in this queue in proper sequence.
      * The elements will be returned in order from first (head) to last (tail).
      *
-     * <p>The returned {@code Iterator} is a "weakly consistent" iterator that
+     * <p>The returned iterator is a "weakly consistent" iterator that
      * will never throw {@link java.util.ConcurrentModificationException
-     * ConcurrentModificationException},
-     * and guarantees to traverse elements as they existed upon
-     * construction of the iterator, and may (but is not guaranteed to)
-     * reflect any modifications subsequent to construction.
+     * ConcurrentModificationException}, and guarantees to traverse
+     * elements as they existed upon construction of the iterator, and
+     * may (but is not guaranteed to) reflect any modifications
+     * subsequent to construction.
      *
      * @return an iterator over the elements in this queue in proper sequence
      */
@@ -724,88 +771,634 @@
     }
 
     /**
-     * Iterator for ArrayBlockingQueue. To maintain weak consistency
-     * with respect to puts and takes, we (1) read ahead one slot, so
-     * as to not report hasNext true but then not have an element to
-     * return -- however we later recheck this slot to use the most
-     * current value; (2) ensure that each array slot is traversed at
-     * most once (by tracking "remaining" elements); (3) skip over
-     * null slots, which can occur if takes race ahead of iterators.
-     * However, for circular array-based queues, we cannot rely on any
-     * well established definition of what it means to be weakly
-     * consistent with respect to interior removes since these may
-     * require slot overwrites in the process of sliding elements to
-     * cover gaps. So we settle for resiliency, operating on
-     * established apparent nexts, which may miss some elements that
-     * have moved between calls to next.
+     * Shared data between iterators and their queue, allowing queue
+     * modifications to update iterators when elements are removed.
+     *
+     * This adds a lot of complexity for the sake of correctly
+     * handling some uncommon operations, but the combination of
+     * circular-arrays and supporting interior removes (i.e., those
+     * not at head) would cause iterators to sometimes lose their
+     * places and/or (re)report elements they shouldn't.  To avoid
+     * this, when a queue has one or more iterators, it keeps iterator
+     * state consistent by:
+     *
+     * (1) keeping track of the number of "cycles", that is, the
+     *     number of times takeIndex has wrapped around to 0.
+     * (2) notifying all iterators via the callback removedAt whenever
+     *     an interior element is removed (and thus other elements may
+     *     be shifted).
+     *
+     * These suffice to eliminate iterator inconsistencies, but
+     * unfortunately add the secondary responsibility of maintaining
+     * the list of iterators.  We track all active iterators in a
+     * simple linked list (accessed only when the queue's lock is
+     * held) of weak references to Itr.  The list is cleaned up using
+     * 3 different mechanisms:
+     *
+     * (1) Whenever a new iterator is created, do some O(1) checking for
+     *     stale list elements.
+     *
+     * (2) Whenever takeIndex wraps around to 0, check for iterators
+     *     that have been unused for more than one wrap-around cycle.
+     *
+     * (3) Whenever the queue becomes empty, all iterators are notified
+     *     and this entire data structure is discarded.
+     *
+     * So in addition to the removedAt callback that is necessary for
+     * correctness, iterators have the shutdown and takeIndexWrapped
+     * callbacks that help remove stale iterators from the list.
+     *
+     * Whenever a list element is examined, it is expunged if either
+     * the GC has determined that the iterator is discarded, or if the
+     * iterator reports that it is "detached" (does not need any
+     * further state updates).  Overhead is maximal when takeIndex
+     * never advances, iterators are discarded before they are
+     * exhausted, and all removals are interior removes, in which case
+     * all stale iterators are discovered by the GC.  But even in this
+     * case we don't increase the amortized complexity.
+     *
+     * Care must be taken to keep list sweeping methods from
+     * reentrantly invoking another such method, causing subtle
+     * corruption bugs.
+     */
+    class Itrs {
+
+        /**
+         * Node in a linked list of weak iterator references.
+         */
+        private class Node extends WeakReference<Itr> {
+            Node next;
+
+            Node(Itr iterator, Node next) {
+                super(iterator);
+                this.next = next;
+            }
+        }
+
+        /** Incremented whenever takeIndex wraps around to 0 */
+        int cycles = 0;
+
+        /** Linked list of weak iterator references */
+        private Node head;
+
+        /** Used to expunge stale iterators */
+        private Node sweeper = null;
+
+        private static final int SHORT_SWEEP_PROBES = 4;
+        private static final int LONG_SWEEP_PROBES = 16;
+
+        Itrs(Itr initial) {
+            register(initial);
+        }
+
+        /**
+         * Sweeps itrs, looking for and expunging stale iterators.
+         * If at least one was found, tries harder to find more.
+         * Called only from iterating thread.
+         *
+         * @param tryHarder whether to start in try-harder mode, because
+         * there is known to be at least one iterator to collect
+         */
+        void doSomeSweeping(boolean tryHarder) {
+            // assert lock.getHoldCount() == 1;
+            // assert head != null;
+            int probes = tryHarder ? LONG_SWEEP_PROBES : SHORT_SWEEP_PROBES;
+            Node o, p;
+            final Node sweeper = this.sweeper;
+            boolean passedGo;   // to limit search to one full sweep
+
+            if (sweeper == null) {
+                o = null;
+                p = head;
+                passedGo = true;
+            } else {
+                o = sweeper;
+                p = o.next;
+                passedGo = false;
+            }
+
+            for (; probes > 0; probes--) {
+                if (p == null) {
+                    if (passedGo)
+                        break;
+                    o = null;
+                    p = head;
+                    passedGo = true;
+                }
+                final Itr it = p.get();
+                final Node next = p.next;
+                if (it == null || it.isDetached()) {
+                    // found a discarded/exhausted iterator
+                    probes = LONG_SWEEP_PROBES; // "try harder"
+                    // unlink p
+                    p.clear();
+                    p.next = null;
+                    if (o == null) {
+                        head = next;
+                        if (next == null) {
+                            // We've run out of iterators to track; retire
+                            itrs = null;
+                            return;
+                        }
+                    }
+                    else
+                        o.next = next;
+                } else {
+                    o = p;
+                }
+                p = next;
+            }
+
+            this.sweeper = (p == null) ? null : o;
+        }
+
+        /**
+         * Adds a new iterator to the linked list of tracked iterators.
+         */
+        void register(Itr itr) {
+            // assert lock.getHoldCount() == 1;
+            head = new Node(itr, head);
+        }
+
+        /**
+         * Called whenever takeIndex wraps around to 0.
+         *
+         * Notifies all iterators, and expunges any that are now stale.
+         */
+        void takeIndexWrapped() {
+            // assert lock.getHoldCount() == 1;
+            cycles++;
+            for (Node o = null, p = head; p != null;) {
+                final Itr it = p.get();
+                final Node next = p.next;
+                if (it == null || it.takeIndexWrapped()) {
+                    // unlink p
+                    // assert it == null || it.isDetached();
+                    p.clear();
+                    p.next = null;
+                    if (o == null)
+                        head = next;
+                    else
+                        o.next = next;
+                } else {
+                    o = p;
+                }
+                p = next;
+            }
+            if (head == null)   // no more iterators to track
+                itrs = null;
+        }
+
+        /**
+         * Called whenever an interior remove (not at takeIndex) occured.
+         *
+         * Notifies all iterators, and expunges any that are now stale.
+         */
+        void removedAt(int removedIndex) {
+            for (Node o = null, p = head; p != null;) {
+                final Itr it = p.get();
+                final Node next = p.next;
+                if (it == null || it.removedAt(removedIndex)) {
+                    // unlink p
+                    // assert it == null || it.isDetached();
+                    p.clear();
+                    p.next = null;
+                    if (o == null)
+                        head = next;
+                    else
+                        o.next = next;
+                } else {
+                    o = p;
+                }
+                p = next;
+            }
+            if (head == null)   // no more iterators to track
+                itrs = null;
+        }
+
+        /**
+         * Called whenever the queue becomes empty.
+         *
+         * Notifies all active iterators that the queue is empty,
+         * clears all weak refs, and unlinks the itrs datastructure.
+         */
+        void queueIsEmpty() {
+            // assert lock.getHoldCount() == 1;
+            for (Node p = head; p != null; p = p.next) {
+                Itr it = p.get();
+                if (it != null) {
+                    p.clear();
+                    it.shutdown();
+                }
+            }
+            head = null;
+            itrs = null;
+        }
+
+        /**
+         * Called whenever an element has been dequeued (at takeIndex).
+         */
+        void elementDequeued() {
+            // assert lock.getHoldCount() == 1;
+            if (count == 0)
+                queueIsEmpty();
+            else if (takeIndex == 0)
+                takeIndexWrapped();
+        }
+    }
+
+    /**
+     * Iterator for ArrayBlockingQueue.
+     *
+     * To maintain weak consistency with respect to puts and takes, we
+     * read ahead one slot, so as to not report hasNext true but then
+     * not have an element to return.
+     *
+     * We switch into "detached" mode (allowing prompt unlinking from
+     * itrs without help from the GC) when all indices are negative, or
+     * when hasNext returns false for the first time.  This allows the
+     * iterator to track concurrent updates completely accurately,
+     * except for the corner case of the user calling Iterator.remove()
+     * after hasNext() returned false.  Even in this case, we ensure
+     * that we don't remove the wrong element by keeping track of the
+     * expected element to remove, in lastItem.  Yes, we may fail to
+     * remove lastItem from the queue if it moved due to an interleaved
+     * interior remove while in detached mode.
      */
     private class Itr implements Iterator<E> {
-        private int remaining; // Number of elements yet to be returned
-        private int nextIndex; // Index of element to be returned by next
-        private E nextItem;    // Element to be returned by next call to next
-        private E lastItem;    // Element returned by last call to next
-        private int lastRet;   // Index of last element returned, or -1 if none
+        /** Index to look for new nextItem; NONE at end */
+        private int cursor;
+
+        /** Element to be returned by next call to next(); null if none */
+        private E nextItem;
+
+        /** Index of nextItem; NONE if none, REMOVED if removed elsewhere */
+        private int nextIndex;
+
+        /** Last element returned; null if none or not detached. */
+        private E lastItem;
+
+        /** Index of lastItem, NONE if none, REMOVED if removed elsewhere */
+        private int lastRet;
+
+        /** Previous value of takeIndex, or DETACHED when detached */
+        private int prevTakeIndex;
+
+        /** Previous value of iters.cycles */
+        private int prevCycles;
+
+        /** Special index value indicating "not available" or "undefined" */
+        private static final int NONE = -1;
+
+        /**
+         * Special index value indicating "removed elsewhere", that is,
+         * removed by some operation other than a call to this.remove().
+         */
+        private static final int REMOVED = -2;
+
+        /** Special value for prevTakeIndex indicating "detached mode" */
+        private static final int DETACHED = -3;
 
         Itr() {
+            // assert lock.getHoldCount() == 0;
+            lastRet = NONE;
             final ReentrantLock lock = ArrayBlockingQueue.this.lock;
             lock.lock();
             try {
-                lastRet = -1;
-                if ((remaining = count) > 0)
+                if (count == 0) {
+                    // assert itrs == null;
+                    cursor = NONE;
+                    nextIndex = NONE;
+                    prevTakeIndex = DETACHED;
+                } else {
+                    final int takeIndex = ArrayBlockingQueue.this.takeIndex;
+                    prevTakeIndex = takeIndex;
                     nextItem = itemAt(nextIndex = takeIndex);
+                    cursor = incCursor(takeIndex);
+                    if (itrs == null) {
+                        itrs = new Itrs(this);
+                    } else {
+                        itrs.register(this); // in this order
+                        itrs.doSomeSweeping(false);
+                    }
+                    prevCycles = itrs.cycles;
+                    // assert takeIndex >= 0;
+                    // assert prevTakeIndex == takeIndex;
+                    // assert nextIndex >= 0;
+                    // assert nextItem != null;
+                }
             } finally {
                 lock.unlock();
             }
         }
 
-        public boolean hasNext() {
-            return remaining > 0;
+        boolean isDetached() {
+            // assert lock.getHoldCount() == 1;
+            return prevTakeIndex < 0;
+        }
+
+        private int incCursor(int index) {
+            // assert lock.getHoldCount() == 1;
+            if (++index == items.length)
+                index = 0;
+            if (index == putIndex)
+                index = NONE;
+            return index;
+        }
+
+        /**
+         * Returns true if index is invalidated by the given number of
+         * dequeues, starting from prevTakeIndex.
+         */
+        private boolean invalidated(int index, int prevTakeIndex,
+                                    long dequeues, int length) {
+            if (index < 0)
+                return false;
+            int distance = index - prevTakeIndex;
+            if (distance < 0)
+                distance += length;
+            return dequeues > distance;
         }
 
-        public E next() {
+        /**
+         * Adjusts indices to incorporate all dequeues since the last
+         * operation on this iterator.  Call only from iterating thread.
+         */
+        private void incorporateDequeues() {
+            // assert lock.getHoldCount() == 1;
+            // assert itrs != null;
+            // assert !isDetached();
+            // assert count > 0;
+
+            final int cycles = itrs.cycles;
+            final int takeIndex = ArrayBlockingQueue.this.takeIndex;
+            final int prevCycles = this.prevCycles;
+            final int prevTakeIndex = this.prevTakeIndex;
+
+            if (cycles != prevCycles || takeIndex != prevTakeIndex) {
+                final int len = items.length;
+                // how far takeIndex has advanced since the previous
+                // operation of this iterator
+                long dequeues = (cycles - prevCycles) * len
+                    + (takeIndex - prevTakeIndex);
+
+                // Check indices for invalidation
+                if (invalidated(lastRet, prevTakeIndex, dequeues, len))
+                    lastRet = REMOVED;
+                if (invalidated(nextIndex, prevTakeIndex, dequeues, len))
+                    nextIndex = REMOVED;
+                if (invalidated(cursor, prevTakeIndex, dequeues, len))
+                    cursor = takeIndex;
+
+                if (cursor < 0 && nextIndex < 0 && lastRet < 0)
+                    detach();
+                else {
+                    this.prevCycles = cycles;
+                    this.prevTakeIndex = takeIndex;
+                }
+            }
+        }
+
+        /**
+         * Called when itrs should stop tracking this iterator, either
+         * because there are no more indices to update (cursor < 0 &&
+         * nextIndex < 0 && lastRet < 0) or as a special exception, when
+         * lastRet >= 0, because hasNext() is about to return false for the
+         * first time.  Call only from iterating thread.
+         */
+        private void detach() {
+            // Switch to detached mode
+            // assert lock.getHoldCount() == 1;
+            // assert cursor == NONE;
+            // assert nextIndex < 0;
+            // assert lastRet < 0 || nextItem == null;
+            // assert lastRet < 0 ^ lastItem != null;
+            if (prevTakeIndex >= 0) {
+                // assert itrs != null;
+                prevTakeIndex = DETACHED;
+                // try to unlink from itrs (but not too hard)
+                itrs.doSomeSweeping(true);
+            }
+        }
+
+        /**
+         * For performance reasons, we would like not to acquire a lock in
+         * hasNext in the common case.  To allow for this, we only access
+         * fields (i.e. nextItem) that are not modified by update operations
+         * triggered by queue modifications.
+         */
+        public boolean hasNext() {
+            // assert lock.getHoldCount() == 0;
+            if (nextItem != null)
+                return true;
+            noNext();
+            return false;
+        }
+
+        private void noNext() {
             final ReentrantLock lock = ArrayBlockingQueue.this.lock;
             lock.lock();
             try {
-                if (remaining <= 0)
-                    throw new NoSuchElementException();
-                lastRet = nextIndex;
-                E x = itemAt(nextIndex);  // check for fresher value
-                if (x == null) {
-                    x = nextItem;         // we are forced to report old value
-                    lastItem = null;      // but ensure remove fails
+                // assert cursor == NONE;
+                // assert nextIndex == NONE;
+                if (!isDetached()) {
+                    // assert lastRet >= 0;
+                    incorporateDequeues(); // might update lastRet
+                    if (lastRet >= 0) {
+                        lastItem = itemAt(lastRet);
+                        // assert lastItem != null;
+                        detach();
+                    }
                 }
-                else
-                    lastItem = x;
-                while (--remaining > 0 && // skip over nulls
-                       (nextItem = itemAt(nextIndex = inc(nextIndex))) == null)
-                    ;
-                return x;
+                // assert isDetached();
+                // assert lastRet < 0 ^ lastItem != null;
             } finally {
                 lock.unlock();
             }
         }
 
-        public void remove() {
+        public E next() {
+            // assert lock.getHoldCount() == 0;
+            final E x = nextItem;
+            if (x == null)
+                throw new NoSuchElementException();
             final ReentrantLock lock = ArrayBlockingQueue.this.lock;
             lock.lock();
             try {
-                int i = lastRet;
-                if (i == -1)
-                    throw new IllegalStateException();
-                lastRet = -1;
-                E x = lastItem;
-                lastItem = null;
-                // only remove if item still at index
-                if (x != null && x == items[i]) {
-                    boolean removingHead = (i == takeIndex);
-                    removeAt(i);
-                    if (!removingHead)
-                        nextIndex = dec(nextIndex);
+                if (!isDetached())
+                    incorporateDequeues();
+                // assert nextIndex != NONE;
+                // assert lastItem == null;
+                lastRet = nextIndex;
+                final int cursor = this.cursor;
+                if (cursor >= 0) {
+                    nextItem = itemAt(nextIndex = cursor);
+                    // assert nextItem != null;
+                    this.cursor = incCursor(cursor);
+                } else {
+                    nextIndex = NONE;
+                    nextItem = null;
                 }
             } finally {
                 lock.unlock();
             }
+            return x;
         }
+
+        public void remove() {
+            // assert lock.getHoldCount() == 0;
+            final ReentrantLock lock = ArrayBlockingQueue.this.lock;
+            lock.lock();
+            try {
+                if (!isDetached())
+                    incorporateDequeues(); // might update lastRet or detach
+                final int lastRet = this.lastRet;
+                this.lastRet = NONE;
+                if (lastRet >= 0) {
+                    if (!isDetached())
+                        removeAt(lastRet);
+                    else {
+                        final E lastItem = this.lastItem;
+                        // assert lastItem != null;
+                        this.lastItem = null;
+                        if (itemAt(lastRet) == lastItem)
+                            removeAt(lastRet);
+                    }
+                } else if (lastRet == NONE)
+                    throw new IllegalStateException();
+                // else lastRet == REMOVED and the last returned element was
+                // previously asynchronously removed via an operation other
+                // than this.remove(), so nothing to do.
+
+                if (cursor < 0 && nextIndex < 0)
+                    detach();
+            } finally {
+                lock.unlock();
+                // assert lastRet == NONE;
+                // assert lastItem == null;
+            }
+        }
+
+        /**
+         * Called to notify the iterator that the queue is empty, or that it
+         * has fallen hopelessly behind, so that it should abandon any
+         * further iteration, except possibly to return one more element
+         * from next(), as promised by returning true from hasNext().
+         */
+        void shutdown() {
+            // assert lock.getHoldCount() == 1;
+            cursor = NONE;
+            if (nextIndex >= 0)
+                nextIndex = REMOVED;
+            if (lastRet >= 0) {
+                lastRet = REMOVED;
+                lastItem = null;
+            }
+            prevTakeIndex = DETACHED;
+            // Don't set nextItem to null because we must continue to be
+            // able to return it on next().
+            //
+            // Caller will unlink from itrs when convenient.
+        }
+
+        private int distance(int index, int prevTakeIndex, int length) {
+            int distance = index - prevTakeIndex;
+            if (distance < 0)
+                distance += length;
+            return distance;
+        }
+
+        /**
+         * Called whenever an interior remove (not at takeIndex) occured.
+         *
+         * @return true if this iterator should be unlinked from itrs
+         */
+        boolean removedAt(int removedIndex) {
+            // assert lock.getHoldCount() == 1;
+            if (isDetached())
+                return true;
+
+            final int cycles = itrs.cycles;
+            final int takeIndex = ArrayBlockingQueue.this.takeIndex;
+            final int prevCycles = this.prevCycles;
+            final int prevTakeIndex = this.prevTakeIndex;
+            final int len = items.length;
+            int cycleDiff = cycles - prevCycles;
+            if (removedIndex < takeIndex)
+                cycleDiff++;
+            final int removedDistance =
+                (cycleDiff * len) + (removedIndex - prevTakeIndex);
+            // assert removedDistance >= 0;
+            int cursor = this.cursor;
+            if (cursor >= 0) {
+                int x = distance(cursor, prevTakeIndex, len);
+                if (x == removedDistance) {
+                    if (cursor == putIndex)
+                        this.cursor = cursor = NONE;
+                }
+                else if (x > removedDistance) {
+                    // assert cursor != prevTakeIndex;
+                    this.cursor = cursor = dec(cursor);
+                }
+            }
+            int lastRet = this.lastRet;
+            if (lastRet >= 0) {
+                int x = distance(lastRet, prevTakeIndex, len);
+                if (x == removedDistance)
+                    this.lastRet = lastRet = REMOVED;
+                else if (x > removedDistance)
+                    this.lastRet = lastRet = dec(lastRet);
+            }
+            int nextIndex = this.nextIndex;
+            if (nextIndex >= 0) {
+                int x = distance(nextIndex, prevTakeIndex, len);
+                if (x == removedDistance)
+                    this.nextIndex = nextIndex = REMOVED;
+                else if (x > removedDistance)
+                    this.nextIndex = nextIndex = dec(nextIndex);
+            }
+            else if (cursor < 0 && nextIndex < 0 && lastRet < 0) {
+                this.prevTakeIndex = DETACHED;
+                return true;
+            }
+            return false;
+        }
+
+        /**
+         * Called whenever takeIndex wraps around to zero.
+         *
+         * @return true if this iterator should be unlinked from itrs
+         */
+        boolean takeIndexWrapped() {
+            // assert lock.getHoldCount() == 1;
+            if (isDetached())
+                return true;
+            if (itrs.cycles - prevCycles > 1) {
+                // All the elements that existed at the time of the last
+                // operation are gone, so abandon further iteration.
+                shutdown();
+                return true;
+            }
+            return false;
+        }
+
+//         /** Uncomment for debugging. */
+//         public String toString() {
+//             return ("cursor=" + cursor + " " +
+//                     "nextIndex=" + nextIndex + " " +
+//                     "lastRet=" + lastRet + " " +
+//                     "nextItem=" + nextItem + " " +
+//                     "lastItem=" + lastItem + " " +
+//                     "prevCycles=" + prevCycles + " " +
+//                     "prevTakeIndex=" + prevTakeIndex + " " +
+//                     "size()=" + size() + " " +
+//                     "remainingCapacity()=" + remainingCapacity());
+//         }
     }
 
+    public Spliterator<E> spliterator() {
+        return Spliterators.spliterator
+            (this, Spliterator.ORDERED | Spliterator.NONNULL |
+             Spliterator.CONCURRENT);
+    }
 }
--- a/src/share/classes/java/util/concurrent/BlockingDeque.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/BlockingDeque.java	Mon Jul 22 17:37:15 2013 -0700
@@ -41,17 +41,18 @@
  * for the deque to become non-empty when retrieving an element, and wait for
  * space to become available in the deque when storing an element.
  *
- * <p><tt>BlockingDeque</tt> methods come in four forms, with different ways
+ * <p>{@code BlockingDeque} methods come in four forms, with different ways
  * of handling operations that cannot be satisfied immediately, but may be
  * satisfied at some point in the future:
  * one throws an exception, the second returns a special value (either
- * <tt>null</tt> or <tt>false</tt>, depending on the operation), the third
+ * {@code null} or {@code false}, depending on the operation), the third
  * blocks the current thread indefinitely until the operation can succeed,
  * and the fourth blocks for only a given maximum time limit before giving
  * up.  These methods are summarized in the following table:
  *
  * <p>
  * <table BORDER CELLPADDING=3 CELLSPACING=1>
+ * <caption>Summary of BlockingDeque methods</caption>
  *  <tr>
  *    <td ALIGN=CENTER COLSPAN = 5> <b>First Element (Head)</b></td>
  *  </tr>
@@ -116,20 +117,21 @@
  *  </tr>
  * </table>
  *
- * <p>Like any {@link BlockingQueue}, a <tt>BlockingDeque</tt> is thread safe,
+ * <p>Like any {@link BlockingQueue}, a {@code BlockingDeque} is thread safe,
  * does not permit null elements, and may (or may not) be
  * capacity-constrained.
  *
- * <p>A <tt>BlockingDeque</tt> implementation may be used directly as a FIFO
- * <tt>BlockingQueue</tt>. The methods inherited from the
- * <tt>BlockingQueue</tt> interface are precisely equivalent to
- * <tt>BlockingDeque</tt> methods as indicated in the following table:
+ * <p>A {@code BlockingDeque} implementation may be used directly as a FIFO
+ * {@code BlockingQueue}. The methods inherited from the
+ * {@code BlockingQueue} interface are precisely equivalent to
+ * {@code BlockingDeque} methods as indicated in the following table:
  *
  * <p>
  * <table BORDER CELLPADDING=3 CELLSPACING=1>
+ * <caption>Comparison of BlockingQueue and BlockingDeque methods</caption>
  *  <tr>
- *    <td ALIGN=CENTER> <b><tt>BlockingQueue</tt> Method</b></td>
- *    <td ALIGN=CENTER> <b>Equivalent <tt>BlockingDeque</tt> Method</b></td>
+ *    <td ALIGN=CENTER> <b>{@code BlockingQueue} Method</b></td>
+ *    <td ALIGN=CENTER> <b>Equivalent {@code BlockingDeque} Method</b></td>
  *  </tr>
  *  <tr>
  *    <td ALIGN=CENTER COLSPAN = 2> <b>Insert</b></td>
@@ -208,7 +210,7 @@
     /**
      * Inserts the specified element at the front of this deque if it is
      * possible to do so immediately without violating capacity restrictions,
-     * throwing an <tt>IllegalStateException</tt> if no space is currently
+     * throwing an {@code IllegalStateException} if no space is currently
      * available.  When using a capacity-restricted deque, it is generally
      * preferable to use {@link #offerFirst(Object) offerFirst}.
      *
@@ -223,7 +225,7 @@
     /**
      * Inserts the specified element at the end of this deque if it is
      * possible to do so immediately without violating capacity restrictions,
-     * throwing an <tt>IllegalStateException</tt> if no space is currently
+     * throwing an {@code IllegalStateException} if no space is currently
      * available.  When using a capacity-restricted deque, it is generally
      * preferable to use {@link #offerLast(Object) offerLast}.
      *
@@ -238,7 +240,7 @@
     /**
      * Inserts the specified element at the front of this deque if it is
      * possible to do so immediately without violating capacity restrictions,
-     * returning <tt>true</tt> upon success and <tt>false</tt> if no space is
+     * returning {@code true} upon success and {@code false} if no space is
      * currently available.
      * When using a capacity-restricted deque, this method is generally
      * preferable to the {@link #addFirst(Object) addFirst} method, which can
@@ -254,7 +256,7 @@
     /**
      * Inserts the specified element at the end of this deque if it is
      * possible to do so immediately without violating capacity restrictions,
-     * returning <tt>true</tt> upon success and <tt>false</tt> if no space is
+     * returning {@code true} upon success and {@code false} if no space is
      * currently available.
      * When using a capacity-restricted deque, this method is generally
      * preferable to the {@link #addLast(Object) addLast} method, which can
@@ -302,10 +304,10 @@
      *
      * @param e the element to add
      * @param timeout how long to wait before giving up, in units of
-     *        <tt>unit</tt>
-     * @param unit a <tt>TimeUnit</tt> determining how to interpret the
-     *        <tt>timeout</tt> parameter
-     * @return <tt>true</tt> if successful, or <tt>false</tt> if
+     *        {@code unit}
+     * @param unit a {@code TimeUnit} determining how to interpret the
+     *        {@code timeout} parameter
+     * @return {@code true} if successful, or {@code false} if
      *         the specified waiting time elapses before space is available
      * @throws InterruptedException if interrupted while waiting
      * @throws ClassCastException if the class of the specified element
@@ -324,10 +326,10 @@
      *
      * @param e the element to add
      * @param timeout how long to wait before giving up, in units of
-     *        <tt>unit</tt>
-     * @param unit a <tt>TimeUnit</tt> determining how to interpret the
-     *        <tt>timeout</tt> parameter
-     * @return <tt>true</tt> if successful, or <tt>false</tt> if
+     *        {@code unit}
+     * @param unit a {@code TimeUnit} determining how to interpret the
+     *        {@code timeout} parameter
+     * @return {@code true} if successful, or {@code false} if
      *         the specified waiting time elapses before space is available
      * @throws InterruptedException if interrupted while waiting
      * @throws ClassCastException if the class of the specified element
@@ -363,10 +365,10 @@
      * become available.
      *
      * @param timeout how long to wait before giving up, in units of
-     *        <tt>unit</tt>
-     * @param unit a <tt>TimeUnit</tt> determining how to interpret the
-     *        <tt>timeout</tt> parameter
-     * @return the head of this deque, or <tt>null</tt> if the specified
+     *        {@code unit}
+     * @param unit a {@code TimeUnit} determining how to interpret the
+     *        {@code timeout} parameter
+     * @return the head of this deque, or {@code null} if the specified
      *         waiting time elapses before an element is available
      * @throws InterruptedException if interrupted while waiting
      */
@@ -379,10 +381,10 @@
      * become available.
      *
      * @param timeout how long to wait before giving up, in units of
-     *        <tt>unit</tt>
-     * @param unit a <tt>TimeUnit</tt> determining how to interpret the
-     *        <tt>timeout</tt> parameter
-     * @return the tail of this deque, or <tt>null</tt> if the specified
+     *        {@code unit}
+     * @param unit a {@code TimeUnit} determining how to interpret the
+     *        {@code timeout} parameter
+     * @return the tail of this deque, or {@code null} if the specified
      *         waiting time elapses before an element is available
      * @throws InterruptedException if interrupted while waiting
      */
@@ -392,13 +394,13 @@
     /**
      * Removes the first occurrence of the specified element from this deque.
      * If the deque does not contain the element, it is unchanged.
-     * More formally, removes the first element <tt>e</tt> such that
-     * <tt>o.equals(e)</tt> (if such an element exists).
-     * Returns <tt>true</tt> if this deque contained the specified element
+     * More formally, removes the first element {@code e} such that
+     * {@code o.equals(e)} (if such an element exists).
+     * Returns {@code true} if this deque contained the specified element
      * (or equivalently, if this deque changed as a result of the call).
      *
      * @param o element to be removed from this deque, if present
-     * @return <tt>true</tt> if an element was removed as a result of this call
+     * @return {@code true} if an element was removed as a result of this call
      * @throws ClassCastException if the class of the specified element
      *         is incompatible with this deque
      *         (<a href="../Collection.html#optional-restrictions">optional</a>)
@@ -410,13 +412,13 @@
     /**
      * Removes the last occurrence of the specified element from this deque.
      * If the deque does not contain the element, it is unchanged.
-     * More formally, removes the last element <tt>e</tt> such that
-     * <tt>o.equals(e)</tt> (if such an element exists).
-     * Returns <tt>true</tt> if this deque contained the specified element
+     * More formally, removes the last element {@code e} such that
+     * {@code o.equals(e)} (if such an element exists).
+     * Returns {@code true} if this deque contained the specified element
      * (or equivalently, if this deque changed as a result of the call).
      *
      * @param o element to be removed from this deque, if present
-     * @return <tt>true</tt> if an element was removed as a result of this call
+     * @return {@code true} if an element was removed as a result of this call
      * @throws ClassCastException if the class of the specified element
      *         is incompatible with this deque
      *         (<a href="../Collection.html#optional-restrictions">optional</a>)
@@ -431,8 +433,8 @@
      * Inserts the specified element into the queue represented by this deque
      * (in other words, at the tail of this deque) if it is possible to do so
      * immediately without violating capacity restrictions, returning
-     * <tt>true</tt> upon success and throwing an
-     * <tt>IllegalStateException</tt> if no space is currently available.
+     * {@code true} upon success and throwing an
+     * {@code IllegalStateException} if no space is currently available.
      * When using a capacity-restricted deque, it is generally preferable to
      * use {@link #offer(Object) offer}.
      *
@@ -452,7 +454,7 @@
      * Inserts the specified element into the queue represented by this deque
      * (in other words, at the tail of this deque) if it is possible to do so
      * immediately without violating capacity restrictions, returning
-     * <tt>true</tt> upon success and <tt>false</tt> if no space is currently
+     * {@code true} upon success and {@code false} if no space is currently
      * available.  When using a capacity-restricted deque, this method is
      * generally preferable to the {@link #add} method, which can fail to
      * insert an element only by throwing an exception.
@@ -494,8 +496,8 @@
      * {@link #offerLast(Object,long,TimeUnit) offerLast}.
      *
      * @param e the element to add
-     * @return <tt>true</tt> if the element was added to this deque, else
-     *         <tt>false</tt>
+     * @return {@code true} if the element was added to this deque, else
+     *         {@code false}
      * @throws InterruptedException {@inheritDoc}
      * @throws ClassCastException if the class of the specified element
      *         prevents it from being added to this deque
@@ -522,11 +524,11 @@
     /**
      * Retrieves and removes the head of the queue represented by this deque
      * (in other words, the first element of this deque), or returns
-     * <tt>null</tt> if this deque is empty.
+     * {@code null} if this deque is empty.
      *
      * <p>This method is equivalent to {@link #pollFirst()}.
      *
-     * @return the head of this deque, or <tt>null</tt> if this deque is empty
+     * @return the head of this deque, or {@code null} if this deque is empty
      */
     E poll();
 
@@ -550,7 +552,7 @@
      * <p>This method is equivalent to
      * {@link #pollFirst(long,TimeUnit) pollFirst}.
      *
-     * @return the head of this deque, or <tt>null</tt> if the
+     * @return the head of this deque, or {@code null} if the
      *         specified waiting time elapses before an element is available
      * @throws InterruptedException if interrupted while waiting
      */
@@ -573,27 +575,27 @@
     /**
      * Retrieves, but does not remove, the head of the queue represented by
      * this deque (in other words, the first element of this deque), or
-     * returns <tt>null</tt> if this deque is empty.
+     * returns {@code null} if this deque is empty.
      *
      * <p>This method is equivalent to {@link #peekFirst() peekFirst}.
      *
-     * @return the head of this deque, or <tt>null</tt> if this deque is empty
+     * @return the head of this deque, or {@code null} if this deque is empty
      */
     E peek();
 
     /**
      * Removes the first occurrence of the specified element from this deque.
      * If the deque does not contain the element, it is unchanged.
-     * More formally, removes the first element <tt>e</tt> such that
-     * <tt>o.equals(e)</tt> (if such an element exists).
-     * Returns <tt>true</tt> if this deque contained the specified element
+     * More formally, removes the first element {@code e} such that
+     * {@code o.equals(e)} (if such an element exists).
+     * Returns {@code true} if this deque contained the specified element
      * (or equivalently, if this deque changed as a result of the call).
      *
      * <p>This method is equivalent to
      * {@link #removeFirstOccurrence(Object) removeFirstOccurrence}.
      *
      * @param o element to be removed from this deque, if present
-     * @return <tt>true</tt> if this deque changed as a result of the call
+     * @return {@code true} if this deque changed as a result of the call
      * @throws ClassCastException if the class of the specified element
      *         is incompatible with this deque
      *         (<a href="../Collection.html#optional-restrictions">optional</a>)
@@ -603,12 +605,12 @@
     boolean remove(Object o);
 
     /**
-     * Returns <tt>true</tt> if this deque contains the specified element.
-     * More formally, returns <tt>true</tt> if and only if this deque contains
-     * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
+     * Returns {@code true} if this deque contains the specified element.
+     * More formally, returns {@code true} if and only if this deque contains
+     * at least one element {@code e} such that {@code o.equals(e)}.
      *
      * @param o object to be checked for containment in this deque
-     * @return <tt>true</tt> if this deque contains the specified element
+     * @return {@code true} if this deque contains the specified element
      * @throws ClassCastException if the class of the specified element
      *         is incompatible with this deque
      *         (<a href="../Collection.html#optional-restrictions">optional</a>)
@@ -635,9 +637,10 @@
     // *** Stack methods ***
 
     /**
-     * Pushes an element onto the stack represented by this deque.  In other
-     * words, inserts the element at the front of this deque unless it would
-     * violate capacity restrictions.
+     * Pushes an element onto the stack represented by this deque (in other
+     * words, at the head of this deque) if it is possible to do so
+     * immediately without violating capacity restrictions, throwing an
+     * {@code IllegalStateException} if no space is currently available.
      *
      * <p>This method is equivalent to {@link #addFirst(Object) addFirst}.
      *
--- a/src/share/classes/java/util/concurrent/BlockingQueue.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/BlockingQueue.java	Mon Jul 22 17:37:15 2013 -0700
@@ -44,17 +44,18 @@
  * element, and wait for space to become available in the queue when
  * storing an element.
  *
- * <p><tt>BlockingQueue</tt> methods come in four forms, with different ways
+ * <p>{@code BlockingQueue} methods come in four forms, with different ways
  * of handling operations that cannot be satisfied immediately, but may be
  * satisfied at some point in the future:
  * one throws an exception, the second returns a special value (either
- * <tt>null</tt> or <tt>false</tt>, depending on the operation), the third
+ * {@code null} or {@code false}, depending on the operation), the third
  * blocks the current thread indefinitely until the operation can succeed,
  * and the fourth blocks for only a given maximum time limit before giving
  * up.  These methods are summarized in the following table:
  *
  * <p>
  * <table BORDER CELLPADDING=3 CELLSPACING=1>
+ * <caption>Summary of BlockingQueue methods</caption>
  *  <tr>
  *    <td></td>
  *    <td ALIGN=CENTER><em>Throws exception</em></td>
@@ -85,37 +86,37 @@
  *  </tr>
  * </table>
  *
- * <p>A <tt>BlockingQueue</tt> does not accept <tt>null</tt> elements.
- * Implementations throw <tt>NullPointerException</tt> on attempts
- * to <tt>add</tt>, <tt>put</tt> or <tt>offer</tt> a <tt>null</tt>.  A
- * <tt>null</tt> is used as a sentinel value to indicate failure of
- * <tt>poll</tt> operations.
+ * <p>A {@code BlockingQueue} does not accept {@code null} elements.
+ * Implementations throw {@code NullPointerException} on attempts
+ * to {@code add}, {@code put} or {@code offer} a {@code null}.  A
+ * {@code null} is used as a sentinel value to indicate failure of
+ * {@code poll} operations.
  *
- * <p>A <tt>BlockingQueue</tt> may be capacity bounded. At any given
- * time it may have a <tt>remainingCapacity</tt> beyond which no
- * additional elements can be <tt>put</tt> without blocking.
- * A <tt>BlockingQueue</tt> without any intrinsic capacity constraints always
- * reports a remaining capacity of <tt>Integer.MAX_VALUE</tt>.
+ * <p>A {@code BlockingQueue} may be capacity bounded. At any given
+ * time it may have a {@code remainingCapacity} beyond which no
+ * additional elements can be {@code put} without blocking.
+ * A {@code BlockingQueue} without any intrinsic capacity constraints always
+ * reports a remaining capacity of {@code Integer.MAX_VALUE}.
  *
- * <p> <tt>BlockingQueue</tt> implementations are designed to be used
+ * <p>{@code BlockingQueue} implementations are designed to be used
  * primarily for producer-consumer queues, but additionally support
  * the {@link java.util.Collection} interface.  So, for example, it is
  * possible to remove an arbitrary element from a queue using
- * <tt>remove(x)</tt>. However, such operations are in general
+ * {@code remove(x)}. However, such operations are in general
  * <em>not</em> performed very efficiently, and are intended for only
  * occasional use, such as when a queued message is cancelled.
  *
- * <p> <tt>BlockingQueue</tt> implementations are thread-safe.  All
+ * <p>{@code BlockingQueue} implementations are thread-safe.  All
  * queuing methods achieve their effects atomically using internal
  * locks or other forms of concurrency control. However, the
- * <em>bulk</em> Collection operations <tt>addAll</tt>,
- * <tt>containsAll</tt>, <tt>retainAll</tt> and <tt>removeAll</tt> are
+ * <em>bulk</em> Collection operations {@code addAll},
+ * {@code containsAll}, {@code retainAll} and {@code removeAll} are
  * <em>not</em> necessarily performed atomically unless specified
  * otherwise in an implementation. So it is possible, for example, for
- * <tt>addAll(c)</tt> to fail (throwing an exception) after adding
- * only some of the elements in <tt>c</tt>.
+ * {@code addAll(c)} to fail (throwing an exception) after adding
+ * only some of the elements in {@code c}.
  *
- * <p>A <tt>BlockingQueue</tt> does <em>not</em> intrinsically support
+ * <p>A {@code BlockingQueue} does <em>not</em> intrinsically support
  * any kind of &quot;close&quot; or &quot;shutdown&quot; operation to
  * indicate that no more items will be added.  The needs and usage of
  * such features tend to be implementation-dependent. For example, a
@@ -125,7 +126,7 @@
  *
  * <p>
  * Usage example, based on a typical producer-consumer scenario.
- * Note that a <tt>BlockingQueue</tt> can safely be used with multiple
+ * Note that a {@code BlockingQueue} can safely be used with multiple
  * producers and multiple consumers.
  *  <pre> {@code
  * class Producer implements Runnable {
@@ -181,13 +182,13 @@
     /**
      * Inserts the specified element into this queue if it is possible to do
      * so immediately without violating capacity restrictions, returning
-     * <tt>true</tt> upon success and throwing an
-     * <tt>IllegalStateException</tt> if no space is currently available.
+     * {@code true} upon success and throwing an
+     * {@code IllegalStateException} if no space is currently available.
      * When using a capacity-restricted queue, it is generally preferable to
      * use {@link #offer(Object) offer}.
      *
      * @param e the element to add
-     * @return <tt>true</tt> (as specified by {@link Collection#add})
+     * @return {@code true} (as specified by {@link Collection#add})
      * @throws IllegalStateException if the element cannot be added at this
      *         time due to capacity restrictions
      * @throws ClassCastException if the class of the specified element
@@ -201,14 +202,14 @@
     /**
      * Inserts the specified element into this queue if it is possible to do
      * so immediately without violating capacity restrictions, returning
-     * <tt>true</tt> upon success and <tt>false</tt> if no space is currently
+     * {@code true} upon success and {@code false} if no space is currently
      * available.  When using a capacity-restricted queue, this method is
      * generally preferable to {@link #add}, which can fail to insert an
      * element only by throwing an exception.
      *
      * @param e the element to add
-     * @return <tt>true</tt> if the element was added to this queue, else
-     *         <tt>false</tt>
+     * @return {@code true} if the element was added to this queue, else
+     *         {@code false}
      * @throws ClassCastException if the class of the specified element
      *         prevents it from being added to this queue
      * @throws NullPointerException if the specified element is null
@@ -237,10 +238,10 @@
      *
      * @param e the element to add
      * @param timeout how long to wait before giving up, in units of
-     *        <tt>unit</tt>
-     * @param unit a <tt>TimeUnit</tt> determining how to interpret the
-     *        <tt>timeout</tt> parameter
-     * @return <tt>true</tt> if successful, or <tt>false</tt> if
+     *        {@code unit}
+     * @param unit a {@code TimeUnit} determining how to interpret the
+     *        {@code timeout} parameter
+     * @return {@code true} if successful, or {@code false} if
      *         the specified waiting time elapses before space is available
      * @throws InterruptedException if interrupted while waiting
      * @throws ClassCastException if the class of the specified element
@@ -266,10 +267,10 @@
      * specified wait time if necessary for an element to become available.
      *
      * @param timeout how long to wait before giving up, in units of
-     *        <tt>unit</tt>
-     * @param unit a <tt>TimeUnit</tt> determining how to interpret the
-     *        <tt>timeout</tt> parameter
-     * @return the head of this queue, or <tt>null</tt> if the
+     *        {@code unit}
+     * @param unit a {@code TimeUnit} determining how to interpret the
+     *        {@code timeout} parameter
+     * @return the head of this queue, or {@code null} if the
      *         specified waiting time elapses before an element is available
      * @throws InterruptedException if interrupted while waiting
      */
@@ -279,11 +280,11 @@
     /**
      * Returns the number of additional elements that this queue can ideally
      * (in the absence of memory or resource constraints) accept without
-     * blocking, or <tt>Integer.MAX_VALUE</tt> if there is no intrinsic
+     * blocking, or {@code Integer.MAX_VALUE} if there is no intrinsic
      * limit.
      *
      * <p>Note that you <em>cannot</em> always tell if an attempt to insert
-     * an element will succeed by inspecting <tt>remainingCapacity</tt>
+     * an element will succeed by inspecting {@code remainingCapacity}
      * because it may be the case that another thread is about to
      * insert or remove an element.
      *
@@ -293,14 +294,14 @@
 
     /**
      * Removes a single instance of the specified element from this queue,
-     * if it is present.  More formally, removes an element <tt>e</tt> such
-     * that <tt>o.equals(e)</tt>, if this queue contains one or more such
+     * if it is present.  More formally, removes an element {@code e} such
+     * that {@code o.equals(e)}, if this queue contains one or more such
      * elements.
-     * Returns <tt>true</tt> if this queue contained the specified element
+     * Returns {@code true} if this queue contained the specified element
      * (or equivalently, if this queue changed as a result of the call).
      *
      * @param o element to be removed from this queue, if present
-     * @return <tt>true</tt> if this queue changed as a result of the call
+     * @return {@code true} if this queue changed as a result of the call
      * @throws ClassCastException if the class of the specified element
      *         is incompatible with this queue
      *         (<a href="../Collection.html#optional-restrictions">optional</a>)
@@ -310,12 +311,12 @@
     boolean remove(Object o);
 
     /**
-     * Returns <tt>true</tt> if this queue contains the specified element.
-     * More formally, returns <tt>true</tt> if and only if this queue contains
-     * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
+     * Returns {@code true} if this queue contains the specified element.
+     * More formally, returns {@code true} if and only if this queue contains
+     * at least one element {@code e} such that {@code o.equals(e)}.
      *
      * @param o object to be checked for containment in this queue
-     * @return <tt>true</tt> if this queue contains the specified element
+     * @return {@code true} if this queue contains the specified element
      * @throws ClassCastException if the class of the specified element
      *         is incompatible with this queue
      *         (<a href="../Collection.html#optional-restrictions">optional</a>)
@@ -329,10 +330,10 @@
      * to the given collection.  This operation may be more
      * efficient than repeatedly polling this queue.  A failure
      * encountered while attempting to add elements to
-     * collection <tt>c</tt> may result in elements being in neither,
+     * collection {@code c} may result in elements being in neither,
      * either or both collections when the associated exception is
      * thrown.  Attempts to drain a queue to itself result in
-     * <tt>IllegalArgumentException</tt>. Further, the behavior of
+     * {@code IllegalArgumentException}. Further, the behavior of
      * this operation is undefined if the specified collection is
      * modified while the operation is in progress.
      *
@@ -353,10 +354,10 @@
      * Removes at most the given number of available elements from
      * this queue and adds them to the given collection.  A failure
      * encountered while attempting to add elements to
-     * collection <tt>c</tt> may result in elements being in neither,
+     * collection {@code c} may result in elements being in neither,
      * either or both collections when the associated exception is
      * thrown.  Attempts to drain a queue to itself result in
-     * <tt>IllegalArgumentException</tt>. Further, the behavior of
+     * {@code IllegalArgumentException}. Further, the behavior of
      * this operation is undefined if the specified collection is
      * modified while the operation is in progress.
      *
--- a/src/share/classes/java/util/concurrent/BrokenBarrierException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/BrokenBarrierException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -49,13 +49,13 @@
     private static final long serialVersionUID = 7117394618823254244L;
 
     /**
-     * Constructs a <tt>BrokenBarrierException</tt> with no specified detail
+     * Constructs a {@code BrokenBarrierException} with no specified detail
      * message.
      */
     public BrokenBarrierException() {}
 
     /**
-     * Constructs a <tt>BrokenBarrierException</tt> with the specified
+     * Constructs a {@code BrokenBarrierException} with the specified
      * detail message.
      *
      * @param message the detail message
--- a/src/share/classes/java/util/concurrent/Callable.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/Callable.java	Mon Jul 22 17:37:15 2013 -0700
@@ -38,21 +38,21 @@
 /**
  * A task that returns a result and may throw an exception.
  * Implementors define a single method with no arguments called
- * <tt>call</tt>.
+ * {@code call}.
  *
- * <p>The <tt>Callable</tt> interface is similar to {@link
+ * <p>The {@code Callable} interface is similar to {@link
  * java.lang.Runnable}, in that both are designed for classes whose
  * instances are potentially executed by another thread.  A
- * <tt>Runnable</tt>, however, does not return a result and cannot
+ * {@code Runnable}, however, does not return a result and cannot
  * throw a checked exception.
  *
- * <p> The {@link Executors} class contains utility methods to
- * convert from other common forms to <tt>Callable</tt> classes.
+ * <p>The {@link Executors} class contains utility methods to
+ * convert from other common forms to {@code Callable} classes.
  *
  * @see Executor
  * @since 1.5
  * @author Doug Lea
- * @param <V> the result type of method <tt>call</tt>
+ * @param <V> the result type of method {@code call}
  */
 public interface Callable<V> {
     /**
--- a/src/share/classes/java/util/concurrent/CancellationException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/CancellationException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -47,12 +47,12 @@
     private static final long serialVersionUID = -9202173006928992231L;
 
     /**
-     * Constructs a <tt>CancellationException</tt> with no detail message.
+     * Constructs a {@code CancellationException} with no detail message.
      */
     public CancellationException() {}
 
     /**
-     * Constructs a <tt>CancellationException</tt> with the specified detail
+     * Constructs a {@code CancellationException} with the specified detail
      * message.
      *
      * @param message the detail message
--- a/src/share/classes/java/util/concurrent/CompletableFuture.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/CompletableFuture.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1209,7 +1209,7 @@
                 (r = a.result) != null &&
                 compareAndSet(0, 1)) {
                 if ((r instanceof AltResult) &&
-                    (ex = ((AltResult)r).ex) != null)  {
+                    (ex = ((AltResult)r).ex) != null) {
                     try {
                         t = fn.apply(ex);
                     } catch (Throwable rex) {
@@ -2892,7 +2892,7 @@
         if (r != null && (d == null || d.compareAndSet(0, 1))) {
             T t = null; Throwable ex, dx = null;
             if (r instanceof AltResult) {
-                if ((ex = ((AltResult)r).ex) != null)  {
+                if ((ex = ((AltResult)r).ex) != null) {
                     try {
                         t = fn.apply(ex);
                     } catch (Throwable rex) {
--- a/src/share/classes/java/util/concurrent/CompletionService.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/CompletionService.java	Mon Jul 22 17:37:15 2013 -0700
@@ -38,17 +38,17 @@
 /**
  * A service that decouples the production of new asynchronous tasks
  * from the consumption of the results of completed tasks.  Producers
- * <tt>submit</tt> tasks for execution. Consumers <tt>take</tt>
+ * {@code submit} tasks for execution. Consumers {@code take}
  * completed tasks and process their results in the order they
- * complete.  A <tt>CompletionService</tt> can for example be used to
- * manage asynchronous IO, in which tasks that perform reads are
+ * complete.  A {@code CompletionService} can for example be used to
+ * manage asynchronous I/O, in which tasks that perform reads are
  * submitted in one part of a program or system, and then acted upon
  * in a different part of the program when the reads complete,
  * possibly in a different order than they were requested.
  *
- * <p>Typically, a <tt>CompletionService</tt> relies on a separate
+ * <p>Typically, a {@code CompletionService} relies on a separate
  * {@link Executor} to actually execute the tasks, in which case the
- * <tt>CompletionService</tt> only manages an internal completion
+ * {@code CompletionService} only manages an internal completion
  * queue. The {@link ExecutorCompletionService} class provides an
  * implementation of this approach.
  *
@@ -80,7 +80,7 @@
      * @param task the task to submit
      * @param result the result to return upon successful completion
      * @return a Future representing pending completion of the task,
-     *         and whose <tt>get()</tt> method will return the given
+     *         and whose {@code get()} method will return the given
      *         result value upon completion
      * @throws RejectedExecutionException if the task cannot be
      *         scheduled for execution
@@ -99,10 +99,10 @@
 
     /**
      * Retrieves and removes the Future representing the next
-     * completed task or <tt>null</tt> if none are present.
+     * completed task, or {@code null} if none are present.
      *
      * @return the Future representing the next completed task, or
-     *         <tt>null</tt> if none are present
+     *         {@code null} if none are present
      */
     Future<V> poll();
 
@@ -112,11 +112,11 @@
      * time if none are yet present.
      *
      * @param timeout how long to wait before giving up, in units of
-     *        <tt>unit</tt>
-     * @param unit a <tt>TimeUnit</tt> determining how to interpret the
-     *        <tt>timeout</tt> parameter
+     *        {@code unit}
+     * @param unit a {@code TimeUnit} determining how to interpret the
+     *        {@code timeout} parameter
      * @return the Future representing the next completed task or
-     *         <tt>null</tt> if the specified waiting time elapses
+     *         {@code null} if the specified waiting time elapses
      *         before one is present
      * @throws InterruptedException if interrupted while waiting
      */
--- a/src/share/classes/java/util/concurrent/ConcurrentHashMap.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/ConcurrentHashMap.java	Mon Jul 22 17:37:15 2013 -0700
@@ -34,8 +34,9 @@
  */
 
 package java.util.concurrent;
+
+import java.io.ObjectStreamField;
 import java.io.Serializable;
-import java.io.ObjectStreamField;
 import java.lang.reflect.ParameterizedType;
 import java.lang.reflect.Type;
 import java.util.AbstractMap;
@@ -54,8 +55,8 @@
 import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.ForkJoinPool;
 import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.locks.LockSupport;
 import java.util.concurrent.locks.ReentrantLock;
-import java.util.concurrent.locks.StampedLock;
 import java.util.function.BiConsumer;
 import java.util.function.BiFunction;
 import java.util.function.BinaryOperator;
@@ -264,10 +265,7 @@
  * @param <K> the type of keys maintained by this map
  * @param <V> the type of mapped values
  */
-@SuppressWarnings({"unchecked", "rawtypes", "serial"})
-public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
-    implements ConcurrentMap<K,V>, Serializable {
-
+public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable {
     private static final long serialVersionUID = 7249069246763182397L;
 
     /*
@@ -280,16 +278,21 @@
      * the same or better than java.util.HashMap, and to support high
      * initial insertion rates on an empty table by many threads.
      *
-     * Each key-value mapping is held in a Node.  Because Node key
-     * fields can contain special values, they are defined using plain
-     * Object types (not type "K"). This leads to a lot of explicit
-     * casting (and the use of class-wide warning suppressions).  It
-     * also allows some of the public methods to be factored into a
-     * smaller number of internal methods (although sadly not so for
-     * the five variants of put-related operations). The
-     * validation-based approach explained below leads to a lot of
-     * code sprawl because retry-control precludes factoring into
-     * smaller methods.
+     * This map usually acts as a binned (bucketed) hash table.  Each
+     * key-value mapping is held in a Node.  Most nodes are instances
+     * of the basic Node class with hash, key, value, and next
+     * fields. However, various subclasses exist: TreeNodes are
+     * arranged in balanced trees, not lists.  TreeBins hold the roots
+     * of sets of TreeNodes. ForwardingNodes are placed at the heads
+     * of bins during resizing. ReservationNodes are used as
+     * placeholders while establishing values in computeIfAbsent and
+     * related methods.  The types TreeBin, ForwardingNode, and
+     * ReservationNode do not hold normal user keys, values, or
+     * hashes, and are readily distinguishable during search etc
+     * because they have negative hash fields and null key and value
+     * fields. (These special nodes are either uncommon or transient,
+     * so the impact of carrying around some unused fields is
+     * insignificant.)
      *
      * The table is lazily initialized to a power-of-two size upon the
      * first insertion.  Each bin in the table normally contains a
@@ -301,10 +304,8 @@
      *
      * We use the top (sign) bit of Node hash fields for control
      * purposes -- it is available anyway because of addressing
-     * constraints.  Nodes with negative hash fields are forwarding
-     * nodes to either TreeBins or resized tables.  The lower 31 bits
-     * of each normal Node's hash field contain a transformation of
-     * the key's hash code.
+     * constraints.  Nodes with negative hash fields are specially
+     * handled or ignored in map methods.
      *
      * Insertion (via put or its variants) of the first node in an
      * empty bin is performed by just CASing it to the bin.  This is
@@ -354,15 +355,12 @@
      * sometimes deviate significantly from uniform randomness.  This
      * includes the case when N > (1<<30), so some keys MUST collide.
      * Similarly for dumb or hostile usages in which multiple keys are
-     * designed to have identical hash codes. Also, although we guard
-     * against the worst effects of this (see method spread), sets of
-     * hashes may differ only in bits that do not impact their bin
-     * index for a given power-of-two mask.  So we use a secondary
-     * strategy that applies when the number of nodes in a bin exceeds
-     * a threshold, and at least one of the keys implements
-     * Comparable.  These TreeBins use a balanced tree to hold nodes
-     * (a specialized form of red-black trees), bounding search time
-     * to O(log N).  Each search step in a TreeBin is at least twice as
+     * designed to have identical hash codes or ones that differs only
+     * in masked-out high bits. So we use a secondary strategy that
+     * applies when the number of nodes in a bin exceeds a
+     * threshold. These TreeBins use a balanced tree to hold nodes (a
+     * specialized form of red-black trees), bounding search time to
+     * O(log N).  Each search step in a TreeBin is at least twice as
      * slow as in a regular list, but given that N cannot exceed
      * (1<<64) (before running out of addresses) this bounds search
      * steps, lock hold times, etc, to reasonable constants (roughly
@@ -428,16 +426,48 @@
      * LongAdder. We need to incorporate a specialization rather than
      * just use a LongAdder in order to access implicit
      * contention-sensing that leads to creation of multiple
-     * Cells.  The counter mechanics avoid contention on
+     * CounterCells.  The counter mechanics avoid contention on
      * updates but can encounter cache thrashing if read too
      * frequently during concurrent access. To avoid reading so often,
      * resizing under contention is attempted only upon adding to a
      * bin already holding two or more nodes. Under uniform hash
      * distributions, the probability of this occurring at threshold
      * is around 13%, meaning that only about 1 in 8 puts check
-     * threshold (and after resizing, many fewer do so). The bulk
-     * putAll operation further reduces contention by only committing
-     * count updates upon these size checks.
+     * threshold (and after resizing, many fewer do so).
+     *
+     * TreeBins use a special form of comparison for search and
+     * related operations (which is the main reason we cannot use
+     * existing collections such as TreeMaps). TreeBins contain
+     * Comparable elements, but may contain others, as well as
+     * elements that are Comparable but not necessarily Comparable
+     * for the same T, so we cannot invoke compareTo among them. To
+     * handle this, the tree is ordered primarily by hash value, then
+     * by Comparable.compareTo order if applicable.  On lookup at a
+     * node, if elements are not comparable or compare as 0 then both
+     * left and right children may need to be searched in the case of
+     * tied hash values. (This corresponds to the full list search
+     * that would be necessary if all elements were non-Comparable and
+     * had tied hashes.)  The red-black balancing code is updated from
+     * pre-jdk-collections
+     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
+     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
+     * Algorithms" (CLR).
+     *
+     * TreeBins also require an additional locking mechanism.  While
+     * list traversal is always possible by readers even during
+     * updates, tree traversal is not, mainly because of tree-rotations
+     * that may change the root node and/or its linkages.  TreeBins
+     * include a simple read-write lock mechanism parasitic on the
+     * main bin-synchronization strategy: Structural adjustments
+     * associated with an insertion or removal are already bin-locked
+     * (and so cannot conflict with other writers) but must wait for
+     * ongoing readers to finish. Since there can be only one such
+     * waiter, we use a simple scheme using a single "waiter" field to
+     * block writers.  However, readers need never block.  If the root
+     * lock is held, they proceed along the slow traversal path (via
+     * next-pointers) until the lock becomes available or the list is
+     * exhausted, whichever comes first. These cases are not fast, but
+     * maximize aggregate expected throughput.
      *
      * Maintaining API and serialization compatibility with previous
      * versions of this class introduces several oddities. Mainly: We
@@ -447,6 +477,13 @@
      * time that we can guarantee to honor it.) We also declare an
      * unused "Segment" class that is instantiated in minimal form
      * only when serializing.
+     *
+     * This file is organized to make things a little easier to follow
+     * while reading than they might otherwise: First the main static
+     * declarations and utilities, then fields, then main public
+     * methods (with a few factorings of multiple public methods into
+     * internal ones), then sizing methods, trees, traversers, and
+     * bulk operations.
      */
 
     /* ---------------- Constants -------------- */
@@ -489,10 +526,28 @@
 
     /**
      * The bin count threshold for using a tree rather than list for a
-     * bin.  The value reflects the approximate break-even point for
-     * using tree-based operations.
+     * bin.  Bins are converted to trees when adding an element to a
+     * bin with at least this many nodes. The value must be greater
+     * than 2, and should be at least 8 to mesh with assumptions in
+     * tree removal about conversion back to plain bins upon
+     * shrinkage.
      */
-    private static final int TREE_THRESHOLD = 8;
+    static final int TREEIFY_THRESHOLD = 8;
+
+    /**
+     * The bin count threshold for untreeifying a (split) bin during a
+     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
+     * most 6 to mesh with shrinkage detection under removal.
+     */
+    static final int UNTREEIFY_THRESHOLD = 6;
+
+    /**
+     * The smallest table capacity for which bins may be treeified.
+     * (Otherwise the table is resized if too many nodes in a bin.)
+     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
+     * conflicts between resizing and treeification thresholds.
+     */
+    static final int MIN_TREEIFY_CAPACITY = 64;
 
     /**
      * Minimum number of rebinnings per transfer step. Ranges are
@@ -506,7 +561,9 @@
     /*
      * Encodings for Node hash fields. See above for explanation.
      */
-    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
+    static final int MOVED     = -1; // hash for forwarding nodes
+    static final int TREEBIN   = -2; // hash for roots of trees
+    static final int RESERVED  = -3; // hash for transient reservations
     static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
 
     /** Number of CPUS, to place bounds on some sizings */
@@ -519,13 +576,162 @@
         new ObjectStreamField("segmentShift", Integer.TYPE)
     };
 
+    /* ---------------- Nodes -------------- */
+
     /**
-     * A padded cell for distributing counts.  Adapted from LongAdder
-     * and Striped64.  See their internal docs for explanation.
+     * Key-value entry.  This class is never exported out as a
+     * user-mutable Map.Entry (i.e., one supporting setValue; see
+     * MapEntry below), but can be used for read-only traversals used
+     * in bulk tasks.  Subclasses of Node with a negative hash field
+     * are special, and contain null keys and values (but are never
+     * exported).  Otherwise, keys and vals are never null.
+     */
+    static class Node<K,V> implements Map.Entry<K,V> {
+        final int hash;
+        final K key;
+        volatile V val;
+        volatile Node<K,V> next;
+
+        Node(int hash, K key, V val, Node<K,V> next) {
+            this.hash = hash;
+            this.key = key;
+            this.val = val;
+            this.next = next;
+        }
+
+        public final K getKey()       { return key; }
+        public final V getValue()     { return val; }
+        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
+        public final String toString(){ return key + "=" + val; }
+        public final V setValue(V value) {
+            throw new UnsupportedOperationException();
+        }
+
+        public final boolean equals(Object o) {
+            Object k, v, u; Map.Entry<?,?> e;
+            return ((o instanceof Map.Entry) &&
+                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
+                    (v = e.getValue()) != null &&
+                    (k == key || k.equals(key)) &&
+                    (v == (u = val) || v.equals(u)));
+        }
+
+        /**
+         * Virtualized support for map.get(); overridden in subclasses.
+         */
+        Node<K,V> find(int h, Object k) {
+            Node<K,V> e = this;
+            if (k != null) {
+                do {
+                    K ek;
+                    if (e.hash == h &&
+                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
+                        return e;
+                } while ((e = e.next) != null);
+            }
+            return null;
+        }
+    }
+
+    /* ---------------- Static utilities -------------- */
+
+    /**
+     * Spreads (XORs) higher bits of hash to lower and also forces top
+     * bit to 0. Because the table uses power-of-two masking, sets of
+     * hashes that vary only in bits above the current mask will
+     * always collide. (Among known examples are sets of Float keys
+     * holding consecutive whole numbers in small tables.)  So we
+     * apply a transform that spreads the impact of higher bits
+     * downward. There is a tradeoff between speed, utility, and
+     * quality of bit-spreading. Because many common sets of hashes
+     * are already reasonably distributed (so don't benefit from
+     * spreading), and because we use trees to handle large sets of
+     * collisions in bins, we just XOR some shifted bits in the
+     * cheapest possible way to reduce systematic lossage, as well as
+     * to incorporate impact of the highest bits that would otherwise
+     * never be used in index calculations because of table bounds.
      */
-    @sun.misc.Contended static final class Cell {
-        volatile long value;
-        Cell(long x) { value = x; }
+    static final int spread(int h) {
+        return (h ^ (h >>> 16)) & HASH_BITS;
+    }
+
+    /**
+     * Returns a power of two table size for the given desired capacity.
+     * See Hackers Delight, sec 3.2
+     */
+    private static final int tableSizeFor(int c) {
+        int n = c - 1;
+        n |= n >>> 1;
+        n |= n >>> 2;
+        n |= n >>> 4;
+        n |= n >>> 8;
+        n |= n >>> 16;
+        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
+    }
+
+    /**
+     * Returns x's Class if it is of the form "class C implements
+     * Comparable<C>", else null.
+     */
+    static Class<?> comparableClassFor(Object x) {
+        if (x instanceof Comparable) {
+            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
+            if ((c = x.getClass()) == String.class) // bypass checks
+                return c;
+            if ((ts = c.getGenericInterfaces()) != null) {
+                for (int i = 0; i < ts.length; ++i) {
+                    if (((t = ts[i]) instanceof ParameterizedType) &&
+                        ((p = (ParameterizedType)t).getRawType() ==
+                         Comparable.class) &&
+                        (as = p.getActualTypeArguments()) != null &&
+                        as.length == 1 && as[0] == c) // type arg is c
+                        return c;
+                }
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Returns k.compareTo(x) if x matches kc (k's screened comparable
+     * class), else 0.
+     */
+    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
+    static int compareComparables(Class<?> kc, Object k, Object x) {
+        return (x == null || x.getClass() != kc ? 0 :
+                ((Comparable)k).compareTo(x));
+    }
+
+    /* ---------------- Table element access -------------- */
+
+    /*
+     * Volatile access methods are used for table elements as well as
+     * elements of in-progress next table while resizing.  All uses of
+     * the tab arguments must be null checked by callers.  All callers
+     * also paranoically precheck that tab's length is not zero (or an
+     * equivalent check), thus ensuring that any index argument taking
+     * the form of a hash value anded with (length - 1) is a valid
+     * index.  Note that, to be correct wrt arbitrary concurrency
+     * errors by users, these checks must operate on local variables,
+     * which accounts for some odd-looking inline assignments below.
+     * Note that calls to setTabAt always occur within locked regions,
+     * and so in principle require only release ordering, not need
+     * full volatile semantics, but are currently coded as volatile
+     * writes to be conservative.
+     */
+
+    @SuppressWarnings("unchecked")
+    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
+        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
+    }
+
+    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
+                                        Node<K,V> c, Node<K,V> v) {
+        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
+    }
+
+    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
+        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
     }
 
     /* ---------------- Fields -------------- */
@@ -569,170 +775,373 @@
     private transient volatile int transferOrigin;
 
     /**
-     * Spinlock (locked via CAS) used when resizing and/or creating Cells.
+     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
      */
     private transient volatile int cellsBusy;
 
     /**
      * Table of counter cells. When non-null, size is a power of 2.
      */
-    private transient volatile Cell[] counterCells;
+    private transient volatile CounterCell[] counterCells;
 
     // views
     private transient KeySetView<K,V> keySet;
     private transient ValuesView<K,V> values;
     private transient EntrySetView<K,V> entrySet;
 
-    /* ---------------- Table element access -------------- */
-
-    /*
-     * Volatile access methods are used for table elements as well as
-     * elements of in-progress next table while resizing.  Uses are
-     * null checked by callers, and implicitly bounds-checked, relying
-     * on the invariants that tab arrays have non-zero size, and all
-     * indices are masked with (tab.length - 1) which is never
-     * negative and always less than length. Note that, to be correct
-     * wrt arbitrary concurrency errors by users, bounds checks must
-     * operate on local variables, which accounts for some odd-looking
-     * inline assignments below.
+
+    /* ---------------- Public operations -------------- */
+
+    /**
+     * Creates a new, empty map with the default initial table size (16).
+     */
+    public ConcurrentHashMap() {
+    }
+
+    /**
+     * Creates a new, empty map with an initial table size
+     * accommodating the specified number of elements without the need
+     * to dynamically resize.
+     *
+     * @param initialCapacity The implementation performs internal
+     * sizing to accommodate this many elements.
+     * @throws IllegalArgumentException if the initial capacity of
+     * elements is negative
      */
-
-    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
-        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
+    public ConcurrentHashMap(int initialCapacity) {
+        if (initialCapacity < 0)
+            throw new IllegalArgumentException();
+        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
+                   MAXIMUM_CAPACITY :
+                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
+        this.sizeCtl = cap;
+    }
+
+    /**
+     * Creates a new map with the same mappings as the given map.
+     *
+     * @param m the map
+     */
+    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
+        this.sizeCtl = DEFAULT_CAPACITY;
+        putAll(m);
     }
 
-    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
-                                        Node<K,V> c, Node<K,V> v) {
-        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
+    /**
+     * Creates a new, empty map with an initial table size based on
+     * the given number of elements ({@code initialCapacity}) and
+     * initial table density ({@code loadFactor}).
+     *
+     * @param initialCapacity the initial capacity. The implementation
+     * performs internal sizing to accommodate this many elements,
+     * given the specified load factor.
+     * @param loadFactor the load factor (table density) for
+     * establishing the initial table size
+     * @throws IllegalArgumentException if the initial capacity of
+     * elements is negative or the load factor is nonpositive
+     *
+     * @since 1.6
+     */
+    public ConcurrentHashMap(int initialCapacity, float loadFactor) {
+        this(initialCapacity, loadFactor, 1);
     }
 
-    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
-        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
-    }
-
-    /* ---------------- Nodes -------------- */
-
     /**
-     * Key-value entry.  This class is never exported out as a
-     * user-mutable Map.Entry (i.e., one supporting setValue; see
-     * MapEntry below), but can be used for read-only traversals used
-     * in bulk tasks.  Nodes with a hash field of MOVED are special,
-     * and do not contain user keys or values (and are never
-     * exported).  Otherwise, keys and vals are never null.
+     * Creates a new, empty map with an initial table size based on
+     * the given number of elements ({@code initialCapacity}), table
+     * density ({@code loadFactor}), and number of concurrently
+     * updating threads ({@code concurrencyLevel}).
+     *
+     * @param initialCapacity the initial capacity. The implementation
+     * performs internal sizing to accommodate this many elements,
+     * given the specified load factor.
+     * @param loadFactor the load factor (table density) for
+     * establishing the initial table size
+     * @param concurrencyLevel the estimated number of concurrently
+     * updating threads. The implementation may use this value as
+     * a sizing hint.
+     * @throws IllegalArgumentException if the initial capacity is
+     * negative or the load factor or concurrencyLevel are
+     * nonpositive
+     */
+    public ConcurrentHashMap(int initialCapacity,
+                             float loadFactor, int concurrencyLevel) {
+        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
+            throw new IllegalArgumentException();
+        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
+            initialCapacity = concurrencyLevel;   // as estimated threads
+        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
+        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
+            MAXIMUM_CAPACITY : tableSizeFor((int)size);
+        this.sizeCtl = cap;
+    }
+
+    // Original (since JDK1.2) Map methods
+
+    /**
+     * {@inheritDoc}
+     */
+    public int size() {
+        long n = sumCount();
+        return ((n < 0L) ? 0 :
+                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
+                (int)n);
+    }
+
+    /**
+     * {@inheritDoc}
      */
-    static class Node<K,V> implements Map.Entry<K,V> {
-        final int hash;
-        final Object key;
-        volatile V val;
-        Node<K,V> next;
-
-        Node(int hash, Object key, V val, Node<K,V> next) {
-            this.hash = hash;
-            this.key = key;
-            this.val = val;
-            this.next = next;
-        }
-
-        public final K getKey()       { return (K)key; }
-        public final V getValue()     { return val; }
-        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
-        public final String toString(){ return key + "=" + val; }
-        public final V setValue(V value) {
-            throw new UnsupportedOperationException();
-        }
-
-        public final boolean equals(Object o) {
-            Object k, v, u; Map.Entry<?,?> e;
-            return ((o instanceof Map.Entry) &&
-                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
-                    (v = e.getValue()) != null &&
-                    (k == key || k.equals(key)) &&
-                    (v == (u = val) || v.equals(u)));
-        }
+    public boolean isEmpty() {
+        return sumCount() <= 0L; // ignore transient negative values
+    }
+
+    /**
+     * Returns the value to which the specified key is mapped,
+     * or {@code null} if this map contains no mapping for the key.
+     *
+     * <p>More formally, if this map contains a mapping from a key
+     * {@code k} to a value {@code v} such that {@code key.equals(k)},
+     * then this method returns {@code v}; otherwise it returns
+     * {@code null}.  (There can be at most one such mapping.)
+     *
+     * @throws NullPointerException if the specified key is null
+     */
+    public V get(Object key) {
+        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
+        int h = spread(key.hashCode());
+        if ((tab = table) != null && (n = tab.length) > 0 &&
+            (e = tabAt(tab, (n - 1) & h)) != null) {
+            if ((eh = e.hash) == h) {
+                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
+                    return e.val;
+            }
+            else if (eh < 0)
+                return (p = e.find(h, key)) != null ? p.val : null;
+            while ((e = e.next) != null) {
+                if (e.hash == h &&
+                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
+                    return e.val;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Tests if the specified object is a key in this table.
+     *
+     * @param  key possible key
+     * @return {@code true} if and only if the specified object
+     *         is a key in this table, as determined by the
+     *         {@code equals} method; {@code false} otherwise
+     * @throws NullPointerException if the specified key is null
+     */
+    public boolean containsKey(Object key) {
+        return get(key) != null;
+    }
+
+    /**
+     * Returns {@code true} if this map maps one or more keys to the
+     * specified value. Note: This method may require a full traversal
+     * of the map, and is much slower than method {@code containsKey}.
+     *
+     * @param value value whose presence in this map is to be tested
+     * @return {@code true} if this map maps one or more keys to the
+     *         specified value
+     * @throws NullPointerException if the specified value is null
+     */
+    public boolean containsValue(Object value) {
+        if (value == null)
+            throw new NullPointerException();
+        Node<K,V>[] t;
+        if ((t = table) != null) {
+            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
+            for (Node<K,V> p; (p = it.advance()) != null; ) {
+                V v;
+                if ((v = p.val) == value || (v != null && value.equals(v)))
+                    return true;
+            }
+        }
+        return false;
     }
 
     /**
-     * Exported Entry for EntryIterator
+     * Maps the specified key to the specified value in this table.
+     * Neither the key nor the value can be null.
+     *
+     * <p>The value can be retrieved by calling the {@code get} method
+     * with a key that is equal to the original key.
+     *
+     * @param key key with which the specified value is to be associated
+     * @param value value to be associated with the specified key
+     * @return the previous value associated with {@code key}, or
+     *         {@code null} if there was no mapping for {@code key}
+     * @throws NullPointerException if the specified key or value is null
      */
-    static final class MapEntry<K,V> implements Map.Entry<K,V> {
-        final K key; // non-null
-        V val;       // non-null
-        final ConcurrentHashMap<K,V> map;
-        MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
-            this.key = key;
-            this.val = val;
-            this.map = map;
-        }
-        public K getKey()        { return key; }
-        public V getValue()      { return val; }
-        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
-        public String toString() { return key + "=" + val; }
-
-        public boolean equals(Object o) {
-            Object k, v; Map.Entry<?,?> e;
-            return ((o instanceof Map.Entry) &&
-                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
-                    (v = e.getValue()) != null &&
-                    (k == key || k.equals(key)) &&
-                    (v == val || v.equals(val)));
-        }
-
-        /**
-         * Sets our entry's value and writes through to the map. The
-         * value to return is somewhat arbitrary here. Since we do not
-         * necessarily track asynchronous changes, the most recent
-         * "previous" value could be different from what we return (or
-         * could even have been removed, in which case the put will
-         * re-establish). We do not and cannot guarantee more.
-         */
-        public V setValue(V value) {
-            if (value == null) throw new NullPointerException();
-            V v = val;
-            val = value;
-            map.put(key, value);
-            return v;
-        }
+    public V put(K key, V value) {
+        return putVal(key, value, false);
     }
 
-
-    /* ---------------- TreeBins -------------- */
-
-    /**
-     * Nodes for use in TreeBins
-     */
-    static final class TreeNode<K,V> extends Node<K,V> {
-        TreeNode<K,V> parent;  // red-black tree links
-        TreeNode<K,V> left;
-        TreeNode<K,V> right;
-        TreeNode<K,V> prev;    // needed to unlink next upon deletion
-        boolean red;
-
-        TreeNode(int hash, Object key, V val, Node<K,V> next,
-                 TreeNode<K,V> parent) {
-            super(hash, key, val, next);
-            this.parent = parent;
-        }
+    /** Implementation for put and putIfAbsent */
+    final V putVal(K key, V value, boolean onlyIfAbsent) {
+        if (key == null || value == null) throw new NullPointerException();
+        int hash = spread(key.hashCode());
+        int binCount = 0;
+        for (Node<K,V>[] tab = table;;) {
+            Node<K,V> f; int n, i, fh;
+            if (tab == null || (n = tab.length) == 0)
+                tab = initTable();
+            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
+                if (casTabAt(tab, i, null,
+                             new Node<K,V>(hash, key, value, null)))
+                    break;                   // no lock when adding to empty bin
+            }
+            else if ((fh = f.hash) == MOVED)
+                tab = helpTransfer(tab, f);
+            else {
+                V oldVal = null;
+                synchronized (f) {
+                    if (tabAt(tab, i) == f) {
+                        if (fh >= 0) {
+                            binCount = 1;
+                            for (Node<K,V> e = f;; ++binCount) {
+                                K ek;
+                                if (e.hash == hash &&
+                                    ((ek = e.key) == key ||
+                                     (ek != null && key.equals(ek)))) {
+                                    oldVal = e.val;
+                                    if (!onlyIfAbsent)
+                                        e.val = value;
+                                    break;
+                                }
+                                Node<K,V> pred = e;
+                                if ((e = e.next) == null) {
+                                    pred.next = new Node<K,V>(hash, key,
+                                                              value, null);
+                                    break;
+                                }
+                            }
+                        }
+                        else if (f instanceof TreeBin) {
+                            Node<K,V> p;
+                            binCount = 2;
+                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
+                                                           value)) != null) {
+                                oldVal = p.val;
+                                if (!onlyIfAbsent)
+                                    p.val = value;
+                            }
+                        }
+                    }
+                }
+                if (binCount != 0) {
+                    if (binCount >= TREEIFY_THRESHOLD)
+                        treeifyBin(tab, i);
+                    if (oldVal != null)
+                        return oldVal;
+                    break;
+                }
+            }
+        }
+        addCount(1L, binCount);
+        return null;
     }
 
     /**
-     * Returns a Class for the given type of the form "class C
-     * implements Comparable<C>", if one exists, else null.  See below
-     * for explanation.
+     * Copies all of the mappings from the specified map to this one.
+     * These mappings replace any mappings that this map had for any of the
+     * keys currently in the specified map.
+     *
+     * @param m mappings to be stored in this map
+     */
+    public void putAll(Map<? extends K, ? extends V> m) {
+        tryPresize(m.size());
+        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
+            putVal(e.getKey(), e.getValue(), false);
+    }
+
+    /**
+     * Removes the key (and its corresponding value) from this map.
+     * This method does nothing if the key is not in the map.
+     *
+     * @param  key the key that needs to be removed
+     * @return the previous value associated with {@code key}, or
+     *         {@code null} if there was no mapping for {@code key}
+     * @throws NullPointerException if the specified key is null
+     */
+    public V remove(Object key) {
+        return replaceNode(key, null, null);
+    }
+
+    /**
+     * Implementation for the four public remove/replace methods:
+     * Replaces node value with v, conditional upon match of cv if
+     * non-null.  If resulting value is null, delete.
      */
-    static Class<?> comparableClassFor(Class<?> c) {
-        Class<?> s, cmpc; Type[] ts, as; Type t; ParameterizedType p;
-        if (c == String.class) // bypass checks
-            return c;
-        if (c != null && (cmpc = Comparable.class).isAssignableFrom(c)) {
-            while (cmpc.isAssignableFrom(s = c.getSuperclass()))
-                c = s; // find topmost comparable class
-            if ((ts = c.getGenericInterfaces()) != null) {
-                for (int i = 0; i < ts.length; ++i) {
-                    if (((t = ts[i]) instanceof ParameterizedType) &&
-                        ((p = (ParameterizedType)t).getRawType() == cmpc) &&
-                        (as = p.getActualTypeArguments()) != null &&
-                        as.length == 1 && as[0] == c) // type arg is c
-                        return c;
+    final V replaceNode(Object key, V value, Object cv) {
+        int hash = spread(key.hashCode());
+        for (Node<K,V>[] tab = table;;) {
+            Node<K,V> f; int n, i, fh;
+            if (tab == null || (n = tab.length) == 0 ||
+                (f = tabAt(tab, i = (n - 1) & hash)) == null)
+                break;
+            else if ((fh = f.hash) == MOVED)
+                tab = helpTransfer(tab, f);
+            else {
+                V oldVal = null;
+                boolean validated = false;
+                synchronized (f) {
+                    if (tabAt(tab, i) == f) {
+                        if (fh >= 0) {
+                            validated = true;
+                            for (Node<K,V> e = f, pred = null;;) {
+                                K ek;
+                                if (e.hash == hash &&
+                                    ((ek = e.key) == key ||
+                                     (ek != null && key.equals(ek)))) {
+                                    V ev = e.val;
+                                    if (cv == null || cv == ev ||
+                                        (ev != null && cv.equals(ev))) {
+                                        oldVal = ev;
+                                        if (value != null)
+                                            e.val = value;
+                                        else if (pred != null)
+                                            pred.next = e.next;
+                                        else
+                                            setTabAt(tab, i, e.next);
+                                    }
+                                    break;
+                                }
+                                pred = e;
+                                if ((e = e.next) == null)
+                                    break;
+                            }
+                        }
+                        else if (f instanceof TreeBin) {
+                            validated = true;
+                            TreeBin<K,V> t = (TreeBin<K,V>)f;
+                            TreeNode<K,V> r, p;
+                            if ((r = t.root) != null &&
+                                (p = r.findTreeNode(hash, key, null)) != null) {
+                                V pv = p.val;
+                                if (cv == null || cv == pv ||
+                                    (pv != null && cv.equals(pv))) {
+                                    oldVal = pv;
+                                    if (value != null)
+                                        p.val = value;
+                                    else if (t.removeTreeNode(p))
+                                        setTabAt(tab, i, untreeify(t.first));
+                                }
+                            }
+                        }
+                    }
+                }
+                if (validated) {
+                    if (oldVal != null) {
+                        if (value == null)
+                            addCount(-1L, -1);
+                        return oldVal;
+                    }
+                    break;
                 }
             }
         }
@@ -740,780 +1149,535 @@
     }
 
     /**
-     * A specialized form of red-black tree for use in bins
-     * whose size exceeds a threshold.
-     *
-     * TreeBins use a special form of comparison for search and
-     * related operations (which is the main reason we cannot use
-     * existing collections such as TreeMaps). TreeBins contain
-     * Comparable elements, but may contain others, as well as
-     * elements that are Comparable but not necessarily Comparable
-     * for the same T, so we cannot invoke compareTo among them. To
-     * handle this, the tree is ordered primarily by hash value, then
-     * by Comparable.compareTo order if applicable.  On lookup at a
-     * node, if elements are not comparable or compare as 0 then both
-     * left and right children may need to be searched in the case of
-     * tied hash values. (This corresponds to the full list search
-     * that would be necessary if all elements were non-Comparable and
-     * had tied hashes.)  The red-black balancing code is updated from
-     * pre-jdk-collections
-     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
-     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
-     * Algorithms" (CLR).
-     *
-     * TreeBins also maintain a separate locking discipline than
-     * regular bins. Because they are forwarded via special MOVED
-     * nodes at bin heads (which can never change once established),
-     * we cannot use those nodes as locks. Instead, TreeBin extends
-     * StampedLock to support a form of read-write lock. For update
-     * operations and table validation, the exclusive form of lock
-     * behaves in the same way as bin-head locks. However, lookups use
-     * shared read-lock mechanics to allow multiple readers in the
-     * absence of writers.  Additionally, these lookups do not ever
-     * block: While the lock is not available, they proceed along the
-     * slow traversal path (via next-pointers) until the lock becomes
-     * available or the list is exhausted, whichever comes
-     * first. These cases are not fast, but maximize aggregate
-     * expected throughput.
+     * Removes all of the mappings from this map.
      */
-    static final class TreeBin<K,V> extends StampedLock {
-        private static final long serialVersionUID = 2249069246763182397L;
-        transient TreeNode<K,V> root;  // root of tree
-        transient TreeNode<K,V> first; // head of next-pointer list
-
-        /** From CLR */
-        private void rotateLeft(TreeNode<K,V> p) {
-            if (p != null) {
-                TreeNode<K,V> r = p.right, pp, rl;
-                if ((rl = p.right = r.left) != null)
-                    rl.parent = p;
-                if ((pp = r.parent = p.parent) == null)
-                    root = r;
-                else if (pp.left == p)
-                    pp.left = r;
-                else
-                    pp.right = r;
-                r.left = p;
-                p.parent = r;
+    public void clear() {
+        long delta = 0L; // negative number of deletions
+        int i = 0;
+        Node<K,V>[] tab = table;
+        while (tab != null && i < tab.length) {
+            int fh;
+            Node<K,V> f = tabAt(tab, i);
+            if (f == null)
+                ++i;
+            else if ((fh = f.hash) == MOVED) {
+                tab = helpTransfer(tab, f);
+                i = 0; // restart
             }
-        }
-
-        /** From CLR */
-        private void rotateRight(TreeNode<K,V> p) {
-            if (p != null) {
-                TreeNode<K,V> l = p.left, pp, lr;
-                if ((lr = p.left = l.right) != null)
-                    lr.parent = p;
-                if ((pp = l.parent = p.parent) == null)
-                    root = l;
-                else if (pp.right == p)
-                    pp.right = l;
-                else
-                    pp.left = l;
-                l.right = p;
-                p.parent = l;
-            }
-        }
-
-        /**
-         * Returns the TreeNode (or null if not found) for the given key
-         * starting at given root.
-         */
-        final TreeNode<K,V> getTreeNode(int h, Object k, TreeNode<K,V> p,
-                                        Class<?> cc) {
-            while (p != null) {
-                int dir, ph; Object pk; Class<?> pc;
-                if ((ph = p.hash) != h)
-                    dir = (h < ph) ? -1 : 1;
-                else if ((pk = p.key) == k || k.equals(pk))
-                    return p;
-                else if (cc == null || pk == null ||
-                         ((pc = pk.getClass()) != cc &&
-                          comparableClassFor(pc) != cc) ||
-                         (dir = ((Comparable<Object>)k).compareTo(pk)) == 0) {
-                    TreeNode<K,V> r, pr; // check both sides
-                    if ((pr = p.right) != null &&
-                        (r = getTreeNode(h, k, pr, cc)) != null)
-                        return r;
-                    else // continue left
-                        dir = -1;
-                }
-                p = (dir > 0) ? p.right : p.left;
-            }
-            return null;
-        }
-
-        /**
-         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
-         * read-lock to call getTreeNode, but during failure to get
-         * lock, searches along next links.
-         */
-        final V getValue(int h, Object k) {
-            Class<?> cc = comparableClassFor(k.getClass());
-            Node<K,V> r = null;
-            for (Node<K,V> e = first; e != null; e = e.next) {
-                long s;
-                if ((s = tryReadLock()) != 0L) {
-                    try {
-                        r = getTreeNode(h, k, root, cc);
-                    } finally {
-                        unlockRead(s);
+            else {
+                synchronized (f) {
+                    if (tabAt(tab, i) == f) {
+                        Node<K,V> p = (fh >= 0 ? f :
+                                       (f instanceof TreeBin) ?
+                                       ((TreeBin<K,V>)f).first : null);
+                        while (p != null) {
+                            --delta;
+                            p = p.next;
+                        }
+                        setTabAt(tab, i++, null);
                     }
-                    break;
-                }
-                else if (e.hash == h && k.equals(e.key)) {
-                    r = e;
-                    break;
                 }
             }
-            return r == null ? null : r.val;
-        }
-
-        /**
-         * Finds or adds a node.
-         * @return null if added
+        }
+        if (delta != 0L)
+            addCount(delta, -1);
+    }
+
+    /**
+     * Returns a {@link Set} view of the keys contained in this map.
+     * The set is backed by the map, so changes to the map are
+     * reflected in the set, and vice-versa. The set supports element
+     * removal, which removes the corresponding mapping from this map,
+     * via the {@code Iterator.remove}, {@code Set.remove},
+     * {@code removeAll}, {@code retainAll}, and {@code clear}
+     * operations.  It does not support the {@code add} or
+     * {@code addAll} operations.
+     *
+     * <p>The view's {@code iterator} is a "weakly consistent" iterator
+     * that will never throw {@link ConcurrentModificationException},
+     * and guarantees to traverse elements as they existed upon
+     * construction of the iterator, and may (but is not guaranteed to)
+     * reflect any modifications subsequent to construction.
+     *
+     * @return the set view
+     */
+    public KeySetView<K,V> keySet() {
+        KeySetView<K,V> ks;
+        return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
+    }
+
+    /**
+     * Returns a {@link Collection} view of the values contained in this map.
+     * The collection is backed by the map, so changes to the map are
+     * reflected in the collection, and vice-versa.  The collection
+     * supports element removal, which removes the corresponding
+     * mapping from this map, via the {@code Iterator.remove},
+     * {@code Collection.remove}, {@code removeAll},
+     * {@code retainAll}, and {@code clear} operations.  It does not
+     * support the {@code add} or {@code addAll} operations.
+     *
+     * <p>The view's {@code iterator} is a "weakly consistent" iterator
+     * that will never throw {@link ConcurrentModificationException},
+     * and guarantees to traverse elements as they existed upon
+     * construction of the iterator, and may (but is not guaranteed to)
+     * reflect any modifications subsequent to construction.
+     *
+     * @return the collection view
+     */
+    public Collection<V> values() {
+        ValuesView<K,V> vs;
+        return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
+    }
+
+    /**
+     * Returns a {@link Set} view of the mappings contained in this map.
+     * The set is backed by the map, so changes to the map are
+     * reflected in the set, and vice-versa.  The set supports element
+     * removal, which removes the corresponding mapping from the map,
+     * via the {@code Iterator.remove}, {@code Set.remove},
+     * {@code removeAll}, {@code retainAll}, and {@code clear}
+     * operations.
+     *
+     * <p>The view's {@code iterator} is a "weakly consistent" iterator
+     * that will never throw {@link ConcurrentModificationException},
+     * and guarantees to traverse elements as they existed upon
+     * construction of the iterator, and may (but is not guaranteed to)
+     * reflect any modifications subsequent to construction.
+     *
+     * @return the set view
+     */
+    public Set<Map.Entry<K,V>> entrySet() {
+        EntrySetView<K,V> es;
+        return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
+    }
+
+    /**
+     * Returns the hash code value for this {@link Map}, i.e.,
+     * the sum of, for each key-value pair in the map,
+     * {@code key.hashCode() ^ value.hashCode()}.
+     *
+     * @return the hash code value for this map
+     */
+    public int hashCode() {
+        int h = 0;
+        Node<K,V>[] t;
+        if ((t = table) != null) {
+            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
+            for (Node<K,V> p; (p = it.advance()) != null; )
+                h += p.key.hashCode() ^ p.val.hashCode();
+        }
+        return h;
+    }
+
+    /**
+     * Returns a string representation of this map.  The string
+     * representation consists of a list of key-value mappings (in no
+     * particular order) enclosed in braces ("{@code {}}").  Adjacent
+     * mappings are separated by the characters {@code ", "} (comma
+     * and space).  Each key-value mapping is rendered as the key
+     * followed by an equals sign ("{@code =}") followed by the
+     * associated value.
+     *
+     * @return a string representation of this map
+     */
+    public String toString() {
+        Node<K,V>[] t;
+        int f = (t = table) == null ? 0 : t.length;
+        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
+        StringBuilder sb = new StringBuilder();
+        sb.append('{');
+        Node<K,V> p;
+        if ((p = it.advance()) != null) {
+            for (;;) {
+                K k = p.key;
+                V v = p.val;
+                sb.append(k == this ? "(this Map)" : k);
+                sb.append('=');
+                sb.append(v == this ? "(this Map)" : v);
+                if ((p = it.advance()) == null)
+                    break;
+                sb.append(',').append(' ');
+            }
+        }
+        return sb.append('}').toString();
+    }
+
+    /**
+     * Compares the specified object with this map for equality.
+     * Returns {@code true} if the given object is a map with the same
+     * mappings as this map.  This operation may return misleading
+     * results if either map is concurrently modified during execution
+     * of this method.
+     *
+     * @param o object to be compared for equality with this map
+     * @return {@code true} if the specified object is equal to this map
+     */
+    public boolean equals(Object o) {
+        if (o != this) {
+            if (!(o instanceof Map))
+                return false;
+            Map<?,?> m = (Map<?,?>) o;
+            Node<K,V>[] t;
+            int f = (t = table) == null ? 0 : t.length;
+            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
+            for (Node<K,V> p; (p = it.advance()) != null; ) {
+                V val = p.val;
+                Object v = m.get(p.key);
+                if (v == null || (v != val && !v.equals(val)))
+                    return false;
+            }
+            for (Map.Entry<?,?> e : m.entrySet()) {
+                Object mk, mv, v;
+                if ((mk = e.getKey()) == null ||
+                    (mv = e.getValue()) == null ||
+                    (v = get(mk)) == null ||
+                    (mv != v && !mv.equals(v)))
+                    return false;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Stripped-down version of helper class used in previous version,
+     * declared for the sake of serialization compatibility
+     */
+    static class Segment<K,V> extends ReentrantLock implements Serializable {
+        private static final long serialVersionUID = 2249069246763182397L;
+        final float loadFactor;
+        Segment(float lf) { this.loadFactor = lf; }
+    }
+
+    /**
+     * Saves the state of the {@code ConcurrentHashMap} instance to a
+     * stream (i.e., serializes it).
+     * @param s the stream
+     * @serialData
+     * the key (Object) and value (Object)
+     * for each key-value mapping, followed by a null pair.
+     * The key-value mappings are emitted in no particular order.
+     */
+    private void writeObject(java.io.ObjectOutputStream s)
+        throws java.io.IOException {
+        // For serialization compatibility
+        // Emulate segment calculation from previous version of this class
+        int sshift = 0;
+        int ssize = 1;
+        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
+            ++sshift;
+            ssize <<= 1;
+        }
+        int segmentShift = 32 - sshift;
+        int segmentMask = ssize - 1;
+        @SuppressWarnings("unchecked") Segment<K,V>[] segments = (Segment<K,V>[])
+            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
+        for (int i = 0; i < segments.length; ++i)
+            segments[i] = new Segment<K,V>(LOAD_FACTOR);
+        s.putFields().put("segments", segments);
+        s.putFields().put("segmentShift", segmentShift);
+        s.putFields().put("segmentMask", segmentMask);
+        s.writeFields();
+
+        Node<K,V>[] t;
+        if ((t = table) != null) {
+            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
+            for (Node<K,V> p; (p = it.advance()) != null; ) {
+                s.writeObject(p.key);
+                s.writeObject(p.val);
+            }
+        }
+        s.writeObject(null);
+        s.writeObject(null);
+        segments = null; // throw away
+    }
+
+    /**
+     * Reconstitutes the instance from a stream (that is, deserializes it).
+     * @param s the stream
+     */
+    private void readObject(java.io.ObjectInputStream s)
+        throws java.io.IOException, ClassNotFoundException {
+        /*
+         * To improve performance in typical cases, we create nodes
+         * while reading, then place in table once size is known.
+         * However, we must also validate uniqueness and deal with
+         * overpopulated bins while doing so, which requires
+         * specialized versions of putVal mechanics.
          */
-        final TreeNode<K,V> putTreeNode(int h, Object k, V v) {
-            Class<?> cc = comparableClassFor(k.getClass());
-            TreeNode<K,V> pp = root, p = null;
-            int dir = 0;
-            while (pp != null) { // find existing node or leaf to insert at
-                int ph; Object pk; Class<?> pc;
-                p = pp;
-                if ((ph = p.hash) != h)
-                    dir = (h < ph) ? -1 : 1;
-                else if ((pk = p.key) == k || k.equals(pk))
-                    return p;
-                else if (cc == null || pk == null ||
-                         ((pc = pk.getClass()) != cc &&
-                          comparableClassFor(pc) != cc) ||
-                         (dir = ((Comparable<Object>)k).compareTo(pk)) == 0) {
-                    TreeNode<K,V> r, pr;
-                    if ((pr = p.right) != null &&
-                        (r = getTreeNode(h, k, pr, cc)) != null)
-                        return r;
-                    else // continue left
-                        dir = -1;
-                }
-                pp = (dir > 0) ? p.right : p.left;
+        sizeCtl = -1; // force exclusion for table construction
+        s.defaultReadObject();
+        long size = 0L;
+        Node<K,V> p = null;
+        for (;;) {
+            @SuppressWarnings("unchecked") K k = (K) s.readObject();
+            @SuppressWarnings("unchecked") V v = (V) s.readObject();
+            if (k != null && v != null) {
+                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
+                ++size;
             }
-
-            TreeNode<K,V> f = first;
-            TreeNode<K,V> x = first = new TreeNode<K,V>(h, k, v, f, p);
-            if (p == null)
-                root = x;
-            else { // attach and rebalance; adapted from CLR
-                if (f != null)
-                    f.prev = x;
-                if (dir <= 0)
-                    p.left = x;
-                else
-                    p.right = x;
-                x.red = true;
-                for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
-                    if ((xp = x.parent) == null) {
-                        (root = x).red = false;
-                        break;
+            else
+                break;
+        }
+        if (size == 0L)
+            sizeCtl = 0;
+        else {
+            int n;
+            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
+                n = MAXIMUM_CAPACITY;
+            else {
+                int sz = (int)size;
+                n = tableSizeFor(sz + (sz >>> 1) + 1);
+            }
+            @SuppressWarnings({"rawtypes","unchecked"})
+                Node<K,V>[] tab = (Node<K,V>[])new Node[n];
+            int mask = n - 1;
+            long added = 0L;
+            while (p != null) {
+                boolean insertAtFront;
+                Node<K,V> next = p.next, first;
+                int h = p.hash, j = h & mask;
+                if ((first = tabAt(tab, j)) == null)
+                    insertAtFront = true;
+                else {
+                    K k = p.key;
+                    if (first.hash < 0) {
+                        TreeBin<K,V> t = (TreeBin<K,V>)first;
+                        if (t.putTreeVal(h, k, p.val) == null)
+                            ++added;
+                        insertAtFront = false;
+                    }
+                    else {
+                        int binCount = 0;
+                        insertAtFront = true;
+                        Node<K,V> q; K qk;
+                        for (q = first; q != null; q = q.next) {
+                            if (q.hash == h &&
+                                ((qk = q.key) == k ||
+                                 (qk != null && k.equals(qk)))) {
+                                insertAtFront = false;
+                                break;
+                            }
+                            ++binCount;
+                        }
+                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
+                            insertAtFront = false;
+                            ++added;
+                            p.next = first;
+                            TreeNode<K,V> hd = null, tl = null;
+                            for (q = p; q != null; q = q.next) {
+                                TreeNode<K,V> t = new TreeNode<K,V>
+                                    (q.hash, q.key, q.val, null, null);
+                                if ((t.prev = tl) == null)
+                                    hd = t;
+                                else
+                                    tl.next = t;
+                                tl = t;
+                            }
+                            setTabAt(tab, j, new TreeBin<K,V>(hd));
+                        }
                     }
-                    else if (!xp.red || (xpp = xp.parent) == null) {
-                        TreeNode<K,V> r = root;
-                        if (r != null && r.red)
-                            r.red = false;
+                }
+                if (insertAtFront) {
+                    ++added;
+                    p.next = first;
+                    setTabAt(tab, j, p);
+                }
+                p = next;
+            }
+            table = tab;
+            sizeCtl = n - (n >>> 2);
+            baseCount = added;
+        }
+    }
+
+    // ConcurrentMap methods
+
+    /**
+     * {@inheritDoc}
+     *
+     * @return the previous value associated with the specified key,
+     *         or {@code null} if there was no mapping for the key
+     * @throws NullPointerException if the specified key or value is null
+     */
+    public V putIfAbsent(K key, V value) {
+        return putVal(key, value, true);
+    }
+
+    /**
+     * {@inheritDoc}
+     *
+     * @throws NullPointerException if the specified key is null
+     */
+    public boolean remove(Object key, Object value) {
+        if (key == null)
+            throw new NullPointerException();
+        return value != null && replaceNode(key, null, value) != null;
+    }
+
+    /**
+     * {@inheritDoc}
+     *
+     * @throws NullPointerException if any of the arguments are null
+     */
+    public boolean replace(K key, V oldValue, V newValue) {
+        if (key == null || oldValue == null || newValue == null)
+            throw new NullPointerException();
+        return replaceNode(key, newValue, oldValue) != null;
+    }
+
+    /**
+     * {@inheritDoc}
+     *
+     * @return the previous value associated with the specified key,
+     *         or {@code null} if there was no mapping for the key
+     * @throws NullPointerException if the specified key or value is null
+     */
+    public V replace(K key, V value) {
+        if (key == null || value == null)
+            throw new NullPointerException();
+        return replaceNode(key, value, null);
+    }
+
+    // Overrides of JDK8+ Map extension method defaults
+
+    /**
+     * Returns the value to which the specified key is mapped, or the
+     * given default value if this map contains no mapping for the
+     * key.
+     *
+     * @param key the key whose associated value is to be returned
+     * @param defaultValue the value to return if this map contains
+     * no mapping for the given key
+     * @return the mapping for the key, if present; else the default value
+     * @throws NullPointerException if the specified key is null
+     */
+    public V getOrDefault(Object key, V defaultValue) {
+        V v;
+        return (v = get(key)) == null ? defaultValue : v;
+    }
+
+    public void forEach(BiConsumer<? super K, ? super V> action) {
+        if (action == null) throw new NullPointerException();
+        Node<K,V>[] t;
+        if ((t = table) != null) {
+            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
+            for (Node<K,V> p; (p = it.advance()) != null; ) {
+                action.accept(p.key, p.val);
+            }
+        }
+    }
+
+    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
+        if (function == null) throw new NullPointerException();
+        Node<K,V>[] t;
+        if ((t = table) != null) {
+            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
+            for (Node<K,V> p; (p = it.advance()) != null; ) {
+                V oldValue = p.val;
+                for (K key = p.key;;) {
+                    V newValue = function.apply(key, oldValue);
+                    if (newValue == null)
+                        throw new NullPointerException();
+                    if (replaceNode(key, newValue, oldValue) != null ||
+                        (oldValue = get(key)) == null)
                         break;
+                }
+            }
+        }
+    }
+
+    /**
+     * If the specified key is not already associated with a value,
+     * attempts to compute its value using the given mapping function
+     * and enters it into this map unless {@code null}.  The entire
+     * method invocation is performed atomically, so the function is
+     * applied at most once per key.  Some attempted update operations
+     * on this map by other threads may be blocked while computation
+     * is in progress, so the computation should be short and simple,
+     * and must not attempt to update any other mappings of this map.
+     *
+     * @param key key with which the specified value is to be associated
+     * @param mappingFunction the function to compute a value
+     * @return the current (existing or computed) value associated with
+     *         the specified key, or null if the computed value is null
+     * @throws NullPointerException if the specified key or mappingFunction
+     *         is null
+     * @throws IllegalStateException if the computation detectably
+     *         attempts a recursive update to this map that would
+     *         otherwise never complete
+     * @throws RuntimeException or Error if the mappingFunction does so,
+     *         in which case the mapping is left unestablished
+     */
+    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
+        if (key == null || mappingFunction == null)
+            throw new NullPointerException();
+        int h = spread(key.hashCode());
+        V val = null;
+        int binCount = 0;
+        for (Node<K,V>[] tab = table;;) {
+            Node<K,V> f; int n, i, fh;
+            if (tab == null || (n = tab.length) == 0)
+                tab = initTable();
+            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
+                Node<K,V> r = new ReservationNode<K,V>();
+                synchronized (r) {
+                    if (casTabAt(tab, i, null, r)) {
+                        binCount = 1;
+                        Node<K,V> node = null;
+                        try {
+                            if ((val = mappingFunction.apply(key)) != null)
+                                node = new Node<K,V>(h, key, val, null);
+                        } finally {
+                            setTabAt(tab, i, node);
+                        }
                     }
-                    else if ((xppl = xpp.left) == xp) {
-                        if ((xppr = xpp.right) != null && xppr.red) {
-                            xppr.red = false;
-                            xp.red = false;
-                            xpp.red = true;
-                            x = xpp;
-                        }
-                        else {
-                            if (x == xp.right) {
-                                rotateLeft(x = xp);
-                                xpp = (xp = x.parent) == null ? null : xp.parent;
-                            }
-                            if (xp != null) {
-                                xp.red = false;
-                                if (xpp != null) {
-                                    xpp.red = true;
-                                    rotateRight(xpp);
+                }
+                if (binCount != 0)
+                    break;
+            }
+            else if ((fh = f.hash) == MOVED)
+                tab = helpTransfer(tab, f);
+            else {
+                boolean added = false;
+                synchronized (f) {
+                    if (tabAt(tab, i) == f) {
+                        if (fh >= 0) {
+                            binCount = 1;
+                            for (Node<K,V> e = f;; ++binCount) {
+                                K ek; V ev;
+                                if (e.hash == h &&
+                                    ((ek = e.key) == key ||
+                                     (ek != null && key.equals(ek)))) {
+                                    val = e.val;
+                                    break;
+                                }
+                                Node<K,V> pred = e;
+                                if ((e = e.next) == null) {
+                                    if ((val = mappingFunction.apply(key)) != null) {
+                                        added = true;
+                                        pred.next = new Node<K,V>(h, key, val, null);
+                                    }
+                                    break;
                                 }
                             }
                         }
-                    }
-                    else {
-                        if (xppl != null && xppl.red) {
-                            xppl.red = false;
-                            xp.red = false;
-                            xpp.red = true;
-                            x = xpp;
-                        }
-                        else {
-                            if (x == xp.left) {
-                                rotateRight(x = xp);
-                                xpp = (xp = x.parent) == null ? null : xp.parent;
-                            }
-                            if (xp != null) {
-                                xp.red = false;
-                                if (xpp != null) {
-                                    xpp.red = true;
-                                    rotateLeft(xpp);
-                                }
+                        else if (f instanceof TreeBin) {
+                            binCount = 2;
+                            TreeBin<K,V> t = (TreeBin<K,V>)f;
+                            TreeNode<K,V> r, p;
+                            if ((r = t.root) != null &&
+                                (p = r.findTreeNode(h, key, null)) != null)
+                                val = p.val;
+                            else if ((val = mappingFunction.apply(key)) != null) {
+                                added = true;
+                                t.putTreeVal(h, key, val);
                             }
                         }
                     }
                 }
-            }
-            assert checkInvariants();
-            return null;
-        }
-
-        /**
-         * Removes the given node, that must be present before this
-         * call.  This is messier than typical red-black deletion code
-         * because we cannot swap the contents of an interior node
-         * with a leaf successor that is pinned by "next" pointers
-         * that are accessible independently of lock. So instead we
-         * swap the tree linkages.
-         */
-        final void deleteTreeNode(TreeNode<K,V> p) {
-            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
-            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
-            if (pred == null)
-                first = next;
-            else
-                pred.next = next;
-            if (next != null)
-                next.prev = pred;
-            else if (pred == null) {
-                root = null;
-                return;
-            }
-            TreeNode<K,V> replacement;
-            TreeNode<K,V> pl = p.left;
-            TreeNode<K,V> pr = p.right;
-            if (pl != null && pr != null) {
-                TreeNode<K,V> s = pr, sl;
-                while ((sl = s.left) != null) // find successor
-                    s = sl;
-                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
-                TreeNode<K,V> sr = s.right;
-                TreeNode<K,V> pp = p.parent;
-                if (s == pr) { // p was s's direct parent
-                    p.parent = s;
-                    s.right = p;
-                }
-                else {
-                    TreeNode<K,V> sp = s.parent;
-                    if ((p.parent = sp) != null) {
-                        if (s == sp.left)
-                            sp.left = p;
-                        else
-                            sp.right = p;
-                    }
-                    if ((s.right = pr) != null)
-                        pr.parent = s;
-                }
-                p.left = null;
-                if ((p.right = sr) != null)
-                    sr.parent = p;
-                if ((s.left = pl) != null)
-                    pl.parent = s;
-                if ((s.parent = pp) == null)
-                    root = s;
-                else if (p == pp.left)
-                    pp.left = s;
-                else
-                    pp.right = s;
-                if (sr != null)
-                    replacement = sr;
-                else
-                    replacement = p;
-            }
-            else if (pl != null)
-                replacement = pl;
-            else if (pr != null)
-                replacement = pr;
-            else
-                replacement = p;
-            if (replacement != p) {
-                TreeNode<K,V> pp = replacement.parent = p.parent;
-                if (pp == null)
-                    root = replacement;
-                else if (p == pp.left)
-                    pp.left = replacement;
-                else
-                    pp.right = replacement;
-                p.left = p.right = p.parent = null;
-            }
-            if (!p.red) { // rebalance, from CLR
-                for (TreeNode<K,V> x = replacement; x != null; ) {
-                    TreeNode<K,V> xp, xpl, xpr;
-                    if (x.red || (xp = x.parent) == null) {
-                        x.red = false;
-                        break;
-                    }
-                    else if ((xpl = xp.left) == x) {
-                        if ((xpr = xp.right) != null && xpr.red) {
-                            xpr.red = false;
-                            xp.red = true;
-                            rotateLeft(xp);
-                            xpr = (xp = x.parent) == null ? null : xp.right;
-                        }
-                        if (xpr == null)
-                            x = xp;
-                        else {
-                            TreeNode<K,V> sl = xpr.left, sr = xpr.right;
-                            if ((sr == null || !sr.red) &&
-                                (sl == null || !sl.red)) {
-                                xpr.red = true;
-                                x = xp;
-                            }
-                            else {
-                                if (sr == null || !sr.red) {
-                                    if (sl != null)
-                                        sl.red = false;
-                                    xpr.red = true;
-                                    rotateRight(xpr);
-                                    xpr = (xp = x.parent) == null ?
-                                        null : xp.right;
-                                }
-                                if (xpr != null) {
-                                    xpr.red = (xp == null) ? false : xp.red;
-                                    if ((sr = xpr.right) != null)
-                                        sr.red = false;
-                                }
-                                if (xp != null) {
-                                    xp.red = false;
-                                    rotateLeft(xp);
-                                }
-                                x = root;
-                            }
-                        }
-                    }
-                    else { // symmetric
-                        if (xpl != null && xpl.red) {
-                            xpl.red = false;
-                            xp.red = true;
-                            rotateRight(xp);
-                            xpl = (xp = x.parent) == null ? null : xp.left;
-                        }
-                        if (xpl == null)
-                            x = xp;
-                        else {
-                            TreeNode<K,V> sl = xpl.left, sr = xpl.right;
-                            if ((sl == null || !sl.red) &&
-                                (sr == null || !sr.red)) {
-                                xpl.red = true;
-                                x = xp;
-                            }
-                            else {
-                                if (sl == null || !sl.red) {
-                                    if (sr != null)
-                                        sr.red = false;
-                                    xpl.red = true;
-                                    rotateLeft(xpl);
-                                    xpl = (xp = x.parent) == null ?
-                                        null : xp.left;
-                                }
-                                if (xpl != null) {
-                                    xpl.red = (xp == null) ? false : xp.red;
-                                    if ((sl = xpl.left) != null)
-                                        sl.red = false;
-                                }
-                                if (xp != null) {
-                                    xp.red = false;
-                                    rotateRight(xp);
-                                }
-                                x = root;
-                            }
-                        }
-                    }
-                }
-            }
-            if (p == replacement) {  // detach pointers
-                TreeNode<K,V> pp;
-                if ((pp = p.parent) != null) {
-                    if (p == pp.left)
-                        pp.left = null;
-                    else if (p == pp.right)
-                        pp.right = null;
-                    p.parent = null;
-                }
-            }
-            assert checkInvariants();
-        }
-
-        /**
-         * Checks linkage and balance invariants at root
-         */
-        final boolean checkInvariants() {
-            TreeNode<K,V> r = root;
-            if (r == null)
-                return (first == null);
-            else
-                return (first != null) && checkTreeNode(r);
-        }
-
-        /**
-         * Recursive invariant check
-         */
-        final boolean checkTreeNode(TreeNode<K,V> t) {
-            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
-                tb = t.prev, tn = (TreeNode<K,V>)t.next;
-            if (tb != null && tb.next != t)
-                return false;
-            if (tn != null && tn.prev != t)
-                return false;
-            if (tp != null && t != tp.left && t != tp.right)
-                return false;
-            if (tl != null && (tl.parent != t || tl.hash > t.hash))
-                return false;
-            if (tr != null && (tr.parent != t || tr.hash < t.hash))
-                return false;
-            if (t.red && tl != null && tl.red && tr != null && tr.red)
-                return false;
-            if (tl != null && !checkTreeNode(tl))
-                return false;
-            if (tr != null && !checkTreeNode(tr))
-                return false;
-            return true;
-        }
-    }
-
-    /* ---------------- Collision reduction methods -------------- */
-
-    /**
-     * Spreads higher bits to lower, and also forces top bit to 0.
-     * Because the table uses power-of-two masking, sets of hashes
-     * that vary only in bits above the current mask will always
-     * collide. (Among known examples are sets of Float keys holding
-     * consecutive whole numbers in small tables.)  To counter this,
-     * we apply a transform that spreads the impact of higher bits
-     * downward. There is a tradeoff between speed, utility, and
-     * quality of bit-spreading. Because many common sets of hashes
-     * are already reasonably distributed across bits (so don't benefit
-     * from spreading), and because we use trees to handle large sets
-     * of collisions in bins, we don't need excessively high quality.
-     */
-    private static final int spread(int h) {
-        h ^= (h >>> 18) ^ (h >>> 12);
-        return (h ^ (h >>> 10)) & HASH_BITS;
-    }
-
-    /**
-     * Replaces a list bin with a tree bin if key is comparable.  Call
-     * only when locked.
-     */
-    private final void replaceWithTreeBin(Node<K,V>[] tab, int index, Object key) {
-        if (tab != null && comparableClassFor(key.getClass()) != null) {
-            TreeBin<K,V> t = new TreeBin<K,V>();
-            for (Node<K,V> e = tabAt(tab, index); e != null; e = e.next)
-                t.putTreeNode(e.hash, e.key, e.val);
-            setTabAt(tab, index, new Node<K,V>(MOVED, t, null, null));
-        }
-    }
-
-    /* ---------------- Internal access and update methods -------------- */
-
-    /** Implementation for get and containsKey */
-    private final V internalGet(Object k) {
-        int h = spread(k.hashCode());
-        V v = null;
-        Node<K,V>[] tab; Node<K,V> e;
-        if ((tab = table) != null &&
-            (e = tabAt(tab, (tab.length - 1) & h)) != null) {
-            for (;;) {
-                int eh; Object ek;
-                if ((eh = e.hash) < 0) {
-                    if ((ek = e.key) instanceof TreeBin) { // search TreeBin
-                        v = ((TreeBin<K,V>)ek).getValue(h, k);
-                        break;
-                    }
-                    else if (!(ek instanceof Node[]) ||    // try new table
-                             (e = tabAt(tab = (Node<K,V>[])ek,
-                                        (tab.length - 1) & h)) == null)
-                        break;
-                }
-                else if (eh == h && ((ek = e.key) == k || k.equals(ek))) {
-                    v = e.val;
-                    break;
-                }
-                else if ((e = e.next) == null)
-                    break;
-            }
-        }
-        return v;
-    }
-
-    /**
-     * Implementation for the four public remove/replace methods:
-     * Replaces node value with v, conditional upon match of cv if
-     * non-null.  If resulting value is null, delete.
-     */
-    private final V internalReplace(Object k, V v, Object cv) {
-        int h = spread(k.hashCode());
-        V oldVal = null;
-        for (Node<K,V>[] tab = table;;) {
-            Node<K,V> f; int i, fh; Object fk;
-            if (tab == null ||
-                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
-                break;
-            else if ((fh = f.hash) < 0) {
-                if ((fk = f.key) instanceof TreeBin) {
-                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
-                    long stamp = t.writeLock();
-                    boolean validated = false;
-                    boolean deleted = false;
-                    try {
-                        if (tabAt(tab, i) == f) {
-                            validated = true;
-                            Class<?> cc = comparableClassFor(k.getClass());
-                            TreeNode<K,V> p = t.getTreeNode(h, k, t.root, cc);
-                            if (p != null) {
-                                V pv = p.val;
-                                if (cv == null || cv == pv || cv.equals(pv)) {
-                                    oldVal = pv;
-                                    if (v != null)
-                                        p.val = v;
-                                    else {
-                                        deleted = true;
-                                        t.deleteTreeNode(p);
-                                    }
-                                }
-                            }
-                        }
-                    } finally {
-                        t.unlockWrite(stamp);
-                    }
-                    if (validated) {
-                        if (deleted)
-                            addCount(-1L, -1);
-                        break;
-                    }
-                }
-                else
-                    tab = (Node<K,V>[])fk;
-            }
-            else {
-                boolean validated = false;
-                boolean deleted = false;
-                synchronized (f) {
-                    if (tabAt(tab, i) == f) {
-                        validated = true;
-                        for (Node<K,V> e = f, pred = null;;) {
-                            Object ek;
-                            if (e.hash == h &&
-                                ((ek = e.key) == k || k.equals(ek))) {
-                                V ev = e.val;
-                                if (cv == null || cv == ev || cv.equals(ev)) {
-                                    oldVal = ev;
-                                    if (v != null)
-                                        e.val = v;
-                                    else {
-                                        deleted = true;
-                                        Node<K,V> en = e.next;
-                                        if (pred != null)
-                                            pred.next = en;
-                                        else
-                                            setTabAt(tab, i, en);
-                                    }
-                                }
-                                break;
-                            }
-                            pred = e;
-                            if ((e = e.next) == null)
-                                break;
-                        }
-                    }
-                }
-                if (validated) {
-                    if (deleted)
-                        addCount(-1L, -1);
-                    break;
-                }
-            }
-        }
-        return oldVal;
-    }
-
-    /*
-     * Internal versions of insertion methods
-     * All have the same basic structure as the first (internalPut):
-     *  1. If table uninitialized, create
-     *  2. If bin empty, try to CAS new node
-     *  3. If bin stale, use new table
-     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
-     *  5. Lock and validate; if valid, scan and add or update
-     *
-     * The putAll method differs mainly in attempting to pre-allocate
-     * enough table space, and also more lazily performs count updates
-     * and checks.
-     *
-     * Most of the function-accepting methods can't be factored nicely
-     * because they require different functional forms, so instead
-     * sprawl out similar mechanics.
-     */
-
-    /** Implementation for put and putIfAbsent */
-    private final V internalPut(K k, V v, boolean onlyIfAbsent) {
-        if (k == null || v == null) throw new NullPointerException();
-        int h = spread(k.hashCode());
-        int len = 0;
-        for (Node<K,V>[] tab = table;;) {
-            int i, fh; Node<K,V> f; Object fk;
-            if (tab == null)
-                tab = initTable();
-            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
-                if (casTabAt(tab, i, null, new Node<K,V>(h, k, v, null)))
-                    break;                   // no lock when adding to empty bin
-            }
-            else if ((fh = f.hash) < 0) {
-                if ((fk = f.key) instanceof TreeBin) {
-                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
-                    long stamp = t.writeLock();
-                    V oldVal = null;
-                    try {
-                        if (tabAt(tab, i) == f) {
-                            len = 2;
-                            TreeNode<K,V> p = t.putTreeNode(h, k, v);
-                            if (p != null) {
-                                oldVal = p.val;
-                                if (!onlyIfAbsent)
-                                    p.val = v;
-                            }
-                        }
-                    } finally {
-                        t.unlockWrite(stamp);
-                    }
-                    if (len != 0) {
-                        if (oldVal != null)
-                            return oldVal;
-                        break;
-                    }
-                }
-                else
-                    tab = (Node<K,V>[])fk;
-            }
-            else {
-                V oldVal = null;
-                synchronized (f) {
-                    if (tabAt(tab, i) == f) {
-                        len = 1;
-                        for (Node<K,V> e = f;; ++len) {
-                            Object ek;
-                            if (e.hash == h &&
-                                ((ek = e.key) == k || k.equals(ek))) {
-                                oldVal = e.val;
-                                if (!onlyIfAbsent)
-                                    e.val = v;
-                                break;
-                            }
-                            Node<K,V> last = e;
-                            if ((e = e.next) == null) {
-                                last.next = new Node<K,V>(h, k, v, null);
-                                if (len > TREE_THRESHOLD)
-                                    replaceWithTreeBin(tab, i, k);
-                                break;
-                            }
-                        }
-                    }
-                }
-                if (len != 0) {
-                    if (oldVal != null)
-                        return oldVal;
-                    break;
-                }
-            }
-        }
-        addCount(1L, len);
-        return null;
-    }
-
-    /** Implementation for computeIfAbsent */
-    private final V internalComputeIfAbsent(K k, Function<? super K, ? extends V> mf) {
-        if (k == null || mf == null)
-            throw new NullPointerException();
-        int h = spread(k.hashCode());
-        V val = null;
-        int len = 0;
-        for (Node<K,V>[] tab = table;;) {
-            Node<K,V> f; int i; Object fk;
-            if (tab == null)
-                tab = initTable();
-            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
-                Node<K,V> node = new Node<K,V>(h, k, null, null);
-                synchronized (node) {
-                    if (casTabAt(tab, i, null, node)) {
-                        len = 1;
-                        try {
-                            if ((val = mf.apply(k)) != null)
-                                node.val = val;
-                        } finally {
-                            if (val == null)
-                                setTabAt(tab, i, null);
-                        }
-                    }
-                }
-                if (len != 0)
-                    break;
-            }
-            else if (f.hash < 0) {
-                if ((fk = f.key) instanceof TreeBin) {
-                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
-                    long stamp = t.writeLock();
-                    boolean added = false;
-                    try {
-                        if (tabAt(tab, i) == f) {
-                            len = 2;
-                            Class<?> cc = comparableClassFor(k.getClass());
-                            TreeNode<K,V> p = t.getTreeNode(h, k, t.root, cc);
-                            if (p != null)
-                                val = p.val;
-                            else if ((val = mf.apply(k)) != null) {
-                                added = true;
-                                t.putTreeNode(h, k, val);
-                            }
-                        }
-                    } finally {
-                        t.unlockWrite(stamp);
-                    }
-                    if (len != 0) {
-                        if (!added)
-                            return val;
-                        break;
-                    }
-                }
-                else
-                    tab = (Node<K,V>[])fk;
-            }
-            else {
-                boolean added = false;
-                synchronized (f) {
-                    if (tabAt(tab, i) == f) {
-                        len = 1;
-                        for (Node<K,V> e = f;; ++len) {
-                            Object ek; V ev;
-                            if (e.hash == h &&
-                                ((ek = e.key) == k || k.equals(ek))) {
-                                val = e.val;
-                                break;
-                            }
-                            Node<K,V> last = e;
-                            if ((e = e.next) == null) {
-                                if ((val = mf.apply(k)) != null) {
-                                    added = true;
-                                    last.next = new Node<K,V>(h, k, val, null);
-                                    if (len > TREE_THRESHOLD)
-                                        replaceWithTreeBin(tab, i, k);
-                                }
-                                break;
-                            }
-                        }
-                    }
-                }
-                if (len != 0) {
+                if (binCount != 0) {
+                    if (binCount >= TREEIFY_THRESHOLD)
+                        treeifyBin(tab, i);
                     if (!added)
                         return val;
                     break;
@@ -1521,384 +1685,511 @@
             }
         }
         if (val != null)
-            addCount(1L, len);
+            addCount(1L, binCount);
         return val;
     }
 
-    /** Implementation for compute */
-    private final V internalCompute(K k, boolean onlyIfPresent,
-                                    BiFunction<? super K, ? super V, ? extends V> mf) {
-        if (k == null || mf == null)
+    /**
+     * If the value for the specified key is present, attempts to
+     * compute a new mapping given the key and its current mapped
+     * value.  The entire method invocation is performed atomically.
+     * Some attempted update operations on this map by other threads
+     * may be blocked while computation is in progress, so the
+     * computation should be short and simple, and must not attempt to
+     * update any other mappings of this map.
+     *
+     * @param key key with which a value may be associated
+     * @param remappingFunction the function to compute a value
+     * @return the new value associated with the specified key, or null if none
+     * @throws NullPointerException if the specified key or remappingFunction
+     *         is null
+     * @throws IllegalStateException if the computation detectably
+     *         attempts a recursive update to this map that would
+     *         otherwise never complete
+     * @throws RuntimeException or Error if the remappingFunction does so,
+     *         in which case the mapping is unchanged
+     */
+    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
+        if (key == null || remappingFunction == null)
             throw new NullPointerException();
-        int h = spread(k.hashCode());
+        int h = spread(key.hashCode());
         V val = null;
         int delta = 0;
-        int len = 0;
+        int binCount = 0;
         for (Node<K,V>[] tab = table;;) {
-            Node<K,V> f; int i, fh; Object fk;
-            if (tab == null)
+            Node<K,V> f; int n, i, fh;
+            if (tab == null || (n = tab.length) == 0)
                 tab = initTable();
-            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
-                if (onlyIfPresent)
-                    break;
-                Node<K,V> node = new Node<K,V>(h, k, null, null);
-                synchronized (node) {
-                    if (casTabAt(tab, i, null, node)) {
-                        try {
-                            len = 1;
-                            if ((val = mf.apply(k, null)) != null) {
-                                node.val = val;
-                                delta = 1;
-                            }
-                        } finally {
-                            if (delta == 0)
-                                setTabAt(tab, i, null);
-                        }
-                    }
-                }
-                if (len != 0)
-                    break;
-            }
-            else if ((fh = f.hash) < 0) {
-                if ((fk = f.key) instanceof TreeBin) {
-                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
-                    long stamp = t.writeLock();
-                    try {
-                        if (tabAt(tab, i) == f) {
-                            len = 2;
-                            Class<?> cc = comparableClassFor(k.getClass());
-                            TreeNode<K,V> p = t.getTreeNode(h, k, t.root, cc);
-                            if (p != null || !onlyIfPresent) {
-                                V pv = (p == null) ? null : p.val;
-                                if ((val = mf.apply(k, pv)) != null) {
-                                    if (p != null)
-                                        p.val = val;
-                                    else {
-                                        delta = 1;
-                                        t.putTreeNode(h, k, val);
-                                    }
-                                }
-                                else if (p != null) {
-                                    delta = -1;
-                                    t.deleteTreeNode(p);
-                                }
-                            }
-                        }
-                    } finally {
-                        t.unlockWrite(stamp);
-                    }
-                    if (len != 0)
-                        break;
-                }
-                else
-                    tab = (Node<K,V>[])fk;
-            }
+            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
+                break;
+            else if ((fh = f.hash) == MOVED)
+                tab = helpTransfer(tab, f);
             else {
                 synchronized (f) {
                     if (tabAt(tab, i) == f) {
-                        len = 1;
-                        for (Node<K,V> e = f, pred = null;; ++len) {
-                            Object ek;
-                            if (e.hash == h &&
-                                ((ek = e.key) == k || k.equals(ek))) {
-                                val = mf.apply(k, e.val);
+                        if (fh >= 0) {
+                            binCount = 1;
+                            for (Node<K,V> e = f, pred = null;; ++binCount) {
+                                K ek;
+                                if (e.hash == h &&
+                                    ((ek = e.key) == key ||
+                                     (ek != null && key.equals(ek)))) {
+                                    val = remappingFunction.apply(key, e.val);
+                                    if (val != null)
+                                        e.val = val;
+                                    else {
+                                        delta = -1;
+                                        Node<K,V> en = e.next;
+                                        if (pred != null)
+                                            pred.next = en;
+                                        else
+                                            setTabAt(tab, i, en);
+                                    }
+                                    break;
+                                }
+                                pred = e;
+                                if ((e = e.next) == null)
+                                    break;
+                            }
+                        }
+                        else if (f instanceof TreeBin) {
+                            binCount = 2;
+                            TreeBin<K,V> t = (TreeBin<K,V>)f;
+                            TreeNode<K,V> r, p;
+                            if ((r = t.root) != null &&
+                                (p = r.findTreeNode(h, key, null)) != null) {
+                                val = remappingFunction.apply(key, p.val);
                                 if (val != null)
-                                    e.val = val;
+                                    p.val = val;
                                 else {
                                     delta = -1;
-                                    Node<K,V> en = e.next;
-                                    if (pred != null)
-                                        pred.next = en;
-                                    else
-                                        setTabAt(tab, i, en);
+                                    if (t.removeTreeNode(p))
+                                        setTabAt(tab, i, untreeify(t.first));
                                 }
-                                break;
-                            }
-                            pred = e;
-                            if ((e = e.next) == null) {
-                                if (!onlyIfPresent &&
-                                    (val = mf.apply(k, null)) != null) {
-                                    pred.next = new Node<K,V>(h, k, val, null);
-                                    delta = 1;
-                                    if (len > TREE_THRESHOLD)
-                                        replaceWithTreeBin(tab, i, k);
-                                }
-                                break;
                             }
                         }
                     }
                 }
-                if (len != 0)
+                if (binCount != 0)
                     break;
             }
         }
         if (delta != 0)
-            addCount((long)delta, len);
+            addCount((long)delta, binCount);
         return val;
     }
 
-    /** Implementation for merge */
-    private final V internalMerge(K k, V v,
-                                  BiFunction<? super V, ? super V, ? extends V> mf) {
-        if (k == null || v == null || mf == null)
+    /**
+     * Attempts to compute a mapping for the specified key and its
+     * current mapped value (or {@code null} if there is no current
+     * mapping). The entire method invocation is performed atomically.
+     * Some attempted update operations on this map by other threads
+     * may be blocked while computation is in progress, so the
+     * computation should be short and simple, and must not attempt to
+     * update any other mappings of this Map.
+     *
+     * @param key key with which the specified value is to be associated
+     * @param remappingFunction the function to compute a value
+     * @return the new value associated with the specified key, or null if none
+     * @throws NullPointerException if the specified key or remappingFunction
+     *         is null
+     * @throws IllegalStateException if the computation detectably
+     *         attempts a recursive update to this map that would
+     *         otherwise never complete
+     * @throws RuntimeException or Error if the remappingFunction does so,
+     *         in which case the mapping is unchanged
+     */
+    public V compute(K key,
+                     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
+        if (key == null || remappingFunction == null)
             throw new NullPointerException();
-        int h = spread(k.hashCode());
+        int h = spread(key.hashCode());
         V val = null;
         int delta = 0;
-        int len = 0;
+        int binCount = 0;
         for (Node<K,V>[] tab = table;;) {
-            int i; Node<K,V> f; Object fk;
-            if (tab == null)
+            Node<K,V> f; int n, i, fh;
+            if (tab == null || (n = tab.length) == 0)
                 tab = initTable();
-            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
-                if (casTabAt(tab, i, null, new Node<K,V>(h, k, v, null))) {
-                    delta = 1;
-                    val = v;
-                    break;
+            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
+                Node<K,V> r = new ReservationNode<K,V>();
+                synchronized (r) {
+                    if (casTabAt(tab, i, null, r)) {
+                        binCount = 1;
+                        Node<K,V> node = null;
+                        try {
+                            if ((val = remappingFunction.apply(key, null)) != null) {
+                                delta = 1;
+                                node = new Node<K,V>(h, key, val, null);
+                            }
+                        } finally {
+                            setTabAt(tab, i, node);
+                        }
+                    }
                 }
+                if (binCount != 0)
+                    break;
             }
-            else if (f.hash < 0) {
-                if ((fk = f.key) instanceof TreeBin) {
-                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
-                    long stamp = t.writeLock();
-                    try {
-                        if (tabAt(tab, i) == f) {
-                            len = 2;
-                            Class<?> cc = comparableClassFor(k.getClass());
-                            TreeNode<K,V> p = t.getTreeNode(h, k, t.root, cc);
-                            val = (p == null) ? v : mf.apply(p.val, v);
+            else if ((fh = f.hash) == MOVED)
+                tab = helpTransfer(tab, f);
+            else {
+                synchronized (f) {
+                    if (tabAt(tab, i) == f) {
+                        if (fh >= 0) {
+                            binCount = 1;
+                            for (Node<K,V> e = f, pred = null;; ++binCount) {
+                                K ek;
+                                if (e.hash == h &&
+                                    ((ek = e.key) == key ||
+                                     (ek != null && key.equals(ek)))) {
+                                    val = remappingFunction.apply(key, e.val);
+                                    if (val != null)
+                                        e.val = val;
+                                    else {
+                                        delta = -1;
+                                        Node<K,V> en = e.next;
+                                        if (pred != null)
+                                            pred.next = en;
+                                        else
+                                            setTabAt(tab, i, en);
+                                    }
+                                    break;
+                                }
+                                pred = e;
+                                if ((e = e.next) == null) {
+                                    val = remappingFunction.apply(key, null);
+                                    if (val != null) {
+                                        delta = 1;
+                                        pred.next =
+                                            new Node<K,V>(h, key, val, null);
+                                    }
+                                    break;
+                                }
+                            }
+                        }
+                        else if (f instanceof TreeBin) {
+                            binCount = 1;
+                            TreeBin<K,V> t = (TreeBin<K,V>)f;
+                            TreeNode<K,V> r, p;
+                            if ((r = t.root) != null)
+                                p = r.findTreeNode(h, key, null);
+                            else
+                                p = null;
+                            V pv = (p == null) ? null : p.val;
+                            val = remappingFunction.apply(key, pv);
                             if (val != null) {
                                 if (p != null)
                                     p.val = val;
                                 else {
                                     delta = 1;
-                                    t.putTreeNode(h, k, val);
+                                    t.putTreeVal(h, key, val);
                                 }
                             }
                             else if (p != null) {
                                 delta = -1;
-                                t.deleteTreeNode(p);
+                                if (t.removeTreeNode(p))
+                                    setTabAt(tab, i, untreeify(t.first));
                             }
                         }
-                    } finally {
-                        t.unlockWrite(stamp);
                     }
-                    if (len != 0)
-                        break;
+                }
+                if (binCount != 0) {
+                    if (binCount >= TREEIFY_THRESHOLD)
+                        treeifyBin(tab, i);
+                    break;
                 }
-                else
-                    tab = (Node<K,V>[])fk;
             }
+        }
+        if (delta != 0)
+            addCount((long)delta, binCount);
+        return val;
+    }
+
+    /**
+     * If the specified key is not already associated with a
+     * (non-null) value, associates it with the given value.
+     * Otherwise, replaces the value with the results of the given
+     * remapping function, or removes if {@code null}. The entire
+     * method invocation is performed atomically.  Some attempted
+     * update operations on this map by other threads may be blocked
+     * while computation is in progress, so the computation should be
+     * short and simple, and must not attempt to update any other
+     * mappings of this Map.
+     *
+     * @param key key with which the specified value is to be associated
+     * @param value the value to use if absent
+     * @param remappingFunction the function to recompute a value if present
+     * @return the new value associated with the specified key, or null if none
+     * @throws NullPointerException if the specified key or the
+     *         remappingFunction is null
+     * @throws RuntimeException or Error if the remappingFunction does so,
+     *         in which case the mapping is unchanged
+     */
+    public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
+        if (key == null || value == null || remappingFunction == null)
+            throw new NullPointerException();
+        int h = spread(key.hashCode());
+        V val = null;
+        int delta = 0;
+        int binCount = 0;
+        for (Node<K,V>[] tab = table;;) {
+            Node<K,V> f; int n, i, fh;
+            if (tab == null || (n = tab.length) == 0)
+                tab = initTable();
+            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
+                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value, null))) {
+                    delta = 1;
+                    val = value;
+                    break;
+                }
+            }
+            else if ((fh = f.hash) == MOVED)
+                tab = helpTransfer(tab, f);
             else {
                 synchronized (f) {
                     if (tabAt(tab, i) == f) {
-                        len = 1;
-                        for (Node<K,V> e = f, pred = null;; ++len) {
-                            Object ek;
-                            if (e.hash == h &&
-                                ((ek = e.key) == k || k.equals(ek))) {
-                                val = mf.apply(e.val, v);
-                                if (val != null)
-                                    e.val = val;
+                        if (fh >= 0) {
+                            binCount = 1;
+                            for (Node<K,V> e = f, pred = null;; ++binCount) {
+                                K ek;
+                                if (e.hash == h &&
+                                    ((ek = e.key) == key ||
+                                     (ek != null && key.equals(ek)))) {
+                                    val = remappingFunction.apply(e.val, value);
+                                    if (val != null)
+                                        e.val = val;
+                                    else {
+                                        delta = -1;
+                                        Node<K,V> en = e.next;
+                                        if (pred != null)
+                                            pred.next = en;
+                                        else
+                                            setTabAt(tab, i, en);
+                                    }
+                                    break;
+                                }
+                                pred = e;
+                                if ((e = e.next) == null) {
+                                    delta = 1;
+                                    val = value;
+                                    pred.next =
+                                        new Node<K,V>(h, key, val, null);
+                                    break;
+                                }
+                            }
+                        }
+                        else if (f instanceof TreeBin) {
+                            binCount = 2;
+                            TreeBin<K,V> t = (TreeBin<K,V>)f;
+                            TreeNode<K,V> r = t.root;
+                            TreeNode<K,V> p = (r == null) ? null :
+                                r.findTreeNode(h, key, null);
+                            val = (p == null) ? value :
+                                remappingFunction.apply(p.val, value);
+                            if (val != null) {
+                                if (p != null)
+                                    p.val = val;
                                 else {
-                                    delta = -1;
-                                    Node<K,V> en = e.next;
-                                    if (pred != null)
-                                        pred.next = en;
-                                    else
-                                        setTabAt(tab, i, en);
+                                    delta = 1;
+                                    t.putTreeVal(h, key, val);
                                 }
-                                break;
                             }
-                            pred = e;
-                            if ((e = e.next) == null) {
-                                delta = 1;
-                                val = v;
-                                pred.next = new Node<K,V>(h, k, val, null);
-                                if (len > TREE_THRESHOLD)
-                                    replaceWithTreeBin(tab, i, k);
-                                break;
+                            else if (p != null) {
+                                delta = -1;
+                                if (t.removeTreeNode(p))
+                                    setTabAt(tab, i, untreeify(t.first));
                             }
                         }
                     }
                 }
-                if (len != 0)
+                if (binCount != 0) {
+                    if (binCount >= TREEIFY_THRESHOLD)
+                        treeifyBin(tab, i);
                     break;
+                }
             }
         }
         if (delta != 0)
-            addCount((long)delta, len);
+            addCount((long)delta, binCount);
         return val;
     }
 
-    /** Implementation for putAll */
-    private final void internalPutAll(Map<? extends K, ? extends V> m) {
-        tryPresize(m.size());
-        long delta = 0L;     // number of uncommitted additions
-        boolean npe = false; // to throw exception on exit for nulls
-        try {                // to clean up counts on other exceptions
-            for (Map.Entry<?, ? extends V> entry : m.entrySet()) {
-                Object k; V v;
-                if (entry == null || (k = entry.getKey()) == null ||
-                    (v = entry.getValue()) == null) {
-                    npe = true;
-                    break;
-                }
-                int h = spread(k.hashCode());
-                for (Node<K,V>[] tab = table;;) {
-                    int i; Node<K,V> f; int fh; Object fk;
-                    if (tab == null)
-                        tab = initTable();
-                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
-                        if (casTabAt(tab, i, null, new Node<K,V>(h, k, v, null))) {
-                            ++delta;
-                            break;
-                        }
-                    }
-                    else if ((fh = f.hash) < 0) {
-                        if ((fk = f.key) instanceof TreeBin) {
-                            TreeBin<K,V> t = (TreeBin<K,V>)fk;
-                            long stamp = t.writeLock();
-                            boolean validated = false;
-                            try {
-                                if (tabAt(tab, i) == f) {
-                                    validated = true;
-                                    Class<?> cc = comparableClassFor(k.getClass());
-                                    TreeNode<K,V> p = t.getTreeNode(h, k,
-                                                                    t.root, cc);
-                                    if (p != null)
-                                        p.val = v;
-                                    else {
-                                        ++delta;
-                                        t.putTreeNode(h, k, v);
-                                    }
-                                }
-                            } finally {
-                                t.unlockWrite(stamp);
-                            }
-                            if (validated)
-                                break;
-                        }
-                        else
-                            tab = (Node<K,V>[])fk;
-                    }
-                    else {
-                        int len = 0;
-                        synchronized (f) {
-                            if (tabAt(tab, i) == f) {
-                                len = 1;
-                                for (Node<K,V> e = f;; ++len) {
-                                    Object ek;
-                                    if (e.hash == h &&
-                                        ((ek = e.key) == k || k.equals(ek))) {
-                                        e.val = v;
-                                        break;
-                                    }
-                                    Node<K,V> last = e;
-                                    if ((e = e.next) == null) {
-                                        ++delta;
-                                        last.next = new Node<K,V>(h, k, v, null);
-                                        if (len > TREE_THRESHOLD)
-                                            replaceWithTreeBin(tab, i, k);
-                                        break;
-                                    }
-                                }
-                            }
-                        }
-                        if (len != 0) {
-                            if (len > 1) {
-                                addCount(delta, len);
-                                delta = 0L;
-                            }
-                            break;
-                        }
-                    }
-                }
-            }
-        } finally {
-            if (delta != 0L)
-                addCount(delta, 2);
-        }
-        if (npe)
-            throw new NullPointerException();
+    // Hashtable legacy methods
+
+    /**
+     * Legacy method testing if some key maps into the specified value
+     * in this table.  This method is identical in functionality to
+     * {@link #containsValue(Object)}, and exists solely to ensure
+     * full compatibility with class {@link java.util.Hashtable},
+     * which supported this method prior to introduction of the
+     * Java Collections framework.
+     *
+     * @param  value a value to search for
+     * @return {@code true} if and only if some key maps to the
+     *         {@code value} argument in this table as
+     *         determined by the {@code equals} method;
+     *         {@code false} otherwise
+     * @throws NullPointerException if the specified value is null
+     */
+    public boolean contains(Object value) {
+        return containsValue(value);
+    }
+
+    /**
+     * Returns an enumeration of the keys in this table.
+     *
+     * @return an enumeration of the keys in this table
+     * @see #keySet()
+     */
+    public Enumeration<K> keys() {
+        Node<K,V>[] t;
+        int f = (t = table) == null ? 0 : t.length;
+        return new KeyIterator<K,V>(t, f, 0, f, this);
+    }
+
+    /**
+     * Returns an enumeration of the values in this table.
+     *
+     * @return an enumeration of the values in this table
+     * @see #values()
+     */
+    public Enumeration<V> elements() {
+        Node<K,V>[] t;
+        int f = (t = table) == null ? 0 : t.length;
+        return new ValueIterator<K,V>(t, f, 0, f, this);
+    }
+
+    // ConcurrentHashMap-only methods
+
+    /**
+     * Returns the number of mappings. This method should be used
+     * instead of {@link #size} because a ConcurrentHashMap may
+     * contain more mappings than can be represented as an int. The
+     * value returned is an estimate; the actual count may differ if
+     * there are concurrent insertions or removals.
+     *
+     * @return the number of mappings
+     * @since 1.8
+     */
+    public long mappingCount() {
+        long n = sumCount();
+        return (n < 0L) ? 0L : n; // ignore transient negative values
+    }
+
+    /**
+     * Creates a new {@link Set} backed by a ConcurrentHashMap
+     * from the given type to {@code Boolean.TRUE}.
+     *
+     * @return the new set
+     * @since 1.8
+     */
+    public static <K> KeySetView<K,Boolean> newKeySet() {
+        return new KeySetView<K,Boolean>
+            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
     }
 
     /**
-     * Implementation for clear. Steps through each bin, removing all
-     * nodes.
+     * Creates a new {@link Set} backed by a ConcurrentHashMap
+     * from the given type to {@code Boolean.TRUE}.
+     *
+     * @param initialCapacity The implementation performs internal
+     * sizing to accommodate this many elements.
+     * @throws IllegalArgumentException if the initial capacity of
+     * elements is negative
+     * @return the new set
+     * @since 1.8
+     */
+    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
+        return new KeySetView<K,Boolean>
+            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
+    }
+
+    /**
+     * Returns a {@link Set} view of the keys in this map, using the
+     * given common mapped value for any additions (i.e., {@link
+     * Collection#add} and {@link Collection#addAll(Collection)}).
+     * This is of course only appropriate if it is acceptable to use
+     * the same value for all additions from this view.
+     *
+     * @param mappedValue the mapped value to use for any additions
+     * @return the set view
+     * @throws NullPointerException if the mappedValue is null
      */
-    private final void internalClear() {
-        long delta = 0L; // negative number of deletions
-        int i = 0;
-        Node<K,V>[] tab = table;
-        while (tab != null && i < tab.length) {
-            Node<K,V> f = tabAt(tab, i);
-            if (f == null)
-                ++i;
-            else if (f.hash < 0) {
-                Object fk;
-                if ((fk = f.key) instanceof TreeBin) {
-                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
-                    long stamp = t.writeLock();
-                    try {
-                        if (tabAt(tab, i) == f) {
-                            for (Node<K,V> p = t.first; p != null; p = p.next)
-                                --delta;
-                            t.first = null;
-                            t.root = null;
-                            ++i;
+    public KeySetView<K,V> keySet(V mappedValue) {
+        if (mappedValue == null)
+            throw new NullPointerException();
+        return new KeySetView<K,V>(this, mappedValue);
+    }
+
+    /* ---------------- Special Nodes -------------- */
+
+    /**
+     * A node inserted at head of bins during transfer operations.
+     */
+    static final class ForwardingNode<K,V> extends Node<K,V> {
+        final Node<K,V>[] nextTable;
+        ForwardingNode(Node<K,V>[] tab) {
+            super(MOVED, null, null, null);
+            this.nextTable = tab;
+        }
+
+        Node<K,V> find(int h, Object k) {
+            // loop to avoid arbitrarily deep recursion on forwarding nodes
+            outer: for (Node<K,V>[] tab = nextTable;;) {
+                Node<K,V> e; int n;
+                if (k == null || tab == null || (n = tab.length) == 0 ||
+                    (e = tabAt(tab, (n - 1) & h)) == null)
+                    return null;
+                for (;;) {
+                    int eh; K ek;
+                    if ((eh = e.hash) == h &&
+                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
+                        return e;
+                    if (eh < 0) {
+                        if (e instanceof ForwardingNode) {
+                            tab = ((ForwardingNode<K,V>)e).nextTable;
+                            continue outer;
                         }
-                    } finally {
-                        t.unlockWrite(stamp);
+                        else
+                            return e.find(h, k);
                     }
-                }
-                else
-                    tab = (Node<K,V>[])fk;
-            }
-            else {
-                synchronized (f) {
-                    if (tabAt(tab, i) == f) {
-                        for (Node<K,V> e = f; e != null; e = e.next)
-                            --delta;
-                        setTabAt(tab, i, null);
-                        ++i;
-                    }
+                    if ((e = e.next) == null)
+                        return null;
                 }
             }
         }
-        if (delta != 0L)
-            addCount(delta, -1);
+    }
+
+    /**
+     * A place-holder node used in computeIfAbsent and compute
+     */
+    static final class ReservationNode<K,V> extends Node<K,V> {
+        ReservationNode() {
+            super(RESERVED, null, null, null);
+        }
+
+        Node<K,V> find(int h, Object k) {
+            return null;
+        }
     }
 
     /* ---------------- Table Initialization and Resizing -------------- */
 
     /**
-     * Returns a power of two table size for the given desired capacity.
-     * See Hackers Delight, sec 3.2
-     */
-    private static final int tableSizeFor(int c) {
-        int n = c - 1;
-        n |= n >>> 1;
-        n |= n >>> 2;
-        n |= n >>> 4;
-        n |= n >>> 8;
-        n |= n >>> 16;
-        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
-    }
-
-    /**
      * Initializes table, using the size recorded in sizeCtl.
      */
     private final Node<K,V>[] initTable() {
         Node<K,V>[] tab; int sc;
-        while ((tab = table) == null) {
+        while ((tab = table) == null || tab.length == 0) {
             if ((sc = sizeCtl) < 0)
                 Thread.yield(); // lost initialization race; just spin
             else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
                 try {
-                    if ((tab = table) == null) {
+                    if ((tab = table) == null || tab.length == 0) {
                         int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
-                        table = tab = (Node<K,V>[])new Node[n];
+                        @SuppressWarnings({"rawtypes","unchecked"})
+                            Node<K,V>[] nt = (Node<K,V>[])new Node[n];
+                        table = tab = nt;
                         sc = n - (n >>> 2);
                     }
                 } finally {
@@ -1921,10 +2212,10 @@
      * @param check if <0, don't check resize, if <= 1 only check if uncontended
      */
     private final void addCount(long x, int check) {
-        Cell[] as; long b, s;
+        CounterCell[] as; long b, s;
         if ((as = counterCells) != null ||
             !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
-            Cell a; long v; int m;
+            CounterCell a; long v; int m;
             boolean uncontended = true;
             if (as == null || (m = as.length - 1) < 0 ||
                 (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
@@ -1956,6 +2247,22 @@
     }
 
     /**
+     * Helps transfer if a resize is in progress.
+     */
+    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
+        Node<K,V>[] nextTab; int sc;
+        if ((f instanceof ForwardingNode) &&
+            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
+            if (nextTab == nextTable && tab == table &&
+                transferIndex > transferOrigin && (sc = sizeCtl) < -1 &&
+                U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
+                transfer(tab, nextTab);
+            return nextTab;
+        }
+        return table;
+    }
+
+    /**
      * Tries to presize table to accommodate the given number of elements.
      *
      * @param size number of elements (doesn't need to be perfectly accurate)
@@ -1971,7 +2278,9 @@
                 if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
                     try {
                         if (table == tab) {
-                            table = (Node<K,V>[])new Node[n];
+                            @SuppressWarnings({"rawtypes","unchecked"})
+                                Node<K,V>[] nt = (Node<K,V>[])new Node[n];
+                            table = nt;
                             sc = n - (n >>> 2);
                         }
                     } finally {
@@ -1997,7 +2306,9 @@
             stride = MIN_TRANSFER_STRIDE; // subdivide range
         if (nextTab == null) {            // initiating
             try {
-                nextTab = (Node<K,V>[])new Node[n << 1];
+                @SuppressWarnings({"rawtypes","unchecked"})
+                    Node<K,V>[] nt = (Node<K,V>[])new Node[n << 1];
+                nextTab = nt;
             } catch (Throwable ex) {      // try to cope with OOME
                 sizeCtl = Integer.MAX_VALUE;
                 return;
@@ -2005,7 +2316,7 @@
             nextTable = nextTab;
             transferOrigin = n;
             transferIndex = n;
-            Node<K,V> rev = new Node<K,V>(MOVED, tab, null, null);
+            ForwardingNode<K,V> rev = new ForwardingNode<K,V>(tab);
             for (int k = n; k > 0;) {    // progressively reveal ready slots
                 int nextk = (k > stride) ? k - stride : 0;
                 for (int m = nextk; m < k; ++m)
@@ -2016,12 +2327,13 @@
             }
         }
         int nextn = nextTab.length;
-        Node<K,V> fwd = new Node<K,V>(MOVED, nextTab, null, null);
+        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
         boolean advance = true;
+        boolean finishing = false; // to ensure sweep before committing nextTab
         for (int i = 0, bound = 0;;) {
-            int nextIndex, nextBound; Node<K,V> f; Object fk;
+            int nextIndex, nextBound, fh; Node<K,V> f;
             while (advance) {
-                if (--i >= bound)
+                if (--i >= bound || finishing)
                     advance = false;
                 else if ((nextIndex = transferIndex) <= transferOrigin) {
                     i = -1;
@@ -2037,14 +2349,19 @@
                 }
             }
             if (i < 0 || i >= n || i + n >= nextn) {
+                if (finishing) {
+                    nextTable = null;
+                    table = nextTab;
+                    sizeCtl = (n << 1) - (n >>> 1);
+                    return;
+                }
                 for (int sc;;) {
                     if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
-                        if (sc == -1) {
-                            nextTable = null;
-                            table = nextTab;
-                            sizeCtl = (n << 1) - (n >>> 1);
-                        }
-                        return;
+                        if (sc != -1)
+                            return;
+                        finishing = advance = true;
+                        i = n; // recheck before commit
+                        break;
                     }
                 }
             }
@@ -2055,106 +2372,96 @@
                     advance = true;
                 }
             }
-            else if (f.hash >= 0) {
+            else if ((fh = f.hash) == MOVED)
+                advance = true; // already processed
+            else {
                 synchronized (f) {
                     if (tabAt(tab, i) == f) {
-                        int runBit = f.hash & n;
-                        Node<K,V> lastRun = f, lo = null, hi = null;
-                        for (Node<K,V> p = f.next; p != null; p = p.next) {
-                            int b = p.hash & n;
-                            if (b != runBit) {
-                                runBit = b;
-                                lastRun = p;
+                        Node<K,V> ln, hn;
+                        if (fh >= 0) {
+                            int runBit = fh & n;
+                            Node<K,V> lastRun = f;
+                            for (Node<K,V> p = f.next; p != null; p = p.next) {
+                                int b = p.hash & n;
+                                if (b != runBit) {
+                                    runBit = b;
+                                    lastRun = p;
+                                }
+                            }
+                            if (runBit == 0) {
+                                ln = lastRun;
+                                hn = null;
                             }
+                            else {
+                                hn = lastRun;
+                                ln = null;
+                            }
+                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
+                                int ph = p.hash; K pk = p.key; V pv = p.val;
+                                if ((ph & n) == 0)
+                                    ln = new Node<K,V>(ph, pk, pv, ln);
+                                else
+                                    hn = new Node<K,V>(ph, pk, pv, hn);
+                            }
+                            setTabAt(nextTab, i, ln);
+                            setTabAt(nextTab, i + n, hn);
+                            setTabAt(tab, i, fwd);
+                            advance = true;
                         }
-                        if (runBit == 0)
-                            lo = lastRun;
-                        else
-                            hi = lastRun;
-                        for (Node<K,V> p = f; p != lastRun; p = p.next) {
-                            int ph = p.hash; Object pk = p.key; V pv = p.val;
-                            if ((ph & n) == 0)
-                                lo = new Node<K,V>(ph, pk, pv, lo);
-                            else
-                                hi = new Node<K,V>(ph, pk, pv, hi);
+                        else if (f instanceof TreeBin) {
+                            TreeBin<K,V> t = (TreeBin<K,V>)f;
+                            TreeNode<K,V> lo = null, loTail = null;
+                            TreeNode<K,V> hi = null, hiTail = null;
+                            int lc = 0, hc = 0;
+                            for (Node<K,V> e = t.first; e != null; e = e.next) {
+                                int h = e.hash;
+                                TreeNode<K,V> p = new TreeNode<K,V>
+                                    (h, e.key, e.val, null, null);
+                                if ((h & n) == 0) {
+                                    if ((p.prev = loTail) == null)
+                                        lo = p;
+                                    else
+                                        loTail.next = p;
+                                    loTail = p;
+                                    ++lc;
+                                }
+                                else {
+                                    if ((p.prev = hiTail) == null)
+                                        hi = p;
+                                    else
+                                        hiTail.next = p;
+                                    hiTail = p;
+                                    ++hc;
+                                }
+                            }
+                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
+                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
+                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
+                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
+                            setTabAt(nextTab, i, ln);
+                            setTabAt(nextTab, i + n, hn);
+                            setTabAt(tab, i, fwd);
+                            advance = true;
                         }
-                        setTabAt(nextTab, i, lo);
-                        setTabAt(nextTab, i + n, hi);
-                        setTabAt(tab, i, fwd);
-                        advance = true;
                     }
                 }
             }
-            else if ((fk = f.key) instanceof TreeBin) {
-                TreeBin<K,V> t = (TreeBin<K,V>)fk;
-                long stamp = t.writeLock();
-                try {
-                    if (tabAt(tab, i) == f) {
-                        TreeNode<K,V> root;
-                        Node<K,V> ln = null, hn = null;
-                        if ((root = t.root) != null) {
-                            Node<K,V> e, p; TreeNode<K,V> lr, rr; int lh;
-                            TreeBin<K,V> lt = null, ht = null;
-                            for (lr = root; lr.left != null; lr = lr.left);
-                            for (rr = root; rr.right != null; rr = rr.right);
-                            if ((lh = lr.hash) == rr.hash) { // move entire tree
-                                if ((lh & n) == 0)
-                                    lt = t;
-                                else
-                                    ht = t;
-                            }
-                            else {
-                                lt = new TreeBin<K,V>();
-                                ht = new TreeBin<K,V>();
-                                int lc = 0, hc = 0;
-                                for (e = t.first; e != null; e = e.next) {
-                                    int h = e.hash;
-                                    Object k = e.key; V v = e.val;
-                                    if ((h & n) == 0) {
-                                        ++lc;
-                                        lt.putTreeNode(h, k, v);
-                                    }
-                                    else {
-                                        ++hc;
-                                        ht.putTreeNode(h, k, v);
-                                    }
-                                }
-                                if (lc < TREE_THRESHOLD) { // throw away
-                                    for (p = lt.first; p != null; p = p.next)
-                                        ln = new Node<K,V>(p.hash, p.key,
-                                                           p.val, ln);
-                                    lt = null;
-                                }
-                                if (hc < TREE_THRESHOLD) {
-                                    for (p = ht.first; p != null; p = p.next)
-                                        hn = new Node<K,V>(p.hash, p.key,
-                                                           p.val, hn);
-                                    ht = null;
-                                }
-                            }
-                            if (ln == null && lt != null)
-                                ln = new Node<K,V>(MOVED, lt, null, null);
-                            if (hn == null && ht != null)
-                                hn = new Node<K,V>(MOVED, ht, null, null);
-                        }
-                        setTabAt(nextTab, i, ln);
-                        setTabAt(nextTab, i + n, hn);
-                        setTabAt(tab, i, fwd);
-                        advance = true;
-                    }
-                } finally {
-                    t.unlockWrite(stamp);
-                }
-            }
-            else
-                advance = true; // already processed
         }
     }
 
     /* ---------------- Counter support -------------- */
 
+    /**
+     * A padded cell for distributing counts.  Adapted from LongAdder
+     * and Striped64.  See their internal docs for explanation.
+     */
+    @sun.misc.Contended static final class CounterCell {
+        volatile long value;
+        CounterCell(long x) { value = x; }
+    }
+
     final long sumCount() {
-        Cell[] as = counterCells; Cell a;
+        CounterCell[] as = counterCells; CounterCell a;
         long sum = baseCount;
         if (as != null) {
             for (int i = 0; i < as.length; ++i) {
@@ -2175,16 +2482,16 @@
         }
         boolean collide = false;                // True if last slot nonempty
         for (;;) {
-            Cell[] as; Cell a; int n; long v;
+            CounterCell[] as; CounterCell a; int n; long v;
             if ((as = counterCells) != null && (n = as.length) > 0) {
                 if ((a = as[(n - 1) & h]) == null) {
                     if (cellsBusy == 0) {            // Try to attach new Cell
-                        Cell r = new Cell(x); // Optimistic create
+                        CounterCell r = new CounterCell(x); // Optimistic create
                         if (cellsBusy == 0 &&
                             U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
                             boolean created = false;
                             try {               // Recheck under lock
-                                Cell[] rs; int m, j;
+                                CounterCell[] rs; int m, j;
                                 if ((rs = counterCells) != null &&
                                     (m = rs.length) > 0 &&
                                     rs[j = (m - 1) & h] == null) {
@@ -2213,7 +2520,7 @@
                          U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
                     try {
                         if (counterCells == as) {// Expand table unless stale
-                            Cell[] rs = new Cell[n << 1];
+                            CounterCell[] rs = new CounterCell[n << 1];
                             for (int i = 0; i < n; ++i)
                                 rs[i] = as[i];
                             counterCells = rs;
@@ -2231,8 +2538,8 @@
                 boolean init = false;
                 try {                           // Initialize table
                     if (counterCells == as) {
-                        Cell[] rs = new Cell[2];
-                        rs[h & 1] = new Cell(x);
+                        CounterCell[] rs = new CounterCell[2];
+                        rs[h & 1] = new CounterCell(x);
                         counterCells = rs;
                         init = true;
                     }
@@ -2247,6 +2554,638 @@
         }
     }
 
+    /* ---------------- Conversion from/to TreeBins -------------- */
+
+    /**
+     * Replaces all linked nodes in bin at given index unless table is
+     * too small, in which case resizes instead.
+     */
+    private final void treeifyBin(Node<K,V>[] tab, int index) {
+        Node<K,V> b; int n, sc;
+        if (tab != null) {
+            if ((n = tab.length) < MIN_TREEIFY_CAPACITY) {
+                if (tab == table && (sc = sizeCtl) >= 0 &&
+                    U.compareAndSwapInt(this, SIZECTL, sc, -2))
+                    transfer(tab, null);
+            }
+            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
+                synchronized (b) {
+                    if (tabAt(tab, index) == b) {
+                        TreeNode<K,V> hd = null, tl = null;
+                        for (Node<K,V> e = b; e != null; e = e.next) {
+                            TreeNode<K,V> p =
+                                new TreeNode<K,V>(e.hash, e.key, e.val,
+                                                  null, null);
+                            if ((p.prev = tl) == null)
+                                hd = p;
+                            else
+                                tl.next = p;
+                            tl = p;
+                        }
+                        setTabAt(tab, index, new TreeBin<K,V>(hd));
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * Returns a list on non-TreeNodes replacing those in given list.
+     */
+    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
+        Node<K,V> hd = null, tl = null;
+        for (Node<K,V> q = b; q != null; q = q.next) {
+            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
+            if (tl == null)
+                hd = p;
+            else
+                tl.next = p;
+            tl = p;
+        }
+        return hd;
+    }
+
+    /* ---------------- TreeNodes -------------- */
+
+    /**
+     * Nodes for use in TreeBins
+     */
+    static final class TreeNode<K,V> extends Node<K,V> {
+        TreeNode<K,V> parent;  // red-black tree links
+        TreeNode<K,V> left;
+        TreeNode<K,V> right;
+        TreeNode<K,V> prev;    // needed to unlink next upon deletion
+        boolean red;
+
+        TreeNode(int hash, K key, V val, Node<K,V> next,
+                 TreeNode<K,V> parent) {
+            super(hash, key, val, next);
+            this.parent = parent;
+        }
+
+        Node<K,V> find(int h, Object k) {
+            return findTreeNode(h, k, null);
+        }
+
+        /**
+         * Returns the TreeNode (or null if not found) for the given key
+         * starting at given root.
+         */
+        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
+            if (k != null) {
+                TreeNode<K,V> p = this;
+                do  {
+                    int ph, dir; K pk; TreeNode<K,V> q;
+                    TreeNode<K,V> pl = p.left, pr = p.right;
+                    if ((ph = p.hash) > h)
+                        p = pl;
+                    else if (ph < h)
+                        p = pr;
+                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
+                        return p;
+                    else if (pl == null && pr == null)
+                        break;
+                    else if ((kc != null ||
+                              (kc = comparableClassFor(k)) != null) &&
+                             (dir = compareComparables(kc, k, pk)) != 0)
+                        p = (dir < 0) ? pl : pr;
+                    else if (pl == null)
+                        p = pr;
+                    else if (pr == null ||
+                             (q = pr.findTreeNode(h, k, kc)) == null)
+                        p = pl;
+                    else
+                        return q;
+                } while (p != null);
+            }
+            return null;
+        }
+    }
+
+    /* ---------------- TreeBins -------------- */
+
+    /**
+     * TreeNodes used at the heads of bins. TreeBins do not hold user
+     * keys or values, but instead point to list of TreeNodes and
+     * their root. They also maintain a parasitic read-write lock
+     * forcing writers (who hold bin lock) to wait for readers (who do
+     * not) to complete before tree restructuring operations.
+     */
+    static final class TreeBin<K,V> extends Node<K,V> {
+        TreeNode<K,V> root;
+        volatile TreeNode<K,V> first;
+        volatile Thread waiter;
+        volatile int lockState;
+        // values for lockState
+        static final int WRITER = 1; // set while holding write lock
+        static final int WAITER = 2; // set when waiting for write lock
+        static final int READER = 4; // increment value for setting read lock
+
+        /**
+         * Creates bin with initial set of nodes headed by b.
+         */
+        TreeBin(TreeNode<K,V> b) {
+            super(TREEBIN, null, null, null);
+            this.first = b;
+            TreeNode<K,V> r = null;
+            for (TreeNode<K,V> x = b, next; x != null; x = next) {
+                next = (TreeNode<K,V>)x.next;
+                x.left = x.right = null;
+                if (r == null) {
+                    x.parent = null;
+                    x.red = false;
+                    r = x;
+                }
+                else {
+                    Object key = x.key;
+                    int hash = x.hash;
+                    Class<?> kc = null;
+                    for (TreeNode<K,V> p = r;;) {
+                        int dir, ph;
+                        if ((ph = p.hash) > hash)
+                            dir = -1;
+                        else if (ph < hash)
+                            dir = 1;
+                        else if ((kc != null ||
+                                  (kc = comparableClassFor(key)) != null))
+                            dir = compareComparables(kc, key, p.key);
+                        else
+                            dir = 0;
+                        TreeNode<K,V> xp = p;
+                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
+                            x.parent = xp;
+                            if (dir <= 0)
+                                xp.left = x;
+                            else
+                                xp.right = x;
+                            r = balanceInsertion(r, x);
+                            break;
+                        }
+                    }
+                }
+            }
+            this.root = r;
+        }
+
+        /**
+         * Acquires write lock for tree restructuring.
+         */
+        private final void lockRoot() {
+            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
+                contendedLock(); // offload to separate method
+        }
+
+        /**
+         * Releases write lock for tree restructuring.
+         */
+        private final void unlockRoot() {
+            lockState = 0;
+        }
+
+        /**
+         * Possibly blocks awaiting root lock.
+         */
+        private final void contendedLock() {
+            boolean waiting = false;
+            for (int s;;) {
+                if (((s = lockState) & WRITER) == 0) {
+                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
+                        if (waiting)
+                            waiter = null;
+                        return;
+                    }
+                }
+                else if ((s | WAITER) == 0) {
+                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
+                        waiting = true;
+                        waiter = Thread.currentThread();
+                    }
+                }
+                else if (waiting)
+                    LockSupport.park(this);
+            }
+        }
+
+        /**
+         * Returns matching node or null if none. Tries to search
+         * using tree comparisons from root, but continues linear
+         * search when lock not available.
+         */
+        final Node<K,V> find(int h, Object k) {
+            if (k != null) {
+                for (Node<K,V> e = first; e != null; e = e.next) {
+                    int s; K ek;
+                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
+                        if (e.hash == h &&
+                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
+                            return e;
+                    }
+                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
+                                                 s + READER)) {
+                        TreeNode<K,V> r, p;
+                        try {
+                            p = ((r = root) == null ? null :
+                                 r.findTreeNode(h, k, null));
+                        } finally {
+                            Thread w;
+                            if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
+                                (READER|WAITER) && (w = waiter) != null)
+                                LockSupport.unpark(w);
+                        }
+                        return p;
+                    }
+                }
+            }
+            return null;
+        }
+
+        /**
+         * Finds or adds a node.
+         * @return null if added
+         */
+        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
+            Class<?> kc = null;
+            for (TreeNode<K,V> p = root;;) {
+                int dir, ph; K pk; TreeNode<K,V> q, pr;
+                if (p == null) {
+                    first = root = new TreeNode<K,V>(h, k, v, null, null);
+                    break;
+                }
+                else if ((ph = p.hash) > h)
+                    dir = -1;
+                else if (ph < h)
+                    dir = 1;
+                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
+                    return p;
+                else if ((kc == null &&
+                          (kc = comparableClassFor(k)) == null) ||
+                         (dir = compareComparables(kc, k, pk)) == 0) {
+                    if (p.left == null)
+                        dir = 1;
+                    else if ((pr = p.right) == null ||
+                             (q = pr.findTreeNode(h, k, kc)) == null)
+                        dir = -1;
+                    else
+                        return q;
+                }
+                TreeNode<K,V> xp = p;
+                if ((p = (dir < 0) ? p.left : p.right) == null) {
+                    TreeNode<K,V> x, f = first;
+                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
+                    if (f != null)
+                        f.prev = x;
+                    if (dir < 0)
+                        xp.left = x;
+                    else
+                        xp.right = x;
+                    if (!xp.red)
+                        x.red = true;
+                    else {
+                        lockRoot();
+                        try {
+                            root = balanceInsertion(root, x);
+                        } finally {
+                            unlockRoot();
+                        }
+                    }
+                    break;
+                }
+            }
+            assert checkInvariants(root);
+            return null;
+        }
+
+        /**
+         * Removes the given node, that must be present before this
+         * call.  This is messier than typical red-black deletion code
+         * because we cannot swap the contents of an interior node
+         * with a leaf successor that is pinned by "next" pointers
+         * that are accessible independently of lock. So instead we
+         * swap the tree linkages.
+         *
+         * @return true if now too small, so should be untreeified
+         */
+        final boolean removeTreeNode(TreeNode<K,V> p) {
+            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
+            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
+            TreeNode<K,V> r, rl;
+            if (pred == null)
+                first = next;
+            else
+                pred.next = next;
+            if (next != null)
+                next.prev = pred;
+            if (first == null) {
+                root = null;
+                return true;
+            }
+            if ((r = root) == null || r.right == null || // too small
+                (rl = r.left) == null || rl.left == null)
+                return true;
+            lockRoot();
+            try {
+                TreeNode<K,V> replacement;
+                TreeNode<K,V> pl = p.left;
+                TreeNode<K,V> pr = p.right;
+                if (pl != null && pr != null) {
+                    TreeNode<K,V> s = pr, sl;
+                    while ((sl = s.left) != null) // find successor
+                        s = sl;
+                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
+                    TreeNode<K,V> sr = s.right;
+                    TreeNode<K,V> pp = p.parent;
+                    if (s == pr) { // p was s's direct parent
+                        p.parent = s;
+                        s.right = p;
+                    }
+                    else {
+                        TreeNode<K,V> sp = s.parent;
+                        if ((p.parent = sp) != null) {
+                            if (s == sp.left)
+                                sp.left = p;
+                            else
+                                sp.right = p;
+                        }
+                        if ((s.right = pr) != null)
+                            pr.parent = s;
+                    }
+                    p.left = null;
+                    if ((p.right = sr) != null)
+                        sr.parent = p;
+                    if ((s.left = pl) != null)
+                        pl.parent = s;
+                    if ((s.parent = pp) == null)
+                        r = s;
+                    else if (p == pp.left)
+                        pp.left = s;
+                    else
+                        pp.right = s;
+                    if (sr != null)
+                        replacement = sr;
+                    else
+                        replacement = p;
+                }
+                else if (pl != null)
+                    replacement = pl;
+                else if (pr != null)
+                    replacement = pr;
+                else
+                    replacement = p;
+                if (replacement != p) {
+                    TreeNode<K,V> pp = replacement.parent = p.parent;
+                    if (pp == null)
+                        r = replacement;
+                    else if (p == pp.left)
+                        pp.left = replacement;
+                    else
+                        pp.right = replacement;
+                    p.left = p.right = p.parent = null;
+                }
+
+                root = (p.red) ? r : balanceDeletion(r, replacement);
+
+                if (p == replacement) {  // detach pointers
+                    TreeNode<K,V> pp;
+                    if ((pp = p.parent) != null) {
+                        if (p == pp.left)
+                            pp.left = null;
+                        else if (p == pp.right)
+                            pp.right = null;
+                        p.parent = null;
+                    }
+                }
+            } finally {
+                unlockRoot();
+            }
+            assert checkInvariants(root);
+            return false;
+        }
+
+        /* ------------------------------------------------------------ */
+        // Red-black tree methods, all adapted from CLR
+
+        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
+                                              TreeNode<K,V> p) {
+            TreeNode<K,V> r, pp, rl;
+            if (p != null && (r = p.right) != null) {
+                if ((rl = p.right = r.left) != null)
+                    rl.parent = p;
+                if ((pp = r.parent = p.parent) == null)
+                    (root = r).red = false;
+                else if (pp.left == p)
+                    pp.left = r;
+                else
+                    pp.right = r;
+                r.left = p;
+                p.parent = r;
+            }
+            return root;
+        }
+
+        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
+                                               TreeNode<K,V> p) {
+            TreeNode<K,V> l, pp, lr;
+            if (p != null && (l = p.left) != null) {
+                if ((lr = p.left = l.right) != null)
+                    lr.parent = p;
+                if ((pp = l.parent = p.parent) == null)
+                    (root = l).red = false;
+                else if (pp.right == p)
+                    pp.right = l;
+                else
+                    pp.left = l;
+                l.right = p;
+                p.parent = l;
+            }
+            return root;
+        }
+
+        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
+                                                    TreeNode<K,V> x) {
+            x.red = true;
+            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
+                if ((xp = x.parent) == null) {
+                    x.red = false;
+                    return x;
+                }
+                else if (!xp.red || (xpp = xp.parent) == null)
+                    return root;
+                if (xp == (xppl = xpp.left)) {
+                    if ((xppr = xpp.right) != null && xppr.red) {
+                        xppr.red = false;
+                        xp.red = false;
+                        xpp.red = true;
+                        x = xpp;
+                    }
+                    else {
+                        if (x == xp.right) {
+                            root = rotateLeft(root, x = xp);
+                            xpp = (xp = x.parent) == null ? null : xp.parent;
+                        }
+                        if (xp != null) {
+                            xp.red = false;
+                            if (xpp != null) {
+                                xpp.red = true;
+                                root = rotateRight(root, xpp);
+                            }
+                        }
+                    }
+                }
+                else {
+                    if (xppl != null && xppl.red) {
+                        xppl.red = false;
+                        xp.red = false;
+                        xpp.red = true;
+                        x = xpp;
+                    }
+                    else {
+                        if (x == xp.left) {
+                            root = rotateRight(root, x = xp);
+                            xpp = (xp = x.parent) == null ? null : xp.parent;
+                        }
+                        if (xp != null) {
+                            xp.red = false;
+                            if (xpp != null) {
+                                xpp.red = true;
+                                root = rotateLeft(root, xpp);
+                            }
+                        }
+                    }
+                }
+            }
+        }
+
+        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
+                                                   TreeNode<K,V> x) {
+            for (TreeNode<K,V> xp, xpl, xpr;;)  {
+                if (x == null || x == root)
+                    return root;
+                else if ((xp = x.parent) == null) {
+                    x.red = false;
+                    return x;
+                }
+                else if (x.red) {
+                    x.red = false;
+                    return root;
+                }
+                else if ((xpl = xp.left) == x) {
+                    if ((xpr = xp.right) != null && xpr.red) {
+                        xpr.red = false;
+                        xp.red = true;
+                        root = rotateLeft(root, xp);
+                        xpr = (xp = x.parent) == null ? null : xp.right;
+                    }
+                    if (xpr == null)
+                        x = xp;
+                    else {
+                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
+                        if ((sr == null || !sr.red) &&
+                            (sl == null || !sl.red)) {
+                            xpr.red = true;
+                            x = xp;
+                        }
+                        else {
+                            if (sr == null || !sr.red) {
+                                if (sl != null)
+                                    sl.red = false;
+                                xpr.red = true;
+                                root = rotateRight(root, xpr);
+                                xpr = (xp = x.parent) == null ?
+                                    null : xp.right;
+                            }
+                            if (xpr != null) {
+                                xpr.red = (xp == null) ? false : xp.red;
+                                if ((sr = xpr.right) != null)
+                                    sr.red = false;
+                            }
+                            if (xp != null) {
+                                xp.red = false;
+                                root = rotateLeft(root, xp);
+                            }
+                            x = root;
+                        }
+                    }
+                }
+                else { // symmetric
+                    if (xpl != null && xpl.red) {
+                        xpl.red = false;
+                        xp.red = true;
+                        root = rotateRight(root, xp);
+                        xpl = (xp = x.parent) == null ? null : xp.left;
+                    }
+                    if (xpl == null)
+                        x = xp;
+                    else {
+                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
+                        if ((sl == null || !sl.red) &&
+                            (sr == null || !sr.red)) {
+                            xpl.red = true;
+                            x = xp;
+                        }
+                        else {
+                            if (sl == null || !sl.red) {
+                                if (sr != null)
+                                    sr.red = false;
+                                xpl.red = true;
+                                root = rotateLeft(root, xpl);
+                                xpl = (xp = x.parent) == null ?
+                                    null : xp.left;
+                            }
+                            if (xpl != null) {
+                                xpl.red = (xp == null) ? false : xp.red;
+                                if ((sl = xpl.left) != null)
+                                    sl.red = false;
+                            }
+                            if (xp != null) {
+                                xp.red = false;
+                                root = rotateRight(root, xp);
+                            }
+                            x = root;
+                        }
+                    }
+                }
+            }
+        }
+
+        /**
+         * Recursive invariant check
+         */
+        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
+            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
+                tb = t.prev, tn = (TreeNode<K,V>)t.next;
+            if (tb != null && tb.next != t)
+                return false;
+            if (tn != null && tn.prev != t)
+                return false;
+            if (tp != null && t != tp.left && t != tp.right)
+                return false;
+            if (tl != null && (tl.parent != t || tl.hash > t.hash))
+                return false;
+            if (tr != null && (tr.parent != t || tr.hash < t.hash))
+                return false;
+            if (t.red && tl != null && tl.red && tr != null && tr.red)
+                return false;
+            if (tl != null && !checkInvariants(tl))
+                return false;
+            if (tr != null && !checkInvariants(tr))
+                return false;
+            return true;
+        }
+
+        private static final sun.misc.Unsafe U;
+        private static final long LOCKSTATE;
+        static {
+            try {
+                U = sun.misc.Unsafe.getUnsafe();
+                Class<?> k = TreeBin.class;
+                LOCKSTATE = U.objectFieldOffset
+                    (k.getDeclaredField("lockState"));
+            } catch (Exception e) {
+                throw new Error(e);
+            }
+        }
+    }
+
     /* ----------------Table Traversal -------------- */
 
     /**
@@ -2294,20 +3233,22 @@
             if ((e = next) != null)
                 e = e.next;
             for (;;) {
-                Node<K,V>[] t; int i, n; Object ek;  // must use locals in checks
+                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
                 if (e != null)
                     return next = e;
                 if (baseIndex >= baseLimit || (t = tab) == null ||
                     (n = t.length) <= (i = index) || i < 0)
                     return next = null;
                 if ((e = tabAt(t, index)) != null && e.hash < 0) {
-                    if ((ek = e.key) instanceof TreeBin)
-                        e = ((TreeBin<K,V>)ek).first;
-                    else {
-                        tab = (Node<K,V>[])ek;
+                    if (e instanceof ForwardingNode) {
+                        tab = ((ForwardingNode<K,V>)e).nextTable;
                         e = null;
                         continue;
                     }
+                    else if (e instanceof TreeBin)
+                        e = ((TreeBin<K,V>)e).first;
+                    else
+                        e = null;
                 }
                 if ((index += baseSize) >= n)
                     index = ++baseIndex;    // visit upper slots if present
@@ -2317,7 +3258,7 @@
 
     /**
      * Base of key, value, and entry Iterators. Adds fields to
-     * Traverser to support iterator.remove
+     * Traverser to support iterator.remove.
      */
     static class BaseIterator<K,V> extends Traverser<K,V> {
         final ConcurrentHashMap<K,V> map;
@@ -2337,7 +3278,7 @@
             if ((p = lastReturned) == null)
                 throw new IllegalStateException();
             lastReturned = null;
-            map.internalReplace((K)p.key, null, null);
+            map.replaceNode(p.key, null, null);
         }
     }
 
@@ -2352,7 +3293,7 @@
             Node<K,V> p;
             if ((p = next) == null)
                 throw new NoSuchElementException();
-            K k = (K)p.key;
+            K k = p.key;
             lastReturned = p;
             advance();
             return k;
@@ -2392,7 +3333,7 @@
             Node<K,V> p;
             if ((p = next) == null)
                 throw new NoSuchElementException();
-            K k = (K)p.key;
+            K k = p.key;
             V v = p.val;
             lastReturned = p;
             advance();
@@ -2400,6 +3341,49 @@
         }
     }
 
+    /**
+     * Exported Entry for EntryIterator
+     */
+    static final class MapEntry<K,V> implements Map.Entry<K,V> {
+        final K key; // non-null
+        V val;       // non-null
+        final ConcurrentHashMap<K,V> map;
+        MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
+            this.key = key;
+            this.val = val;
+            this.map = map;
+        }
+        public K getKey()        { return key; }
+        public V getValue()      { return val; }
+        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
+        public String toString() { return key + "=" + val; }
+
+        public boolean equals(Object o) {
+            Object k, v; Map.Entry<?,?> e;
+            return ((o instanceof Map.Entry) &&
+                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
+                    (v = e.getValue()) != null &&
+                    (k == key || k.equals(key)) &&
+                    (v == val || v.equals(val)));
+        }
+
+        /**
+         * Sets our entry's value and writes through to the map. The
+         * value to return is somewhat arbitrary here. Since we do not
+         * necessarily track asynchronous changes, the most recent
+         * "previous" value could be different from what we return (or
+         * could even have been removed, in which case the put will
+         * re-establish). We do not and cannot guarantee more.
+         */
+        public V setValue(V value) {
+            if (value == null) throw new NullPointerException();
+            V v = val;
+            val = value;
+            map.put(key, value);
+            return v;
+        }
+    }
+
     static final class KeySpliterator<K,V> extends Traverser<K,V>
         implements Spliterator<K> {
         long est;               // size estimate
@@ -2419,7 +3403,7 @@
         public void forEachRemaining(Consumer<? super K> action) {
             if (action == null) throw new NullPointerException();
             for (Node<K,V> p; (p = advance()) != null;)
-                action.accept((K)p.key);
+                action.accept(p.key);
         }
 
         public boolean tryAdvance(Consumer<? super K> action) {
@@ -2427,7 +3411,7 @@
             Node<K,V> p;
             if ((p = advance()) == null)
                 return false;
-            action.accept((K)p.key);
+            action.accept(p.key);
             return true;
         }
 
@@ -2498,7 +3482,7 @@
         public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
             if (action == null) throw new NullPointerException();
             for (Node<K,V> p; (p = advance()) != null; )
-                action.accept(new MapEntry<K,V>((K)p.key, p.val, map));
+                action.accept(new MapEntry<K,V>(p.key, p.val, map));
         }
 
         public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
@@ -2506,7 +3490,7 @@
             Node<K,V> p;
             if ((p = advance()) == null)
                 return false;
-            action.accept(new MapEntry<K,V>((K)p.key, p.val, map));
+            action.accept(new MapEntry<K,V>(p.key, p.val, map));
             return true;
         }
 
@@ -2518,798 +3502,6 @@
         }
     }
 
-
-    /* ---------------- Public operations -------------- */
-
-    /**
-     * Creates a new, empty map with the default initial table size (16).
-     */
-    public ConcurrentHashMap() {
-    }
-
-    /**
-     * Creates a new, empty map with an initial table size
-     * accommodating the specified number of elements without the need
-     * to dynamically resize.
-     *
-     * @param initialCapacity The implementation performs internal
-     * sizing to accommodate this many elements.
-     * @throws IllegalArgumentException if the initial capacity of
-     * elements is negative
-     */
-    public ConcurrentHashMap(int initialCapacity) {
-        if (initialCapacity < 0)
-            throw new IllegalArgumentException();
-        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
-                   MAXIMUM_CAPACITY :
-                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
-        this.sizeCtl = cap;
-    }
-
-    /**
-     * Creates a new map with the same mappings as the given map.
-     *
-     * @param m the map
-     */
-    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
-        this.sizeCtl = DEFAULT_CAPACITY;
-        internalPutAll(m);
-    }
-
-    /**
-     * Creates a new, empty map with an initial table size based on
-     * the given number of elements ({@code initialCapacity}) and
-     * initial table density ({@code loadFactor}).
-     *
-     * @param initialCapacity the initial capacity. The implementation
-     * performs internal sizing to accommodate this many elements,
-     * given the specified load factor.
-     * @param loadFactor the load factor (table density) for
-     * establishing the initial table size
-     * @throws IllegalArgumentException if the initial capacity of
-     * elements is negative or the load factor is nonpositive
-     *
-     * @since 1.6
-     */
-    public ConcurrentHashMap(int initialCapacity, float loadFactor) {
-        this(initialCapacity, loadFactor, 1);
-    }
-
-    /**
-     * Creates a new, empty map with an initial table size based on
-     * the given number of elements ({@code initialCapacity}), table
-     * density ({@code loadFactor}), and number of concurrently
-     * updating threads ({@code concurrencyLevel}).
-     *
-     * @param initialCapacity the initial capacity. The implementation
-     * performs internal sizing to accommodate this many elements,
-     * given the specified load factor.
-     * @param loadFactor the load factor (table density) for
-     * establishing the initial table size
-     * @param concurrencyLevel the estimated number of concurrently
-     * updating threads. The implementation may use this value as
-     * a sizing hint.
-     * @throws IllegalArgumentException if the initial capacity is
-     * negative or the load factor or concurrencyLevel are
-     * nonpositive
-     */
-    public ConcurrentHashMap(int initialCapacity,
-                             float loadFactor, int concurrencyLevel) {
-        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
-            throw new IllegalArgumentException();
-        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
-            initialCapacity = concurrencyLevel;   // as estimated threads
-        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
-        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
-            MAXIMUM_CAPACITY : tableSizeFor((int)size);
-        this.sizeCtl = cap;
-    }
-
-    /**
-     * Creates a new {@link Set} backed by a ConcurrentHashMap
-     * from the given type to {@code Boolean.TRUE}.
-     *
-     * @return the new set
-     * @since 1.8
-     */
-    public static <K> KeySetView<K,Boolean> newKeySet() {
-        return new KeySetView<K,Boolean>
-            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
-    }
-
-    /**
-     * Creates a new {@link Set} backed by a ConcurrentHashMap
-     * from the given type to {@code Boolean.TRUE}.
-     *
-     * @param initialCapacity The implementation performs internal
-     * sizing to accommodate this many elements.
-     * @throws IllegalArgumentException if the initial capacity of
-     * elements is negative
-     * @return the new set
-     * @since 1.8
-     */
-    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
-        return new KeySetView<K,Boolean>
-            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
-    }
-
-    /**
-     * Returns {@code true} if this map contains no key-value mappings.
-     *
-     * @return {@code true} if this map contains no key-value mappings
-     */
-    public boolean isEmpty() {
-        return sumCount() <= 0L; // ignore transient negative values
-    }
-
-    /**
-     * Returns the number of key-value mappings in this map.  If the
-     * map contains more than {@code Integer.MAX_VALUE} elements, returns
-     * {@code Integer.MAX_VALUE}.
-     *
-     * @return the number of key-value mappings in this map
-     */
-    public int size() {
-        long n = sumCount();
-        return ((n < 0L) ? 0 :
-                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
-                (int)n);
-    }
-
-    /**
-     * Returns the number of mappings. This method should be used
-     * instead of {@link #size} because a ConcurrentHashMap may
-     * contain more mappings than can be represented as an int. The
-     * value returned is an estimate; the actual count may differ if
-     * there are concurrent insertions or removals.
-     *
-     * @return the number of mappings
-     * @since 1.8
-     */
-    public long mappingCount() {
-        long n = sumCount();
-        return (n < 0L) ? 0L : n; // ignore transient negative values
-    }
-
-    /**
-     * Returns the value to which the specified key is mapped,
-     * or {@code null} if this map contains no mapping for the key.
-     *
-     * <p>More formally, if this map contains a mapping from a key
-     * {@code k} to a value {@code v} such that {@code key.equals(k)},
-     * then this method returns {@code v}; otherwise it returns
-     * {@code null}.  (There can be at most one such mapping.)
-     *
-     * @throws NullPointerException if the specified key is null
-     */
-    public V get(Object key) {
-        return internalGet(key);
-    }
-
-    /**
-     * Returns the value to which the specified key is mapped, or the
-     * given default value if this map contains no mapping for the
-     * key.
-     *
-     * @param key the key whose associated value is to be returned
-     * @param defaultValue the value to return if this map contains
-     * no mapping for the given key
-     * @return the mapping for the key, if present; else the default value
-     * @throws NullPointerException if the specified key is null
-     */
-    public V getOrDefault(Object key, V defaultValue) {
-        V v;
-        return (v = internalGet(key)) == null ? defaultValue : v;
-    }
-
-    /**
-     * Tests if the specified object is a key in this table.
-     *
-     * @param  key possible key
-     * @return {@code true} if and only if the specified object
-     *         is a key in this table, as determined by the
-     *         {@code equals} method; {@code false} otherwise
-     * @throws NullPointerException if the specified key is null
-     */
-    public boolean containsKey(Object key) {
-        return internalGet(key) != null;
-    }
-
-    /**
-     * Returns {@code true} if this map maps one or more keys to the
-     * specified value. Note: This method may require a full traversal
-     * of the map, and is much slower than method {@code containsKey}.
-     *
-     * @param value value whose presence in this map is to be tested
-     * @return {@code true} if this map maps one or more keys to the
-     *         specified value
-     * @throws NullPointerException if the specified value is null
-     */
-    public boolean containsValue(Object value) {
-        if (value == null)
-            throw new NullPointerException();
-        Node<K,V>[] t;
-        if ((t = table) != null) {
-            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
-            for (Node<K,V> p; (p = it.advance()) != null; ) {
-                V v;
-                if ((v = p.val) == value || value.equals(v))
-                    return true;
-            }
-        }
-        return false;
-    }
-
-    /**
-     * Legacy method testing if some key maps into the specified value
-     * in this table.  This method is identical in functionality to
-     * {@link #containsValue(Object)}, and exists solely to ensure
-     * full compatibility with class {@link java.util.Hashtable},
-     * which supported this method prior to introduction of the
-     * Java Collections framework.
-     *
-     * @param  value a value to search for
-     * @return {@code true} if and only if some key maps to the
-     *         {@code value} argument in this table as
-     *         determined by the {@code equals} method;
-     *         {@code false} otherwise
-     * @throws NullPointerException if the specified value is null
-     */
-    public boolean contains(Object value) {
-        return containsValue(value);
-    }
-
-    /**
-     * Maps the specified key to the specified value in this table.
-     * Neither the key nor the value can be null.
-     *
-     * <p>The value can be retrieved by calling the {@code get} method
-     * with a key that is equal to the original key.
-     *
-     * @param key key with which the specified value is to be associated
-     * @param value value to be associated with the specified key
-     * @return the previous value associated with {@code key}, or
-     *         {@code null} if there was no mapping for {@code key}
-     * @throws NullPointerException if the specified key or value is null
-     */
-    public V put(K key, V value) {
-        return internalPut(key, value, false);
-    }
-
-    /**
-     * {@inheritDoc}
-     *
-     * @return the previous value associated with the specified key,
-     *         or {@code null} if there was no mapping for the key
-     * @throws NullPointerException if the specified key or value is null
-     */
-    public V putIfAbsent(K key, V value) {
-        return internalPut(key, value, true);
-    }
-
-    /**
-     * Copies all of the mappings from the specified map to this one.
-     * These mappings replace any mappings that this map had for any of the
-     * keys currently in the specified map.
-     *
-     * @param m mappings to be stored in this map
-     */
-    public void putAll(Map<? extends K, ? extends V> m) {
-        internalPutAll(m);
-    }
-
-    /**
-     * If the specified key is not already associated with a value,
-     * attempts to compute its value using the given mapping function
-     * and enters it into this map unless {@code null}.  The entire
-     * method invocation is performed atomically, so the function is
-     * applied at most once per key.  Some attempted update operations
-     * on this map by other threads may be blocked while computation
-     * is in progress, so the computation should be short and simple,
-     * and must not attempt to update any other mappings of this map.
-     *
-     * @param key key with which the specified value is to be associated
-     * @param mappingFunction the function to compute a value
-     * @return the current (existing or computed) value associated with
-     *         the specified key, or null if the computed value is null
-     * @throws NullPointerException if the specified key or mappingFunction
-     *         is null
-     * @throws IllegalStateException if the computation detectably
-     *         attempts a recursive update to this map that would
-     *         otherwise never complete
-     * @throws RuntimeException or Error if the mappingFunction does so,
-     *         in which case the mapping is left unestablished
-     */
-    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
-        return internalComputeIfAbsent(key, mappingFunction);
-    }
-
-    /**
-     * If the value for the specified key is present, attempts to
-     * compute a new mapping given the key and its current mapped
-     * value.  The entire method invocation is performed atomically.
-     * Some attempted update operations on this map by other threads
-     * may be blocked while computation is in progress, so the
-     * computation should be short and simple, and must not attempt to
-     * update any other mappings of this map.
-     *
-     * @param key key with which a value may be associated
-     * @param remappingFunction the function to compute a value
-     * @return the new value associated with the specified key, or null if none
-     * @throws NullPointerException if the specified key or remappingFunction
-     *         is null
-     * @throws IllegalStateException if the computation detectably
-     *         attempts a recursive update to this map that would
-     *         otherwise never complete
-     * @throws RuntimeException or Error if the remappingFunction does so,
-     *         in which case the mapping is unchanged
-     */
-    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
-        return internalCompute(key, true, remappingFunction);
-    }
-
-    /**
-     * Attempts to compute a mapping for the specified key and its
-     * current mapped value (or {@code null} if there is no current
-     * mapping). The entire method invocation is performed atomically.
-     * Some attempted update operations on this map by other threads
-     * may be blocked while computation is in progress, so the
-     * computation should be short and simple, and must not attempt to
-     * update any other mappings of this Map.
-     *
-     * @param key key with which the specified value is to be associated
-     * @param remappingFunction the function to compute a value
-     * @return the new value associated with the specified key, or null if none
-     * @throws NullPointerException if the specified key or remappingFunction
-     *         is null
-     * @throws IllegalStateException if the computation detectably
-     *         attempts a recursive update to this map that would
-     *         otherwise never complete
-     * @throws RuntimeException or Error if the remappingFunction does so,
-     *         in which case the mapping is unchanged
-     */
-    public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
-        return internalCompute(key, false, remappingFunction);
-    }
-
-    /**
-     * If the specified key is not already associated with a
-     * (non-null) value, associates it with the given value.
-     * Otherwise, replaces the value with the results of the given
-     * remapping function, or removes if {@code null}. The entire
-     * method invocation is performed atomically.  Some attempted
-     * update operations on this map by other threads may be blocked
-     * while computation is in progress, so the computation should be
-     * short and simple, and must not attempt to update any other
-     * mappings of this Map.
-     *
-     * @param key key with which the specified value is to be associated
-     * @param value the value to use if absent
-     * @param remappingFunction the function to recompute a value if present
-     * @return the new value associated with the specified key, or null if none
-     * @throws NullPointerException if the specified key or the
-     *         remappingFunction is null
-     * @throws RuntimeException or Error if the remappingFunction does so,
-     *         in which case the mapping is unchanged
-     */
-    public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
-        return internalMerge(key, value, remappingFunction);
-    }
-
-    /**
-     * Removes the key (and its corresponding value) from this map.
-     * This method does nothing if the key is not in the map.
-     *
-     * @param  key the key that needs to be removed
-     * @return the previous value associated with {@code key}, or
-     *         {@code null} if there was no mapping for {@code key}
-     * @throws NullPointerException if the specified key is null
-     */
-    public V remove(Object key) {
-        return internalReplace(key, null, null);
-    }
-
-    /**
-     * {@inheritDoc}
-     *
-     * @throws NullPointerException if the specified key is null
-     */
-    public boolean remove(Object key, Object value) {
-        if (key == null)
-            throw new NullPointerException();
-        return value != null && internalReplace(key, null, value) != null;
-    }
-
-    /**
-     * {@inheritDoc}
-     *
-     * @throws NullPointerException if any of the arguments are null
-     */
-    public boolean replace(K key, V oldValue, V newValue) {
-        if (key == null || oldValue == null || newValue == null)
-            throw new NullPointerException();
-        return internalReplace(key, newValue, oldValue) != null;
-    }
-
-    /**
-     * {@inheritDoc}
-     *
-     * @return the previous value associated with the specified key,
-     *         or {@code null} if there was no mapping for the key
-     * @throws NullPointerException if the specified key or value is null
-     */
-    public V replace(K key, V value) {
-        if (key == null || value == null)
-            throw new NullPointerException();
-        return internalReplace(key, value, null);
-    }
-
-    /**
-     * Removes all of the mappings from this map.
-     */
-    public void clear() {
-        internalClear();
-    }
-
-    /**
-     * Returns a {@link Set} view of the keys contained in this map.
-     * The set is backed by the map, so changes to the map are
-     * reflected in the set, and vice-versa. The set supports element
-     * removal, which removes the corresponding mapping from this map,
-     * via the {@code Iterator.remove}, {@code Set.remove},
-     * {@code removeAll}, {@code retainAll}, and {@code clear}
-     * operations.  It does not support the {@code add} or
-     * {@code addAll} operations.
-     *
-     * <p>The view's {@code iterator} is a "weakly consistent" iterator
-     * that will never throw {@link ConcurrentModificationException},
-     * and guarantees to traverse elements as they existed upon
-     * construction of the iterator, and may (but is not guaranteed to)
-     * reflect any modifications subsequent to construction.
-     *
-     * @return the set view
-     */
-    public KeySetView<K,V> keySet() {
-        KeySetView<K,V> ks = keySet;
-        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
-    }
-
-    /**
-     * Returns a {@link Set} view of the keys in this map, using the
-     * given common mapped value for any additions (i.e., {@link
-     * Collection#add} and {@link Collection#addAll(Collection)}).
-     * This is of course only appropriate if it is acceptable to use
-     * the same value for all additions from this view.
-     *
-     * @param mappedValue the mapped value to use for any additions
-     * @return the set view
-     * @throws NullPointerException if the mappedValue is null
-     */
-    public KeySetView<K,V> keySet(V mappedValue) {
-        if (mappedValue == null)
-            throw new NullPointerException();
-        return new KeySetView<K,V>(this, mappedValue);
-    }
-
-    /**
-     * Returns a {@link Collection} view of the values contained in this map.
-     * The collection is backed by the map, so changes to the map are
-     * reflected in the collection, and vice-versa.  The collection
-     * supports element removal, which removes the corresponding
-     * mapping from this map, via the {@code Iterator.remove},
-     * {@code Collection.remove}, {@code removeAll},
-     * {@code retainAll}, and {@code clear} operations.  It does not
-     * support the {@code add} or {@code addAll} operations.
-     *
-     * <p>The view's {@code iterator} is a "weakly consistent" iterator
-     * that will never throw {@link ConcurrentModificationException},
-     * and guarantees to traverse elements as they existed upon
-     * construction of the iterator, and may (but is not guaranteed to)
-     * reflect any modifications subsequent to construction.
-     *
-     * @return the collection view
-     */
-    public Collection<V> values() {
-        ValuesView<K,V> vs = values;
-        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
-    }
-
-    /**
-     * Returns a {@link Set} view of the mappings contained in this map.
-     * The set is backed by the map, so changes to the map are
-     * reflected in the set, and vice-versa.  The set supports element
-     * removal, which removes the corresponding mapping from the map,
-     * via the {@code Iterator.remove}, {@code Set.remove},
-     * {@code removeAll}, {@code retainAll}, and {@code clear}
-     * operations.
-     *
-     * <p>The view's {@code iterator} is a "weakly consistent" iterator
-     * that will never throw {@link ConcurrentModificationException},
-     * and guarantees to traverse elements as they existed upon
-     * construction of the iterator, and may (but is not guaranteed to)
-     * reflect any modifications subsequent to construction.
-     *
-     * @return the set view
-     */
-    public Set<Map.Entry<K,V>> entrySet() {
-        EntrySetView<K,V> es = entrySet;
-        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
-    }
-
-    /**
-     * Returns an enumeration of the keys in this table.
-     *
-     * @return an enumeration of the keys in this table
-     * @see #keySet()
-     */
-    public Enumeration<K> keys() {
-        Node<K,V>[] t;
-        int f = (t = table) == null ? 0 : t.length;
-        return new KeyIterator<K,V>(t, f, 0, f, this);
-    }
-
-    /**
-     * Returns an enumeration of the values in this table.
-     *
-     * @return an enumeration of the values in this table
-     * @see #values()
-     */
-    public Enumeration<V> elements() {
-        Node<K,V>[] t;
-        int f = (t = table) == null ? 0 : t.length;
-        return new ValueIterator<K,V>(t, f, 0, f, this);
-    }
-
-    /**
-     * Returns the hash code value for this {@link Map}, i.e.,
-     * the sum of, for each key-value pair in the map,
-     * {@code key.hashCode() ^ value.hashCode()}.
-     *
-     * @return the hash code value for this map
-     */
-    public int hashCode() {
-        int h = 0;
-        Node<K,V>[] t;
-        if ((t = table) != null) {
-            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
-            for (Node<K,V> p; (p = it.advance()) != null; )
-                h += p.key.hashCode() ^ p.val.hashCode();
-        }
-        return h;
-    }
-
-    /**
-     * Returns a string representation of this map.  The string
-     * representation consists of a list of key-value mappings (in no
-     * particular order) enclosed in braces ("{@code {}}").  Adjacent
-     * mappings are separated by the characters {@code ", "} (comma
-     * and space).  Each key-value mapping is rendered as the key
-     * followed by an equals sign ("{@code =}") followed by the
-     * associated value.
-     *
-     * @return a string representation of this map
-     */
-    public String toString() {
-        Node<K,V>[] t;
-        int f = (t = table) == null ? 0 : t.length;
-        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
-        StringBuilder sb = new StringBuilder();
-        sb.append('{');
-        Node<K,V> p;
-        if ((p = it.advance()) != null) {
-            for (;;) {
-                K k = (K)p.key;
-                V v = p.val;
-                sb.append(k == this ? "(this Map)" : k);
-                sb.append('=');
-                sb.append(v == this ? "(this Map)" : v);
-                if ((p = it.advance()) == null)
-                    break;
-                sb.append(',').append(' ');
-            }
-        }
-        return sb.append('}').toString();
-    }
-
-    /**
-     * Compares the specified object with this map for equality.
-     * Returns {@code true} if the given object is a map with the same
-     * mappings as this map.  This operation may return misleading
-     * results if either map is concurrently modified during execution
-     * of this method.
-     *
-     * @param o object to be compared for equality with this map
-     * @return {@code true} if the specified object is equal to this map
-     */
-    public boolean equals(Object o) {
-        if (o != this) {
-            if (!(o instanceof Map))
-                return false;
-            Map<?,?> m = (Map<?,?>) o;
-            Node<K,V>[] t;
-            int f = (t = table) == null ? 0 : t.length;
-            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
-            for (Node<K,V> p; (p = it.advance()) != null; ) {
-                V val = p.val;
-                Object v = m.get(p.key);
-                if (v == null || (v != val && !v.equals(val)))
-                    return false;
-            }
-            for (Map.Entry<?,?> e : m.entrySet()) {
-                Object mk, mv, v;
-                if ((mk = e.getKey()) == null ||
-                    (mv = e.getValue()) == null ||
-                    (v = internalGet(mk)) == null ||
-                    (mv != v && !mv.equals(v)))
-                    return false;
-            }
-        }
-        return true;
-    }
-
-    /* ---------------- Serialization Support -------------- */
-
-    /**
-     * Stripped-down version of helper class used in previous version,
-     * declared for the sake of serialization compatibility
-     */
-    static class Segment<K,V> extends ReentrantLock implements Serializable {
-        private static final long serialVersionUID = 2249069246763182397L;
-        final float loadFactor;
-        Segment(float lf) { this.loadFactor = lf; }
-    }
-
-    /**
-     * Saves the state of the {@code ConcurrentHashMap} instance to a
-     * stream (i.e., serializes it).
-     * @param s the stream
-     * @serialData
-     * the key (Object) and value (Object)
-     * for each key-value mapping, followed by a null pair.
-     * The key-value mappings are emitted in no particular order.
-     */
-    private void writeObject(java.io.ObjectOutputStream s)
-        throws java.io.IOException {
-        // For serialization compatibility
-        // Emulate segment calculation from previous version of this class
-        int sshift = 0;
-        int ssize = 1;
-        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
-            ++sshift;
-            ssize <<= 1;
-        }
-        int segmentShift = 32 - sshift;
-        int segmentMask = ssize - 1;
-        Segment<K,V>[] segments = (Segment<K,V>[])
-            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
-        for (int i = 0; i < segments.length; ++i)
-            segments[i] = new Segment<K,V>(LOAD_FACTOR);
-        s.putFields().put("segments", segments);
-        s.putFields().put("segmentShift", segmentShift);
-        s.putFields().put("segmentMask", segmentMask);
-        s.writeFields();
-
-        Node<K,V>[] t;
-        if ((t = table) != null) {
-            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
-            for (Node<K,V> p; (p = it.advance()) != null; ) {
-                s.writeObject(p.key);
-                s.writeObject(p.val);
-            }
-        }
-        s.writeObject(null);
-        s.writeObject(null);
-        segments = null; // throw away
-    }
-
-    /**
-     * Reconstitutes the instance from a stream (that is, deserializes it).
-     * @param s the stream
-     */
-    private void readObject(java.io.ObjectInputStream s)
-        throws java.io.IOException, ClassNotFoundException {
-        s.defaultReadObject();
-
-        // Create all nodes, then place in table once size is known
-        long size = 0L;
-        Node<K,V> p = null;
-        for (;;) {
-            K k = (K) s.readObject();
-            V v = (V) s.readObject();
-            if (k != null && v != null) {
-                int h = spread(k.hashCode());
-                p = new Node<K,V>(h, k, v, p);
-                ++size;
-            }
-            else
-                break;
-        }
-        if (p != null) {
-            boolean init = false;
-            int n;
-            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
-                n = MAXIMUM_CAPACITY;
-            else {
-                int sz = (int)size;
-                n = tableSizeFor(sz + (sz >>> 1) + 1);
-            }
-            int sc = sizeCtl;
-            boolean collide = false;
-            if (n > sc &&
-                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
-                try {
-                    if (table == null) {
-                        init = true;
-                        Node<K,V>[] tab = (Node<K,V>[])new Node[n];
-                        int mask = n - 1;
-                        while (p != null) {
-                            int j = p.hash & mask;
-                            Node<K,V> next = p.next;
-                            Node<K,V> q = p.next = tabAt(tab, j);
-                            setTabAt(tab, j, p);
-                            if (!collide && q != null && q.hash == p.hash)
-                                collide = true;
-                            p = next;
-                        }
-                        table = tab;
-                        addCount(size, -1);
-                        sc = n - (n >>> 2);
-                    }
-                } finally {
-                    sizeCtl = sc;
-                }
-                if (collide) { // rescan and convert to TreeBins
-                    Node<K,V>[] tab = table;
-                    for (int i = 0; i < tab.length; ++i) {
-                        int c = 0;
-                        for (Node<K,V> e = tabAt(tab, i); e != null; e = e.next) {
-                            if (++c > TREE_THRESHOLD &&
-                                (e.key instanceof Comparable)) {
-                                replaceWithTreeBin(tab, i, e.key);
-                                break;
-                            }
-                        }
-                    }
-                }
-            }
-            if (!init) { // Can only happen if unsafely published.
-                while (p != null) {
-                    internalPut((K)p.key, p.val, false);
-                    p = p.next;
-                }
-            }
-        }
-    }
-
-    // -------------------------------------------------------
-
-    // Overrides of other default Map methods
-
-    public void forEach(BiConsumer<? super K, ? super V> action) {
-        if (action == null) throw new NullPointerException();
-        Node<K,V>[] t;
-        if ((t = table) != null) {
-            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
-            for (Node<K,V> p; (p = it.advance()) != null; ) {
-                action.accept((K)p.key, p.val);
-            }
-        }
-    }
-
-    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
-        if (function == null) throw new NullPointerException();
-        Node<K,V>[] t;
-        if ((t = table) != null) {
-            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
-            for (Node<K,V> p; (p = it.advance()) != null; ) {
-                K k = (K)p.key;
-                internalPut(k, function.apply(k, p.val), false);
-            }
-        }
-    }
-
-    // -------------------------------------------------------
-
     // Parallel bulk operations
 
     /**
@@ -3429,10 +3621,10 @@
      * of all (key, value) pairs
      * @since 1.8
      */
-    public double reduceToDoubleIn(long parallelismThreshold,
-                                   ToDoubleBiFunction<? super K, ? super V> transformer,
-                                   double basis,
-                                   DoubleBinaryOperator reducer) {
+    public double reduceToDouble(long parallelismThreshold,
+                                 ToDoubleBiFunction<? super K, ? super V> transformer,
+                                 double basis,
+                                 DoubleBinaryOperator reducer) {
         if (transformer == null || reducer == null)
             throw new NullPointerException();
         return new MapReduceMappingsToDoubleTask<K,V>
@@ -4104,6 +4296,7 @@
             return (i == n) ? r : Arrays.copyOf(r, i);
         }
 
+        @SuppressWarnings("unchecked")
         public final <T> T[] toArray(T[] a) {
             long sz = map.mappingCount();
             if (sz > MAX_ARRAY_SIZE)
@@ -4202,6 +4395,7 @@
      * {@link #keySet(Object) keySet(V)},
      * {@link #newKeySet() newKeySet()},
      * {@link #newKeySet(int) newKeySet(int)}.
+     *
      * @since 1.8
      */
     public static class KeySetView<K,V> extends CollectionView<K,V,K>
@@ -4263,7 +4457,7 @@
             V v;
             if ((v = value) == null)
                 throw new UnsupportedOperationException();
-            return map.internalPut(e, v, true) == null;
+            return map.putVal(e, v, true) == null;
         }
 
         /**
@@ -4283,7 +4477,7 @@
             if ((v = value) == null)
                 throw new UnsupportedOperationException();
             for (K e : c) {
-                if (map.internalPut(e, v, true) == null)
+                if (map.putVal(e, v, true) == null)
                     added = true;
             }
             return added;
@@ -4317,7 +4511,7 @@
             if ((t = map.table) != null) {
                 Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
                 for (Node<K,V> p; (p = it.advance()) != null; )
-                    action.accept((K)p.key);
+                    action.accept(p.key);
             }
         }
     }
@@ -4418,7 +4612,7 @@
         }
 
         public boolean add(Entry<K,V> e) {
-            return map.internalPut(e.getKey(), e.getValue(), false) == null;
+            return map.putVal(e.getKey(), e.getValue(), false) == null;
         }
 
         public boolean addAll(Collection<? extends Entry<K,V>> c) {
@@ -4463,7 +4657,7 @@
             if ((t = map.table) != null) {
                 Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
                 for (Node<K,V> p; (p = it.advance()) != null; )
-                    action.accept(new MapEntry<K,V>((K)p.key, p.val, map));
+                    action.accept(new MapEntry<K,V>(p.key, p.val, map));
             }
         }
 
@@ -4506,23 +4700,25 @@
             if ((e = next) != null)
                 e = e.next;
             for (;;) {
-                Node<K,V>[] t; int i, n; Object ek;
+                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
                 if (e != null)
                     return next = e;
                 if (baseIndex >= baseLimit || (t = tab) == null ||
                     (n = t.length) <= (i = index) || i < 0)
                     return next = null;
                 if ((e = tabAt(t, index)) != null && e.hash < 0) {
-                    if ((ek = e.key) instanceof TreeBin)
-                        e = ((TreeBin<K,V>)ek).first;
-                    else {
-                        tab = (Node<K,V>[])ek;
+                    if (e instanceof ForwardingNode) {
+                        tab = ((ForwardingNode<K,V>)e).nextTable;
                         e = null;
                         continue;
                     }
+                    else if (e instanceof TreeBin)
+                        e = ((TreeBin<K,V>)e).first;
+                    else
+                        e = null;
                 }
                 if ((index += baseSize) >= n)
-                    index = ++baseIndex;
+                    index = ++baseIndex;    // visit upper slots if present
             }
         }
     }
@@ -4534,7 +4730,7 @@
      * that we've already null-checked task arguments, so we force
      * simplest hoisted bypass to help avoid convoluted traps.
      */
-
+    @SuppressWarnings("serial")
     static final class ForEachKeyTask<K,V>
         extends BulkTask<K,V,Void> {
         final Consumer<? super K> action;
@@ -4555,12 +4751,13 @@
                          action).fork();
                 }
                 for (Node<K,V> p; (p = advance()) != null;)
-                    action.accept((K)p.key);
+                    action.accept(p.key);
                 propagateCompletion();
             }
         }
     }
 
+    @SuppressWarnings("serial")
     static final class ForEachValueTask<K,V>
         extends BulkTask<K,V,Void> {
         final Consumer<? super V> action;
@@ -4587,6 +4784,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class ForEachEntryTask<K,V>
         extends BulkTask<K,V,Void> {
         final Consumer<? super Entry<K,V>> action;
@@ -4613,6 +4811,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class ForEachMappingTask<K,V>
         extends BulkTask<K,V,Void> {
         final BiConsumer<? super K, ? super V> action;
@@ -4633,12 +4832,13 @@
                          action).fork();
                 }
                 for (Node<K,V> p; (p = advance()) != null; )
-                    action.accept((K)p.key, p.val);
+                    action.accept(p.key, p.val);
                 propagateCompletion();
             }
         }
     }
 
+    @SuppressWarnings("serial")
     static final class ForEachTransformedKeyTask<K,V,U>
         extends BulkTask<K,V,Void> {
         final Function<? super K, ? extends U> transformer;
@@ -4663,7 +4863,7 @@
                 }
                 for (Node<K,V> p; (p = advance()) != null; ) {
                     U u;
-                    if ((u = transformer.apply((K)p.key)) != null)
+                    if ((u = transformer.apply(p.key)) != null)
                         action.accept(u);
                 }
                 propagateCompletion();
@@ -4671,6 +4871,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class ForEachTransformedValueTask<K,V,U>
         extends BulkTask<K,V,Void> {
         final Function<? super V, ? extends U> transformer;
@@ -4703,6 +4904,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class ForEachTransformedEntryTask<K,V,U>
         extends BulkTask<K,V,Void> {
         final Function<Map.Entry<K,V>, ? extends U> transformer;
@@ -4735,6 +4937,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class ForEachTransformedMappingTask<K,V,U>
         extends BulkTask<K,V,Void> {
         final BiFunction<? super K, ? super V, ? extends U> transformer;
@@ -4760,7 +4963,7 @@
                 }
                 for (Node<K,V> p; (p = advance()) != null; ) {
                     U u;
-                    if ((u = transformer.apply((K)p.key, p.val)) != null)
+                    if ((u = transformer.apply(p.key, p.val)) != null)
                         action.accept(u);
                 }
                 propagateCompletion();
@@ -4768,6 +4971,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class SearchKeysTask<K,V,U>
         extends BulkTask<K,V,U> {
         final Function<? super K, ? extends U> searchFunction;
@@ -4801,7 +5005,7 @@
                         propagateCompletion();
                         break;
                     }
-                    if ((u = searchFunction.apply((K)p.key)) != null) {
+                    if ((u = searchFunction.apply(p.key)) != null) {
                         if (result.compareAndSet(null, u))
                             quietlyCompleteRoot();
                         break;
@@ -4811,6 +5015,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class SearchValuesTask<K,V,U>
         extends BulkTask<K,V,U> {
         final Function<? super V, ? extends U> searchFunction;
@@ -4854,6 +5059,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class SearchEntriesTask<K,V,U>
         extends BulkTask<K,V,U> {
         final Function<Entry<K,V>, ? extends U> searchFunction;
@@ -4897,6 +5103,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class SearchMappingsTask<K,V,U>
         extends BulkTask<K,V,U> {
         final BiFunction<? super K, ? super V, ? extends U> searchFunction;
@@ -4930,7 +5137,7 @@
                         propagateCompletion();
                         break;
                     }
-                    if ((u = searchFunction.apply((K)p.key, p.val)) != null) {
+                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
                         if (result.compareAndSet(null, u))
                             quietlyCompleteRoot();
                         break;
@@ -4940,6 +5147,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class ReduceKeysTask<K,V>
         extends BulkTask<K,V,K> {
         final BiFunction<? super K, ? super K, ? extends K> reducer;
@@ -4965,13 +5173,13 @@
                 }
                 K r = null;
                 for (Node<K,V> p; (p = advance()) != null; ) {
-                    K u = (K)p.key;
+                    K u = p.key;
                     r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
                 }
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    ReduceKeysTask<K,V>
+                    @SuppressWarnings("unchecked") ReduceKeysTask<K,V>
                         t = (ReduceKeysTask<K,V>)c,
                         s = t.rights;
                     while (s != null) {
@@ -4986,6 +5194,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class ReduceValuesTask<K,V>
         extends BulkTask<K,V,V> {
         final BiFunction<? super V, ? super V, ? extends V> reducer;
@@ -5017,7 +5226,7 @@
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    ReduceValuesTask<K,V>
+                    @SuppressWarnings("unchecked") ReduceValuesTask<K,V>
                         t = (ReduceValuesTask<K,V>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5032,6 +5241,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class ReduceEntriesTask<K,V>
         extends BulkTask<K,V,Map.Entry<K,V>> {
         final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
@@ -5061,7 +5271,7 @@
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    ReduceEntriesTask<K,V>
+                    @SuppressWarnings("unchecked") ReduceEntriesTask<K,V>
                         t = (ReduceEntriesTask<K,V>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5076,6 +5286,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class MapReduceKeysTask<K,V,U>
         extends BulkTask<K,V,U> {
         final Function<? super K, ? extends U> transformer;
@@ -5107,13 +5318,13 @@
                 U r = null;
                 for (Node<K,V> p; (p = advance()) != null; ) {
                     U u;
-                    if ((u = transformer.apply((K)p.key)) != null)
+                    if ((u = transformer.apply(p.key)) != null)
                         r = (r == null) ? u : reducer.apply(r, u);
                 }
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    MapReduceKeysTask<K,V,U>
+                    @SuppressWarnings("unchecked") MapReduceKeysTask<K,V,U>
                         t = (MapReduceKeysTask<K,V,U>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5128,6 +5339,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class MapReduceValuesTask<K,V,U>
         extends BulkTask<K,V,U> {
         final Function<? super V, ? extends U> transformer;
@@ -5165,7 +5377,7 @@
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    MapReduceValuesTask<K,V,U>
+                    @SuppressWarnings("unchecked") MapReduceValuesTask<K,V,U>
                         t = (MapReduceValuesTask<K,V,U>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5180,6 +5392,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class MapReduceEntriesTask<K,V,U>
         extends BulkTask<K,V,U> {
         final Function<Map.Entry<K,V>, ? extends U> transformer;
@@ -5217,7 +5430,7 @@
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    MapReduceEntriesTask<K,V,U>
+                    @SuppressWarnings("unchecked") MapReduceEntriesTask<K,V,U>
                         t = (MapReduceEntriesTask<K,V,U>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5232,6 +5445,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class MapReduceMappingsTask<K,V,U>
         extends BulkTask<K,V,U> {
         final BiFunction<? super K, ? super V, ? extends U> transformer;
@@ -5263,13 +5477,13 @@
                 U r = null;
                 for (Node<K,V> p; (p = advance()) != null; ) {
                     U u;
-                    if ((u = transformer.apply((K)p.key, p.val)) != null)
+                    if ((u = transformer.apply(p.key, p.val)) != null)
                         r = (r == null) ? u : reducer.apply(r, u);
                 }
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    MapReduceMappingsTask<K,V,U>
+                    @SuppressWarnings("unchecked") MapReduceMappingsTask<K,V,U>
                         t = (MapReduceMappingsTask<K,V,U>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5284,6 +5498,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class MapReduceKeysToDoubleTask<K,V>
         extends BulkTask<K,V,Double> {
         final ToDoubleFunction<? super K> transformer;
@@ -5316,11 +5531,11 @@
                       rights, transformer, r, reducer)).fork();
                 }
                 for (Node<K,V> p; (p = advance()) != null; )
-                    r = reducer.applyAsDouble(r, transformer.applyAsDouble((K)p.key));
+                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    MapReduceKeysToDoubleTask<K,V>
+                    @SuppressWarnings("unchecked") MapReduceKeysToDoubleTask<K,V>
                         t = (MapReduceKeysToDoubleTask<K,V>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5332,6 +5547,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class MapReduceValuesToDoubleTask<K,V>
         extends BulkTask<K,V,Double> {
         final ToDoubleFunction<? super V> transformer;
@@ -5368,7 +5584,7 @@
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    MapReduceValuesToDoubleTask<K,V>
+                    @SuppressWarnings("unchecked") MapReduceValuesToDoubleTask<K,V>
                         t = (MapReduceValuesToDoubleTask<K,V>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5380,6 +5596,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class MapReduceEntriesToDoubleTask<K,V>
         extends BulkTask<K,V,Double> {
         final ToDoubleFunction<Map.Entry<K,V>> transformer;
@@ -5416,7 +5633,7 @@
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    MapReduceEntriesToDoubleTask<K,V>
+                    @SuppressWarnings("unchecked") MapReduceEntriesToDoubleTask<K,V>
                         t = (MapReduceEntriesToDoubleTask<K,V>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5428,6 +5645,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class MapReduceMappingsToDoubleTask<K,V>
         extends BulkTask<K,V,Double> {
         final ToDoubleBiFunction<? super K, ? super V> transformer;
@@ -5460,11 +5678,11 @@
                       rights, transformer, r, reducer)).fork();
                 }
                 for (Node<K,V> p; (p = advance()) != null; )
-                    r = reducer.applyAsDouble(r, transformer.applyAsDouble((K)p.key, p.val));
+                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    MapReduceMappingsToDoubleTask<K,V>
+                    @SuppressWarnings("unchecked") MapReduceMappingsToDoubleTask<K,V>
                         t = (MapReduceMappingsToDoubleTask<K,V>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5476,6 +5694,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class MapReduceKeysToLongTask<K,V>
         extends BulkTask<K,V,Long> {
         final ToLongFunction<? super K> transformer;
@@ -5508,11 +5727,11 @@
                       rights, transformer, r, reducer)).fork();
                 }
                 for (Node<K,V> p; (p = advance()) != null; )
-                    r = reducer.applyAsLong(r, transformer.applyAsLong((K)p.key));
+                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    MapReduceKeysToLongTask<K,V>
+                    @SuppressWarnings("unchecked") MapReduceKeysToLongTask<K,V>
                         t = (MapReduceKeysToLongTask<K,V>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5524,6 +5743,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class MapReduceValuesToLongTask<K,V>
         extends BulkTask<K,V,Long> {
         final ToLongFunction<? super V> transformer;
@@ -5560,7 +5780,7 @@
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    MapReduceValuesToLongTask<K,V>
+                    @SuppressWarnings("unchecked") MapReduceValuesToLongTask<K,V>
                         t = (MapReduceValuesToLongTask<K,V>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5572,6 +5792,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class MapReduceEntriesToLongTask<K,V>
         extends BulkTask<K,V,Long> {
         final ToLongFunction<Map.Entry<K,V>> transformer;
@@ -5608,7 +5829,7 @@
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    MapReduceEntriesToLongTask<K,V>
+                    @SuppressWarnings("unchecked") MapReduceEntriesToLongTask<K,V>
                         t = (MapReduceEntriesToLongTask<K,V>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5620,6 +5841,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class MapReduceMappingsToLongTask<K,V>
         extends BulkTask<K,V,Long> {
         final ToLongBiFunction<? super K, ? super V> transformer;
@@ -5652,11 +5874,11 @@
                       rights, transformer, r, reducer)).fork();
                 }
                 for (Node<K,V> p; (p = advance()) != null; )
-                    r = reducer.applyAsLong(r, transformer.applyAsLong((K)p.key, p.val));
+                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    MapReduceMappingsToLongTask<K,V>
+                    @SuppressWarnings("unchecked") MapReduceMappingsToLongTask<K,V>
                         t = (MapReduceMappingsToLongTask<K,V>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5668,6 +5890,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class MapReduceKeysToIntTask<K,V>
         extends BulkTask<K,V,Integer> {
         final ToIntFunction<? super K> transformer;
@@ -5700,11 +5923,11 @@
                       rights, transformer, r, reducer)).fork();
                 }
                 for (Node<K,V> p; (p = advance()) != null; )
-                    r = reducer.applyAsInt(r, transformer.applyAsInt((K)p.key));
+                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    MapReduceKeysToIntTask<K,V>
+                    @SuppressWarnings("unchecked") MapReduceKeysToIntTask<K,V>
                         t = (MapReduceKeysToIntTask<K,V>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5716,6 +5939,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class MapReduceValuesToIntTask<K,V>
         extends BulkTask<K,V,Integer> {
         final ToIntFunction<? super V> transformer;
@@ -5752,7 +5976,7 @@
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    MapReduceValuesToIntTask<K,V>
+                    @SuppressWarnings("unchecked") MapReduceValuesToIntTask<K,V>
                         t = (MapReduceValuesToIntTask<K,V>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5764,6 +5988,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class MapReduceEntriesToIntTask<K,V>
         extends BulkTask<K,V,Integer> {
         final ToIntFunction<Map.Entry<K,V>> transformer;
@@ -5800,7 +6025,7 @@
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    MapReduceEntriesToIntTask<K,V>
+                    @SuppressWarnings("unchecked") MapReduceEntriesToIntTask<K,V>
                         t = (MapReduceEntriesToIntTask<K,V>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5812,6 +6037,7 @@
         }
     }
 
+    @SuppressWarnings("serial")
     static final class MapReduceMappingsToIntTask<K,V>
         extends BulkTask<K,V,Integer> {
         final ToIntBiFunction<? super K, ? super V> transformer;
@@ -5844,11 +6070,11 @@
                       rights, transformer, r, reducer)).fork();
                 }
                 for (Node<K,V> p; (p = advance()) != null; )
-                    r = reducer.applyAsInt(r, transformer.applyAsInt((K)p.key, p.val));
+                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));
                 result = r;
                 CountedCompleter<?> c;
                 for (c = firstComplete(); c != null; c = c.nextComplete()) {
-                    MapReduceMappingsToIntTask<K,V>
+                    @SuppressWarnings("unchecked") MapReduceMappingsToIntTask<K,V>
                         t = (MapReduceMappingsToIntTask<K,V>)c,
                         s = t.rights;
                     while (s != null) {
@@ -5885,12 +6111,12 @@
                 (k.getDeclaredField("baseCount"));
             CELLSBUSY = U.objectFieldOffset
                 (k.getDeclaredField("cellsBusy"));
-            Class<?> ck = Cell.class;
+            Class<?> ck = CounterCell.class;
             CELLVALUE = U.objectFieldOffset
                 (ck.getDeclaredField("value"));
-            Class<?> sc = Node[].class;
-            ABASE = U.arrayBaseOffset(sc);
-            int scale = U.arrayIndexScale(sc);
+            Class<?> ak = Node[].class;
+            ABASE = U.arrayBaseOffset(ak);
+            int scale = U.arrayIndexScale(ak);
             if ((scale & (scale - 1)) != 0)
                 throw new Error("data type scale not a power of two");
             ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
--- a/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java	Mon Jul 22 17:37:15 2013 -0700
@@ -42,6 +42,9 @@
 import java.util.Iterator;
 import java.util.NoSuchElementException;
 import java.util.Queue;
+import java.util.Spliterator;
+import java.util.Spliterators;
+import java.util.function.Consumer;
 
 /**
  * An unbounded concurrent {@linkplain Deque deque} based on linked nodes.
@@ -816,7 +819,7 @@
      * Creates an array list and fills it with elements of this list.
      * Used by toArray.
      *
-     * @return the arrayList
+     * @return the array list
      */
     private ArrayList<E> toArrayList() {
         ArrayList<E> list = new ArrayList<E>();
@@ -1024,11 +1027,27 @@
     }
 
     public E poll()           { return pollFirst(); }
+    public E peek()           { return peekFirst(); }
+
+    /**
+     * @throws NoSuchElementException {@inheritDoc}
+     */
     public E remove()         { return removeFirst(); }
-    public E peek()           { return peekFirst(); }
+
+    /**
+     * @throws NoSuchElementException {@inheritDoc}
+     */
+    public E pop()            { return removeFirst(); }
+
+    /**
+     * @throws NoSuchElementException {@inheritDoc}
+     */
     public E element()        { return getFirst(); }
+
+    /**
+     * @throws NullPointerException {@inheritDoc}
+     */
     public void push(E e)     { addFirst(e); }
-    public E pop()            { return removeFirst(); }
 
     /**
      * Removes the first element {@code e} such that
@@ -1385,6 +1404,99 @@
         Node<E> nextNode(Node<E> p) { return pred(p); }
     }
 
+    /** A customized variant of Spliterators.IteratorSpliterator */
+    static final class CLDSpliterator<E> implements Spliterator<E> {
+        static final int MAX_BATCH = 1 << 25;  // max batch array size;
+        final ConcurrentLinkedDeque<E> queue;
+        Node<E> current;    // current node; null until initialized
+        int batch;          // batch size for splits
+        boolean exhausted;  // true when no more nodes
+        CLDSpliterator(ConcurrentLinkedDeque<E> queue) {
+            this.queue = queue;
+        }
+
+        public Spliterator<E> trySplit() {
+            Node<E> p;
+            final ConcurrentLinkedDeque<E> q = this.queue;
+            int b = batch;
+            int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
+            if (!exhausted &&
+                ((p = current) != null || (p = q.first()) != null)) {
+                if (p.item == null && p == (p = p.next))
+                    current = p = q.first();
+                if (p != null && p.next != null) {
+                    Object[] a = new Object[n];
+                    int i = 0;
+                    do {
+                        if ((a[i] = p.item) != null)
+                            ++i;
+                        if (p == (p = p.next))
+                            p = q.first();
+                    } while (p != null && i < n);
+                    if ((current = p) == null)
+                        exhausted = true;
+                    if (i > 0) {
+                        batch = i;
+                        return Spliterators.spliterator
+                            (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
+                             Spliterator.CONCURRENT);
+                    }
+                }
+            }
+            return null;
+        }
+
+        public void forEachRemaining(Consumer<? super E> action) {
+            Node<E> p;
+            if (action == null) throw new NullPointerException();
+            final ConcurrentLinkedDeque<E> q = this.queue;
+            if (!exhausted &&
+                ((p = current) != null || (p = q.first()) != null)) {
+                exhausted = true;
+                do {
+                    E e = p.item;
+                    if (p == (p = p.next))
+                        p = q.first();
+                    if (e != null)
+                        action.accept(e);
+                } while (p != null);
+            }
+        }
+
+        public boolean tryAdvance(Consumer<? super E> action) {
+            Node<E> p;
+            if (action == null) throw new NullPointerException();
+            final ConcurrentLinkedDeque<E> q = this.queue;
+            if (!exhausted &&
+                ((p = current) != null || (p = q.first()) != null)) {
+                E e;
+                do {
+                    e = p.item;
+                    if (p == (p = p.next))
+                        p = q.first();
+                } while (e == null && p != null);
+                if ((current = p) == null)
+                    exhausted = true;
+                if (e != null) {
+                    action.accept(e);
+                    return true;
+                }
+            }
+            return false;
+        }
+
+        public long estimateSize() { return Long.MAX_VALUE; }
+
+        public int characteristics() {
+            return Spliterator.ORDERED | Spliterator.NONNULL |
+                Spliterator.CONCURRENT;
+        }
+    }
+
+    public Spliterator<E> spliterator() {
+        return new CLDSpliterator<E>(this);
+    }
+
     /**
      * Saves this deque to a stream (that is, serializes it).
      *
--- a/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java	Mon Jul 22 17:37:15 2013 -0700
@@ -41,6 +41,9 @@
 import java.util.Iterator;
 import java.util.NoSuchElementException;
 import java.util.Queue;
+import java.util.Spliterator;
+import java.util.Spliterators;
+import java.util.function.Consumer;
 
 /**
  * An unbounded thread-safe {@linkplain Queue queue} based on linked nodes.
@@ -56,7 +59,7 @@
  * Like most other concurrent collection implementations, this class
  * does not permit the use of {@code null} elements.
  *
- * <p>This implementation employs an efficient &quot;wait-free&quot;
+ * <p>This implementation employs an efficient <em>non-blocking</em>
  * algorithm based on one described in <a
  * href="http://www.cs.rochester.edu/u/michael/PODC96.html"> Simple,
  * Fast, and Practical Non-Blocking and Blocking Concurrent Queue
@@ -295,7 +298,7 @@
     }
 
     /**
-     * Try to CAS head to p. If successful, repoint old head to itself
+     * Tries to CAS head to p. If successful, repoint old head to itself
      * as sentinel for succ(), below.
      */
     final void updateHead(Node<E> h, Node<E> p) {
@@ -792,6 +795,96 @@
         tail = t;
     }
 
+    /** A customized variant of Spliterators.IteratorSpliterator */
+    static final class CLQSpliterator<E> implements Spliterator<E> {
+        static final int MAX_BATCH = 1 << 25;  // max batch array size;
+        final ConcurrentLinkedQueue<E> queue;
+        Node<E> current;    // current node; null until initialized
+        int batch;          // batch size for splits
+        boolean exhausted;  // true when no more nodes
+        CLQSpliterator(ConcurrentLinkedQueue<E> queue) {
+            this.queue = queue;
+        }
+
+        public Spliterator<E> trySplit() {
+            Node<E> p;
+            final ConcurrentLinkedQueue<E> q = this.queue;
+            int b = batch;
+            int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
+            if (!exhausted &&
+                ((p = current) != null || (p = q.first()) != null) &&
+                p.next != null) {
+                Object[] a = new Object[n];
+                int i = 0;
+                do {
+                    if ((a[i] = p.item) != null)
+                        ++i;
+                    if (p == (p = p.next))
+                        p = q.first();
+                } while (p != null && i < n);
+                if ((current = p) == null)
+                    exhausted = true;
+                if (i > 0) {
+                    batch = i;
+                    return Spliterators.spliterator
+                        (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
+                         Spliterator.CONCURRENT);
+                }
+            }
+            return null;
+        }
+
+        public void forEachRemaining(Consumer<? super E> action) {
+            Node<E> p;
+            if (action == null) throw new NullPointerException();
+            final ConcurrentLinkedQueue<E> q = this.queue;
+            if (!exhausted &&
+                ((p = current) != null || (p = q.first()) != null)) {
+                exhausted = true;
+                do {
+                    E e = p.item;
+                    if (p == (p = p.next))
+                        p = q.first();
+                    if (e != null)
+                        action.accept(e);
+                } while (p != null);
+            }
+        }
+
+        public boolean tryAdvance(Consumer<? super E> action) {
+            Node<E> p;
+            if (action == null) throw new NullPointerException();
+            final ConcurrentLinkedQueue<E> q = this.queue;
+            if (!exhausted &&
+                ((p = current) != null || (p = q.first()) != null)) {
+                E e;
+                do {
+                    e = p.item;
+                    if (p == (p = p.next))
+                        p = q.first();
+                } while (e == null && p != null);
+                if ((current = p) == null)
+                    exhausted = true;
+                if (e != null) {
+                    action.accept(e);
+                    return true;
+                }
+            }
+            return false;
+        }
+
+        public long estimateSize() { return Long.MAX_VALUE; }
+
+        public int characteristics() {
+            return Spliterator.ORDERED | Spliterator.NONNULL |
+                Spliterator.CONCURRENT;
+        }
+    }
+
+    public Spliterator<E> spliterator() {
+        return new CLQSpliterator<E>(this);
+    }
+
     /**
      * Throws NullPointerException if argument is null.
      *
--- a/src/share/classes/java/util/concurrent/ConcurrentMap.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/ConcurrentMap.java	Mon Jul 22 17:37:15 2013 -0700
@@ -39,8 +39,8 @@
 import java.util.function.BiFunction;
 
 /**
- * A {@link java.util.Map} providing additional atomic
- * {@code putIfAbsent}, {@code remove}, and {@code replace} methods.
+ * A {@link java.util.Map} providing thread safety and atomicity
+ * guarantees.
  *
  * <p>Memory consistency effects: As with other concurrent
  * collections, actions in a thread prior to placing an object into a
@@ -89,11 +89,11 @@
      * @param key key with which the specified value is to be associated
      * @param value value to be associated with the specified key
      * @return the previous value associated with the specified key, or
-     *         <tt>null</tt> if there was no mapping for the key.
-     *         (A <tt>null</tt> return can also indicate that the map
-     *         previously associated <tt>null</tt> with the key,
+     *         {@code null} if there was no mapping for the key.
+     *         (A {@code null} return can also indicate that the map
+     *         previously associated {@code null} with the key,
      *         if the implementation supports null values.)
-     * @throws UnsupportedOperationException if the <tt>put</tt> operation
+     * @throws UnsupportedOperationException if the {@code put} operation
      *         is not supported by this map
      * @throws ClassCastException if the class of the specified key or value
      *         prevents it from being stored in this map
--- a/src/share/classes/java/util/concurrent/ConcurrentNavigableMap.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/ConcurrentNavigableMap.java	Mon Jul 22 17:37:15 2013 -0700
@@ -101,7 +101,7 @@
      * reflected in the descending map, and vice-versa.
      *
      * <p>The returned map has an ordering equivalent to
-     * <tt>{@link Collections#reverseOrder(Comparator) Collections.reverseOrder}(comparator())</tt>.
+     * {@link Collections#reverseOrder(Comparator) Collections.reverseOrder}{@code (comparator())}.
      * The expression {@code m.descendingMap().descendingMap()} returns a
      * view of {@code m} essentially equivalent to {@code m}.
      *
--- a/src/share/classes/java/util/concurrent/ConcurrentSkipListMap.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/ConcurrentSkipListMap.java	Mon Jul 22 17:37:15 2013 -0700
@@ -34,7 +34,25 @@
  */
 
 package java.util.concurrent;
-import java.util.*;
+import java.util.AbstractCollection;
+import java.util.AbstractMap;
+import java.util.AbstractSet;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableSet;
+import java.util.NoSuchElementException;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.Spliterator;
+import java.util.function.BiFunction;
+import java.util.function.Consumer;
+import java.util.function.BiConsumer;
+import java.util.function.Function;
 
 /**
  * A scalable concurrent {@link ConcurrentNavigableMap} implementation.
@@ -45,38 +63,38 @@
  * <p>This class implements a concurrent variant of <a
  * href="http://en.wikipedia.org/wiki/Skip_list" target="_top">SkipLists</a>
  * providing expected average <i>log(n)</i> time cost for the
- * <tt>containsKey</tt>, <tt>get</tt>, <tt>put</tt> and
- * <tt>remove</tt> operations and their variants.  Insertion, removal,
+ * {@code containsKey}, {@code get}, {@code put} and
+ * {@code remove} operations and their variants.  Insertion, removal,
  * update, and access operations safely execute concurrently by
  * multiple threads.  Iterators are <i>weakly consistent</i>, returning
  * elements reflecting the state of the map at some point at or since
  * the creation of the iterator.  They do <em>not</em> throw {@link
- * ConcurrentModificationException}, and may proceed concurrently with
- * other operations. Ascending key ordered views and their iterators
- * are faster than descending ones.
+ * java.util.ConcurrentModificationException ConcurrentModificationException},
+ * and may proceed concurrently with other operations. Ascending key ordered
+ * views and their iterators are faster than descending ones.
  *
- * <p>All <tt>Map.Entry</tt> pairs returned by methods in this class
+ * <p>All {@code Map.Entry} pairs returned by methods in this class
  * and its views represent snapshots of mappings at the time they were
- * produced. They do <em>not</em> support the <tt>Entry.setValue</tt>
+ * produced. They do <em>not</em> support the {@code Entry.setValue}
  * method. (Note however that it is possible to change mappings in the
- * associated map using <tt>put</tt>, <tt>putIfAbsent</tt>, or
- * <tt>replace</tt>, depending on exactly which effect you need.)
+ * associated map using {@code put}, {@code putIfAbsent}, or
+ * {@code replace}, depending on exactly which effect you need.)
  *
- * <p>Beware that, unlike in most collections, the <tt>size</tt>
+ * <p>Beware that, unlike in most collections, the {@code size}
  * method is <em>not</em> a constant-time operation. Because of the
  * asynchronous nature of these maps, determining the current number
  * of elements requires a traversal of the elements, and so may report
  * inaccurate results if this collection is modified during traversal.
- * Additionally, the bulk operations <tt>putAll</tt>, <tt>equals</tt>,
- * <tt>toArray</tt>, <tt>containsValue</tt>, and <tt>clear</tt> are
+ * Additionally, the bulk operations {@code putAll}, {@code equals},
+ * {@code toArray}, {@code containsValue}, and {@code clear} are
  * <em>not</em> guaranteed to be performed atomically. For example, an
- * iterator operating concurrently with a <tt>putAll</tt> operation
+ * iterator operating concurrently with a {@code putAll} operation
  * might view only some of the added elements.
  *
  * <p>This class and its views and iterators implement all of the
  * <em>optional</em> methods of the {@link Map} and {@link Iterator}
  * interfaces. Like most other concurrent collections, this class does
- * <em>not</em> permit the use of <tt>null</tt> keys or values because some
+ * <em>not</em> permit the use of {@code null} keys or values because some
  * null return values cannot be reliably distinguished from the absence of
  * elements.
  *
@@ -89,7 +107,6 @@
  * @param <V> the type of mapped values
  * @since 1.6
  */
-@SuppressWarnings("unchecked")
 public class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V>
     implements ConcurrentNavigableMap<K,V>,
                Cloneable,
@@ -257,7 +274,7 @@
      *
      * Indexing uses skip list parameters that maintain good search
      * performance while using sparser-than-usual indices: The
-     * hardwired parameters k=1, p=0.5 (see method randomLevel) mean
+     * hardwired parameters k=1, p=0.5 (see method doPut) mean
      * that about one-quarter of the nodes have indices. Of those that
      * do, half have one level, a quarter have two, and so on (see
      * Pugh's Skip List Cookbook, sec 3.4).  The expected total space
@@ -295,6 +312,20 @@
      * there is a fair amount of near-duplication of code to handle
      * variants.
      *
+     * To produce random values without interference across threads,
+     * we use within-JDK thread local random support (via the
+     * "secondary seed", to avoid interference with user-level
+     * ThreadLocalRandom.)
+     *
+     * A previous version of this class wrapped non-comparable keys
+     * with their comparators to emulate Comparables when using
+     * comparators vs Comparables.  However, JVMs now appear to better
+     * handle infusing comparator-vs-comparable choice into search
+     * loops. Static method cpr(comparator, x, y) is used for all
+     * comparisons, which works well as long as the comparator
+     * argument is set up outside of loops (thus sometimes passed as
+     * an argument to internal methods) to avoid field re-reads.
+     *
      * For explanation of algorithms sharing at least a couple of
      * features with this one, see Mikhail Fomitchev's thesis
      * (http://www.cs.yorku.ca/~mikhail/), Keir Fraser's thesis
@@ -323,12 +354,6 @@
     private static final long serialVersionUID = -8627078645895051609L;
 
     /**
-     * Generates the initial random seed for the cheaper per-instance
-     * random number generators used in randomLevel.
-     */
-    private static final Random seedGenerator = new Random();
-
-    /**
      * Special value used to identify base-level header
      */
     private static final Object BASE_HEADER = new Object();
@@ -339,17 +364,12 @@
     private transient volatile HeadIndex<K,V> head;
 
     /**
-     * The comparator used to maintain order in this map, or null
-     * if using natural ordering.
+     * The comparator used to maintain order in this map, or null if
+     * using natural ordering.  (Non-private to simplify access in
+     * nested classes.)
      * @serial
      */
-    private final Comparator<? super K> comparator;
-
-    /**
-     * Seed for simple random number generator.  Not volatile since it
-     * doesn't matter too much if different threads don't see updates.
-     */
-    private transient int randomSeed;
+    final Comparator<? super K> comparator;
 
     /** Lazily initialized key set */
     private transient KeySet<K> keySet;
@@ -365,12 +385,11 @@
      * clear, readObject. and ConcurrentSkipListSet.clone.
      * (Note that comparator must be separately initialized.)
      */
-    final void initialize() {
+    private void initialize() {
         keySet = null;
         entrySet = null;
         values = null;
         descendingMap = null;
-        randomSeed = seedGenerator.nextInt() | 0x0100; // ensure nonzero
         head = new HeadIndex<K,V>(new Node<K,V>(null, BASE_HEADER, null),
                                   null, null, 1);
     }
@@ -438,7 +457,7 @@
          * because callers will have already read value field and need
          * to use that read (not another done here) and so directly
          * test if value points to node.
-         * @param n a possibly null reference to a node
+         *
          * @return true if this node is a marker node
          */
         boolean isMarker() {
@@ -477,7 +496,7 @@
              */
             if (f == next && this == b.next) {
                 if (f == null || f.value != f) // not already marked
-                    appendMarker(f);
+                    casNext(f, new Node<K,V>(f));
                 else
                     b.casNext(this, f.next);
             }
@@ -487,13 +506,14 @@
          * Returns value if this node contains a valid key-value pair,
          * else null.
          * @return this node's value if it isn't a marker or header or
-         * is deleted, else null.
+         * is deleted, else null
          */
         V getValidValue() {
             Object v = value;
             if (v == this || v == BASE_HEADER)
                 return null;
-            return (V)v;
+            @SuppressWarnings("unchecked") V vv = (V)v;
+            return vv;
         }
 
         /**
@@ -502,10 +522,11 @@
          * @return new entry or null
          */
         AbstractMap.SimpleImmutableEntry<K,V> createSnapshot() {
-            V v = getValidValue();
-            if (v == null)
+            Object v = value;
+            if (v == null || v == this || v == BASE_HEADER)
                 return null;
-            return new AbstractMap.SimpleImmutableEntry<K,V>(key, v);
+            @SuppressWarnings("unchecked") V vv = (V)v;
+            return new AbstractMap.SimpleImmutableEntry<K,V>(key, vv);
         }
 
         // UNSAFE mechanics
@@ -588,7 +609,7 @@
          * @return true if successful
          */
         final boolean unlink(Index<K,V> succ) {
-            return !indexesDeletedNode() && casRight(succ, succ.right);
+            return node.value != null && casRight(succ, succ.right);
         }
 
         // Unsafe mechanics
@@ -622,80 +643,12 @@
     /* ---------------- Comparison utilities -------------- */
 
     /**
-     * Represents a key with a comparator as a Comparable.
-     *
-     * Because most sorted collections seem to use natural ordering on
-     * Comparables (Strings, Integers, etc), most internal methods are
-     * geared to use them. This is generally faster than checking
-     * per-comparison whether to use comparator or comparable because
-     * it doesn't require a (Comparable) cast for each comparison.
-     * (Optimizers can only sometimes remove such redundant checks
-     * themselves.) When Comparators are used,
-     * ComparableUsingComparators are created so that they act in the
-     * same way as natural orderings. This penalizes use of
-     * Comparators vs Comparables, which seems like the right
-     * tradeoff.
-     */
-    static final class ComparableUsingComparator<K> implements Comparable<K> {
-        final K actualKey;
-        final Comparator<? super K> cmp;
-        ComparableUsingComparator(K key, Comparator<? super K> cmp) {
-            this.actualKey = key;
-            this.cmp = cmp;
-        }
-        public int compareTo(K k2) {
-            return cmp.compare(actualKey, k2);
-        }
-    }
-
-    /**
-     * If using comparator, return a ComparableUsingComparator, else
-     * cast key as Comparable, which may cause ClassCastException,
-     * which is propagated back to caller.
+     * Compares using comparator or natural ordering if null.
+     * Called only by methods that have performed required type checks.
      */
-    private Comparable<? super K> comparable(Object key)
-            throws ClassCastException {
-        if (key == null)
-            throw new NullPointerException();
-        if (comparator != null)
-            return new ComparableUsingComparator<K>((K)key, comparator);
-        else
-            return (Comparable<? super K>)key;
-    }
-
-    /**
-     * Compares using comparator or natural ordering. Used when the
-     * ComparableUsingComparator approach doesn't apply.
-     */
-    int compare(K k1, K k2) throws ClassCastException {
-        Comparator<? super K> cmp = comparator;
-        if (cmp != null)
-            return cmp.compare(k1, k2);
-        else
-            return ((Comparable<? super K>)k1).compareTo(k2);
-    }
-
-    /**
-     * Returns true if given key greater than or equal to least and
-     * strictly less than fence, bypassing either test if least or
-     * fence are null. Needed mainly in submap operations.
-     */
-    boolean inHalfOpenRange(K key, K least, K fence) {
-        if (key == null)
-            throw new NullPointerException();
-        return ((least == null || compare(key, least) >= 0) &&
-                (fence == null || compare(key, fence) <  0));
-    }
-
-    /**
-     * Returns true if given key greater than or equal to least and less
-     * or equal to fence. Needed mainly in submap operations.
-     */
-    boolean inOpenRange(K key, K least, K fence) {
-        if (key == null)
-            throw new NullPointerException();
-        return ((least == null || compare(key, least) >= 0) &&
-                (fence == null || compare(key, fence) <= 0));
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    static final int cpr(Comparator c, Object x, Object y) {
+        return (c != null) ? c.compare(x, y) : ((Comparable)x).compareTo(y);
     }
 
     /* ---------------- Traversal -------------- */
@@ -708,13 +661,11 @@
      * @param key the key
      * @return a predecessor of key
      */
-    private Node<K,V> findPredecessor(Comparable<? super K> key) {
+    private Node<K,V> findPredecessor(Object key, Comparator<? super K> cmp) {
         if (key == null)
             throw new NullPointerException(); // don't postpone errors
         for (;;) {
-            Index<K,V> q = head;
-            Index<K,V> r = q.right;
-            for (;;) {
+            for (Index<K,V> q = head, r = q.right, d;;) {
                 if (r != null) {
                     Node<K,V> n = r.node;
                     K k = n.key;
@@ -724,18 +675,16 @@
                         r = q.right;         // reread r
                         continue;
                     }
-                    if (key.compareTo(k) > 0) {
+                    if (cpr(cmp, key, k) > 0) {
                         q = r;
                         r = r.right;
                         continue;
                     }
                 }
-                Index<K,V> d = q.down;
-                if (d != null) {
-                    q = d;
-                    r = d.right;
-                } else
+                if ((d = q.down) == null)
                     return q.node;
+                q = d;
+                r = d.right;
             }
         }
     }
@@ -784,54 +733,71 @@
      * @param key the key
      * @return node holding key, or null if no such
      */
-    private Node<K,V> findNode(Comparable<? super K> key) {
-        for (;;) {
-            Node<K,V> b = findPredecessor(key);
-            Node<K,V> n = b.next;
-            for (;;) {
+    private Node<K,V> findNode(Object key) {
+        if (key == null)
+            throw new NullPointerException(); // don't postpone errors
+        Comparator<? super K> cmp = comparator;
+        outer: for (;;) {
+            for (Node<K,V> b = findPredecessor(key, cmp), n = b.next;;) {
+                Object v; int c;
                 if (n == null)
-                    return null;
+                    break outer;
                 Node<K,V> f = n.next;
                 if (n != b.next)                // inconsistent read
                     break;
-                Object v = n.value;
-                if (v == null) {                // n is deleted
+                if ((v = n.value) == null) {    // n is deleted
                     n.helpDelete(b, f);
                     break;
                 }
-                if (v == n || b.value == null)  // b is deleted
+                if (b.value == null || v == n)  // b is deleted
                     break;
-                int c = key.compareTo(n.key);
-                if (c == 0)
+                if ((c = cpr(cmp, key, n.key)) == 0)
                     return n;
                 if (c < 0)
-                    return null;
+                    break outer;
                 b = n;
                 n = f;
             }
         }
+        return null;
     }
 
     /**
-     * Gets value for key using findNode.
-     * @param okey the key
+     * Gets value for key. Almost the same as findNode, but returns
+     * the found value (to avoid retries during re-reads)
+     *
+     * @param key the key
      * @return the value, or null if absent
      */
-    private V doGet(Object okey) {
-        Comparable<? super K> key = comparable(okey);
-        /*
-         * Loop needed here and elsewhere in case value field goes
-         * null just as it is about to be returned, in which case we
-         * lost a race with a deletion, so must retry.
-         */
-        for (;;) {
-            Node<K,V> n = findNode(key);
-            if (n == null)
-                return null;
-            Object v = n.value;
-            if (v != null)
-                return (V)v;
+    private V doGet(Object key) {
+        if (key == null)
+            throw new NullPointerException();
+        Comparator<? super K> cmp = comparator;
+        outer: for (;;) {
+            for (Node<K,V> b = findPredecessor(key, cmp), n = b.next;;) {
+                Object v; int c;
+                if (n == null)
+                    break outer;
+                Node<K,V> f = n.next;
+                if (n != b.next)                // inconsistent read
+                    break;
+                if ((v = n.value) == null) {    // n is deleted
+                    n.helpDelete(b, f);
+                    break;
+                }
+                if (b.value == null || v == n)  // b is deleted
+                    break;
+                if ((c = cpr(cmp, key, n.key)) == 0) {
+                    @SuppressWarnings("unchecked") V vv = (V)v;
+                    return vv;
+                }
+                if (c < 0)
+                    break outer;
+                b = n;
+                n = f;
+            }
         }
+        return null;
     }
 
     /* ---------------- Insertion -------------- */
@@ -839,187 +805,126 @@
     /**
      * Main insertion method.  Adds element if not present, or
      * replaces value if present and onlyIfAbsent is false.
-     * @param kkey the key
-     * @param value  the value that must be associated with key
+     * @param key the key
+     * @param value the value that must be associated with key
      * @param onlyIfAbsent if should not insert if already present
      * @return the old value, or null if newly inserted
      */
-    private V doPut(K kkey, V value, boolean onlyIfAbsent) {
-        Comparable<? super K> key = comparable(kkey);
-        for (;;) {
-            Node<K,V> b = findPredecessor(key);
-            Node<K,V> n = b.next;
-            for (;;) {
+    private V doPut(K key, V value, boolean onlyIfAbsent) {
+        Node<K,V> z;             // added node
+        if (key == null)
+            throw new NullPointerException();
+        Comparator<? super K> cmp = comparator;
+        outer: for (;;) {
+            for (Node<K,V> b = findPredecessor(key, cmp), n = b.next;;) {
                 if (n != null) {
+                    Object v; int c;
                     Node<K,V> f = n.next;
                     if (n != b.next)               // inconsistent read
                         break;
-                    Object v = n.value;
-                    if (v == null) {               // n is deleted
+                    if ((v = n.value) == null) {   // n is deleted
                         n.helpDelete(b, f);
                         break;
                     }
-                    if (v == n || b.value == null) // b is deleted
+                    if (b.value == null || v == n) // b is deleted
                         break;
-                    int c = key.compareTo(n.key);
-                    if (c > 0) {
+                    if ((c = cpr(cmp, key, n.key)) > 0) {
                         b = n;
                         n = f;
                         continue;
                     }
                     if (c == 0) {
-                        if (onlyIfAbsent || n.casValue(v, value))
-                            return (V)v;
-                        else
-                            break; // restart if lost race to replace value
+                        if (onlyIfAbsent || n.casValue(v, value)) {
+                            @SuppressWarnings("unchecked") V vv = (V)v;
+                            return vv;
+                        }
+                        break; // restart if lost race to replace value
                     }
                     // else c < 0; fall through
                 }
 
-                Node<K,V> z = new Node<K,V>(kkey, value, n);
+                z = new Node<K,V>(key, value, n);
                 if (!b.casNext(n, z))
                     break;         // restart if lost race to append to b
-                int level = randomLevel();
-                if (level > 0)
-                    insertIndex(z, level);
-                return null;
+                break outer;
             }
         }
-    }
 
-    /**
-     * Returns a random level for inserting a new node.
-     * Hardwired to k=1, p=0.5, max 31 (see above and
-     * Pugh's "Skip List Cookbook", sec 3.4).
-     *
-     * This uses the simplest of the generators described in George
-     * Marsaglia's "Xorshift RNGs" paper.  This is not a high-quality
-     * generator but is acceptable here.
-     */
-    private int randomLevel() {
-        int x = randomSeed;
-        x ^= x << 13;
-        x ^= x >>> 17;
-        randomSeed = x ^= x << 5;
-        if ((x & 0x80000001) != 0) // test highest and lowest bits
-            return 0;
-        int level = 1;
-        while (((x >>>= 1) & 1) != 0) ++level;
-        return level;
-    }
-
-    /**
-     * Creates and adds index nodes for the given node.
-     * @param z the node
-     * @param level the level of the index
-     */
-    private void insertIndex(Node<K,V> z, int level) {
-        HeadIndex<K,V> h = head;
-        int max = h.level;
-
-        if (level <= max) {
+        int rnd = ThreadLocalRandom.nextSecondarySeed();
+        if ((rnd & 0x80000001) == 0) { // test highest and lowest bits
+            int level = 1, max;
+            while (((rnd >>>= 1) & 1) != 0)
+                ++level;
             Index<K,V> idx = null;
-            for (int i = 1; i <= level; ++i)
-                idx = new Index<K,V>(z, idx, null);
-            addIndex(idx, h, level);
-
-        } else { // Add a new level
-            /*
-             * To reduce interference by other threads checking for
-             * empty levels in tryReduceLevel, new levels are added
-             * with initialized right pointers. Which in turn requires
-             * keeping levels in an array to access them while
-             * creating new head index nodes from the opposite
-             * direction.
-             */
-            level = max + 1;
-            Index<K,V>[] idxs = (Index<K,V>[])new Index<?,?>[level+1];
-            Index<K,V> idx = null;
-            for (int i = 1; i <= level; ++i)
-                idxs[i] = idx = new Index<K,V>(z, idx, null);
-
-            HeadIndex<K,V> oldh;
-            int k;
-            for (;;) {
-                oldh = head;
-                int oldLevel = oldh.level;
-                if (level <= oldLevel) { // lost race to add level
-                    k = level;
-                    break;
-                }
-                HeadIndex<K,V> newh = oldh;
-                Node<K,V> oldbase = oldh.node;
-                for (int j = oldLevel+1; j <= level; ++j)
-                    newh = new HeadIndex<K,V>(oldbase, newh, idxs[j], j);
-                if (casHead(oldh, newh)) {
-                    k = oldLevel;
-                    break;
+            HeadIndex<K,V> h = head;
+            if (level <= (max = h.level)) {
+                for (int i = 1; i <= level; ++i)
+                    idx = new Index<K,V>(z, idx, null);
+            }
+            else { // try to grow by one level
+                level = max + 1; // hold in array and later pick the one to use
+                @SuppressWarnings("unchecked")Index<K,V>[] idxs =
+                    (Index<K,V>[])new Index<?,?>[level+1];
+                for (int i = 1; i <= level; ++i)
+                    idxs[i] = idx = new Index<K,V>(z, idx, null);
+                for (;;) {
+                    h = head;
+                    int oldLevel = h.level;
+                    if (level <= oldLevel) // lost race to add level
+                        break;
+                    HeadIndex<K,V> newh = h;
+                    Node<K,V> oldbase = h.node;
+                    for (int j = oldLevel+1; j <= level; ++j)
+                        newh = new HeadIndex<K,V>(oldbase, newh, idxs[j], j);
+                    if (casHead(h, newh)) {
+                        h = newh;
+                        idx = idxs[level = oldLevel];
+                        break;
+                    }
                 }
             }
-            addIndex(idxs[k], oldh, k);
-        }
-    }
-
-    /**
-     * Adds given index nodes from given level down to 1.
-     * @param idx the topmost index node being inserted
-     * @param h the value of head to use to insert. This must be
-     * snapshotted by callers to provide correct insertion level
-     * @param indexLevel the level of the index
-     */
-    private void addIndex(Index<K,V> idx, HeadIndex<K,V> h, int indexLevel) {
-        // Track next level to insert in case of retries
-        int insertionLevel = indexLevel;
-        Comparable<? super K> key = comparable(idx.node.key);
-        if (key == null) throw new NullPointerException();
+            // find insertion points and splice in
+            splice: for (int insertionLevel = level;;) {
+                int j = h.level;
+                for (Index<K,V> q = h, r = q.right, t = idx;;) {
+                    if (q == null || t == null)
+                        break splice;
+                    if (r != null) {
+                        Node<K,V> n = r.node;
+                        // compare before deletion check avoids needing recheck
+                        int c = cpr(cmp, key, n.key);
+                        if (n.value == null) {
+                            if (!q.unlink(r))
+                                break;
+                            r = q.right;
+                            continue;
+                        }
+                        if (c > 0) {
+                            q = r;
+                            r = r.right;
+                            continue;
+                        }
+                    }
 
-        // Similar to findPredecessor, but adding index nodes along
-        // path to key.
-        for (;;) {
-            int j = h.level;
-            Index<K,V> q = h;
-            Index<K,V> r = q.right;
-            Index<K,V> t = idx;
-            for (;;) {
-                if (r != null) {
-                    Node<K,V> n = r.node;
-                    // compare before deletion check avoids needing recheck
-                    int c = key.compareTo(n.key);
-                    if (n.value == null) {
-                        if (!q.unlink(r))
-                            break;
-                        r = q.right;
-                        continue;
-                    }
-                    if (c > 0) {
-                        q = r;
-                        r = r.right;
-                        continue;
+                    if (j == insertionLevel) {
+                        if (!q.link(r, t))
+                            break; // restart
+                        if (t.node.value == null) {
+                            findNode(key);
+                            break splice;
+                        }
+                        if (--insertionLevel == 0)
+                            break splice;
                     }
+
+                    if (--j >= insertionLevel && j < level)
+                        t = t.down;
+                    q = q.down;
+                    r = q.right;
                 }
-
-                if (j == insertionLevel) {
-                    // Don't insert index if node already deleted
-                    if (t.indexesDeletedNode()) {
-                        findNode(key); // cleans up
-                        return;
-                    }
-                    if (!q.link(r, t))
-                        break; // restart
-                    if (--insertionLevel == 0) {
-                        // need final deletion check before return
-                        if (t.indexesDeletedNode())
-                            findNode(key);
-                        return;
-                    }
-                }
-
-                if (--j >= insertionLevel && j < indexLevel)
-                    t = t.down;
-                q = q.down;
-                r = q.right;
             }
         }
+        return null;
     }
 
     /* ---------------- Deletion -------------- */
@@ -1038,51 +943,52 @@
      * search for it, and we'd like to ensure lack of garbage
      * retention, so must call to be sure.
      *
-     * @param okey the key
+     * @param key the key
      * @param value if non-null, the value that must be
      * associated with key
      * @return the node, or null if not found
      */
-    final V doRemove(Object okey, Object value) {
-        Comparable<? super K> key = comparable(okey);
-        for (;;) {
-            Node<K,V> b = findPredecessor(key);
-            Node<K,V> n = b.next;
-            for (;;) {
+    final V doRemove(Object key, Object value) {
+        if (key == null)
+            throw new NullPointerException();
+        Comparator<? super K> cmp = comparator;
+        outer: for (;;) {
+            for (Node<K,V> b = findPredecessor(key, cmp), n = b.next;;) {
+                Object v; int c;
                 if (n == null)
-                    return null;
+                    break outer;
                 Node<K,V> f = n.next;
                 if (n != b.next)                    // inconsistent read
                     break;
-                Object v = n.value;
-                if (v == null) {                    // n is deleted
+                if ((v = n.value) == null) {        // n is deleted
                     n.helpDelete(b, f);
                     break;
                 }
-                if (v == n || b.value == null)      // b is deleted
+                if (b.value == null || v == n)      // b is deleted
                     break;
-                int c = key.compareTo(n.key);
-                if (c < 0)
-                    return null;
+                if ((c = cpr(cmp, key, n.key)) < 0)
+                    break outer;
                 if (c > 0) {
                     b = n;
                     n = f;
                     continue;
                 }
                 if (value != null && !value.equals(v))
-                    return null;
+                    break outer;
                 if (!n.casValue(v, null))
                     break;
                 if (!n.appendMarker(f) || !b.casNext(n, f))
-                    findNode(key);                  // Retry via findNode
+                    findNode(key);                  // retry via findNode
                 else {
-                    findPredecessor(key);           // Clean index
+                    findPredecessor(key, cmp);      // clean index
                     if (head.right == null)
                         tryReduceLevel();
                 }
-                return (V)v;
+                @SuppressWarnings("unchecked") V vv = (V)v;
+                return vv;
             }
         }
+        return null;
     }
 
     /**
@@ -1126,11 +1032,9 @@
      * Specialized variant of findNode to get first valid node.
      * @return first node or null if empty
      */
-    Node<K,V> findFirst() {
-        for (;;) {
-            Node<K,V> b = head.node;
-            Node<K,V> n = b.next;
-            if (n == null)
+    final Node<K,V> findFirst() {
+        for (Node<K,V> b, n;;) {
+            if ((n = (b = head.node).next) == null)
                 return null;
             if (n.value != null)
                 return n;
@@ -1142,11 +1046,9 @@
      * Removes first entry; returns its snapshot.
      * @return null if empty, else snapshot of first entry
      */
-    Map.Entry<K,V> doRemoveFirstEntry() {
-        for (;;) {
-            Node<K,V> b = head.node;
-            Node<K,V> n = b.next;
-            if (n == null)
+    private Map.Entry<K,V> doRemoveFirstEntry() {
+        for (Node<K,V> b, n;;) {
+            if ((n = (b = head.node).next) == null)
                 return null;
             Node<K,V> f = n.next;
             if (n != b.next)
@@ -1161,7 +1063,8 @@
             if (!n.appendMarker(f) || !b.casNext(n, f))
                 findFirst(); // retry
             clearIndexToFirst();
-            return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, (V)v);
+            @SuppressWarnings("unchecked") V vv = (V)v;
+            return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, vv);
         }
     }
 
@@ -1170,8 +1073,7 @@
      */
     private void clearIndexToFirst() {
         for (;;) {
-            Index<K,V> q = head;
-            for (;;) {
+            for (Index<K,V> q = head;;) {
                 Index<K,V> r = q.right;
                 if (r != null && r.indexesDeletedNode() && !q.unlink(r))
                     break;
@@ -1184,6 +1086,52 @@
         }
     }
 
+    /**
+     * Removes last entry; returns its snapshot.
+     * Specialized variant of doRemove.
+     * @return null if empty, else snapshot of last entry
+     */
+    private Map.Entry<K,V> doRemoveLastEntry() {
+        for (;;) {
+            Node<K,V> b = findPredecessorOfLast();
+            Node<K,V> n = b.next;
+            if (n == null) {
+                if (b.isBaseHeader())               // empty
+                    return null;
+                else
+                    continue; // all b's successors are deleted; retry
+            }
+            for (;;) {
+                Node<K,V> f = n.next;
+                if (n != b.next)                    // inconsistent read
+                    break;
+                Object v = n.value;
+                if (v == null) {                    // n is deleted
+                    n.helpDelete(b, f);
+                    break;
+                }
+                if (b.value == null || v == n)      // b is deleted
+                    break;
+                if (f != null) {
+                    b = n;
+                    n = f;
+                    continue;
+                }
+                if (!n.casValue(v, null))
+                    break;
+                K key = n.key;
+                if (!n.appendMarker(f) || !b.casNext(n, f))
+                    findNode(key);                  // retry via findNode
+                else {                              // clean index
+                    findPredecessor(key, comparator);
+                    if (head.right == null)
+                        tryReduceLevel();
+                }
+                @SuppressWarnings("unchecked") V vv = (V)v;
+                return new AbstractMap.SimpleImmutableEntry<K,V>(key, vv);
+            }
+        }
+    }
 
     /* ---------------- Finding and removing last element -------------- */
 
@@ -1191,7 +1139,7 @@
      * Specialized version of find to get last valid node.
      * @return last node or null if empty
      */
-    Node<K,V> findLast() {
+    final Node<K,V> findLast() {
         /*
          * findPredecessor can't be used to traverse index level
          * because this doesn't use comparisons.  So traversals of
@@ -1210,9 +1158,7 @@
             } else if ((d = q.down) != null) {
                 q = d;
             } else {
-                Node<K,V> b = q.node;
-                Node<K,V> n = b.next;
-                for (;;) {
+                for (Node<K,V> b = q.node, n = b.next;;) {
                     if (n == null)
                         return b.isBaseHeader() ? null : b;
                     Node<K,V> f = n.next;            // inconsistent read
@@ -1223,7 +1169,7 @@
                         n.helpDelete(b, f);
                         break;
                     }
-                    if (v == n || b.value == null)   // b is deleted
+                    if (b.value == null || v == n)      // b is deleted
                         break;
                     b = n;
                     n = f;
@@ -1242,8 +1188,7 @@
      */
     private Node<K,V> findPredecessorOfLast() {
         for (;;) {
-            Index<K,V> q = head;
-            for (;;) {
+            for (Index<K,V> q = head;;) {
                 Index<K,V> d, r;
                 if ((r = q.right) != null) {
                     if (r.indexesDeletedNode()) {
@@ -1264,53 +1209,6 @@
         }
     }
 
-    /**
-     * Removes last entry; returns its snapshot.
-     * Specialized variant of doRemove.
-     * @return null if empty, else snapshot of last entry
-     */
-    Map.Entry<K,V> doRemoveLastEntry() {
-        for (;;) {
-            Node<K,V> b = findPredecessorOfLast();
-            Node<K,V> n = b.next;
-            if (n == null) {
-                if (b.isBaseHeader())               // empty
-                    return null;
-                else
-                    continue; // all b's successors are deleted; retry
-            }
-            for (;;) {
-                Node<K,V> f = n.next;
-                if (n != b.next)                    // inconsistent read
-                    break;
-                Object v = n.value;
-                if (v == null) {                    // n is deleted
-                    n.helpDelete(b, f);
-                    break;
-                }
-                if (v == n || b.value == null)      // b is deleted
-                    break;
-                if (f != null) {
-                    b = n;
-                    n = f;
-                    continue;
-                }
-                if (!n.casValue(v, null))
-                    break;
-                K key = n.key;
-                Comparable<? super K> ck = comparable(key);
-                if (!n.appendMarker(f) || !b.casNext(n, f))
-                    findNode(ck);                  // Retry via findNode
-                else {
-                    findPredecessor(ck);           // Clean index
-                    if (head.right == null)
-                        tryReduceLevel();
-                }
-                return new AbstractMap.SimpleImmutableEntry<K,V>(key, (V)v);
-            }
-        }
-    }
-
     /* ---------------- Relational operations -------------- */
 
     // Control values OR'ed as arguments to findNear
@@ -1321,29 +1219,28 @@
 
     /**
      * Utility for ceiling, floor, lower, higher methods.
-     * @param kkey the key
+     * @param key the key
      * @param rel the relation -- OR'ed combination of EQ, LT, GT
      * @return nearest node fitting relation, or null if no such
      */
-    Node<K,V> findNear(K kkey, int rel) {
-        Comparable<? super K> key = comparable(kkey);
+    final Node<K,V> findNear(K key, int rel, Comparator<? super K> cmp) {
+        if (key == null)
+            throw new NullPointerException();
         for (;;) {
-            Node<K,V> b = findPredecessor(key);
-            Node<K,V> n = b.next;
-            for (;;) {
+            for (Node<K,V> b = findPredecessor(key, cmp), n = b.next;;) {
+                Object v;
                 if (n == null)
                     return ((rel & LT) == 0 || b.isBaseHeader()) ? null : b;
                 Node<K,V> f = n.next;
                 if (n != b.next)                  // inconsistent read
                     break;
-                Object v = n.value;
-                if (v == null) {                  // n is deleted
+                if ((v = n.value) == null) {      // n is deleted
                     n.helpDelete(b, f);
                     break;
                 }
-                if (v == n || b.value == null)    // b is deleted
+                if (b.value == null || v == n)      // b is deleted
                     break;
-                int c = key.compareTo(n.key);
+                int c = cpr(cmp, key, n.key);
                 if ((c == 0 && (rel & EQ) != 0) ||
                     (c <  0 && (rel & LT) == 0))
                     return n;
@@ -1361,9 +1258,10 @@
      * @param rel the relation -- OR'ed combination of EQ, LT, GT
      * @return Entry fitting relation, or null if no such
      */
-    AbstractMap.SimpleImmutableEntry<K,V> getNear(K key, int rel) {
+    final AbstractMap.SimpleImmutableEntry<K,V> getNear(K key, int rel) {
+        Comparator<? super K> cmp = comparator;
         for (;;) {
-            Node<K,V> n = findNear(key, rel);
+            Node<K,V> n = findNear(key, rel, cmp);
             if (n == null)
                 return null;
             AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
@@ -1372,7 +1270,6 @@
         }
     }
 
-
     /* ---------------- Constructors -------------- */
 
     /**
@@ -1389,7 +1286,7 @@
      * comparator.
      *
      * @param comparator the comparator that will be used to order this map.
-     *        If <tt>null</tt>, the {@linkplain Comparable natural
+     *        If {@code null}, the {@linkplain Comparable natural
      *        ordering} of the keys will be used.
      */
     public ConcurrentSkipListMap(Comparator<? super K> comparator) {
@@ -1403,7 +1300,7 @@
      * the keys.
      *
      * @param  m the map whose mappings are to be placed in this map
-     * @throws ClassCastException if the keys in <tt>m</tt> are not
+     * @throws ClassCastException if the keys in {@code m} are not
      *         {@link Comparable}, or are not mutually comparable
      * @throws NullPointerException if the specified map or any of its keys
      *         or values are null
@@ -1430,7 +1327,7 @@
     }
 
     /**
-     * Returns a shallow copy of this <tt>ConcurrentSkipListMap</tt>
+     * Returns a shallow copy of this {@code ConcurrentSkipListMap}
      * instance. (The keys and values themselves are not cloned.)
      *
      * @return a shallow copy of this map
@@ -1477,8 +1374,14 @@
             map.entrySet().iterator();
         while (it.hasNext()) {
             Map.Entry<? extends K, ? extends V> e = it.next();
-            int j = randomLevel();
-            if (j > h.level) j = h.level + 1;
+            int rnd = ThreadLocalRandom.current().nextInt();
+            int j = 0;
+            if ((rnd & 0x80000001) == 0) {
+                do {
+                    ++j;
+                } while (((rnd >>>= 1) & 1) != 0);
+                if (j > h.level) j = h.level + 1;
+            }
             K k = e.getKey();
             V v = e.getValue();
             if (k == null || v == null)
@@ -1511,7 +1414,7 @@
      *
      * @serialData The key (Object) and value (Object) for each
      * key-value mapping represented by the map, followed by
-     * <tt>null</tt>. The key-value mappings are emitted in key-order
+     * {@code null}. The key-value mappings are emitted in key-order
      * (as determined by the Comparator, or by the keys' natural
      * ordering if no Comparator).
      */
@@ -1534,6 +1437,7 @@
     /**
      * Reconstitutes this map from a stream (that is, deserializes it).
      */
+    @SuppressWarnings("unchecked")
     private void readObject(final java.io.ObjectInputStream s)
         throws java.io.IOException, ClassNotFoundException {
         // Read in the Comparator and any hidden stuff
@@ -1569,8 +1473,14 @@
                 throw new NullPointerException();
             K key = (K) k;
             V val = (V) v;
-            int j = randomLevel();
-            if (j > h.level) j = h.level + 1;
+            int rnd = ThreadLocalRandom.current().nextInt();
+            int j = 0;
+            if ((rnd & 0x80000001) == 0) {
+                do {
+                    ++j;
+                } while (((rnd >>>= 1) & 1) != 0);
+                if (j > h.level) j = h.level + 1;
+            }
             Node<K,V> z = new Node<K,V>(key, val, null);
             basepred.next = z;
             basepred = z;
@@ -1595,11 +1505,11 @@
     /* ------ Map API methods ------ */
 
     /**
-     * Returns <tt>true</tt> if this map contains a mapping for the specified
+     * Returns {@code true} if this map contains a mapping for the specified
      * key.
      *
      * @param key key whose presence in this map is to be tested
-     * @return <tt>true</tt> if this map contains a mapping for the specified key
+     * @return {@code true} if this map contains a mapping for the specified key
      * @throws ClassCastException if the specified key cannot be compared
      *         with the keys currently in the map
      * @throws NullPointerException if the specified key is null
@@ -1627,6 +1537,22 @@
     }
 
     /**
+     * Returns the value to which the specified key is mapped,
+     * or the given defaultValue if this map contains no mapping for the key.
+     *
+     * @param key the key
+     * @param defaultValue the value to return if this map contains
+     * no mapping for the given key
+     * @return the mapping for the key, if present; else the defaultValue
+     * @throws NullPointerException if the specified key is null
+     * @since 1.8
+     */
+    public V getOrDefault(Object key, V defaultValue) {
+        V v;
+        return (v = doGet(key)) == null ? defaultValue : v;
+    }
+
+    /**
      * Associates the specified value with the specified key in this map.
      * If the map previously contained a mapping for the key, the old
      * value is replaced.
@@ -1634,7 +1560,7 @@
      * @param key key with which the specified value is to be associated
      * @param value value to be associated with the specified key
      * @return the previous value associated with the specified key, or
-     *         <tt>null</tt> if there was no mapping for the key
+     *         {@code null} if there was no mapping for the key
      * @throws ClassCastException if the specified key cannot be compared
      *         with the keys currently in the map
      * @throws NullPointerException if the specified key or value is null
@@ -1650,7 +1576,7 @@
      *
      * @param  key key for which mapping should be removed
      * @return the previous value associated with the specified key, or
-     *         <tt>null</tt> if there was no mapping for the key
+     *         {@code null} if there was no mapping for the key
      * @throws ClassCastException if the specified key cannot be compared
      *         with the keys currently in the map
      * @throws NullPointerException if the specified key is null
@@ -1660,15 +1586,15 @@
     }
 
     /**
-     * Returns <tt>true</tt> if this map maps one or more keys to the
+     * Returns {@code true} if this map maps one or more keys to the
      * specified value.  This operation requires time linear in the
      * map size. Additionally, it is possible for the map to change
      * during execution of this method, in which case the returned
      * result may be inaccurate.
      *
      * @param value value whose presence in this map is to be tested
-     * @return <tt>true</tt> if a mapping to <tt>value</tt> exists;
-     *         <tt>false</tt> otherwise
+     * @return {@code true} if a mapping to {@code value} exists;
+     *         {@code false} otherwise
      * @throws NullPointerException if the specified value is null
      */
     public boolean containsValue(Object value) {
@@ -1684,8 +1610,8 @@
 
     /**
      * Returns the number of key-value mappings in this map.  If this map
-     * contains more than <tt>Integer.MAX_VALUE</tt> elements, it
-     * returns <tt>Integer.MAX_VALUE</tt>.
+     * contains more than {@code Integer.MAX_VALUE} elements, it
+     * returns {@code Integer.MAX_VALUE}.
      *
      * <p>Beware that, unlike in most collections, this method is
      * <em>NOT</em> a constant-time operation. Because of the
@@ -1708,8 +1634,8 @@
     }
 
     /**
-     * Returns <tt>true</tt> if this map contains no key-value mappings.
-     * @return <tt>true</tt> if this map contains no key-value mappings
+     * Returns {@code true} if this map contains no key-value mappings.
+     * @return {@code true} if this map contains no key-value mappings
      */
     public boolean isEmpty() {
         return findFirst() == null;
@@ -1722,6 +1648,140 @@
         initialize();
     }
 
+    /**
+     * If the specified key is not already associated with a value,
+     * attempts to compute its value using the given mapping function
+     * and enters it into this map unless {@code null}.  The function
+     * is <em>NOT</em> guaranteed to be applied once atomically only
+     * if the value is not present.
+     *
+     * @param key key with which the specified value is to be associated
+     * @param mappingFunction the function to compute a value
+     * @return the current (existing or computed) value associated with
+     *         the specified key, or null if the computed value is null
+     * @throws NullPointerException if the specified key is null
+     *         or the mappingFunction is null
+     * @since 1.8
+     */
+    public V computeIfAbsent(K key,
+                             Function<? super K, ? extends V> mappingFunction) {
+        if (key == null || mappingFunction == null)
+            throw new NullPointerException();
+        V v, p, r;
+        if ((v = doGet(key)) == null &&
+            (r = mappingFunction.apply(key)) != null)
+            v = (p = doPut(key, r, true)) == null ? r : p;
+        return v;
+    }
+
+    /**
+     * If the value for the specified key is present, attempts to
+     * compute a new mapping given the key and its current mapped
+     * value. The function is <em>NOT</em> guaranteed to be applied
+     * once atomically.
+     *
+     * @param key key with which a value may be associated
+     * @param remappingFunction the function to compute a value
+     * @return the new value associated with the specified key, or null if none
+     * @throws NullPointerException if the specified key is null
+     *         or the remappingFunction is null
+     * @since 1.8
+     */
+    public V computeIfPresent(K key,
+                              BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
+        if (key == null || remappingFunction == null)
+            throw new NullPointerException();
+        Node<K,V> n; Object v;
+        while ((n = findNode(key)) != null) {
+            if ((v = n.value) != null) {
+                @SuppressWarnings("unchecked") V vv = (V) v;
+                V r = remappingFunction.apply(key, vv);
+                if (r != null) {
+                    if (n.casValue(vv, r))
+                        return r;
+                }
+                else if (doRemove(key, vv) != null)
+                    break;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Attempts to compute a mapping for the specified key and its
+     * current mapped value (or {@code null} if there is no current
+     * mapping). The function is <em>NOT</em> guaranteed to be applied
+     * once atomically.
+     *
+     * @param key key with which the specified value is to be associated
+     * @param remappingFunction the function to compute a value
+     * @return the new value associated with the specified key, or null if none
+     * @throws NullPointerException if the specified key is null
+     *         or the remappingFunction is null
+     * @since 1.8
+     */
+    public V compute(K key,
+                     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
+        if (key == null || remappingFunction == null)
+            throw new NullPointerException();
+        for (;;) {
+            Node<K,V> n; Object v; V r;
+            if ((n = findNode(key)) == null) {
+                if ((r = remappingFunction.apply(key, null)) == null)
+                    break;
+                if (doPut(key, r, true) == null)
+                    return r;
+            }
+            else if ((v = n.value) != null) {
+                @SuppressWarnings("unchecked") V vv = (V) v;
+                if ((r = remappingFunction.apply(key, vv)) != null) {
+                    if (n.casValue(vv, r))
+                        return r;
+                }
+                else if (doRemove(key, vv) != null)
+                    break;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * If the specified key is not already associated with a value,
+     * associates it with the given value.  Otherwise, replaces the
+     * value with the results of the given remapping function, or
+     * removes if {@code null}. The function is <em>NOT</em>
+     * guaranteed to be applied once atomically.
+     *
+     * @param key key with which the specified value is to be associated
+     * @param value the value to use if absent
+     * @param remappingFunction the function to recompute a value if present
+     * @return the new value associated with the specified key, or null if none
+     * @throws NullPointerException if the specified key or value is null
+     *         or the remappingFunction is null
+     * @since 1.8
+     */
+    public V merge(K key, V value,
+                   BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
+        if (key == null || value == null || remappingFunction == null)
+            throw new NullPointerException();
+        for (;;) {
+            Node<K,V> n; Object v; V r;
+            if ((n = findNode(key)) == null) {
+                if (doPut(key, value, true) == null)
+                    return value;
+            }
+            else if ((v = n.value) != null) {
+                @SuppressWarnings("unchecked") V vv = (V) v;
+                if ((r = remappingFunction.apply(vv, value)) != null) {
+                    if (n.casValue(vv, r))
+                        return r;
+                }
+                else if (doRemove(key, vv) != null)
+                    return null;
+            }
+        }
+    }
+
     /* ---------------- View methods -------------- */
 
     /*
@@ -1744,11 +1804,11 @@
      * operations.  It does not support the {@code add} or {@code addAll}
      * operations.
      *
-     * <p>The view's {@code iterator} is a "weakly consistent" iterator
-     * that will never throw {@link ConcurrentModificationException},
-     * and guarantees to traverse elements as they existed upon
-     * construction of the iterator, and may (but is not guaranteed to)
-     * reflect any modifications subsequent to construction.
+     * <p>The view's {@code iterator} is a "weakly consistent" iterator that
+     * will never throw {@link java.util.ConcurrentModificationException
+     * ConcurrentModificationException}, and guarantees to traverse elements
+     * as they existed upon construction of the iterator, and may (but is not
+     * guaranteed to) reflect any modifications subsequent to construction.
      *
      * <p>This method is equivalent to method {@code navigableKeySet}.
      *
@@ -1771,16 +1831,16 @@
      * The collection is backed by the map, so changes to the map are
      * reflected in the collection, and vice-versa.  The collection
      * supports element removal, which removes the corresponding
-     * mapping from the map, via the <tt>Iterator.remove</tt>,
-     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
-     * <tt>retainAll</tt> and <tt>clear</tt> operations.  It does not
-     * support the <tt>add</tt> or <tt>addAll</tt> operations.
+     * mapping from the map, via the {@code Iterator.remove},
+     * {@code Collection.remove}, {@code removeAll},
+     * {@code retainAll} and {@code clear} operations.  It does not
+     * support the {@code add} or {@code addAll} operations.
      *
-     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
-     * that will never throw {@link ConcurrentModificationException},
-     * and guarantees to traverse elements as they existed upon
-     * construction of the iterator, and may (but is not guaranteed to)
-     * reflect any modifications subsequent to construction.
+     * <p>The view's {@code iterator} is a "weakly consistent" iterator that
+     * will never throw {@link java.util.ConcurrentModificationException
+     * ConcurrentModificationException}, and guarantees to traverse elements
+     * as they existed upon construction of the iterator, and may (but is not
+     * guaranteed to) reflect any modifications subsequent to construction.
      */
     public Collection<V> values() {
         Values<V> vs = values;
@@ -1793,20 +1853,20 @@
      * The set is backed by the map, so changes to the map are
      * reflected in the set, and vice-versa.  The set supports element
      * removal, which removes the corresponding mapping from the map,
-     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
-     * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt>
-     * operations.  It does not support the <tt>add</tt> or
-     * <tt>addAll</tt> operations.
+     * via the {@code Iterator.remove}, {@code Set.remove},
+     * {@code removeAll}, {@code retainAll} and {@code clear}
+     * operations.  It does not support the {@code add} or
+     * {@code addAll} operations.
      *
-     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
-     * that will never throw {@link ConcurrentModificationException},
-     * and guarantees to traverse elements as they existed upon
-     * construction of the iterator, and may (but is not guaranteed to)
-     * reflect any modifications subsequent to construction.
+     * <p>The view's {@code iterator} is a "weakly consistent" iterator that
+     * will never throw {@link java.util.ConcurrentModificationException
+     * ConcurrentModificationException}, and guarantees to traverse elements
+     * as they existed upon construction of the iterator, and may (but is not
+     * guaranteed to) reflect any modifications subsequent to construction.
      *
-     * <p>The <tt>Map.Entry</tt> elements returned by
-     * <tt>iterator.next()</tt> do <em>not</em> support the
-     * <tt>setValue</tt> operation.
+     * <p>The {@code Map.Entry} elements returned by
+     * {@code iterator.next()} do <em>not</em> support the
+     * {@code setValue} operation.
      *
      * @return a set view of the mappings contained in this map,
      *         sorted in ascending key order
@@ -1830,15 +1890,15 @@
 
     /**
      * Compares the specified object with this map for equality.
-     * Returns <tt>true</tt> if the given object is also a map and the
+     * Returns {@code true} if the given object is also a map and the
      * two maps represent the same mappings.  More formally, two maps
-     * <tt>m1</tt> and <tt>m2</tt> represent the same mappings if
-     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This
+     * {@code m1} and {@code m2} represent the same mappings if
+     * {@code m1.entrySet().equals(m2.entrySet())}.  This
      * operation may return misleading results if either map is
      * concurrently modified during execution of this method.
      *
      * @param o object to be compared for equality with this map
-     * @return <tt>true</tt> if the specified object is equal to this map
+     * @return {@code true} if the specified object is equal to this map
      */
     public boolean equals(Object o) {
         if (o == this)
@@ -1870,7 +1930,7 @@
      * {@inheritDoc}
      *
      * @return the previous value associated with the specified key,
-     *         or <tt>null</tt> if there was no mapping for the key
+     *         or {@code null} if there was no mapping for the key
      * @throws ClassCastException if the specified key cannot be compared
      *         with the keys currently in the map
      * @throws NullPointerException if the specified key or value is null
@@ -1891,9 +1951,7 @@
     public boolean remove(Object key, Object value) {
         if (key == null)
             throw new NullPointerException();
-        if (value == null)
-            return false;
-        return doRemove(key, value) != null;
+        return value != null && doRemove(key, value) != null;
     }
 
     /**
@@ -1904,15 +1962,13 @@
      * @throws NullPointerException if any of the arguments are null
      */
     public boolean replace(K key, V oldValue, V newValue) {
-        if (oldValue == null || newValue == null)
+        if (key == null || oldValue == null || newValue == null)
             throw new NullPointerException();
-        Comparable<? super K> k = comparable(key);
         for (;;) {
-            Node<K,V> n = findNode(k);
-            if (n == null)
+            Node<K,V> n; Object v;
+            if ((n = findNode(key)) == null)
                 return false;
-            Object v = n.value;
-            if (v != null) {
+            if ((v = n.value) != null) {
                 if (!oldValue.equals(v))
                     return false;
                 if (n.casValue(v, newValue))
@@ -1925,22 +1981,22 @@
      * {@inheritDoc}
      *
      * @return the previous value associated with the specified key,
-     *         or <tt>null</tt> if there was no mapping for the key
+     *         or {@code null} if there was no mapping for the key
      * @throws ClassCastException if the specified key cannot be compared
      *         with the keys currently in the map
      * @throws NullPointerException if the specified key or value is null
      */
     public V replace(K key, V value) {
-        if (value == null)
+        if (key == null || value == null)
             throw new NullPointerException();
-        Comparable<? super K> k = comparable(key);
         for (;;) {
-            Node<K,V> n = findNode(k);
-            if (n == null)
+            Node<K,V> n; Object v;
+            if ((n = findNode(key)) == null)
                 return null;
-            Object v = n.value;
-            if (v != null && n.casValue(v, value))
-                return (V)v;
+            if ((v = n.value) != null && n.casValue(v, value)) {
+                @SuppressWarnings("unchecked") V vv = (V)v;
+                return vv;
+            }
         }
     }
 
@@ -2042,9 +2098,9 @@
 
     /**
      * Returns a key-value mapping associated with the greatest key
-     * strictly less than the given key, or <tt>null</tt> if there is
+     * strictly less than the given key, or {@code null} if there is
      * no such key. The returned entry does <em>not</em> support the
-     * <tt>Entry.setValue</tt> method.
+     * {@code Entry.setValue} method.
      *
      * @throws ClassCastException {@inheritDoc}
      * @throws NullPointerException if the specified key is null
@@ -2058,15 +2114,15 @@
      * @throws NullPointerException if the specified key is null
      */
     public K lowerKey(K key) {
-        Node<K,V> n = findNear(key, LT);
+        Node<K,V> n = findNear(key, LT, comparator);
         return (n == null) ? null : n.key;
     }
 
     /**
      * Returns a key-value mapping associated with the greatest key
-     * less than or equal to the given key, or <tt>null</tt> if there
+     * less than or equal to the given key, or {@code null} if there
      * is no such key. The returned entry does <em>not</em> support
-     * the <tt>Entry.setValue</tt> method.
+     * the {@code Entry.setValue} method.
      *
      * @param key the key
      * @throws ClassCastException {@inheritDoc}
@@ -2082,15 +2138,15 @@
      * @throws NullPointerException if the specified key is null
      */
     public K floorKey(K key) {
-        Node<K,V> n = findNear(key, LT|EQ);
+        Node<K,V> n = findNear(key, LT|EQ, comparator);
         return (n == null) ? null : n.key;
     }
 
     /**
      * Returns a key-value mapping associated with the least key
-     * greater than or equal to the given key, or <tt>null</tt> if
+     * greater than or equal to the given key, or {@code null} if
      * there is no such entry. The returned entry does <em>not</em>
-     * support the <tt>Entry.setValue</tt> method.
+     * support the {@code Entry.setValue} method.
      *
      * @throws ClassCastException {@inheritDoc}
      * @throws NullPointerException if the specified key is null
@@ -2104,15 +2160,15 @@
      * @throws NullPointerException if the specified key is null
      */
     public K ceilingKey(K key) {
-        Node<K,V> n = findNear(key, GT|EQ);
+        Node<K,V> n = findNear(key, GT|EQ, comparator);
         return (n == null) ? null : n.key;
     }
 
     /**
      * Returns a key-value mapping associated with the least key
-     * strictly greater than the given key, or <tt>null</tt> if there
+     * strictly greater than the given key, or {@code null} if there
      * is no such key. The returned entry does <em>not</em> support
-     * the <tt>Entry.setValue</tt> method.
+     * the {@code Entry.setValue} method.
      *
      * @param key the key
      * @throws ClassCastException {@inheritDoc}
@@ -2128,15 +2184,15 @@
      * @throws NullPointerException if the specified key is null
      */
     public K higherKey(K key) {
-        Node<K,V> n = findNear(key, GT);
+        Node<K,V> n = findNear(key, GT, comparator);
         return (n == null) ? null : n.key;
     }
 
     /**
      * Returns a key-value mapping associated with the least
-     * key in this map, or <tt>null</tt> if the map is empty.
+     * key in this map, or {@code null} if the map is empty.
      * The returned entry does <em>not</em> support
-     * the <tt>Entry.setValue</tt> method.
+     * the {@code Entry.setValue} method.
      */
     public Map.Entry<K,V> firstEntry() {
         for (;;) {
@@ -2151,9 +2207,9 @@
 
     /**
      * Returns a key-value mapping associated with the greatest
-     * key in this map, or <tt>null</tt> if the map is empty.
+     * key in this map, or {@code null} if the map is empty.
      * The returned entry does <em>not</em> support
-     * the <tt>Entry.setValue</tt> method.
+     * the {@code Entry.setValue} method.
      */
     public Map.Entry<K,V> lastEntry() {
         for (;;) {
@@ -2168,9 +2224,9 @@
 
     /**
      * Removes and returns a key-value mapping associated with
-     * the least key in this map, or <tt>null</tt> if the map is empty.
+     * the least key in this map, or {@code null} if the map is empty.
      * The returned entry does <em>not</em> support
-     * the <tt>Entry.setValue</tt> method.
+     * the {@code Entry.setValue} method.
      */
     public Map.Entry<K,V> pollFirstEntry() {
         return doRemoveFirstEntry();
@@ -2178,9 +2234,9 @@
 
     /**
      * Removes and returns a key-value mapping associated with
-     * the greatest key in this map, or <tt>null</tt> if the map is empty.
+     * the greatest key in this map, or {@code null} if the map is empty.
      * The returned entry does <em>not</em> support
-     * the <tt>Entry.setValue</tt> method.
+     * the {@code Entry.setValue} method.
      */
     public Map.Entry<K,V> pollLastEntry() {
         return doRemoveLastEntry();
@@ -2202,13 +2258,11 @@
 
         /** Initializes ascending iterator for entire range. */
         Iter() {
-            for (;;) {
-                next = findFirst();
-                if (next == null)
-                    break;
+            while ((next = findFirst()) != null) {
                 Object x = next.value;
                 if (x != null && x != next) {
-                    nextValue = (V) x;
+                    @SuppressWarnings("unchecked") V vv = (V)x;
+                    nextValue = vv;
                     break;
                 }
             }
@@ -2223,13 +2277,11 @@
             if (next == null)
                 throw new NoSuchElementException();
             lastReturned = next;
-            for (;;) {
-                next = next.next;
-                if (next == null)
-                    break;
+            while ((next = next.next) != null) {
                 Object x = next.value;
                 if (x != null && x != next) {
-                    nextValue = (V) x;
+                    @SuppressWarnings("unchecked") V vv = (V)x;
+                    nextValue = vv;
                     break;
                 }
             }
@@ -2296,7 +2348,7 @@
 
     static final <E> List<E> toList(Collection<E> c) {
         // Using size() here would be a pessimization.
-        List<E> list = new ArrayList<E>();
+        ArrayList<E> list = new ArrayList<E>();
         for (E e : c)
             list.add(e);
         return list;
@@ -2304,7 +2356,7 @@
 
     static final class KeySet<E>
             extends AbstractSet<E> implements NavigableSet<E> {
-        private final ConcurrentNavigableMap<E,?> m;
+        final ConcurrentNavigableMap<E,?> m;
         KeySet(ConcurrentNavigableMap<E,?> map) { m = map; }
         public int size() { return m.size(); }
         public boolean isEmpty() { return m.isEmpty(); }
@@ -2326,6 +2378,7 @@
             Map.Entry<E,?> e = m.pollLastEntry();
             return (e == null) ? null : e.getKey();
         }
+        @SuppressWarnings("unchecked")
         public Iterator<E> iterator() {
             if (m instanceof ConcurrentSkipListMap)
                 return ((ConcurrentSkipListMap<E,Object>)m).keyIterator();
@@ -2376,13 +2429,21 @@
         public NavigableSet<E> descendingSet() {
             return new KeySet<E>(m.descendingMap());
         }
+        @SuppressWarnings("unchecked")
+        public Spliterator<E> spliterator() {
+            if (m instanceof ConcurrentSkipListMap)
+                return ((ConcurrentSkipListMap<E,?>)m).keySpliterator();
+            else
+                return (Spliterator<E>)((SubMap<E,?>)m).keyIterator();
+        }
     }
 
     static final class Values<E> extends AbstractCollection<E> {
-        private final ConcurrentNavigableMap<?, E> m;
+        final ConcurrentNavigableMap<?, E> m;
         Values(ConcurrentNavigableMap<?, E> map) {
             m = map;
         }
+        @SuppressWarnings("unchecked")
         public Iterator<E> iterator() {
             if (m instanceof ConcurrentSkipListMap)
                 return ((ConcurrentSkipListMap<?,E>)m).valueIterator();
@@ -2403,14 +2464,21 @@
         }
         public Object[] toArray()     { return toList(this).toArray();  }
         public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
+        @SuppressWarnings("unchecked")
+        public Spliterator<E> spliterator() {
+            if (m instanceof ConcurrentSkipListMap)
+                return ((ConcurrentSkipListMap<?,E>)m).valueSpliterator();
+            else
+                return (Spliterator<E>)((SubMap<?,E>)m).valueIterator();
+        }
     }
 
     static final class EntrySet<K1,V1> extends AbstractSet<Map.Entry<K1,V1>> {
-        private final ConcurrentNavigableMap<K1, V1> m;
+        final ConcurrentNavigableMap<K1, V1> m;
         EntrySet(ConcurrentNavigableMap<K1, V1> map) {
             m = map;
         }
-
+        @SuppressWarnings("unchecked")
         public Iterator<Map.Entry<K1,V1>> iterator() {
             if (m instanceof ConcurrentSkipListMap)
                 return ((ConcurrentSkipListMap<K1,V1>)m).entryIterator();
@@ -2457,6 +2525,14 @@
         }
         public Object[] toArray()     { return toList(this).toArray();  }
         public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
+        @SuppressWarnings("unchecked")
+        public Spliterator<Map.Entry<K1,V1>> spliterator() {
+            if (m instanceof ConcurrentSkipListMap)
+                return ((ConcurrentSkipListMap<K1,V1>)m).entrySpliterator();
+            else
+                return (Spliterator<Map.Entry<K1,V1>>)
+                    ((SubMap<K1,V1>)m).entryIterator();
+        }
     }
 
     /**
@@ -2466,8 +2542,8 @@
      * underlying maps, differing in that mappings outside their range are
      * ignored, and attempts to add mappings outside their ranges result
      * in {@link IllegalArgumentException}.  Instances of this class are
-     * constructed only using the <tt>subMap</tt>, <tt>headMap</tt>, and
-     * <tt>tailMap</tt> methods of their underlying maps.
+     * constructed only using the {@code subMap}, {@code headMap}, and
+     * {@code tailMap} methods of their underlying maps.
      *
      * @serial include
      */
@@ -2495,14 +2571,15 @@
         private transient Collection<V> valuesView;
 
         /**
-         * Creates a new submap, initializing all fields
+         * Creates a new submap, initializing all fields.
          */
         SubMap(ConcurrentSkipListMap<K,V> map,
                K fromKey, boolean fromInclusive,
                K toKey, boolean toInclusive,
                boolean isDescending) {
+            Comparator<? super K> cmp = map.comparator;
             if (fromKey != null && toKey != null &&
-                map.compare(fromKey, toKey) > 0)
+                cpr(cmp, fromKey, toKey) > 0)
                 throw new IllegalArgumentException("inconsistent range");
             this.m = map;
             this.lo = fromKey;
@@ -2514,39 +2591,34 @@
 
         /* ----------------  Utilities -------------- */
 
-        private boolean tooLow(K key) {
-            if (lo != null) {
-                int c = m.compare(key, lo);
-                if (c < 0 || (c == 0 && !loInclusive))
-                    return true;
-            }
-            return false;
+        boolean tooLow(Object key, Comparator<? super K> cmp) {
+            int c;
+            return (lo != null && ((c = cpr(cmp, key, lo)) < 0 ||
+                                   (c == 0 && !loInclusive)));
         }
 
-        private boolean tooHigh(K key) {
-            if (hi != null) {
-                int c = m.compare(key, hi);
-                if (c > 0 || (c == 0 && !hiInclusive))
-                    return true;
-            }
-            return false;
+        boolean tooHigh(Object key, Comparator<? super K> cmp) {
+            int c;
+            return (hi != null && ((c = cpr(cmp, key, hi)) > 0 ||
+                                   (c == 0 && !hiInclusive)));
         }
 
-        private boolean inBounds(K key) {
-            return !tooLow(key) && !tooHigh(key);
+        boolean inBounds(Object key, Comparator<? super K> cmp) {
+            return !tooLow(key, cmp) && !tooHigh(key, cmp);
         }
 
-        private void checkKeyBounds(K key) throws IllegalArgumentException {
+        void checkKeyBounds(K key, Comparator<? super K> cmp) {
             if (key == null)
                 throw new NullPointerException();
-            if (!inBounds(key))
+            if (!inBounds(key, cmp))
                 throw new IllegalArgumentException("key out of range");
         }
 
         /**
-         * Returns true if node key is less than upper bound of range
+         * Returns true if node key is less than upper bound of range.
          */
-        private boolean isBeforeEnd(ConcurrentSkipListMap.Node<K,V> n) {
+        boolean isBeforeEnd(ConcurrentSkipListMap.Node<K,V> n,
+                            Comparator<? super K> cmp) {
             if (n == null)
                 return false;
             if (hi == null)
@@ -2554,7 +2626,7 @@
             K k = n.key;
             if (k == null) // pass by markers and headers
                 return true;
-            int c = m.compare(k, hi);
+            int c = cpr(cmp, k, hi);
             if (c > 0 || (c == 0 && !hiInclusive))
                 return false;
             return true;
@@ -2562,58 +2634,61 @@
 
         /**
          * Returns lowest node. This node might not be in range, so
-         * most usages need to check bounds
+         * most usages need to check bounds.
          */
-        private ConcurrentSkipListMap.Node<K,V> loNode() {
+        ConcurrentSkipListMap.Node<K,V> loNode(Comparator<? super K> cmp) {
             if (lo == null)
                 return m.findFirst();
             else if (loInclusive)
-                return m.findNear(lo, GT|EQ);
+                return m.findNear(lo, GT|EQ, cmp);
             else
-                return m.findNear(lo, GT);
+                return m.findNear(lo, GT, cmp);
         }
 
         /**
          * Returns highest node. This node might not be in range, so
-         * most usages need to check bounds
+         * most usages need to check bounds.
          */
-        private ConcurrentSkipListMap.Node<K,V> hiNode() {
+        ConcurrentSkipListMap.Node<K,V> hiNode(Comparator<? super K> cmp) {
             if (hi == null)
                 return m.findLast();
             else if (hiInclusive)
-                return m.findNear(hi, LT|EQ);
+                return m.findNear(hi, LT|EQ, cmp);
             else
-                return m.findNear(hi, LT);
+                return m.findNear(hi, LT, cmp);
         }
 
         /**
-         * Returns lowest absolute key (ignoring directonality)
+         * Returns lowest absolute key (ignoring directonality).
          */
-        private K lowestKey() {
-            ConcurrentSkipListMap.Node<K,V> n = loNode();
-            if (isBeforeEnd(n))
+        K lowestKey() {
+            Comparator<? super K> cmp = m.comparator;
+            ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
+            if (isBeforeEnd(n, cmp))
                 return n.key;
             else
                 throw new NoSuchElementException();
         }
 
         /**
-         * Returns highest absolute key (ignoring directonality)
+         * Returns highest absolute key (ignoring directonality).
          */
-        private K highestKey() {
-            ConcurrentSkipListMap.Node<K,V> n = hiNode();
+        K highestKey() {
+            Comparator<? super K> cmp = m.comparator;
+            ConcurrentSkipListMap.Node<K,V> n = hiNode(cmp);
             if (n != null) {
                 K last = n.key;
-                if (inBounds(last))
+                if (inBounds(last, cmp))
                     return last;
             }
             throw new NoSuchElementException();
         }
 
-        private Map.Entry<K,V> lowestEntry() {
+        Map.Entry<K,V> lowestEntry() {
+            Comparator<? super K> cmp = m.comparator;
             for (;;) {
-                ConcurrentSkipListMap.Node<K,V> n = loNode();
-                if (!isBeforeEnd(n))
+                ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
+                if (!isBeforeEnd(n, cmp))
                     return null;
                 Map.Entry<K,V> e = n.createSnapshot();
                 if (e != null)
@@ -2621,10 +2696,11 @@
             }
         }
 
-        private Map.Entry<K,V> highestEntry() {
+        Map.Entry<K,V> highestEntry() {
+            Comparator<? super K> cmp = m.comparator;
             for (;;) {
-                ConcurrentSkipListMap.Node<K,V> n = hiNode();
-                if (n == null || !inBounds(n.key))
+                ConcurrentSkipListMap.Node<K,V> n = hiNode(cmp);
+                if (n == null || !inBounds(n.key, cmp))
                     return null;
                 Map.Entry<K,V> e = n.createSnapshot();
                 if (e != null)
@@ -2632,13 +2708,14 @@
             }
         }
 
-        private Map.Entry<K,V> removeLowest() {
+        Map.Entry<K,V> removeLowest() {
+            Comparator<? super K> cmp = m.comparator;
             for (;;) {
-                Node<K,V> n = loNode();
+                Node<K,V> n = loNode(cmp);
                 if (n == null)
                     return null;
                 K k = n.key;
-                if (!inBounds(k))
+                if (!inBounds(k, cmp))
                     return null;
                 V v = m.doRemove(k, null);
                 if (v != null)
@@ -2646,13 +2723,14 @@
             }
         }
 
-        private Map.Entry<K,V> removeHighest() {
+        Map.Entry<K,V> removeHighest() {
+            Comparator<? super K> cmp = m.comparator;
             for (;;) {
-                Node<K,V> n = hiNode();
+                Node<K,V> n = hiNode(cmp);
                 if (n == null)
                     return null;
                 K k = n.key;
-                if (!inBounds(k))
+                if (!inBounds(k, cmp))
                     return null;
                 V v = m.doRemove(k, null);
                 if (v != null)
@@ -2663,20 +2741,21 @@
         /**
          * Submap version of ConcurrentSkipListMap.getNearEntry
          */
-        private Map.Entry<K,V> getNearEntry(K key, int rel) {
+        Map.Entry<K,V> getNearEntry(K key, int rel) {
+            Comparator<? super K> cmp = m.comparator;
             if (isDescending) { // adjust relation for direction
                 if ((rel & LT) == 0)
                     rel |= LT;
                 else
                     rel &= ~LT;
             }
-            if (tooLow(key))
+            if (tooLow(key, cmp))
                 return ((rel & LT) != 0) ? null : lowestEntry();
-            if (tooHigh(key))
+            if (tooHigh(key, cmp))
                 return ((rel & LT) != 0) ? highestEntry() : null;
             for (;;) {
-                Node<K,V> n = m.findNear(key, rel);
-                if (n == null || !inBounds(n.key))
+                Node<K,V> n = m.findNear(key, rel, cmp);
+                if (n == null || !inBounds(n.key, cmp))
                     return null;
                 K k = n.key;
                 V v = n.getValidValue();
@@ -2686,35 +2765,36 @@
         }
 
         // Almost the same as getNearEntry, except for keys
-        private K getNearKey(K key, int rel) {
+        K getNearKey(K key, int rel) {
+            Comparator<? super K> cmp = m.comparator;
             if (isDescending) { // adjust relation for direction
                 if ((rel & LT) == 0)
                     rel |= LT;
                 else
                     rel &= ~LT;
             }
-            if (tooLow(key)) {
+            if (tooLow(key, cmp)) {
                 if ((rel & LT) == 0) {
-                    ConcurrentSkipListMap.Node<K,V> n = loNode();
-                    if (isBeforeEnd(n))
+                    ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
+                    if (isBeforeEnd(n, cmp))
                         return n.key;
                 }
                 return null;
             }
-            if (tooHigh(key)) {
+            if (tooHigh(key, cmp)) {
                 if ((rel & LT) != 0) {
-                    ConcurrentSkipListMap.Node<K,V> n = hiNode();
+                    ConcurrentSkipListMap.Node<K,V> n = hiNode(cmp);
                     if (n != null) {
                         K last = n.key;
-                        if (inBounds(last))
+                        if (inBounds(last, cmp))
                             return last;
                     }
                 }
                 return null;
             }
             for (;;) {
-                Node<K,V> n = m.findNear(key, rel);
-                if (n == null || !inBounds(n.key))
+                Node<K,V> n = m.findNear(key, rel, cmp);
+                if (n == null || !inBounds(n.key, cmp))
                     return null;
                 K k = n.key;
                 V v = n.getValidValue();
@@ -2727,30 +2807,28 @@
 
         public boolean containsKey(Object key) {
             if (key == null) throw new NullPointerException();
-            K k = (K)key;
-            return inBounds(k) && m.containsKey(k);
+            return inBounds(key, m.comparator) && m.containsKey(key);
         }
 
         public V get(Object key) {
             if (key == null) throw new NullPointerException();
-            K k = (K)key;
-            return (!inBounds(k)) ? null : m.get(k);
+            return (!inBounds(key, m.comparator)) ? null : m.get(key);
         }
 
         public V put(K key, V value) {
-            checkKeyBounds(key);
+            checkKeyBounds(key, m.comparator);
             return m.put(key, value);
         }
 
         public V remove(Object key) {
-            K k = (K)key;
-            return (!inBounds(k)) ? null : m.remove(k);
+            return (!inBounds(key, m.comparator)) ? null : m.remove(key);
         }
 
         public int size() {
+            Comparator<? super K> cmp = m.comparator;
             long count = 0;
-            for (ConcurrentSkipListMap.Node<K,V> n = loNode();
-                 isBeforeEnd(n);
+            for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
+                 isBeforeEnd(n, cmp);
                  n = n.next) {
                 if (n.getValidValue() != null)
                     ++count;
@@ -2759,14 +2837,16 @@
         }
 
         public boolean isEmpty() {
-            return !isBeforeEnd(loNode());
+            Comparator<? super K> cmp = m.comparator;
+            return !isBeforeEnd(loNode(cmp), cmp);
         }
 
         public boolean containsValue(Object value) {
             if (value == null)
                 throw new NullPointerException();
-            for (ConcurrentSkipListMap.Node<K,V> n = loNode();
-                 isBeforeEnd(n);
+            Comparator<? super K> cmp = m.comparator;
+            for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
+                 isBeforeEnd(n, cmp);
                  n = n.next) {
                 V v = n.getValidValue();
                 if (v != null && value.equals(v))
@@ -2776,8 +2856,9 @@
         }
 
         public void clear() {
-            for (ConcurrentSkipListMap.Node<K,V> n = loNode();
-                 isBeforeEnd(n);
+            Comparator<? super K> cmp = m.comparator;
+            for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
+                 isBeforeEnd(n, cmp);
                  n = n.next) {
                 if (n.getValidValue() != null)
                     m.remove(n.key);
@@ -2787,22 +2868,21 @@
         /* ----------------  ConcurrentMap API methods -------------- */
 
         public V putIfAbsent(K key, V value) {
-            checkKeyBounds(key);
+            checkKeyBounds(key, m.comparator);
             return m.putIfAbsent(key, value);
         }
 
         public boolean remove(Object key, Object value) {
-            K k = (K)key;
-            return inBounds(k) && m.remove(k, value);
+            return inBounds(key, m.comparator) && m.remove(key, value);
         }
 
         public boolean replace(K key, V oldValue, V newValue) {
-            checkKeyBounds(key);
+            checkKeyBounds(key, m.comparator);
             return m.replace(key, oldValue, newValue);
         }
 
         public V replace(K key, V value) {
-            checkKeyBounds(key);
+            checkKeyBounds(key, m.comparator);
             return m.replace(key, value);
         }
 
@@ -2820,10 +2900,9 @@
          * Utility to create submaps, where given bounds override
          * unbounded(null) ones and/or are checked against bounded ones.
          */
-        private SubMap<K,V> newSubMap(K fromKey,
-                                      boolean fromInclusive,
-                                      K toKey,
-                                      boolean toInclusive) {
+        SubMap<K,V> newSubMap(K fromKey, boolean fromInclusive,
+                              K toKey, boolean toInclusive) {
+            Comparator<? super K> cmp = m.comparator;
             if (isDescending) { // flip senses
                 K tk = fromKey;
                 fromKey = toKey;
@@ -2838,7 +2917,7 @@
                     fromInclusive = loInclusive;
                 }
                 else {
-                    int c = m.compare(fromKey, lo);
+                    int c = cpr(cmp, fromKey, lo);
                     if (c < 0 || (c == 0 && !loInclusive && fromInclusive))
                         throw new IllegalArgumentException("key out of range");
                 }
@@ -2849,7 +2928,7 @@
                     toInclusive = hiInclusive;
                 }
                 else {
-                    int c = m.compare(toKey, hi);
+                    int c = cpr(cmp, toKey, hi);
                     if (c > 0 || (c == 0 && !hiInclusive && toInclusive))
                         throw new IllegalArgumentException("key out of range");
                 }
@@ -2858,24 +2937,20 @@
                                    toKey, toInclusive, isDescending);
         }
 
-        public SubMap<K,V> subMap(K fromKey,
-                                  boolean fromInclusive,
-                                  K toKey,
-                                  boolean toInclusive) {
+        public SubMap<K,V> subMap(K fromKey, boolean fromInclusive,
+                                  K toKey, boolean toInclusive) {
             if (fromKey == null || toKey == null)
                 throw new NullPointerException();
             return newSubMap(fromKey, fromInclusive, toKey, toInclusive);
         }
 
-        public SubMap<K,V> headMap(K toKey,
-                                   boolean inclusive) {
+        public SubMap<K,V> headMap(K toKey, boolean inclusive) {
             if (toKey == null)
                 throw new NullPointerException();
             return newSubMap(null, false, toKey, inclusive);
         }
 
-        public SubMap<K,V> tailMap(K fromKey,
-                                   boolean inclusive) {
+        public SubMap<K,V> tailMap(K fromKey, boolean inclusive) {
             if (fromKey == null)
                 throw new NullPointerException();
             return newSubMap(fromKey, inclusive, null, false);
@@ -2996,8 +3071,9 @@
 
         /**
          * Variant of main Iter class to traverse through submaps.
+         * Also serves as back-up Spliterator for views
          */
-        abstract class SubMapIter<T> implements Iterator<T> {
+        abstract class SubMapIter<T> implements Iterator<T>, Spliterator<T> {
             /** the last node returned by next() */
             Node<K,V> lastReturned;
             /** the next node to return from next(); */
@@ -3006,16 +3082,19 @@
             V nextValue;
 
             SubMapIter() {
+                Comparator<? super K> cmp = m.comparator;
                 for (;;) {
-                    next = isDescending ? hiNode() : loNode();
+                    next = isDescending ? hiNode(cmp) : loNode(cmp);
                     if (next == null)
                         break;
                     Object x = next.value;
                     if (x != null && x != next) {
-                        if (! inBounds(next.key))
+                        if (! inBounds(next.key, cmp))
                             next = null;
-                        else
-                            nextValue = (V) x;
+                        else {
+                            @SuppressWarnings("unchecked") V vv = (V)x;
+                            nextValue = vv;
+                        }
                         break;
                     }
                 }
@@ -3036,32 +3115,38 @@
             }
 
             private void ascend() {
+                Comparator<? super K> cmp = m.comparator;
                 for (;;) {
                     next = next.next;
                     if (next == null)
                         break;
                     Object x = next.value;
                     if (x != null && x != next) {
-                        if (tooHigh(next.key))
+                        if (tooHigh(next.key, cmp))
                             next = null;
-                        else
-                            nextValue = (V) x;
+                        else {
+                            @SuppressWarnings("unchecked") V vv = (V)x;
+                            nextValue = vv;
+                        }
                         break;
                     }
                 }
             }
 
             private void descend() {
+                Comparator<? super K> cmp = m.comparator;
                 for (;;) {
-                    next = m.findNear(lastReturned.key, LT);
+                    next = m.findNear(lastReturned.key, LT, cmp);
                     if (next == null)
                         break;
                     Object x = next.value;
                     if (x != null && x != next) {
-                        if (tooLow(next.key))
+                        if (tooLow(next.key, cmp))
                             next = null;
-                        else
-                            nextValue = (V) x;
+                        else {
+                            @SuppressWarnings("unchecked") V vv = (V)x;
+                            nextValue = vv;
+                        }
                         break;
                     }
                 }
@@ -3075,6 +3160,26 @@
                 lastReturned = null;
             }
 
+            public Spliterator<T> trySplit() {
+                return null;
+            }
+
+            public boolean tryAdvance(Consumer<? super T> action) {
+                if (hasNext()) {
+                    action.accept(next());
+                    return true;
+                }
+                return false;
+            }
+
+            public void forEachRemaining(Consumer<? super T> action) {
+                while (hasNext())
+                    action.accept(next());
+            }
+
+            public long estimateSize() {
+                return Long.MAX_VALUE;
+            }
         }
 
         final class SubMapValueIterator extends SubMapIter<V> {
@@ -3083,6 +3188,9 @@
                 advance();
                 return v;
             }
+            public int characteristics() {
+                return 0;
+            }
         }
 
         final class SubMapKeyIterator extends SubMapIter<K> {
@@ -3091,6 +3199,13 @@
                 advance();
                 return n.key;
             }
+            public int characteristics() {
+                return Spliterator.DISTINCT | Spliterator.ORDERED |
+                    Spliterator.SORTED;
+            }
+            public final Comparator<? super K> getComparator() {
+                return SubMap.this.comparator();
+            }
         }
 
         final class SubMapEntryIterator extends SubMapIter<Map.Entry<K,V>> {
@@ -3100,18 +3215,351 @@
                 advance();
                 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
             }
+            public int characteristics() {
+                return Spliterator.DISTINCT;
+            }
+        }
+    }
+
+    // default Map method overrides
+
+    public void forEach(BiConsumer<? super K, ? super V> action) {
+        if (action == null) throw new NullPointerException();
+        V v;
+        for (Node<K,V> n = findFirst(); n != null; n = n.next) {
+            if ((v = n.getValidValue()) != null)
+                action.accept(n.key, v);
+        }
+    }
+
+    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
+        if (function == null) throw new NullPointerException();
+        V v;
+        for (Node<K,V> n = findFirst(); n != null; n = n.next) {
+            while ((v = n.getValidValue()) != null) {
+                V r = function.apply(n.key, v);
+                if (r == null) throw new NullPointerException();
+                if (n.casValue(v, r))
+                    break;
+            }
+        }
+    }
+
+    /**
+     * Base class providing common structure for Spliterators.
+     * (Although not all that much common functionality; as usual for
+     * view classes, details annoyingly vary in key, value, and entry
+     * subclasses in ways that are not worth abstracting out for
+     * internal classes.)
+     *
+     * The basic split strategy is to recursively descend from top
+     * level, row by row, descending to next row when either split
+     * off, or the end of row is encountered. Control of the number of
+     * splits relies on some statistical estimation: The expected
+     * remaining number of elements of a skip list when advancing
+     * either across or down decreases by about 25%. To make this
+     * observation useful, we need to know initial size, which we
+     * don't. But we can just use Integer.MAX_VALUE so that we
+     * don't prematurely zero out while splitting.
+     */
+    abstract static class CSLMSpliterator<K,V> {
+        final Comparator<? super K> comparator;
+        final K fence;     // exclusive upper bound for keys, or null if to end
+        Index<K,V> row;    // the level to split out
+        Node<K,V> current; // current traversal node; initialize at origin
+        int est;           // pseudo-size estimate
+        CSLMSpliterator(Comparator<? super K> comparator, Index<K,V> row,
+                        Node<K,V> origin, K fence, int est) {
+            this.comparator = comparator; this.row = row;
+            this.current = origin; this.fence = fence; this.est = est;
+        }
+
+        public final long estimateSize() { return (long)est; }
+    }
+
+    static final class KeySpliterator<K,V> extends CSLMSpliterator<K,V>
+        implements Spliterator<K> {
+        KeySpliterator(Comparator<? super K> comparator, Index<K,V> row,
+                       Node<K,V> origin, K fence, int est) {
+            super(comparator, row, origin, fence, est);
+        }
+
+        public Spliterator<K> trySplit() {
+            Node<K,V> e; K ek;
+            Comparator<? super K> cmp = comparator;
+            K f = fence;
+            if ((e = current) != null && (ek = e.key) != null) {
+                for (Index<K,V> q = row; q != null; q = row = q.down) {
+                    Index<K,V> s; Node<K,V> b, n; K sk;
+                    if ((s = q.right) != null && (b = s.node) != null &&
+                        (n = b.next) != null && n.value != null &&
+                        (sk = n.key) != null && cpr(cmp, sk, ek) > 0 &&
+                        (f == null || cpr(cmp, sk, f) < 0)) {
+                        current = n;
+                        Index<K,V> r = q.down;
+                        row = (s.right != null) ? s : s.down;
+                        est -= est >>> 2;
+                        return new KeySpliterator<K,V>(cmp, r, e, sk, est);
+                    }
+                }
+            }
+            return null;
+        }
+
+        public void forEachRemaining(Consumer<? super K> action) {
+            if (action == null) throw new NullPointerException();
+            Comparator<? super K> cmp = comparator;
+            K f = fence;
+            Node<K,V> e = current;
+            current = null;
+            for (; e != null; e = e.next) {
+                K k; Object v;
+                if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
+                    break;
+                if ((v = e.value) != null && v != e)
+                    action.accept(k);
+            }
+        }
+
+        public boolean tryAdvance(Consumer<? super K> action) {
+            if (action == null) throw new NullPointerException();
+            Comparator<? super K> cmp = comparator;
+            K f = fence;
+            Node<K,V> e = current;
+            for (; e != null; e = e.next) {
+                K k; Object v;
+                if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) {
+                    e = null;
+                    break;
+                }
+                if ((v = e.value) != null && v != e) {
+                    current = e.next;
+                    action.accept(k);
+                    return true;
+                }
+            }
+            current = e;
+            return false;
+        }
+
+        public int characteristics() {
+            return Spliterator.DISTINCT | Spliterator.SORTED |
+                Spliterator.ORDERED | Spliterator.CONCURRENT |
+                Spliterator.NONNULL;
+        }
+
+        public final Comparator<? super K> getComparator() {
+            return comparator;
+        }
+    }
+    // factory method for KeySpliterator
+    final KeySpliterator<K,V> keySpliterator() {
+        Comparator<? super K> cmp = comparator;
+        for (;;) { // ensure h corresponds to origin p
+            HeadIndex<K,V> h; Node<K,V> p;
+            Node<K,V> b = (h = head).node;
+            if ((p = b.next) == null || p.value != null)
+                return new KeySpliterator<K,V>(cmp, h, p, null, (p == null) ?
+                                               0 : Integer.MAX_VALUE);
+            p.helpDelete(b, p.next);
+        }
+    }
+
+    static final class ValueSpliterator<K,V> extends CSLMSpliterator<K,V>
+        implements Spliterator<V> {
+        ValueSpliterator(Comparator<? super K> comparator, Index<K,V> row,
+                       Node<K,V> origin, K fence, int est) {
+            super(comparator, row, origin, fence, est);
+        }
+
+        public Spliterator<V> trySplit() {
+            Node<K,V> e; K ek;
+            Comparator<? super K> cmp = comparator;
+            K f = fence;
+            if ((e = current) != null && (ek = e.key) != null) {
+                for (Index<K,V> q = row; q != null; q = row = q.down) {
+                    Index<K,V> s; Node<K,V> b, n; K sk;
+                    if ((s = q.right) != null && (b = s.node) != null &&
+                        (n = b.next) != null && n.value != null &&
+                        (sk = n.key) != null && cpr(cmp, sk, ek) > 0 &&
+                        (f == null || cpr(cmp, sk, f) < 0)) {
+                        current = n;
+                        Index<K,V> r = q.down;
+                        row = (s.right != null) ? s : s.down;
+                        est -= est >>> 2;
+                        return new ValueSpliterator<K,V>(cmp, r, e, sk, est);
+                    }
+                }
+            }
+            return null;
+        }
+
+        public void forEachRemaining(Consumer<? super V> action) {
+            if (action == null) throw new NullPointerException();
+            Comparator<? super K> cmp = comparator;
+            K f = fence;
+            Node<K,V> e = current;
+            current = null;
+            for (; e != null; e = e.next) {
+                K k; Object v;
+                if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
+                    break;
+                if ((v = e.value) != null && v != e) {
+                    @SuppressWarnings("unchecked") V vv = (V)v;
+                    action.accept(vv);
+                }
+            }
+        }
+
+        public boolean tryAdvance(Consumer<? super V> action) {
+            if (action == null) throw new NullPointerException();
+            Comparator<? super K> cmp = comparator;
+            K f = fence;
+            Node<K,V> e = current;
+            for (; e != null; e = e.next) {
+                K k; Object v;
+                if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) {
+                    e = null;
+                    break;
+                }
+                if ((v = e.value) != null && v != e) {
+                    current = e.next;
+                    @SuppressWarnings("unchecked") V vv = (V)v;
+                    action.accept(vv);
+                    return true;
+                }
+            }
+            current = e;
+            return false;
+        }
+
+        public int characteristics() {
+            return Spliterator.CONCURRENT | Spliterator.NONNULL;
+        }
+    }
+
+    // Almost the same as keySpliterator()
+    final ValueSpliterator<K,V> valueSpliterator() {
+        Comparator<? super K> cmp = comparator;
+        for (;;) {
+            HeadIndex<K,V> h; Node<K,V> p;
+            Node<K,V> b = (h = head).node;
+            if ((p = b.next) == null || p.value != null)
+                return new ValueSpliterator<K,V>(cmp, h, p, null, (p == null) ?
+                                                 0 : Integer.MAX_VALUE);
+            p.helpDelete(b, p.next);
+        }
+    }
+
+    static final class EntrySpliterator<K,V> extends CSLMSpliterator<K,V>
+        implements Spliterator<Map.Entry<K,V>> {
+        EntrySpliterator(Comparator<? super K> comparator, Index<K,V> row,
+                         Node<K,V> origin, K fence, int est) {
+            super(comparator, row, origin, fence, est);
+        }
+
+        public Spliterator<Map.Entry<K,V>> trySplit() {
+            Node<K,V> e; K ek;
+            Comparator<? super K> cmp = comparator;
+            K f = fence;
+            if ((e = current) != null && (ek = e.key) != null) {
+                for (Index<K,V> q = row; q != null; q = row = q.down) {
+                    Index<K,V> s; Node<K,V> b, n; K sk;
+                    if ((s = q.right) != null && (b = s.node) != null &&
+                        (n = b.next) != null && n.value != null &&
+                        (sk = n.key) != null && cpr(cmp, sk, ek) > 0 &&
+                        (f == null || cpr(cmp, sk, f) < 0)) {
+                        current = n;
+                        Index<K,V> r = q.down;
+                        row = (s.right != null) ? s : s.down;
+                        est -= est >>> 2;
+                        return new EntrySpliterator<K,V>(cmp, r, e, sk, est);
+                    }
+                }
+            }
+            return null;
+        }
+
+        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
+            if (action == null) throw new NullPointerException();
+            Comparator<? super K> cmp = comparator;
+            K f = fence;
+            Node<K,V> e = current;
+            current = null;
+            for (; e != null; e = e.next) {
+                K k; Object v;
+                if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
+                    break;
+                if ((v = e.value) != null && v != e) {
+                    @SuppressWarnings("unchecked") V vv = (V)v;
+                    action.accept
+                        (new AbstractMap.SimpleImmutableEntry<K,V>(k, vv));
+                }
+            }
+        }
+
+        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
+            if (action == null) throw new NullPointerException();
+            Comparator<? super K> cmp = comparator;
+            K f = fence;
+            Node<K,V> e = current;
+            for (; e != null; e = e.next) {
+                K k; Object v;
+                if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) {
+                    e = null;
+                    break;
+                }
+                if ((v = e.value) != null && v != e) {
+                    current = e.next;
+                    @SuppressWarnings("unchecked") V vv = (V)v;
+                    action.accept
+                        (new AbstractMap.SimpleImmutableEntry<K,V>(k, vv));
+                    return true;
+                }
+            }
+            current = e;
+            return false;
+        }
+
+        public int characteristics() {
+            return Spliterator.DISTINCT | Spliterator.SORTED |
+                Spliterator.ORDERED | Spliterator.CONCURRENT |
+                Spliterator.NONNULL;
+        }
+
+        public final Comparator<Map.Entry<K,V>> getComparator() {
+            return comparator == null ? null :
+                Map.Entry.comparingByKey(comparator);
+        }
+    }
+
+    // Almost the same as keySpliterator()
+    final EntrySpliterator<K,V> entrySpliterator() {
+        Comparator<? super K> cmp = comparator;
+        for (;;) { // almost same as key version
+            HeadIndex<K,V> h; Node<K,V> p;
+            Node<K,V> b = (h = head).node;
+            if ((p = b.next) == null || p.value != null)
+                return new EntrySpliterator<K,V>(cmp, h, p, null, (p == null) ?
+                                                 0 : Integer.MAX_VALUE);
+            p.helpDelete(b, p.next);
         }
     }
 
     // Unsafe mechanics
     private static final sun.misc.Unsafe UNSAFE;
     private static final long headOffset;
+    private static final long SECONDARY;
     static {
         try {
             UNSAFE = sun.misc.Unsafe.getUnsafe();
             Class<?> k = ConcurrentSkipListMap.class;
             headOffset = UNSAFE.objectFieldOffset
                 (k.getDeclaredField("head"));
+            Class<?> tk = Thread.class;
+            SECONDARY = UNSAFE.objectFieldOffset
+                (tk.getDeclaredField("threadLocalRandomSecondarySeed"));
+
         } catch (Exception e) {
             throw new Error(e);
         }
--- a/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java	Mon Jul 22 17:37:15 2013 -0700
@@ -34,7 +34,17 @@
  */
 
 package java.util.concurrent;
-import java.util.*;
+import java.util.AbstractSet;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NavigableSet;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.Spliterator;
 
 /**
  * A scalable concurrent {@link NavigableSet} implementation based on
@@ -44,33 +54,33 @@
  * on which constructor is used.
  *
  * <p>This implementation provides expected average <i>log(n)</i> time
- * cost for the <tt>contains</tt>, <tt>add</tt>, and <tt>remove</tt>
+ * cost for the {@code contains}, {@code add}, and {@code remove}
  * operations and their variants.  Insertion, removal, and access
  * operations safely execute concurrently by multiple threads.
  * Iterators are <i>weakly consistent</i>, returning elements
  * reflecting the state of the set at some point at or since the
  * creation of the iterator.  They do <em>not</em> throw {@link
- * ConcurrentModificationException}, and may proceed concurrently with
- * other operations.  Ascending ordered views and their iterators are
- * faster than descending ones.
+ * java.util.ConcurrentModificationException}, and may proceed
+ * concurrently with other operations.  Ascending ordered views and
+ * their iterators are faster than descending ones.
  *
- * <p>Beware that, unlike in most collections, the <tt>size</tt>
+ * <p>Beware that, unlike in most collections, the {@code size}
  * method is <em>not</em> a constant-time operation. Because of the
  * asynchronous nature of these sets, determining the current number
  * of elements requires a traversal of the elements, and so may report
  * inaccurate results if this collection is modified during traversal.
- * Additionally, the bulk operations <tt>addAll</tt>,
- * <tt>removeAll</tt>, <tt>retainAll</tt>, <tt>containsAll</tt>,
- * <tt>equals</tt>, and <tt>toArray</tt> are <em>not</em> guaranteed
+ * Additionally, the bulk operations {@code addAll},
+ * {@code removeAll}, {@code retainAll}, {@code containsAll},
+ * {@code equals}, and {@code toArray} are <em>not</em> guaranteed
  * to be performed atomically. For example, an iterator operating
- * concurrently with an <tt>addAll</tt> operation might view only some
+ * concurrently with an {@code addAll} operation might view only some
  * of the added elements.
  *
  * <p>This class and its iterators implement all of the
  * <em>optional</em> methods of the {@link Set} and {@link Iterator}
  * interfaces. Like most other concurrent collection implementations,
- * this class does not permit the use of <tt>null</tt> elements,
- * because <tt>null</tt> arguments and return values cannot be reliably
+ * this class does not permit the use of {@code null} elements,
+ * because {@code null} arguments and return values cannot be reliably
  * distinguished from the absence of elements.
  *
  * <p>This class is a member of the
@@ -90,7 +100,7 @@
     /**
      * The underlying map. Uses Boolean.TRUE as value for each
      * element.  This field is declared final for the sake of thread
-     * safety, which entails some ugliness in clone()
+     * safety, which entails some ugliness in clone().
      */
     private final ConcurrentNavigableMap<E,Object> m;
 
@@ -107,7 +117,7 @@
      * the specified comparator.
      *
      * @param comparator the comparator that will be used to order this set.
-     *        If <tt>null</tt>, the {@linkplain Comparable natural
+     *        If {@code null}, the {@linkplain Comparable natural
      *        ordering} of the elements will be used.
      */
     public ConcurrentSkipListSet(Comparator<? super E> comparator) {
@@ -120,7 +130,7 @@
      * {@linkplain Comparable natural ordering}.
      *
      * @param c The elements that will comprise the new set
-     * @throws ClassCastException if the elements in <tt>c</tt> are
+     * @throws ClassCastException if the elements in {@code c} are
      *         not {@link Comparable}, or are not mutually comparable
      * @throws NullPointerException if the specified collection or any
      *         of its elements are null
@@ -151,7 +161,7 @@
     }
 
     /**
-     * Returns a shallow copy of this <tt>ConcurrentSkipListSet</tt>
+     * Returns a shallow copy of this {@code ConcurrentSkipListSet}
      * instance. (The elements themselves are not cloned.)
      *
      * @return a shallow copy of this set
@@ -172,8 +182,8 @@
 
     /**
      * Returns the number of elements in this set.  If this set
-     * contains more than <tt>Integer.MAX_VALUE</tt> elements, it
-     * returns <tt>Integer.MAX_VALUE</tt>.
+     * contains more than {@code Integer.MAX_VALUE} elements, it
+     * returns {@code Integer.MAX_VALUE}.
      *
      * <p>Beware that, unlike in most collections, this method is
      * <em>NOT</em> a constant-time operation. Because of the
@@ -191,20 +201,20 @@
     }
 
     /**
-     * Returns <tt>true</tt> if this set contains no elements.
-     * @return <tt>true</tt> if this set contains no elements
+     * Returns {@code true} if this set contains no elements.
+     * @return {@code true} if this set contains no elements
      */
     public boolean isEmpty() {
         return m.isEmpty();
     }
 
     /**
-     * Returns <tt>true</tt> if this set contains the specified element.
-     * More formally, returns <tt>true</tt> if and only if this set
-     * contains an element <tt>e</tt> such that <tt>o.equals(e)</tt>.
+     * Returns {@code true} if this set contains the specified element.
+     * More formally, returns {@code true} if and only if this set
+     * contains an element {@code e} such that {@code o.equals(e)}.
      *
      * @param o object to be checked for containment in this set
-     * @return <tt>true</tt> if this set contains the specified element
+     * @return {@code true} if this set contains the specified element
      * @throws ClassCastException if the specified element cannot be
      *         compared with the elements currently in this set
      * @throws NullPointerException if the specified element is null
@@ -215,15 +225,15 @@
 
     /**
      * Adds the specified element to this set if it is not already present.
-     * More formally, adds the specified element <tt>e</tt> to this set if
-     * the set contains no element <tt>e2</tt> such that <tt>e.equals(e2)</tt>.
+     * More formally, adds the specified element {@code e} to this set if
+     * the set contains no element {@code e2} such that {@code e.equals(e2)}.
      * If this set already contains the element, the call leaves the set
-     * unchanged and returns <tt>false</tt>.
+     * unchanged and returns {@code false}.
      *
      * @param e element to be added to this set
-     * @return <tt>true</tt> if this set did not already contain the
+     * @return {@code true} if this set did not already contain the
      *         specified element
-     * @throws ClassCastException if <tt>e</tt> cannot be compared
+     * @throws ClassCastException if {@code e} cannot be compared
      *         with the elements currently in this set
      * @throws NullPointerException if the specified element is null
      */
@@ -233,15 +243,15 @@
 
     /**
      * Removes the specified element from this set if it is present.
-     * More formally, removes an element <tt>e</tt> such that
-     * <tt>o.equals(e)</tt>, if this set contains such an element.
-     * Returns <tt>true</tt> if this set contained the element (or
+     * More formally, removes an element {@code e} such that
+     * {@code o.equals(e)}, if this set contains such an element.
+     * Returns {@code true} if this set contained the element (or
      * equivalently, if this set changed as a result of the call).
      * (This set will not contain the element once the call returns.)
      *
      * @param o object to be removed from this set, if present
-     * @return <tt>true</tt> if this set contained the specified element
-     * @throws ClassCastException if <tt>o</tt> cannot be compared
+     * @return {@code true} if this set contained the specified element
+     * @throws ClassCastException if {@code o} cannot be compared
      *         with the elements currently in this set
      * @throws NullPointerException if the specified element is null
      */
@@ -279,7 +289,7 @@
 
     /**
      * Compares the specified object with this set for equality.  Returns
-     * <tt>true</tt> if the specified object is also a set, the two sets
+     * {@code true} if the specified object is also a set, the two sets
      * have the same size, and every member of the specified set is
      * contained in this set (or equivalently, every member of this set is
      * contained in the specified set).  This definition ensures that the
@@ -287,7 +297,7 @@
      * set interface.
      *
      * @param o the object to be compared for equality with this set
-     * @return <tt>true</tt> if the specified object is equal to this set
+     * @return {@code true} if the specified object is equal to this set
      */
     public boolean equals(Object o) {
         // Override AbstractSet version to avoid calling size()
@@ -312,7 +322,7 @@
      * value is the <i>asymmetric set difference</i> of the two sets.
      *
      * @param  c collection containing elements to be removed from this set
-     * @return <tt>true</tt> if this set changed as a result of the call
+     * @return {@code true} if this set changed as a result of the call
      * @throws ClassCastException if the types of one or more elements in this
      *         set are incompatible with the specified collection
      * @throws NullPointerException if the specified collection or any
@@ -380,14 +390,14 @@
     }
 
     /**
-     * @throws NoSuchElementException {@inheritDoc}
+     * @throws java.util.NoSuchElementException {@inheritDoc}
      */
     public E first() {
         return m.firstKey();
     }
 
     /**
-     * @throws NoSuchElementException {@inheritDoc}
+     * @throws java.util.NoSuchElementException {@inheritDoc}
      */
     public E last() {
         return m.lastKey();
@@ -460,7 +470,7 @@
      * reflected in the descending set, and vice-versa.
      *
      * <p>The returned set has an ordering equivalent to
-     * <tt>{@link Collections#reverseOrder(Comparator) Collections.reverseOrder}(comparator())</tt>.
+     * {@link Collections#reverseOrder(Comparator) Collections.reverseOrder}{@code (comparator())}.
      * The expression {@code s.descendingSet().descendingSet()} returns a
      * view of {@code s} essentially equivalent to {@code s}.
      *
@@ -470,6 +480,14 @@
         return new ConcurrentSkipListSet<E>(m.descendingMap());
     }
 
+    @SuppressWarnings("unchecked")
+    public Spliterator<E> spliterator() {
+        if (m instanceof ConcurrentSkipListMap)
+            return ((ConcurrentSkipListMap<E,?>)m).keySpliterator();
+        else
+            return (Spliterator<E>)((ConcurrentSkipListMap.SubMap<E,?>)m).keyIterator();
+    }
+
     // Support for resetting map in clone
     private void setMap(ConcurrentNavigableMap<E,Object> map) {
         UNSAFE.putObjectVolatile(this, mapOffset, map);
--- a/src/share/classes/java/util/concurrent/CopyOnWriteArrayList.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/CopyOnWriteArrayList.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,4 @@
 /*
- * 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
@@ -34,7 +33,19 @@
  */
 
 package java.util.concurrent;
-import java.util.*;
+import java.util.AbstractList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.ConcurrentModificationException;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.RandomAccess;
+import java.util.Spliterator;
+import java.util.Spliterators;
 import java.util.concurrent.locks.ReentrantLock;
 import java.util.function.Consumer;
 import java.util.function.Predicate;
@@ -42,10 +53,10 @@
 
 /**
  * A thread-safe variant of {@link java.util.ArrayList} in which all mutative
- * operations (<tt>add</tt>, <tt>set</tt>, and so on) are implemented by
+ * operations ({@code add}, {@code set}, and so on) are implemented by
  * making a fresh copy of the underlying array.
  *
- * <p> This is ordinarily too costly, but may be <em>more</em> efficient
+ * <p>This is ordinarily too costly, but may be <em>more</em> efficient
  * than alternatives when traversal operations vastly outnumber
  * mutations, and is useful when you cannot or don't want to
  * synchronize traversals, yet need to preclude interference among
@@ -53,14 +64,14 @@
  * reference to the state of the array at the point that the iterator
  * was created. This array never changes during the lifetime of the
  * iterator, so interference is impossible and the iterator is
- * guaranteed not to throw <tt>ConcurrentModificationException</tt>.
+ * guaranteed not to throw {@code ConcurrentModificationException}.
  * The iterator will not reflect additions, removals, or changes to
  * the list since the iterator was created.  Element-changing
- * operations on iterators themselves (<tt>remove</tt>, <tt>set</tt>, and
- * <tt>add</tt>) are not supported. These methods throw
- * <tt>UnsupportedOperationException</tt>.
+ * operations on iterators themselves ({@code remove}, {@code set}, and
+ * {@code add}) are not supported. These methods throw
+ * {@code UnsupportedOperationException}.
  *
- * <p>All elements are permitted, including <tt>null</tt>.
+ * <p>All elements are permitted, including {@code null}.
  *
  * <p>Memory consistency effects: As with other concurrent
  * collections, actions in a thread prior to placing an object into a
@@ -82,10 +93,10 @@
     private static final long serialVersionUID = 8673264195747942595L;
 
     /** The lock protecting all mutators */
-    transient final ReentrantLock lock = new ReentrantLock();
+    final transient ReentrantLock lock = new ReentrantLock();
 
     /** The array, accessed only via getArray/setArray. */
-    private volatile transient Object[] array;
+    private transient volatile Object[] array;
 
     /**
      * Gets the array.  Non-private so as to also be accessible
@@ -118,10 +129,15 @@
      * @throws NullPointerException if the specified collection is null
      */
     public CopyOnWriteArrayList(Collection<? extends E> c) {
-        Object[] elements = c.toArray();
-        // c.toArray might (incorrectly) not return Object[] (see 6260652)
-        if (elements.getClass() != Object[].class)
-            elements = Arrays.copyOf(elements, elements.length, Object[].class);
+        Object[] elements;
+        if (c.getClass() == CopyOnWriteArrayList.class)
+            elements = ((CopyOnWriteArrayList<?>)c).getArray();
+        else {
+            elements = c.toArray();
+            // c.toArray might (incorrectly) not return Object[] (see 6260652)
+            if (elements.getClass() != Object[].class)
+                elements = Arrays.copyOf(elements, elements.length, Object[].class);
+        }
         setArray(elements);
     }
 
@@ -146,9 +162,9 @@
     }
 
     /**
-     * Returns <tt>true</tt> if this list contains no elements.
+     * Returns {@code true} if this list contains no elements.
      *
-     * @return <tt>true</tt> if this list contains no elements
+     * @return {@code true} if this list contains no elements
      */
     public boolean isEmpty() {
         return size() == 0;
@@ -158,7 +174,7 @@
      * Tests for equality, coping with nulls.
      */
     private static boolean eq(Object o1, Object o2) {
-        return (o1 == null ? o2 == null : o1.equals(o2));
+        return (o1 == null) ? o2 == null : o1.equals(o2);
     }
 
     /**
@@ -205,13 +221,13 @@
     }
 
     /**
-     * Returns <tt>true</tt> if this list contains the specified element.
-     * More formally, returns <tt>true</tt> if and only if this list contains
-     * at least one element <tt>e</tt> such that
+     * Returns {@code true} if this list contains the specified element.
+     * More formally, returns {@code true} if and only if this list contains
+     * at least one element {@code e} such that
      * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
      *
      * @param o element whose presence in this list is to be tested
-     * @return <tt>true</tt> if this list contains the specified element
+     * @return {@code true} if this list contains the specified element
      */
     public boolean contains(Object o) {
         Object[] elements = getArray();
@@ -228,17 +244,17 @@
 
     /**
      * Returns the index of the first occurrence of the specified element in
-     * this list, searching forwards from <tt>index</tt>, or returns -1 if
+     * this list, searching forwards from {@code index}, or returns -1 if
      * the element is not found.
-     * More formally, returns the lowest index <tt>i</tt> such that
+     * More formally, returns the lowest index {@code i} such that
      * <tt>(i&nbsp;&gt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(e==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;e.equals(get(i))))</tt>,
      * or -1 if there is no such index.
      *
      * @param e element to search for
      * @param index index to start searching from
      * @return the index of the first occurrence of the element in
-     *         this list at position <tt>index</tt> or later in the list;
-     *         <tt>-1</tt> if the element is not found.
+     *         this list at position {@code index} or later in the list;
+     *         {@code -1} if the element is not found.
      * @throws IndexOutOfBoundsException if the specified index is negative
      */
     public int indexOf(E e, int index) {
@@ -256,16 +272,16 @@
 
     /**
      * Returns the index of the last occurrence of the specified element in
-     * this list, searching backwards from <tt>index</tt>, or returns -1 if
+     * this list, searching backwards from {@code index}, or returns -1 if
      * the element is not found.
-     * More formally, returns the highest index <tt>i</tt> such that
+     * More formally, returns the highest index {@code i} such that
      * <tt>(i&nbsp;&lt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(e==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;e.equals(get(i))))</tt>,
      * or -1 if there is no such index.
      *
      * @param e element to search for
      * @param index index to start searching backwards from
      * @return the index of the last occurrence of the element at position
-     *         less than or equal to <tt>index</tt> in this list;
+     *         less than or equal to {@code index} in this list;
      *         -1 if the element is not found.
      * @throws IndexOutOfBoundsException if the specified index is greater
      *         than or equal to the current size of this list
@@ -323,7 +339,7 @@
      * <p>If this list fits in the specified array with room to spare
      * (i.e., the array has more elements than this list), the element in
      * the array immediately following the end of the list is set to
-     * <tt>null</tt>.  (This is useful in determining the length of this
+     * {@code null}.  (This is useful in determining the length of this
      * list <i>only</i> if the caller knows that this list does not contain
      * any null elements.)
      *
@@ -332,14 +348,14 @@
      * precise control over the runtime type of the output array, and may,
      * under certain circumstances, be used to save allocation costs.
      *
-     * <p>Suppose <tt>x</tt> is a list known to contain only strings.
+     * <p>Suppose {@code x} is a list known to contain only strings.
      * The following code can be used to dump the list into a newly
-     * allocated array of <tt>String</tt>:
+     * allocated array of {@code String}:
      *
      *  <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
      *
-     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
-     * <tt>toArray()</tt>.
+     * Note that {@code toArray(new Object[0])} is identical in function to
+     * {@code toArray()}.
      *
      * @param a the array into which the elements of the list are to
      *          be stored, if it is big enough; otherwise, a new array of the
@@ -412,7 +428,7 @@
      * Appends the specified element to the end of this list.
      *
      * @param e element to be appended to this list
-     * @return <tt>true</tt> (as specified by {@link Collection#add})
+     * @return {@code true} (as specified by {@link Collection#add})
      */
     public boolean add(E e) {
         final ReentrantLock lock = this.lock;
@@ -496,45 +512,54 @@
      * Removes the first occurrence of the specified element from this list,
      * if it is present.  If this list does not contain the element, it is
      * unchanged.  More formally, removes the element with the lowest index
-     * <tt>i</tt> such that
+     * {@code i} such that
      * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
-     * (if such an element exists).  Returns <tt>true</tt> if this list
+     * (if such an element exists).  Returns {@code true} if this list
      * contained the specified element (or equivalently, if this list
      * changed as a result of the call).
      *
      * @param o element to be removed from this list, if present
-     * @return <tt>true</tt> if this list contained the specified element
+     * @return {@code true} if this list contained the specified element
      */
     public boolean remove(Object o) {
+        Object[] snapshot = getArray();
+        int index = indexOf(o, snapshot, 0, snapshot.length);
+        return (index < 0) ? false : remove(o, snapshot, index);
+    }
+
+    /**
+     * A version of remove(Object) using the strong hint that given
+     * recent snapshot contains o at the given index.
+     */
+    private boolean remove(Object o, Object[] snapshot, int index) {
         final ReentrantLock lock = this.lock;
         lock.lock();
         try {
-            Object[] elements = getArray();
-            int len = elements.length;
-            if (len != 0) {
-                // Copy while searching for element to remove
-                // This wins in the normal case of element being present
-                int newlen = len - 1;
-                Object[] newElements = new Object[newlen];
-
-                for (int i = 0; i < newlen; ++i) {
-                    if (eq(o, elements[i])) {
-                        // found one;  copy remaining and exit
-                        for (int k = i + 1; k < len; ++k)
-                            newElements[k-1] = elements[k];
-                        setArray(newElements);
-                        return true;
-                    } else
-                        newElements[i] = elements[i];
+            Object[] current = getArray();
+            int len = current.length;
+            if (snapshot != current) findIndex: {
+                int prefix = Math.min(index, len);
+                for (int i = 0; i < prefix; i++) {
+                    if (current[i] != snapshot[i] && eq(o, current[i])) {
+                        index = i;
+                        break findIndex;
+                    }
                 }
-
-                // special handling for last cell
-                if (eq(o, elements[newlen])) {
-                    setArray(newElements);
-                    return true;
-                }
+                if (index >= len)
+                    return false;
+                if (current[index] == o)
+                    break findIndex;
+                index = indexOf(o, current, index, len);
+                if (index < 0)
+                    return false;
             }
-            return false;
+            Object[] newElements = new Object[len - 1];
+            System.arraycopy(current, 0, newElements, 0, index);
+            System.arraycopy(current, index + 1,
+                             newElements, index,
+                             len - index - 1);
+            setArray(newElements);
+            return true;
         } finally {
             lock.unlock();
         }
@@ -542,10 +567,10 @@
 
     /**
      * Removes from this list all of the elements whose index is between
-     * <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive.
+     * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
      * Shifts any succeeding elements to the left (reduces their index).
-     * This call shortens the list by <tt>(toIndex - fromIndex)</tt> elements.
-     * (If <tt>toIndex==fromIndex</tt>, this operation has no effect.)
+     * This call shortens the list by {@code (toIndex - fromIndex)} elements.
+     * (If {@code toIndex==fromIndex}, this operation has no effect.)
      *
      * @param fromIndex index of first element to be removed
      * @param toIndex index after last element to be removed
@@ -581,23 +606,34 @@
      * Appends the element, if not present.
      *
      * @param e element to be added to this list, if absent
-     * @return <tt>true</tt> if the element was added
+     * @return {@code true} if the element was added
      */
     public boolean addIfAbsent(E e) {
+        Object[] snapshot = getArray();
+        return indexOf(e, snapshot, 0, snapshot.length) >= 0 ? false :
+            addIfAbsent(e, snapshot);
+    }
+
+    /**
+     * A version of addIfAbsent using the strong hint that given
+     * recent snapshot does not contain e.
+     */
+    private boolean addIfAbsent(E e, Object[] snapshot) {
         final ReentrantLock lock = this.lock;
         lock.lock();
         try {
-            // Copy while checking if already present.
-            // This wins in the most common case where it is not present
-            Object[] elements = getArray();
-            int len = elements.length;
-            Object[] newElements = new Object[len + 1];
-            for (int i = 0; i < len; ++i) {
-                if (eq(e, elements[i]))
-                    return false; // exit, throwing away copy
-                else
-                    newElements[i] = elements[i];
+            Object[] current = getArray();
+            int len = current.length;
+            if (snapshot != current) {
+                // Optimize for lost race to another addXXX operation
+                int common = Math.min(snapshot.length, len);
+                for (int i = 0; i < common; i++)
+                    if (current[i] != snapshot[i] && eq(e, current[i]))
+                        return false;
+                if (indexOf(e, current, common, len) >= 0)
+                        return false;
             }
+            Object[] newElements = Arrays.copyOf(current, len + 1);
             newElements[len] = e;
             setArray(newElements);
             return true;
@@ -607,11 +643,11 @@
     }
 
     /**
-     * Returns <tt>true</tt> if this list contains all of the elements of the
+     * Returns {@code true} if this list contains all of the elements of the
      * specified collection.
      *
      * @param c collection to be checked for containment in this list
-     * @return <tt>true</tt> if this list contains all of the elements of the
+     * @return {@code true} if this list contains all of the elements of the
      *         specified collection
      * @throws NullPointerException if the specified collection is null
      * @see #contains(Object)
@@ -632,7 +668,7 @@
      * in this class because of the need for an internal temporary array.
      *
      * @param c collection containing elements to be removed from this list
-     * @return <tt>true</tt> if this list changed as a result of the call
+     * @return {@code true} if this list changed as a result of the call
      * @throws ClassCastException if the class of an element of this list
      *         is incompatible with the specified collection
      *         (<a href="../Collection.html#optional-restrictions">optional</a>)
@@ -675,7 +711,7 @@
      * its elements that are not contained in the specified collection.
      *
      * @param c collection containing elements to be retained in this list
-     * @return <tt>true</tt> if this list changed as a result of the call
+     * @return {@code true} if this list changed as a result of the call
      * @throws ClassCastException if the class of an element of this list
      *         is incompatible with the specified collection
      *         (<a href="../Collection.html#optional-restrictions">optional</a>)
@@ -727,22 +763,22 @@
         Object[] cs = c.toArray();
         if (cs.length == 0)
             return 0;
-        Object[] uniq = new Object[cs.length];
         final ReentrantLock lock = this.lock;
         lock.lock();
         try {
             Object[] elements = getArray();
             int len = elements.length;
             int added = 0;
-            for (int i = 0; i < cs.length; ++i) { // scan for duplicates
+            // uniquify and compact elements in cs
+            for (int i = 0; i < cs.length; ++i) {
                 Object e = cs[i];
                 if (indexOf(e, elements, 0, len) < 0 &&
-                    indexOf(e, uniq, 0, added) < 0)
-                    uniq[added++] = e;
+                    indexOf(e, cs, 0, added) < 0)
+                    cs[added++] = e;
             }
             if (added > 0) {
                 Object[] newElements = Arrays.copyOf(elements, len + added);
-                System.arraycopy(uniq, 0, newElements, len, added);
+                System.arraycopy(cs, 0, newElements, len, added);
                 setArray(newElements);
             }
             return added;
@@ -771,12 +807,13 @@
      * collection's iterator.
      *
      * @param c collection containing elements to be added to this list
-     * @return <tt>true</tt> if this list changed as a result of the call
+     * @return {@code true} if this list changed as a result of the call
      * @throws NullPointerException if the specified collection is null
      * @see #add(Object)
      */
     public boolean addAll(Collection<? extends E> c) {
-        Object[] cs = c.toArray();
+        Object[] cs = (c.getClass() == CopyOnWriteArrayList.class) ?
+            ((CopyOnWriteArrayList<?>)c).getArray() : c.toArray();
         if (cs.length == 0)
             return false;
         final ReentrantLock lock = this.lock;
@@ -784,9 +821,13 @@
         try {
             Object[] elements = getArray();
             int len = elements.length;
-            Object[] newElements = Arrays.copyOf(elements, len + cs.length);
-            System.arraycopy(cs, 0, newElements, len, cs.length);
-            setArray(newElements);
+            if (len == 0 && cs.getClass() == Object[].class)
+                setArray(cs);
+            else {
+                Object[] newElements = Arrays.copyOf(elements, len + cs.length);
+                System.arraycopy(cs, 0, newElements, len, cs.length);
+                setArray(newElements);
+            }
             return true;
         } finally {
             lock.unlock();
@@ -804,7 +845,7 @@
      * @param index index at which to insert the first element
      *        from the specified collection
      * @param c collection containing elements to be added to this list
-     * @return <tt>true</tt> if this list changed as a result of the call
+     * @return {@code true} if this list changed as a result of the call
      * @throws IndexOutOfBoundsException {@inheritDoc}
      * @throws NullPointerException if the specified collection is null
      * @see #add(int,Object)
@@ -840,6 +881,74 @@
         }
     }
 
+    public void forEach(Consumer<? super E> action) {
+        if (action == null) throw new NullPointerException();
+        Object[] elements = getArray();
+        int len = elements.length;
+        for (int i = 0; i < len; ++i) {
+            @SuppressWarnings("unchecked") E e = (E) elements[i];
+            action.accept(e);
+        }
+    }
+
+    public boolean removeIf(Predicate<? super E> filter) {
+        if (filter == null) throw new NullPointerException();
+        final ReentrantLock lock = this.lock;
+        lock.lock();
+        try {
+            Object[] elements = getArray();
+            int len = elements.length;
+            if (len != 0) {
+                int newlen = 0;
+                Object[] temp = new Object[len];
+                for (int i = 0; i < len; ++i) {
+                    @SuppressWarnings("unchecked") E e = (E) elements[i];
+                    if (!filter.test(e))
+                        temp[newlen++] = e;
+                }
+                if (newlen != len) {
+                    setArray(Arrays.copyOf(temp, newlen));
+                    return true;
+                }
+            }
+            return false;
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    public void replaceAll(UnaryOperator<E> operator) {
+        if (operator == null) throw new NullPointerException();
+        final ReentrantLock lock = this.lock;
+        lock.lock();
+        try {
+            Object[] elements = getArray();
+            int len = elements.length;
+            Object[] newElements = Arrays.copyOf(elements, len);
+            for (int i = 0; i < len; ++i) {
+                @SuppressWarnings("unchecked") E e = (E) elements[i];
+                newElements[i] = operator.apply(e);
+            }
+            setArray(newElements);
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    public void sort(Comparator<? super E> c) {
+        final ReentrantLock lock = this.lock;
+        lock.lock();
+        try {
+            Object[] elements = getArray();
+            Object[] newElements = Arrays.copyOf(elements, elements.length);
+            @SuppressWarnings("unchecked") E[] es = (E[])newElements;
+            Arrays.sort(es, c);
+            setArray(newElements);
+        } finally {
+            lock.unlock();
+        }
+    }
+
     /**
      * Saves this list to a stream (that is, serializes it).
      *
@@ -886,8 +995,8 @@
      * Returns a string representation of this list.  The string
      * representation consists of the string representations of the list's
      * elements in the order they are returned by its iterator, enclosed in
-     * square brackets (<tt>"[]"</tt>).  Adjacent elements are separated by
-     * the characters <tt>", "</tt> (comma and space).  Elements are
+     * square brackets ({@code "[]"}).  Adjacent elements are separated by
+     * the characters {@code ", "} (comma and space).  Elements are
      * converted to strings as by {@link String#valueOf(Object)}.
      *
      * @return a string representation of this list
@@ -953,7 +1062,7 @@
      * <p>The returned iterator provides a snapshot of the state of the list
      * when the iterator was constructed. No synchronization is needed while
      * traversing the iterator. The iterator does <em>NOT</em> support the
-     * <tt>remove</tt> method.
+     * {@code remove} method.
      *
      * @return an iterator over the elements in this list in proper sequence
      */
@@ -967,7 +1076,7 @@
      * <p>The returned iterator provides a snapshot of the state of the list
      * when the iterator was constructed. No synchronization is needed while
      * traversing the iterator. The iterator does <em>NOT</em> support the
-     * <tt>remove</tt>, <tt>set</tt> or <tt>add</tt> methods.
+     * {@code remove}, {@code set} or {@code add} methods.
      */
     public ListIterator<E> listIterator() {
         return new COWIterator<E>(getArray(), 0);
@@ -979,7 +1088,7 @@
      * <p>The returned iterator provides a snapshot of the state of the list
      * when the iterator was constructed. No synchronization is needed while
      * traversing the iterator. The iterator does <em>NOT</em> support the
-     * <tt>remove</tt>, <tt>set</tt> or <tt>add</tt> methods.
+     * {@code remove}, {@code set} or {@code add} methods.
      *
      * @throws IndexOutOfBoundsException {@inheritDoc}
      */
@@ -992,7 +1101,12 @@
         return new COWIterator<E>(elements, index);
     }
 
-    private static class COWIterator<E> implements ListIterator<E> {
+    public Spliterator<E> spliterator() {
+        return Spliterators.spliterator
+            (getArray(), Spliterator.IMMUTABLE | Spliterator.ORDERED);
+    }
+
+    static final class COWIterator<E> implements ListIterator<E> {
         /** Snapshot of the array */
         private final Object[] snapshot;
         /** Index of element to be returned by subsequent call to next.  */
@@ -1035,7 +1149,7 @@
 
         /**
          * Not supported. Always throws UnsupportedOperationException.
-         * @throws UnsupportedOperationException always; <tt>remove</tt>
+         * @throws UnsupportedOperationException always; {@code remove}
          *         is not supported by this iterator.
          */
         public void remove() {
@@ -1044,7 +1158,7 @@
 
         /**
          * Not supported. Always throws UnsupportedOperationException.
-         * @throws UnsupportedOperationException always; <tt>set</tt>
+         * @throws UnsupportedOperationException always; {@code set}
          *         is not supported by this iterator.
          */
         public void set(E e) {
@@ -1053,7 +1167,7 @@
 
         /**
          * Not supported. Always throws UnsupportedOperationException.
-         * @throws UnsupportedOperationException always; <tt>add</tt>
+         * @throws UnsupportedOperationException always; {@code add}
          *         is not supported by this iterator.
          */
         public void add(E e) {
@@ -1061,12 +1175,13 @@
         }
 
         @Override
-        @SuppressWarnings("unchecked")
         public void forEachRemaining(Consumer<? super E> action) {
             Objects.requireNonNull(action);
-            final int size = snapshot.length;
-            for (int i=cursor; i < size; i++) {
-                action.accept((E) snapshot[i]);
+            Object[] elements = snapshot;
+            final int size = elements.length;
+            for (int i = cursor; i < size; i++) {
+                @SuppressWarnings("unchecked") E e = (E) elements[i];
+                action.accept(e);
             }
             cursor = size;
         }
@@ -1074,7 +1189,7 @@
 
     /**
      * Returns a view of the portion of this list between
-     * <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive.
+     * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
      * The returned list is backed by this list, so changes in the
      * returned list are reflected in this list.
      *
@@ -1274,55 +1389,196 @@
             }
         }
 
-        @Override
         public void forEach(Consumer<? super E> action) {
-            @SuppressWarnings("unchecked")
-            final E[] elements = (E[]) l.getArray();
-            checkForComodification();
-            l.forEach(action, elements, offset, offset + size);
+            if (action == null) throw new NullPointerException();
+            int lo = offset;
+            int hi = offset + size;
+            Object[] a = expectedArray;
+            if (l.getArray() != a)
+                throw new ConcurrentModificationException();
+            if (lo < 0 || hi > a.length)
+                throw new IndexOutOfBoundsException();
+            for (int i = lo; i < hi; ++i) {
+                @SuppressWarnings("unchecked") E e = (E) a[i];
+                action.accept(e);
+            }
         }
 
-        @Override
+        public void replaceAll(UnaryOperator<E> operator) {
+            if (operator == null) throw new NullPointerException();
+            final ReentrantLock lock = l.lock;
+            lock.lock();
+            try {
+                int lo = offset;
+                int hi = offset + size;
+                Object[] elements = expectedArray;
+                if (l.getArray() != elements)
+                    throw new ConcurrentModificationException();
+                int len = elements.length;
+                if (lo < 0 || hi > len)
+                    throw new IndexOutOfBoundsException();
+                Object[] newElements = Arrays.copyOf(elements, len);
+                for (int i = lo; i < hi; ++i) {
+                    @SuppressWarnings("unchecked") E e = (E) elements[i];
+                    newElements[i] = operator.apply(e);
+                }
+                l.setArray(expectedArray = newElements);
+            } finally {
+                lock.unlock();
+            }
+        }
+
         public void sort(Comparator<? super E> c) {
             final ReentrantLock lock = l.lock;
             lock.lock();
             try {
-                checkForComodification();
-                l.sort(c, offset, offset + size);
-                expectedArray = l.getArray();
+                int lo = offset;
+                int hi = offset + size;
+                Object[] elements = expectedArray;
+                if (l.getArray() != elements)
+                    throw new ConcurrentModificationException();
+                int len = elements.length;
+                if (lo < 0 || hi > len)
+                    throw new IndexOutOfBoundsException();
+                Object[] newElements = Arrays.copyOf(elements, len);
+                @SuppressWarnings("unchecked") E[] es = (E[])newElements;
+                Arrays.sort(es, lo, hi, c);
+                l.setArray(expectedArray = newElements);
             } finally {
                 lock.unlock();
             }
         }
 
-        @Override
-        public boolean removeIf(Predicate<? super E> filter) {
-            Objects.requireNonNull(filter);
+        public boolean removeAll(Collection<?> c) {
+            if (c == null) throw new NullPointerException();
+            boolean removed = false;
+            final ReentrantLock lock = l.lock;
+            lock.lock();
+            try {
+                int n = size;
+                if (n > 0) {
+                    int lo = offset;
+                    int hi = offset + n;
+                    Object[] elements = expectedArray;
+                    if (l.getArray() != elements)
+                        throw new ConcurrentModificationException();
+                    int len = elements.length;
+                    if (lo < 0 || hi > len)
+                        throw new IndexOutOfBoundsException();
+                    int newSize = 0;
+                    Object[] temp = new Object[n];
+                    for (int i = lo; i < hi; ++i) {
+                        Object element = elements[i];
+                        if (!c.contains(element))
+                            temp[newSize++] = element;
+                    }
+                    if (newSize != n) {
+                        Object[] newElements = new Object[len - n + newSize];
+                        System.arraycopy(elements, 0, newElements, 0, lo);
+                        System.arraycopy(temp, 0, newElements, lo, newSize);
+                        System.arraycopy(elements, hi, newElements,
+                                         lo + newSize, len - hi);
+                        size = newSize;
+                        removed = true;
+                        l.setArray(expectedArray = newElements);
+                    }
+                }
+            } finally {
+                lock.unlock();
+            }
+            return removed;
+        }
+
+        public boolean retainAll(Collection<?> c) {
+            if (c == null) throw new NullPointerException();
+            boolean removed = false;
             final ReentrantLock lock = l.lock;
             lock.lock();
             try {
-                checkForComodification();
-                final int removeCount =
-                        l.removeIf(filter, offset, offset + size);
-                expectedArray = l.getArray();
-                size -= removeCount;
-                return removeCount > 0;
+                int n = size;
+                if (n > 0) {
+                    int lo = offset;
+                    int hi = offset + n;
+                    Object[] elements = expectedArray;
+                    if (l.getArray() != elements)
+                        throw new ConcurrentModificationException();
+                    int len = elements.length;
+                    if (lo < 0 || hi > len)
+                        throw new IndexOutOfBoundsException();
+                    int newSize = 0;
+                    Object[] temp = new Object[n];
+                    for (int i = lo; i < hi; ++i) {
+                        Object element = elements[i];
+                        if (c.contains(element))
+                            temp[newSize++] = element;
+                    }
+                    if (newSize != n) {
+                        Object[] newElements = new Object[len - n + newSize];
+                        System.arraycopy(elements, 0, newElements, 0, lo);
+                        System.arraycopy(temp, 0, newElements, lo, newSize);
+                        System.arraycopy(elements, hi, newElements,
+                                         lo + newSize, len - hi);
+                        size = newSize;
+                        removed = true;
+                        l.setArray(expectedArray = newElements);
+                    }
+                }
             } finally {
                 lock.unlock();
             }
+            return removed;
         }
 
-        @Override
-        public void replaceAll(UnaryOperator<E> operator) {
+        public boolean removeIf(Predicate<? super E> filter) {
+            if (filter == null) throw new NullPointerException();
+            boolean removed = false;
             final ReentrantLock lock = l.lock;
             lock.lock();
             try {
-                checkForComodification();
-                l.replaceAll(operator, offset, offset + size);
-                expectedArray = l.getArray();
+                int n = size;
+                if (n > 0) {
+                    int lo = offset;
+                    int hi = offset + n;
+                    Object[] elements = expectedArray;
+                    if (l.getArray() != elements)
+                        throw new ConcurrentModificationException();
+                    int len = elements.length;
+                    if (lo < 0 || hi > len)
+                        throw new IndexOutOfBoundsException();
+                    int newSize = 0;
+                    Object[] temp = new Object[n];
+                    for (int i = lo; i < hi; ++i) {
+                        @SuppressWarnings("unchecked") E e = (E) elements[i];
+                        if (!filter.test(e))
+                            temp[newSize++] = e;
+                    }
+                    if (newSize != n) {
+                        Object[] newElements = new Object[len - n + newSize];
+                        System.arraycopy(elements, 0, newElements, 0, lo);
+                        System.arraycopy(temp, 0, newElements, lo, newSize);
+                        System.arraycopy(elements, hi, newElements,
+                                         lo + newSize, len - hi);
+                        size = newSize;
+                        removed = true;
+                        l.setArray(expectedArray = newElements);
+                    }
+                }
             } finally {
                 lock.unlock();
             }
+            return removed;
+        }
+
+        public Spliterator<E> spliterator() {
+            int lo = offset;
+            int hi = offset + size;
+            Object[] a = expectedArray;
+            if (l.getArray() != a)
+                throw new ConcurrentModificationException();
+            if (lo < 0 || hi > a.length)
+                throw new IndexOutOfBoundsException();
+            return Spliterators.spliterator
+                (a, lo, hi, Spliterator.IMMUTABLE | Spliterator.ORDERED);
         }
     }
 
@@ -1380,11 +1636,12 @@
         }
 
         @Override
-        @SuppressWarnings("unchecked")
         public void forEachRemaining(Consumer<? super E> action) {
             Objects.requireNonNull(action);
-            while (nextIndex() < size) {
-                action.accept(it.next());
+            int s = size;
+            ListIterator<E> i = it;
+            while (nextIndex() < s) {
+                action.accept(i.next());
             }
         }
     }
@@ -1405,139 +1662,4 @@
             throw new Error(e);
         }
     }
-
-    @Override
-    @SuppressWarnings("unchecked")
-    public void forEach(Consumer<? super E> action) {
-        forEach(action, (E[]) getArray(), 0, size());
-    }
-
-    private void forEach(Consumer<? super E> action,
-                         final E[] elements,
-                         final int from, final int to) {
-        Objects.requireNonNull(action);
-        for (int i = from; i < to; i++) {
-            action.accept(elements[i]);
-        }
-    }
-
-    @Override
-    public void sort(Comparator<? super E> c) {
-        final ReentrantLock lock = this.lock;
-        lock.lock();
-        try {
-            sort(c, 0, size());
-        } finally {
-            lock.unlock();
-        }
-    }
-
-    // must be called with this.lock held
-    @SuppressWarnings("unchecked")
-    private void sort(Comparator<? super E> c, final int from, final int to) {
-        final E[] elements = (E[]) getArray();
-        final E[] newElements = Arrays.copyOf(elements, elements.length);
-        // only elements [from, to) are sorted
-        Arrays.sort(newElements, from, to, c);
-        setArray(newElements);
-    }
-
-    @Override
-    public boolean removeIf(Predicate<? super E> filter) {
-        Objects.requireNonNull(filter);
-        final ReentrantLock lock = this.lock;
-        lock.lock();
-        try {
-            return removeIf(filter, 0, size()) > 0;
-        } finally {
-            lock.unlock();
-        }
-    }
-
-    // must be called with this.lock held
-    private int removeIf(Predicate<? super E> filter, final int from, final int to) {
-        Objects.requireNonNull(filter);
-        final ReentrantLock lock = this.lock;
-        lock.lock();
-        try {
-            @SuppressWarnings("unchecked")
-            final E[] elements = (E[]) getArray();
-
-            // figure out which elements are to be removed
-            // any exception thrown from the filter predicate at this stage
-            // will leave the collection unmodified
-            int removeCount = 0;
-            final int range = to - from;
-            final BitSet removeSet = new BitSet(range);
-            for (int i = 0; i < range; i++) {
-                final E element = elements[from + i];
-                if (filter.test(element)) {
-                    // removeSet is zero-based to keep its size small
-                    removeSet.set(i);
-                    removeCount++;
-                }
-            }
-
-            // copy surviving elements into a new array
-            if (removeCount > 0) {
-                final int newSize = elements.length - removeCount;
-                final int newRange = newSize - from;
-                @SuppressWarnings("unchecked")
-                final E[] newElements = (E[]) new Object[newSize];
-                // copy elements before [from, to) unmodified
-                for (int i = 0; i < from; i++) {
-                    newElements[i] = elements[i];
-                }
-                // elements [from, to) are subject to removal
-                int j = 0;
-                for (int i = 0; (i < range) && (j < newRange); i++) {
-                    i = removeSet.nextClearBit(i);
-                    if (i >= range) {
-                        break;
-                    }
-                    newElements[from + (j++)] = elements[from + i];
-                }
-                // copy any remaining elements beyond [from, to)
-                j += from;
-                for (int i = to; (i < elements.length) && (j < newSize); i++) {
-                    newElements[j++] = elements[i];
-                }
-                setArray(newElements);
-            }
-
-            return removeCount;
-        } finally {
-            lock.unlock();
-        }
-    }
-
-    @Override
-    public void replaceAll(UnaryOperator<E> operator) {
-        Objects.requireNonNull(operator);
-        final ReentrantLock lock = this.lock;
-        lock.lock();
-        try {
-            replaceAll(operator, 0, size());
-        } finally {
-            lock.unlock();
-        }
-    }
-
-    // must be called with this.lock held
-    @SuppressWarnings("unchecked")
-    private void replaceAll(UnaryOperator<E> operator, final int from, final int to) {
-        final E[] elements = (E[]) getArray();
-        final E[] newElements = (E[]) new Object[elements.length];
-        for (int i = 0; i < from; i++) {
-            newElements[i] = elements[i];
-        }
-        // the operator is only applied to elements [from, to)
-        for (int i = from; i < to; i++) {
-            newElements[i] = operator.apply(elements[i]);
-        }
-        for (int i = to; i < elements.length; i++) {
-            newElements[i] = elements[i];
-        }
-        setArray(newElements);
-    }
 }
--- a/src/share/classes/java/util/concurrent/CopyOnWriteArraySet.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/CopyOnWriteArraySet.java	Mon Jul 22 17:37:15 2013 -0700
@@ -34,7 +34,14 @@
  */
 
 package java.util.concurrent;
-import java.util.*;
+import java.util.Collection;
+import java.util.Set;
+import java.util.AbstractSet;
+import java.util.Iterator;
+import java.util.Spliterator;
+import java.util.Spliterators;
+import java.util.function.Predicate;
+import java.util.function.Consumer;
 
 /**
  * A {@link java.util.Set} that uses an internal {@link CopyOnWriteArrayList}
@@ -45,17 +52,17 @@
  *       vastly outnumber mutative operations, and you need
  *       to prevent interference among threads during traversal.
  *  <li>It is thread-safe.
- *  <li>Mutative operations (<tt>add</tt>, <tt>set</tt>, <tt>remove</tt>, etc.)
+ *  <li>Mutative operations ({@code add}, {@code set}, {@code remove}, etc.)
  *      are expensive since they usually entail copying the entire underlying
  *      array.
- *  <li>Iterators do not support the mutative <tt>remove</tt> operation.
+ *  <li>Iterators do not support the mutative {@code remove} operation.
  *  <li>Traversal via iterators is fast and cannot encounter
  *      interference from other threads. Iterators rely on
  *      unchanging snapshots of the array at the time the iterators were
  *      constructed.
  * </ul>
  *
- * <p> <b>Sample Usage.</b> The following code sketch uses a
+ * <p><b>Sample Usage.</b> The following code sketch uses a
  * copy-on-write set to maintain a set of Handler objects that
  * perform some action upon state updates.
  *
@@ -73,7 +80,7 @@
  *   public void update() {
  *     changeState();
  *     for (Handler handler : handlers)
- *        handler.handle();
+ *       handler.handle();
  *   }
  * }}</pre>
  *
@@ -107,8 +114,15 @@
      * @throws NullPointerException if the specified collection is null
      */
     public CopyOnWriteArraySet(Collection<? extends E> c) {
-        al = new CopyOnWriteArrayList<E>();
-        al.addAllAbsent(c);
+        if (c.getClass() == CopyOnWriteArraySet.class) {
+            @SuppressWarnings("unchecked") CopyOnWriteArraySet<E> cc =
+                (CopyOnWriteArraySet<E>)c;
+            al = new CopyOnWriteArrayList<E>(cc.al);
+        }
+        else {
+            al = new CopyOnWriteArrayList<E>();
+            al.addAllAbsent(c);
+        }
     }
 
     /**
@@ -121,22 +135,22 @@
     }
 
     /**
-     * Returns <tt>true</tt> if this set contains no elements.
+     * Returns {@code true} if this set contains no elements.
      *
-     * @return <tt>true</tt> if this set contains no elements
+     * @return {@code true} if this set contains no elements
      */
     public boolean isEmpty() {
         return al.isEmpty();
     }
 
     /**
-     * Returns <tt>true</tt> if this set contains the specified element.
-     * More formally, returns <tt>true</tt> if and only if this set
-     * contains an element <tt>e</tt> such that
+     * Returns {@code true} if this set contains the specified element.
+     * More formally, returns {@code true} if and only if this set
+     * contains an element {@code e} such that
      * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
      *
      * @param o element whose presence in this set is to be tested
-     * @return <tt>true</tt> if this set contains the specified element
+     * @return {@code true} if this set contains the specified element
      */
     public boolean contains(Object o) {
         return al.contains(o);
@@ -172,7 +186,7 @@
      * <p>If this set fits in the specified array with room to spare
      * (i.e., the array has more elements than this set), the element in
      * the array immediately following the end of the set is set to
-     * <tt>null</tt>.  (This is useful in determining the length of this
+     * {@code null}.  (This is useful in determining the length of this
      * set <i>only</i> if the caller knows that this set does not contain
      * any null elements.)
      *
@@ -185,14 +199,14 @@
      * precise control over the runtime type of the output array, and may,
      * under certain circumstances, be used to save allocation costs.
      *
-     * <p>Suppose <tt>x</tt> is a set known to contain only strings.
+     * <p>Suppose {@code x} is a set known to contain only strings.
      * The following code can be used to dump the set into a newly allocated
-     * array of <tt>String</tt>:
+     * array of {@code String}:
      *
      *  <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
      *
-     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
-     * <tt>toArray()</tt>.
+     * Note that {@code toArray(new Object[0])} is identical in function to
+     * {@code toArray()}.
      *
      * @param a the array into which the elements of this set are to be
      *        stored, if it is big enough; otherwise, a new array of the same
@@ -217,15 +231,15 @@
 
     /**
      * Removes the specified element from this set if it is present.
-     * More formally, removes an element <tt>e</tt> such that
+     * More formally, removes an element {@code e} such that
      * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>,
-     * if this set contains such an element.  Returns <tt>true</tt> if
+     * if this set contains such an element.  Returns {@code true} if
      * this set contained the element (or equivalently, if this set
      * changed as a result of the call).  (This set will not contain the
      * element once the call returns.)
      *
      * @param o object to be removed from this set, if present
-     * @return <tt>true</tt> if this set contained the specified element
+     * @return {@code true} if this set contained the specified element
      */
     public boolean remove(Object o) {
         return al.remove(o);
@@ -233,14 +247,14 @@
 
     /**
      * Adds the specified element to this set if it is not already present.
-     * More formally, adds the specified element <tt>e</tt> to this set if
-     * the set contains no element <tt>e2</tt> such that
+     * More formally, adds the specified element {@code e} to this set if
+     * the set contains no element {@code e2} such that
      * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>.
      * If this set already contains the element, the call leaves the set
-     * unchanged and returns <tt>false</tt>.
+     * unchanged and returns {@code false}.
      *
      * @param e element to be added to this set
-     * @return <tt>true</tt> if this set did not already contain the specified
+     * @return {@code true} if this set did not already contain the specified
      *         element
      */
     public boolean add(E e) {
@@ -248,12 +262,12 @@
     }
 
     /**
-     * Returns <tt>true</tt> if this set contains all of the elements of the
+     * Returns {@code true} if this set contains all of the elements of the
      * specified collection.  If the specified collection is also a set, this
-     * method returns <tt>true</tt> if it is a <i>subset</i> of this set.
+     * method returns {@code true} if it is a <i>subset</i> of this set.
      *
      * @param  c collection to be checked for containment in this set
-     * @return <tt>true</tt> if this set contains all of the elements of the
+     * @return {@code true} if this set contains all of the elements of the
      *         specified collection
      * @throws NullPointerException if the specified collection is null
      * @see #contains(Object)
@@ -265,13 +279,13 @@
     /**
      * Adds all of the elements in the specified collection to this set if
      * they're not already present.  If the specified collection is also a
-     * set, the <tt>addAll</tt> operation effectively modifies this set so
+     * set, the {@code addAll} operation effectively modifies this set so
      * that its value is the <i>union</i> of the two sets.  The behavior of
      * this operation is undefined if the specified collection is modified
      * while the operation is in progress.
      *
      * @param  c collection containing elements to be added to this set
-     * @return <tt>true</tt> if this set changed as a result of the call
+     * @return {@code true} if this set changed as a result of the call
      * @throws NullPointerException if the specified collection is null
      * @see #add(Object)
      */
@@ -286,7 +300,7 @@
      * <i>asymmetric set difference</i> of the two sets.
      *
      * @param  c collection containing elements to be removed from this set
-     * @return <tt>true</tt> if this set changed as a result of the call
+     * @return {@code true} if this set changed as a result of the call
      * @throws ClassCastException if the class of an element of this set
      *         is incompatible with the specified collection (optional)
      * @throws NullPointerException if this set contains a null element and the
@@ -307,7 +321,7 @@
      * two sets.
      *
      * @param  c collection containing elements to be retained in this set
-     * @return <tt>true</tt> if this set changed as a result of the call
+     * @return {@code true} if this set changed as a result of the call
      * @throws ClassCastException if the class of an element of this set
      *         is incompatible with the specified collection (optional)
      * @throws NullPointerException if this set contains a null element and the
@@ -326,7 +340,7 @@
      * <p>The returned iterator provides a snapshot of the state of the set
      * when the iterator was constructed. No synchronization is needed while
      * traversing the iterator. The iterator does <em>NOT</em> support the
-     * <tt>remove</tt> method.
+     * {@code remove} method.
      *
      * @return an iterator over the elements in this set
      */
@@ -338,7 +352,7 @@
      * Compares the specified object with this set for equality.
      * Returns {@code true} if the specified object is the same object
      * as this object, or if it is also a {@link Set} and the elements
-     * returned by an {@linkplain List#iterator() iterator} over the
+     * returned by an {@linkplain Set#iterator() iterator} over the
      * specified set are the same as the elements returned by an
      * iterator over this set.  More formally, the two iterators are
      * considered to return the same elements if they return the same
@@ -382,6 +396,19 @@
         return k == len;
     }
 
+    public boolean removeIf(Predicate<? super E> filter) {
+        return al.removeIf(filter);
+    }
+
+    public void forEach(Consumer<? super E> action) {
+        al.forEach(action);
+    }
+
+    public Spliterator<E> spliterator() {
+        return Spliterators.spliterator
+            (al.getArray(), Spliterator.IMMUTABLE | Spliterator.DISTINCT);
+    }
+
     /**
      * Tests for equality, coping with nulls.
      */
--- a/src/share/classes/java/util/concurrent/CountDownLatch.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/CountDownLatch.java	Mon Jul 22 17:37:15 2013 -0700
@@ -92,15 +92,15 @@
  *   private final CountDownLatch startSignal;
  *   private final CountDownLatch doneSignal;
  *   Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
- *      this.startSignal = startSignal;
- *      this.doneSignal = doneSignal;
+ *     this.startSignal = startSignal;
+ *     this.doneSignal = doneSignal;
  *   }
  *   public void run() {
- *      try {
- *        startSignal.await();
- *        doWork();
- *        doneSignal.countDown();
- *      } catch (InterruptedException ex) {} // return;
+ *     try {
+ *       startSignal.await();
+ *       doWork();
+ *       doneSignal.countDown();
+ *     } catch (InterruptedException ex) {} // return;
  *   }
  *
  *   void doWork() { ... }
@@ -130,14 +130,14 @@
  *   private final CountDownLatch doneSignal;
  *   private final int i;
  *   WorkerRunnable(CountDownLatch doneSignal, int i) {
- *      this.doneSignal = doneSignal;
- *      this.i = i;
+ *     this.doneSignal = doneSignal;
+ *     this.i = i;
  *   }
  *   public void run() {
- *      try {
- *        doWork(i);
- *        doneSignal.countDown();
- *      } catch (InterruptedException ex) {} // return;
+ *     try {
+ *       doWork(i);
+ *       doneSignal.countDown();
+ *     } catch (InterruptedException ex) {} // return;
  *   }
  *
  *   void doWork() { ... }
--- a/src/share/classes/java/util/concurrent/CountedCompleter.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/CountedCompleter.java	Mon Jul 22 17:37:15 2013 -0700
@@ -37,14 +37,15 @@
 
 /**
  * A {@link ForkJoinTask} with a completion action performed when
- * triggered and there are no remaining pending
- * actions. CountedCompleters are in general more robust in the
+ * triggered and there are no remaining pending actions.
+ * CountedCompleters are in general more robust in the
  * presence of subtask stalls and blockage than are other forms of
  * ForkJoinTasks, but are less intuitive to program.  Uses of
  * CountedCompleter are similar to those of other completion based
  * components (such as {@link java.nio.channels.CompletionHandler})
  * except that multiple <em>pending</em> completions may be necessary
- * to trigger the completion action {@link #onCompletion}, not just one.
+ * to trigger the completion action {@link #onCompletion(CountedCompleter)},
+ * not just one.
  * Unless initialized otherwise, the {@linkplain #getPendingCount pending
  * count} starts at zero, but may be (atomically) changed using
  * methods {@link #setPendingCount}, {@link #addToPendingCount}, and
@@ -69,9 +70,10 @@
  * <p>A concrete CountedCompleter class must define method {@link
  * #compute}, that should in most cases (as illustrated below), invoke
  * {@code tryComplete()} once before returning. The class may also
- * optionally override method {@link #onCompletion} to perform an
- * action upon normal completion, and method {@link
- * #onExceptionalCompletion} to perform an action upon any exception.
+ * optionally override method {@link #onCompletion(CountedCompleter)}
+ * to perform an action upon normal completion, and method
+ * {@link #onExceptionalCompletion(Throwable, CountedCompleter)} to
+ * perform an action upon any exception.
  *
  * <p>CountedCompleters most often do not bear results, in which case
  * they are normally declared as {@code CountedCompleter<Void>}, and
@@ -92,13 +94,14 @@
  * only as an internal helper for other computations, so its own task
  * status (as reported in methods such as {@link ForkJoinTask#isDone})
  * is arbitrary; this status changes only upon explicit invocations of
- * {@link #complete}, {@link ForkJoinTask#cancel}, {@link
- * ForkJoinTask#completeExceptionally} or upon exceptional completion
- * of method {@code compute}. Upon any exceptional completion, the
- * exception may be relayed to a task's completer (and its completer,
- * and so on), if one exists and it has not otherwise already
- * completed. Similarly, cancelling an internal CountedCompleter has
- * only a local effect on that completer, so is not often useful.
+ * {@link #complete}, {@link ForkJoinTask#cancel},
+ * {@link ForkJoinTask#completeExceptionally(Throwable)} or upon
+ * exceptional completion of method {@code compute}. Upon any
+ * exceptional completion, the exception may be relayed to a task's
+ * completer (and its completer, and so on), if one exists and it has
+ * not otherwise already completed. Similarly, cancelling an internal
+ * CountedCompleter has only a local effect on that completer, so is
+ * not often useful.
  *
  * <p><b>Sample Usages.</b>
  *
@@ -125,8 +128,8 @@
  * improve load balancing. In the recursive case, the second of each
  * pair of subtasks to finish triggers completion of its parent
  * (because no result combination is performed, the default no-op
- * implementation of method {@code onCompletion} is not overridden). A
- * static utility method sets up the base task and invokes it
+ * implementation of method {@code onCompletion} is not overridden).
+ * A static utility method sets up the base task and invokes it
  * (here, implicitly using the {@link ForkJoinPool#commonPool()}).
  *
  * <pre> {@code
@@ -181,12 +184,11 @@
  *   }
  * }</pre>
  *
- * As a further improvement, notice that the left task need not even
- * exist.  Instead of creating a new one, we can iterate using the
- * original task, and add a pending count for each fork. Additionally,
- * because no task in this tree implements an {@link #onCompletion}
- * method, {@code tryComplete()} can be replaced with {@link
- * #propagateCompletion}.
+ * As a further improvement, notice that the left task need not even exist.
+ * Instead of creating a new one, we can iterate using the original task,
+ * and add a pending count for each fork.  Additionally, because no task
+ * in this tree implements an {@link #onCompletion(CountedCompleter)} method,
+ * {@code tryComplete()} can be replaced with {@link #propagateCompletion}.
  *
  * <pre> {@code
  * class ForEach<E> ...
@@ -253,7 +255,7 @@
  *   public static <E> E search(E[] array) {
  *       return new Searcher<E>(null, array, new AtomicReference<E>(), 0, array.length).invoke();
  *   }
- *}}</pre>
+ * }}</pre>
  *
  * In this example, as well as others in which tasks have no other
  * effects except to compareAndSet a common result, the trailing
@@ -264,7 +266,7 @@
  *
  * <p><b>Recording subtasks.</b> CountedCompleter tasks that combine
  * results of multiple subtasks usually need to access these results
- * in method {@link #onCompletion}. As illustrated in the following
+ * in method {@link #onCompletion(CountedCompleter)}. As illustrated in the following
  * class (that performs a simplified form of map-reduce where mappings
  * and reductions are all of type {@code E}), one way to do this in
  * divide and conquer designs is to have each subtask record its
@@ -365,7 +367,7 @@
  *     while (h - l >= 2) {
  *       int mid = (l + h) >>> 1;
  *       addToPendingCount(1);
- *       (forks = new MapReducer(this, array, mapper, reducer, mid, h, forks)).fork;
+ *       (forks = new MapReducer(this, array, mapper, reducer, mid, h, forks)).fork();
  *       h = mid;
  *     }
  *     if (h > l)
@@ -386,7 +388,7 @@
  *
  * <p><b>Triggers.</b> Some CountedCompleters are themselves never
  * forked, but instead serve as bits of plumbing in other designs;
- * including those in which the completion of one of more async tasks
+ * including those in which the completion of one or more async tasks
  * triggers another async task. For example:
  *
  * <pre> {@code
@@ -460,27 +462,28 @@
      * (and/or links to other results) to combine.
      *
      * @param caller the task invoking this method (which may
-     * be this task itself).
+     * be this task itself)
      */
     public void onCompletion(CountedCompleter<?> caller) {
     }
 
     /**
-     * Performs an action when method {@link #completeExceptionally}
-     * is invoked or method {@link #compute} throws an exception, and
-     * this task has not otherwise already completed normally. On
-     * entry to this method, this task {@link
-     * ForkJoinTask#isCompletedAbnormally}.  The return value of this
-     * method controls further propagation: If {@code true} and this
-     * task has a completer, then this completer is also completed
-     * exceptionally.  The default implementation of this method does
-     * nothing except return {@code true}.
+     * Performs an action when method {@link
+     * #completeExceptionally(Throwable)} is invoked or method {@link
+     * #compute} throws an exception, and this task has not already
+     * otherwise completed normally. On entry to this method, this task
+     * {@link ForkJoinTask#isCompletedAbnormally}.  The return value
+     * of this method controls further propagation: If {@code true}
+     * and this task has a completer that has not completed, then that
+     * completer is also completed exceptionally, with the same
+     * exception as this completer.  The default implementation of
+     * this method does nothing except return {@code true}.
      *
      * @param ex the exception
      * @param caller the task invoking this method (which may
-     * be this task itself).
-     * @return true if this exception should be propagated to this
-     * task's completer, if one exists.
+     * be this task itself)
+     * @return {@code true} if this exception should be propagated to this
+     * task's completer, if one exists
      */
     public boolean onExceptionalCompletion(Throwable ex, CountedCompleter<?> caller) {
         return true;
@@ -520,8 +523,7 @@
      * @param delta the value to add
      */
     public final void addToPendingCount(int delta) {
-        int c; // note: can replace with intrinsic in jdk8
-        do {} while (!U.compareAndSwapInt(this, PENDING, c = pending, c+delta));
+        U.getAndAddInt(this, PENDING, delta);
     }
 
     /**
@@ -530,7 +532,7 @@
      *
      * @param expected the expected value
      * @param count the new value
-     * @return true if successful
+     * @return {@code true} if successful
      */
     public final boolean compareAndSetPendingCount(int expected, int count) {
         return U.compareAndSwapInt(this, PENDING, expected, count);
@@ -564,9 +566,9 @@
 
     /**
      * If the pending count is nonzero, decrements the count;
-     * otherwise invokes {@link #onCompletion} and then similarly
-     * tries to complete this task's completer, if one exists,
-     * else marks this task as complete.
+     * otherwise invokes {@link #onCompletion(CountedCompleter)}
+     * and then similarly tries to complete this task's completer,
+     * if one exists, else marks this task as complete.
      */
     public final void tryComplete() {
         CountedCompleter<?> a = this, s = a;
@@ -585,12 +587,12 @@
 
     /**
      * Equivalent to {@link #tryComplete} but does not invoke {@link
-     * #onCompletion} along the completion path: If the pending count
-     * is nonzero, decrements the count; otherwise, similarly tries to
-     * complete this task's completer, if one exists, else marks this
-     * task as complete. This method may be useful in cases where
-     * {@code onCompletion} should not, or need not, be invoked for
-     * each completer in a computation.
+     * #onCompletion(CountedCompleter)} along the completion path:
+     * If the pending count is nonzero, decrements the count;
+     * otherwise, similarly tries to complete this task's completer, if
+     * one exists, else marks this task as complete. This method may be
+     * useful in cases where {@code onCompletion} should not, or need
+     * not, be invoked for each completer in a computation.
      */
     public final void propagateCompletion() {
         CountedCompleter<?> a = this, s = a;
@@ -607,13 +609,15 @@
     }
 
     /**
-     * Regardless of pending count, invokes {@link #onCompletion},
-     * marks this task as complete and further triggers {@link
-     * #tryComplete} on this task's completer, if one exists.  The
-     * given rawResult is used as an argument to {@link #setRawResult}
-     * before invoking {@link #onCompletion} or marking this task as
-     * complete; its value is meaningful only for classes overriding
-     * {@code setRawResult}.
+     * Regardless of pending count, invokes
+     * {@link #onCompletion(CountedCompleter)}, marks this task as
+     * complete and further triggers {@link #tryComplete} on this
+     * task's completer, if one exists.  The given rawResult is
+     * used as an argument to {@link #setRawResult} before invoking
+     * {@link #onCompletion(CountedCompleter)} or marking this task
+     * as complete; its value is meaningful only for classes
+     * overriding {@code setRawResult}.  This method does not modify
+     * the pending count.
      *
      * <p>This method may be useful when forcing completion as soon as
      * any one (versus all) of several subtask results are obtained.
@@ -632,7 +636,6 @@
             p.tryComplete();
     }
 
-
     /**
      * If this task's pending count is zero, returns this task;
      * otherwise decrements its pending count and returns {@code
@@ -653,8 +656,8 @@
     /**
      * If this task does not have a completer, invokes {@link
      * ForkJoinTask#quietlyComplete} and returns {@code null}.  Or, if
-     * this task's pending count is non-zero, decrements its pending
-     * count and returns {@code null}.  Otherwise, returns the
+     * the completer's pending count is non-zero, decrements that
+     * pending count and returns {@code null}.  Otherwise, returns the
      * completer.  This method can be used as part of a completion
      * traversal loop for homogeneous task hierarchies:
      *
@@ -691,13 +694,34 @@
     }
 
     /**
+     * If this task has not completed, attempts to process at most the
+     * given number of other unprocessed tasks for which this task is
+     * on the completion path, if any are known to exist.
+     *
+     * @param maxTasks the maximum number of tasks to process.  If
+     *                 less than or equal to zero, then no tasks are
+     *                 processed.
+     */
+    public final void helpComplete(int maxTasks) {
+        Thread t; ForkJoinWorkerThread wt;
+        if (maxTasks > 0 && status >= 0) {
+            if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
+                (wt = (ForkJoinWorkerThread)t).pool.
+                    helpComplete(wt.workQueue, this, maxTasks);
+            else
+                ForkJoinPool.common.externalHelpComplete(this, maxTasks);
+        }
+    }
+
+    /**
      * Supports ForkJoinTask exception propagation.
      */
     void internalPropagateException(Throwable ex) {
         CountedCompleter<?> a = this, s = a;
         while (a.onExceptionalCompletion(ex, s) &&
-               (a = (s = a).completer) != null && a.status >= 0)
-            a.recordExceptionalCompletion(ex);
+               (a = (s = a).completer) != null && a.status >= 0 &&
+               a.recordExceptionalCompletion(ex) == EXCEPTIONAL)
+            ;
     }
 
     /**
--- a/src/share/classes/java/util/concurrent/CyclicBarrier.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/CyclicBarrier.java	Mon Jul 22 17:37:15 2013 -0700
@@ -45,14 +45,14 @@
  * <em>cyclic</em> because it can be re-used after the waiting threads
  * are released.
  *
- * <p>A <tt>CyclicBarrier</tt> supports an optional {@link Runnable} command
+ * <p>A {@code CyclicBarrier} supports an optional {@link Runnable} command
  * that is run once per barrier point, after the last thread in the party
  * arrives, but before any threads are released.
  * This <em>barrier action</em> is useful
  * for updating shared-state before any of the parties continue.
  *
- * <p><b>Sample usage:</b> Here is an example of
- *  using a barrier in a parallel decomposition design:
+ * <p><b>Sample usage:</b> Here is an example of using a barrier in a
+ * parallel decomposition design:
  *
  *  <pre> {@code
  * class Solver {
@@ -81,16 +81,20 @@
  *   public Solver(float[][] matrix) {
  *     data = matrix;
  *     N = matrix.length;
- *     barrier = new CyclicBarrier(N,
- *                                 new Runnable() {
- *                                   public void run() {
- *                                     mergeRows(...);
- *                                   }
- *                                 });
- *     for (int i = 0; i < N; ++i)
- *       new Thread(new Worker(i)).start();
+ *     Runnable barrierAction =
+ *       new Runnable() { public void run() { mergeRows(...); }};
+ *     barrier = new CyclicBarrier(N, barrierAction);
  *
- *     waitUntilDone();
+ *     List<Thread> threads = new ArrayList<Thread>(N);
+ *     for (int i = 0; i < N; i++) {
+ *       Thread thread = new Thread(new Worker(i));
+ *       threads.add(thread);
+ *       thread.start();
+ *     }
+ *
+ *     // wait until done
+ *     for (Thread thread : threads)
+ *       thread.join();
  *   }
  * }}</pre>
  *
@@ -98,8 +102,8 @@
  * barrier until all rows have been processed. When all rows are processed
  * the supplied {@link Runnable} barrier action is executed and merges the
  * rows. If the merger
- * determines that a solution has been found then <tt>done()</tt> will return
- * <tt>true</tt> and each worker will terminate.
+ * determines that a solution has been found then {@code done()} will return
+ * {@code true} and each worker will terminate.
  *
  * <p>If the barrier action does not rely on the parties being suspended when
  * it is executed, then any of the threads in the party could execute that
@@ -112,7 +116,7 @@
  *   // log the completion of this iteration
  * }}</pre>
  *
- * <p>The <tt>CyclicBarrier</tt> uses an all-or-none breakage model
+ * <p>The {@code CyclicBarrier} uses an all-or-none breakage model
  * for failed synchronization attempts: If a thread leaves a barrier
  * point prematurely because of interruption, failure, or timeout, all
  * other threads waiting at that barrier point will also leave
@@ -139,7 +143,7 @@
      * is reset. There can be many generations associated with threads
      * using the barrier - due to the non-deterministic way the lock
      * may be allocated to waiting threads - but only one of these
-     * can be active at a time (the one to which <tt>count</tt> applies)
+     * can be active at a time (the one to which {@code count} applies)
      * and all the rest are either broken or tripped.
      * There need not be an active generation if there has been a break
      * but no subsequent reset.
@@ -259,7 +263,7 @@
     }
 
     /**
-     * Creates a new <tt>CyclicBarrier</tt> that will trip when the
+     * Creates a new {@code CyclicBarrier} that will trip when the
      * given number of parties (threads) are waiting upon it, and which
      * will execute the given barrier action when the barrier is tripped,
      * performed by the last thread entering the barrier.
@@ -278,7 +282,7 @@
     }
 
     /**
-     * Creates a new <tt>CyclicBarrier</tt> that will trip when the
+     * Creates a new {@code CyclicBarrier} that will trip when the
      * given number of parties (threads) are waiting upon it, and
      * does not perform a predefined action when the barrier is tripped.
      *
@@ -301,7 +305,7 @@
 
     /**
      * Waits until all {@linkplain #getParties parties} have invoked
-     * <tt>await</tt> on this barrier.
+     * {@code await} on this barrier.
      *
      * <p>If the current thread is not the last to arrive then it is
      * disabled for thread scheduling purposes and lies dormant until
@@ -326,7 +330,7 @@
      *
      * <p>If the barrier is {@link #reset} while any thread is waiting,
      * or if the barrier {@linkplain #isBroken is broken} when
-     * <tt>await</tt> is invoked, or while any thread is waiting, then
+     * {@code await} is invoked, or while any thread is waiting, then
      * {@link BrokenBarrierException} is thrown.
      *
      * <p>If any thread is {@linkplain Thread#interrupt interrupted} while waiting,
@@ -343,7 +347,7 @@
      * the broken state.
      *
      * @return the arrival index of the current thread, where index
-     *         <tt>{@link #getParties()} - 1</tt> indicates the first
+     *         {@code getParties() - 1} indicates the first
      *         to arrive and zero indicates the last to arrive
      * @throws InterruptedException if the current thread was interrupted
      *         while waiting
@@ -351,7 +355,7 @@
      *         interrupted or timed out while the current thread was
      *         waiting, or the barrier was reset, or the barrier was
      *         broken when {@code await} was called, or the barrier
-     *         action (if present) failed due an exception.
+     *         action (if present) failed due to an exception
      */
     public int await() throws InterruptedException, BrokenBarrierException {
         try {
@@ -363,7 +367,7 @@
 
     /**
      * Waits until all {@linkplain #getParties parties} have invoked
-     * <tt>await</tt> on this barrier, or the specified waiting time elapses.
+     * {@code await} on this barrier, or the specified waiting time elapses.
      *
      * <p>If the current thread is not the last to arrive then it is
      * disabled for thread scheduling purposes and lies dormant until
@@ -393,7 +397,7 @@
      *
      * <p>If the barrier is {@link #reset} while any thread is waiting,
      * or if the barrier {@linkplain #isBroken is broken} when
-     * <tt>await</tt> is invoked, or while any thread is waiting, then
+     * {@code await} is invoked, or while any thread is waiting, then
      * {@link BrokenBarrierException} is thrown.
      *
      * <p>If any thread is {@linkplain Thread#interrupt interrupted} while
@@ -412,16 +416,17 @@
      * @param timeout the time to wait for the barrier
      * @param unit the time unit of the timeout parameter
      * @return the arrival index of the current thread, where index
-     *         <tt>{@link #getParties()} - 1</tt> indicates the first
+     *         {@code getParties() - 1} indicates the first
      *         to arrive and zero indicates the last to arrive
      * @throws InterruptedException if the current thread was interrupted
      *         while waiting
-     * @throws TimeoutException if the specified timeout elapses
+     * @throws TimeoutException if the specified timeout elapses.
+     *         In this case the barrier will be broken.
      * @throws BrokenBarrierException if <em>another</em> thread was
      *         interrupted or timed out while the current thread was
      *         waiting, or the barrier was reset, or the barrier was broken
      *         when {@code await} was called, or the barrier action (if
-     *         present) failed due an exception
+     *         present) failed due to an exception
      */
     public int await(long timeout, TimeUnit unit)
         throws InterruptedException,
--- a/src/share/classes/java/util/concurrent/DelayQueue.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/DelayQueue.java	Mon Jul 22 17:37:15 2013 -0700
@@ -33,28 +33,31 @@
  * http://creativecommons.org/publicdomain/zero/1.0/
  */
 
-
 package java.util.concurrent;
-import java.util.concurrent.locks.*;
+import static java.util.concurrent.TimeUnit.NANOSECONDS;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.ReentrantLock;
 import java.util.*;
 
 /**
  * An unbounded {@linkplain BlockingQueue blocking queue} of
- * <tt>Delayed</tt> elements, in which an element can only be taken
+ * {@code Delayed} elements, in which an element can only be taken
  * when its delay has expired.  The <em>head</em> of the queue is that
- * <tt>Delayed</tt> element whose delay expired furthest in the
- * past.  If no delay has expired there is no head and <tt>poll</tt>
- * will return <tt>null</tt>. Expiration occurs when an element's
- * <tt>getDelay(TimeUnit.NANOSECONDS)</tt> method returns a value less
+ * {@code Delayed} element whose delay expired furthest in the
+ * past.  If no delay has expired there is no head and {@code poll}
+ * will return {@code null}. Expiration occurs when an element's
+ * {@code getDelay(TimeUnit.NANOSECONDS)} method returns a value less
  * than or equal to zero.  Even though unexpired elements cannot be
- * removed using <tt>take</tt> or <tt>poll</tt>, they are otherwise
- * treated as normal elements. For example, the <tt>size</tt> method
+ * removed using {@code take} or {@code poll}, they are otherwise
+ * treated as normal elements. For example, the {@code size} method
  * returns the count of both expired and unexpired elements.
  * This queue does not permit null elements.
  *
  * <p>This class and its iterator implement all of the
  * <em>optional</em> methods of the {@link Collection} and {@link
- * Iterator} interfaces.
+ * Iterator} interfaces.  The Iterator provided in method {@link
+ * #iterator()} is <em>not</em> guaranteed to traverse the elements of
+ * the DelayQueue in any particular order.
  *
  * <p>This class is a member of the
  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
@@ -64,11 +67,10 @@
  * @author Doug Lea
  * @param <E> the type of elements held in this collection
  */
-
 public class DelayQueue<E extends Delayed> extends AbstractQueue<E>
     implements BlockingQueue<E> {
 
-    private transient final ReentrantLock lock = new ReentrantLock();
+    private final transient ReentrantLock lock = new ReentrantLock();
     private final PriorityQueue<E> q = new PriorityQueue<E>();
 
     /**
@@ -97,12 +99,12 @@
     private final Condition available = lock.newCondition();
 
     /**
-     * Creates a new <tt>DelayQueue</tt> that is initially empty.
+     * Creates a new {@code DelayQueue} that is initially empty.
      */
     public DelayQueue() {}
 
     /**
-     * Creates a <tt>DelayQueue</tt> initially containing the elements of the
+     * Creates a {@code DelayQueue} initially containing the elements of the
      * given collection of {@link Delayed} instances.
      *
      * @param c the collection of elements to initially contain
@@ -117,7 +119,7 @@
      * Inserts the specified element into this delay queue.
      *
      * @param e the element to add
-     * @return <tt>true</tt> (as specified by {@link Collection#add})
+     * @return {@code true} (as specified by {@link Collection#add})
      * @throws NullPointerException if the specified element is null
      */
     public boolean add(E e) {
@@ -128,7 +130,7 @@
      * Inserts the specified element into this delay queue.
      *
      * @param e the element to add
-     * @return <tt>true</tt>
+     * @return {@code true}
      * @throws NullPointerException if the specified element is null
      */
     public boolean offer(E e) {
@@ -164,7 +166,7 @@
      * @param e the element to add
      * @param timeout This parameter is ignored as the method never blocks
      * @param unit This parameter is ignored as the method never blocks
-     * @return <tt>true</tt>
+     * @return {@code true}
      * @throws NullPointerException {@inheritDoc}
      */
     public boolean offer(E e, long timeout, TimeUnit unit) {
@@ -172,10 +174,10 @@
     }
 
     /**
-     * Retrieves and removes the head of this queue, or returns <tt>null</tt>
+     * Retrieves and removes the head of this queue, or returns {@code null}
      * if this queue has no elements with an expired delay.
      *
-     * @return the head of this queue, or <tt>null</tt> if this
+     * @return the head of this queue, or {@code null} if this
      *         queue has no elements with an expired delay
      */
     public E poll() {
@@ -183,7 +185,7 @@
         lock.lock();
         try {
             E first = q.peek();
-            if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
+            if (first == null || first.getDelay(NANOSECONDS) > 0)
                 return null;
             else
                 return q.poll();
@@ -208,10 +210,11 @@
                 if (first == null)
                     available.await();
                 else {
-                    long delay = first.getDelay(TimeUnit.NANOSECONDS);
+                    long delay = first.getDelay(NANOSECONDS);
                     if (delay <= 0)
                         return q.poll();
-                    else if (leader != null)
+                    first = null; // don't retain ref while waiting
+                    if (leader != null)
                         available.await();
                     else {
                         Thread thisThread = Thread.currentThread();
@@ -237,7 +240,7 @@
      * until an element with an expired delay is available on this queue,
      * or the specified wait time expires.
      *
-     * @return the head of this queue, or <tt>null</tt> if the
+     * @return the head of this queue, or {@code null} if the
      *         specified waiting time elapses before an element with
      *         an expired delay becomes available
      * @throws InterruptedException {@inheritDoc}
@@ -255,11 +258,12 @@
                     else
                         nanos = available.awaitNanos(nanos);
                 } else {
-                    long delay = first.getDelay(TimeUnit.NANOSECONDS);
+                    long delay = first.getDelay(NANOSECONDS);
                     if (delay <= 0)
                         return q.poll();
                     if (nanos <= 0)
                         return null;
+                    first = null; // don't retain ref while waiting
                     if (nanos < delay || leader != null)
                         nanos = available.awaitNanos(nanos);
                     else {
@@ -284,13 +288,13 @@
 
     /**
      * Retrieves, but does not remove, the head of this queue, or
-     * returns <tt>null</tt> if this queue is empty.  Unlike
-     * <tt>poll</tt>, if no expired elements are available in the queue,
+     * returns {@code null} if this queue is empty.  Unlike
+     * {@code poll}, if no expired elements are available in the queue,
      * this method returns the element that will expire next,
      * if one exists.
      *
-     * @return the head of this queue, or <tt>null</tt> if this
-     *         queue is empty.
+     * @return the head of this queue, or {@code null} if this
+     *         queue is empty
      */
     public E peek() {
         final ReentrantLock lock = this.lock;
@@ -313,6 +317,17 @@
     }
 
     /**
+     * Returns first element only if it is expired.
+     * Used only by drainTo.  Call only when holding lock.
+     */
+    private E peekExpired() {
+        // assert lock.isHeldByCurrentThread();
+        E first = q.peek();
+        return (first == null || first.getDelay(NANOSECONDS) > 0) ?
+            null : first;
+    }
+
+    /**
      * @throws UnsupportedOperationException {@inheritDoc}
      * @throws ClassCastException            {@inheritDoc}
      * @throws NullPointerException          {@inheritDoc}
@@ -327,11 +342,9 @@
         lock.lock();
         try {
             int n = 0;
-            for (;;) {
-                E first = q.peek();
-                if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
-                    break;
-                c.add(q.poll());
+            for (E e; (e = peekExpired()) != null;) {
+                c.add(e);       // In this order, in case add() throws.
+                q.poll();
                 ++n;
             }
             return n;
@@ -357,11 +370,9 @@
         lock.lock();
         try {
             int n = 0;
-            while (n < maxElements) {
-                E first = q.peek();
-                if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
-                    break;
-                c.add(q.poll());
+            for (E e; n < maxElements && (e = peekExpired()) != null;) {
+                c.add(e);       // In this order, in case add() throws.
+                q.poll();
                 ++n;
             }
             return n;
@@ -387,10 +398,10 @@
     }
 
     /**
-     * Always returns <tt>Integer.MAX_VALUE</tt> because
-     * a <tt>DelayQueue</tt> is not capacity constrained.
+     * Always returns {@code Integer.MAX_VALUE} because
+     * a {@code DelayQueue} is not capacity constrained.
      *
-     * @return <tt>Integer.MAX_VALUE</tt>
+     * @return {@code Integer.MAX_VALUE}
      */
     public int remainingCapacity() {
         return Integer.MAX_VALUE;
@@ -430,7 +441,7 @@
      * <p>If this queue fits in the specified array with room to spare
      * (i.e., the array has more elements than this queue), the element in
      * the array immediately following the end of the queue is set to
-     * <tt>null</tt>.
+     * {@code null}.
      *
      * <p>Like the {@link #toArray()} method, this method acts as bridge between
      * array-based and collection-based APIs.  Further, this method allows
@@ -438,13 +449,12 @@
      * under certain circumstances, be used to save allocation costs.
      *
      * <p>The following code can be used to dump a delay queue into a newly
-     * allocated array of <tt>Delayed</tt>:
+     * allocated array of {@code Delayed}:
      *
-     * <pre>
-     *     Delayed[] a = q.toArray(new Delayed[0]);</pre>
+     * <pre> {@code Delayed[] a = q.toArray(new Delayed[0]);}</pre>
      *
-     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
-     * <tt>toArray()</tt>.
+     * Note that {@code toArray(new Object[0])} is identical in function to
+     * {@code toArray()}.
      *
      * @param a the array into which the elements of the queue are to
      *          be stored, if it is big enough; otherwise, a new array of the
@@ -480,6 +490,24 @@
     }
 
     /**
+     * Identity-based version for use in Itr.remove
+     */
+    void removeEQ(Object o) {
+        final ReentrantLock lock = this.lock;
+        lock.lock();
+        try {
+            for (Iterator<E> it = q.iterator(); it.hasNext(); ) {
+                if (o == it.next()) {
+                    it.remove();
+                    break;
+                }
+            }
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    /**
      * Returns an iterator over all the elements (both expired and
      * unexpired) in this queue. The iterator does not return the
      * elements in any particular order.
@@ -502,7 +530,7 @@
      */
     private class Itr implements Iterator<E> {
         final Object[] array; // Array of all elements
-        int cursor;           // index of next element to return;
+        int cursor;           // index of next element to return
         int lastRet;          // index of last element, or -1 if no such
 
         Itr(Object[] array) {
@@ -525,21 +553,8 @@
         public void remove() {
             if (lastRet < 0)
                 throw new IllegalStateException();
-            Object x = array[lastRet];
+            removeEQ(array[lastRet]);
             lastRet = -1;
-            // Traverse underlying queue to find == element,
-            // not just a .equals element.
-            lock.lock();
-            try {
-                for (Iterator<E> it = q.iterator(); it.hasNext(); ) {
-                    if (it.next() == x) {
-                        it.remove();
-                        return;
-                    }
-                }
-            } finally {
-                lock.unlock();
-            }
         }
     }
 
--- a/src/share/classes/java/util/concurrent/Delayed.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/Delayed.java	Mon Jul 22 17:37:15 2013 -0700
@@ -40,8 +40,8 @@
  * acted upon after a given delay.
  *
  * <p>An implementation of this interface must define a
- * <tt>compareTo</tt> method that provides an ordering consistent with
- * its <tt>getDelay</tt> method.
+ * {@code compareTo} method that provides an ordering consistent with
+ * its {@code getDelay} method.
  *
  * @since 1.5
  * @author Doug Lea
--- a/src/share/classes/java/util/concurrent/Exchanger.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/Exchanger.java	Mon Jul 22 17:37:15 2013 -0700
@@ -35,7 +35,8 @@
  */
 
 package java.util.concurrent;
-import java.util.concurrent.atomic.*;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
 import java.util.concurrent.locks.LockSupport;
 
 /**
@@ -52,7 +53,7 @@
  * to swap buffers between threads so that the thread filling the
  * buffer gets a freshly emptied one when it needs it, handing off the
  * filled one to the thread emptying the buffer.
- * <pre>{@code
+ *  <pre> {@code
  * class FillAndEmpty {
  *   Exchanger<DataBuffer> exchanger = new Exchanger<DataBuffer>();
  *   DataBuffer initialEmptyBuffer = ... a made-up type
@@ -88,8 +89,7 @@
  *     new Thread(new FillingLoop()).start();
  *     new Thread(new EmptyingLoop()).start();
  *   }
- * }
- * }</pre>
+ * }}</pre>
  *
  * <p>Memory consistency effects: For each pair of threads that
  * successfully exchange objects via an {@code Exchanger}, actions
@@ -103,486 +103,425 @@
  * @param <V> The type of objects that may be exchanged
  */
 public class Exchanger<V> {
+
     /*
-     * Algorithm Description:
+     * Overview: The core algorithm is, for an exchange "slot",
+     * and a participant (caller) with an item:
      *
-     * The basic idea is to maintain a "slot", which is a reference to
-     * a Node containing both an Item to offer and a "hole" waiting to
-     * get filled in.  If an incoming "occupying" thread sees that the
-     * slot is null, it CAS'es (compareAndSets) a Node there and waits
-     * for another to invoke exchange.  That second "fulfilling" thread
-     * sees that the slot is non-null, and so CASes it back to null,
-     * also exchanging items by CASing the hole, plus waking up the
-     * occupying thread if it is blocked.  In each case CAS'es may
-     * fail because a slot at first appears non-null but is null upon
-     * CAS, or vice-versa.  So threads may need to retry these
-     * actions.
+     * for (;;) {
+     *   if (slot is empty) {                       // offer
+     *     place item in a Node;
+     *     if (can CAS slot from empty to node) {
+     *       wait for release;
+     *       return matching item in node;
+     *     }
+     *   }
+     *   else if (can CAS slot from node to empty) { // release
+     *     get the item in node;
+     *     set matching item in node;
+     *     release waiting thread;
+     *   }
+     *   // else retry on CAS failure
+     * }
+     *
+     * This is among the simplest forms of a "dual data structure" --
+     * see Scott and Scherer's DISC 04 paper and
+     * http://www.cs.rochester.edu/research/synchronization/pseudocode/duals.html
      *
-     * This simple approach works great when there are only a few
-     * threads using an Exchanger, but performance rapidly
-     * deteriorates due to CAS contention on the single slot when
-     * there are lots of threads using an exchanger.  So instead we use
-     * an "arena"; basically a kind of hash table with a dynamically
-     * varying number of slots, any one of which can be used by
-     * threads performing an exchange.  Incoming threads pick slots
-     * based on a hash of their Thread ids.  If an incoming thread
-     * fails to CAS in its chosen slot, it picks an alternative slot
-     * instead.  And similarly from there.  If a thread successfully
-     * CASes into a slot but no other thread arrives, it tries
-     * another, heading toward the zero slot, which always exists even
-     * if the table shrinks.  The particular mechanics controlling this
-     * are as follows:
+     * This works great in principle. But in practice, like many
+     * algorithms centered on atomic updates to a single location, it
+     * scales horribly when there are more than a few participants
+     * using the same Exchanger. So the implementation instead uses a
+     * form of elimination arena, that spreads out this contention by
+     * arranging that some threads typically use different slots,
+     * while still ensuring that eventually, any two parties will be
+     * able to exchange items. That is, we cannot completely partition
+     * across threads, but instead give threads arena indices that
+     * will on average grow under contention and shrink under lack of
+     * contention. We approach this by defining the Nodes that we need
+     * anyway as ThreadLocals, and include in them per-thread index
+     * and related bookkeeping state. (We can safely reuse per-thread
+     * nodes rather than creating them fresh each time because slots
+     * alternate between pointing to a node vs null, so cannot
+     * encounter ABA problems. However, we do need some care in
+     * resetting them between uses.)
      *
-     * Waiting: Slot zero is special in that it is the only slot that
-     * exists when there is no contention.  A thread occupying slot
-     * zero will block if no thread fulfills it after a short spin.
-     * In other cases, occupying threads eventually give up and try
-     * another slot.  Waiting threads spin for a while (a period that
-     * should be a little less than a typical context-switch time)
-     * before either blocking (if slot zero) or giving up (if other
-     * slots) and restarting.  There is no reason for threads to block
-     * unless there are unlikely to be any other threads present.
-     * Occupants are mainly avoiding memory contention so sit there
-     * quietly polling for a shorter period than it would take to
-     * block and then unblock them.  Non-slot-zero waits that elapse
-     * because of lack of other threads waste around one extra
-     * context-switch time per try, which is still on average much
-     * faster than alternative approaches.
+     * Implementing an effective arena requires allocating a bunch of
+     * space, so we only do so upon detecting contention (except on
+     * uniprocessors, where they wouldn't help, so aren't used).
+     * Otherwise, exchanges use the single-slot slotExchange method.
+     * On contention, not only must the slots be in different
+     * locations, but the locations must not encounter memory
+     * contention due to being on the same cache line (or more
+     * generally, the same coherence unit).  Because, as of this
+     * writing, there is no way to determine cacheline size, we define
+     * a value that is enough for common platforms.  Additionally,
+     * extra care elsewhere is taken to avoid other false/unintended
+     * sharing and to enhance locality, including adding padding (via
+     * sun.misc.Contended) to Nodes, embedding "bound" as an Exchanger
+     * field, and reworking some park/unpark mechanics compared to
+     * LockSupport versions.
+     *
+     * The arena starts out with only one used slot. We expand the
+     * effective arena size by tracking collisions; i.e., failed CASes
+     * while trying to exchange. By nature of the above algorithm, the
+     * only kinds of collision that reliably indicate contention are
+     * when two attempted releases collide -- one of two attempted
+     * offers can legitimately fail to CAS without indicating
+     * contention by more than one other thread. (Note: it is possible
+     * but not worthwhile to more precisely detect contention by
+     * reading slot values after CAS failures.)  When a thread has
+     * collided at each slot within the current arena bound, it tries
+     * to expand the arena size by one. We track collisions within
+     * bounds by using a version (sequence) number on the "bound"
+     * field, and conservatively reset collision counts when a
+     * participant notices that bound has been updated (in either
+     * direction).
      *
-     * Sizing: Usually, using only a few slots suffices to reduce
-     * contention.  Especially with small numbers of threads, using
-     * too many slots can lead to just as poor performance as using
-     * too few of them, and there's not much room for error.  The
-     * variable "max" maintains the number of slots actually in
-     * use.  It is increased when a thread sees too many CAS
-     * failures.  (This is analogous to resizing a regular hash table
-     * based on a target load factor, except here, growth steps are
-     * just one-by-one rather than proportional.)  Growth requires
-     * contention failures in each of three tried slots.  Requiring
-     * multiple failures for expansion copes with the fact that some
-     * failed CASes are not due to contention but instead to simple
-     * races between two threads or thread pre-emptions occurring
-     * between reading and CASing.  Also, very transient peak
-     * contention can be much higher than the average sustainable
-     * levels.  An attempt to decrease the max limit is usually made
-     * when a non-slot-zero wait elapses without being fulfilled.
-     * Threads experiencing elapsed waits move closer to zero, so
-     * eventually find existing (or future) threads even if the table
-     * has been shrunk due to inactivity.  The chosen mechanics and
-     * thresholds for growing and shrinking are intrinsically
-     * entangled with indexing and hashing inside the exchange code,
-     * and can't be nicely abstracted out.
+     * The effective arena size is reduced (when there is more than
+     * one slot) by giving up on waiting after a while and trying to
+     * decrement the arena size on expiration. The value of "a while"
+     * is an empirical matter.  We implement by piggybacking on the
+     * use of spin->yield->block that is essential for reasonable
+     * waiting performance anyway -- in a busy exchanger, offers are
+     * usually almost immediately released, in which case context
+     * switching on multiprocessors is extremely slow/wasteful.  Arena
+     * waits just omit the blocking part, and instead cancel. The spin
+     * count is empirically chosen to be a value that avoids blocking
+     * 99% of the time under maximum sustained exchange rates on a
+     * range of test machines. Spins and yields entail some limited
+     * randomness (using a cheap xorshift) to avoid regular patterns
+     * that can induce unproductive grow/shrink cycles. (Using a
+     * pseudorandom also helps regularize spin cycle duration by
+     * making branches unpredictable.)  Also, during an offer, a
+     * waiter can "know" that it will be released when its slot has
+     * changed, but cannot yet proceed until match is set.  In the
+     * mean time it cannot cancel the offer, so instead spins/yields.
+     * Note: It is possible to avoid this secondary check by changing
+     * the linearization point to be a CAS of the match field (as done
+     * in one case in the Scott & Scherer DISC paper), which also
+     * increases asynchrony a bit, at the expense of poorer collision
+     * detection and inability to always reuse per-thread nodes. So
+     * the current scheme is typically a better tradeoff.
+     *
+     * On collisions, indices traverse the arena cyclically in reverse
+     * order, restarting at the maximum index (which will tend to be
+     * sparsest) when bounds change. (On expirations, indices instead
+     * are halved until reaching 0.) It is possible (and has been
+     * tried) to use randomized, prime-value-stepped, or double-hash
+     * style traversal instead of simple cyclic traversal to reduce
+     * bunching.  But empirically, whatever benefits these may have
+     * don't overcome their added overhead: We are managing operations
+     * that occur very quickly unless there is sustained contention,
+     * so simpler/faster control policies work better than more
+     * accurate but slower ones.
+     *
+     * Because we use expiration for arena size control, we cannot
+     * throw TimeoutExceptions in the timed version of the public
+     * exchange method until the arena size has shrunken to zero (or
+     * the arena isn't enabled). This may delay response to timeout
+     * but is still within spec.
      *
-     * Hashing: Each thread picks its initial slot to use in accord
-     * with a simple hashcode.  The sequence is the same on each
-     * encounter by any given thread, but effectively random across
-     * threads.  Using arenas encounters the classic cost vs quality
-     * tradeoffs of all hash tables.  Here, we use a one-step FNV-1a
-     * hash code based on the current thread's Thread.getId(), along
-     * with a cheap approximation to a mod operation to select an
-     * index.  The downside of optimizing index selection in this way
-     * is that the code is hardwired to use a maximum table size of
-     * 32.  But this value more than suffices for known platforms and
-     * applications.
+     * Essentially all of the implementation is in methods
+     * slotExchange and arenaExchange. These have similar overall
+     * structure, but differ in too many details to combine. The
+     * slotExchange method uses the single Exchanger field "slot"
+     * rather than arena array elements. However, it still needs
+     * minimal collision detection to trigger arena construction.
+     * (The messiest part is making sure interrupt status and
+     * InterruptedExceptions come out right during transitions when
+     * both methods may be called. This is done by using null return
+     * as a sentinel to recheck interrupt status.)
      *
-     * Probing: On sensed contention of a selected slot, we probe
-     * sequentially through the table, analogously to linear probing
-     * after collision in a hash table.  (We move circularly, in
-     * reverse order, to mesh best with table growth and shrinkage
-     * rules.)  Except that to minimize the effects of false-alarms
-     * and cache thrashing, we try the first selected slot twice
-     * before moving.
-     *
-     * Padding: Even with contention management, slots are heavily
-     * contended, so use cache-padding to avoid poor memory
-     * performance.  Because of this, slots are lazily constructed
-     * only when used, to avoid wasting this space unnecessarily.
-     * While isolation of locations is not much of an issue at first
-     * in an application, as time goes on and garbage-collectors
-     * perform compaction, slots are very likely to be moved adjacent
-     * to each other, which can cause much thrashing of cache lines on
-     * MPs unless padding is employed.
-     *
-     * This is an improvement of the algorithm described in the paper
-     * "A Scalable Elimination-based Exchange Channel" by William
-     * Scherer, Doug Lea, and Michael Scott in Proceedings of SCOOL05
-     * workshop.  Available at: http://hdl.handle.net/1802/2104
+     * As is too common in this sort of code, methods are monolithic
+     * because most of the logic relies on reads of fields that are
+     * maintained as local variables so can't be nicely factored --
+     * mainly, here, bulky spin->yield->block/cancel code), and
+     * heavily dependent on intrinsics (Unsafe) to use inlined
+     * embedded CAS and related memory access operations (that tend
+     * not to be as readily inlined by dynamic compilers when they are
+     * hidden behind other methods that would more nicely name and
+     * encapsulate the intended effects). This includes the use of
+     * putOrderedX to clear fields of the per-thread Nodes between
+     * uses. Note that field Node.item is not declared as volatile
+     * even though it is read by releasing threads, because they only
+     * do so after CAS operations that must precede access, and all
+     * uses by the owning thread are otherwise acceptably ordered by
+     * other operations. (Because the actual points of atomicity are
+     * slot CASes, it would also be legal for the write to Node.match
+     * in a release to be weaker than a full volatile write. However,
+     * this is not done because it could allow further postponement of
+     * the write, delaying progress.)
      */
 
+    /**
+     * The byte distance (as a shift value) between any two used slots
+     * in the arena.  1 << ASHIFT should be at least cacheline size.
+     */
+    private static final int ASHIFT = 7;
+
+    /**
+     * The maximum supported arena index. The maximum allocatable
+     * arena size is MMASK + 1. Must be a power of two minus one, less
+     * than (1<<(31-ASHIFT)). The cap of 255 (0xff) more than suffices
+     * for the expected scaling limits of the main algorithms.
+     */
+    private static final int MMASK = 0xff;
+
+    /**
+     * Unit for sequence/version bits of bound field. Each successful
+     * change to the bound also adds SEQ.
+     */
+    private static final int SEQ = MMASK + 1;
+
     /** The number of CPUs, for sizing and spin control */
     private static final int NCPU = Runtime.getRuntime().availableProcessors();
 
     /**
-     * The capacity of the arena.  Set to a value that provides more
-     * than enough space to handle contention.  On small machines
-     * most slots won't be used, but it is still not wasted because
-     * the extra space provides some machine-level address padding
-     * to minimize interference with heavily CAS'ed Slot locations.
-     * And on very large machines, performance eventually becomes
-     * bounded by memory bandwidth, not numbers of threads/CPUs.
-     * This constant cannot be changed without also modifying
-     * indexing and hashing algorithms.
+     * The maximum slot index of the arena: The number of slots that
+     * can in principle hold all threads without contention, or at
+     * most the maximum indexable value.
      */
-    private static final int CAPACITY = 32;
-
-    /**
-     * The value of "max" that will hold all threads without
-     * contention.  When this value is less than CAPACITY, some
-     * otherwise wasted expansion can be avoided.
-     */
-    private static final int FULL =
-        Math.max(0, Math.min(CAPACITY, NCPU / 2) - 1);
+    static final int FULL = (NCPU >= (MMASK << 1)) ? MMASK : NCPU >>> 1;
 
     /**
-     * The number of times to spin (doing nothing except polling a
-     * memory location) before blocking or giving up while waiting to
-     * be fulfilled.  Should be zero on uniprocessors.  On
-     * multiprocessors, this value should be large enough so that two
-     * threads exchanging items as fast as possible block only when
-     * one of them is stalled (due to GC or preemption), but not much
-     * longer, to avoid wasting CPU resources.  Seen differently, this
-     * value is a little over half the number of cycles of an average
-     * context switch time on most systems.  The value here is
-     * approximately the average of those across a range of tested
-     * systems.
+     * The bound for spins while waiting for a match. The actual
+     * number of iterations will on average be about twice this value
+     * due to randomization. Note: Spinning is disabled when NCPU==1.
      */
-    private static final int SPINS = (NCPU == 1) ? 0 : 2000;
-
-    /**
-     * The number of times to spin before blocking in timed waits.
-     * Timed waits spin more slowly because checking the time takes
-     * time.  The best value relies mainly on the relative rate of
-     * System.nanoTime vs memory accesses.  The value is empirically
-     * derived to work well across a variety of systems.
-     */
-    private static final int TIMED_SPINS = SPINS / 20;
-
-    /**
-     * Sentinel item representing cancellation of a wait due to
-     * interruption, timeout, or elapsed spin-waits.  This value is
-     * placed in holes on cancellation, and used as a return value
-     * from waiting methods to indicate failure to set or get hole.
-     */
-    private static final Object CANCEL = new Object();
+    private static final int SPINS = 1 << 10;
 
     /**
      * Value representing null arguments/returns from public
-     * methods.  This disambiguates from internal requirement that
-     * holes start out as null to mean they are not yet set.
+     * methods. Needed because the API originally didn't disallow null
+     * arguments, which it should have.
      */
     private static final Object NULL_ITEM = new Object();
 
     /**
-     * Nodes hold partially exchanged data.  This class
-     * opportunistically subclasses AtomicReference to represent the
-     * hole.  So get() returns hole, and compareAndSet CAS'es value
-     * into hole.  This class cannot be parameterized as "V" because
-     * of the use of non-V CANCEL sentinels.
+     * Sentinel value returned by internal exchange methods upon
+     * timeout, to avoid need for separate timed versions of these
+     * methods.
      */
-    @SuppressWarnings("serial")
-    private static final class Node extends AtomicReference<Object> {
-        /** The element offered by the Thread creating this node. */
-        public final Object item;
+    private static final Object TIMED_OUT = new Object();
 
-        /** The Thread waiting to be signalled; null until waiting. */
-        public volatile Thread waiter;
-
-        /**
-         * Creates node with given item and empty hole.
-         * @param item the item
-         */
-        public Node(Object item) {
-            this.item = item;
-        }
+    /**
+     * Nodes hold partially exchanged data, plus other per-thread
+     * bookkeeping. Padded via @sun.misc.Contended to reduce memory
+     * contention.
+     */
+    @sun.misc.Contended static final class Node {
+        int index;              // Arena index
+        int bound;              // Last recorded value of Exchanger.bound
+        int collides;           // Number of CAS failures at current bound
+        int hash;               // Pseudo-random for spins
+        Object item;            // This thread's current item
+        volatile Object match;  // Item provided by releasing thread
+        volatile Thread parked; // Set to this thread when parked, else null
     }
 
-    /**
-     * A Slot is an AtomicReference with heuristic padding to lessen
-     * cache effects of this heavily CAS'ed location.  While the
-     * padding adds noticeable space, all slots are created only on
-     * demand, and there will be more than one of them only when it
-     * would improve throughput more than enough to outweigh using
-     * extra space.
-     */
-    @SuppressWarnings("serial")
-    private static final class Slot extends AtomicReference<Object> {
-        // Improve likelihood of isolation on <= 64 byte cache lines
-        long q0, q1, q2, q3, q4, q5, q6, q7, q8, q9, qa, qb, qc, qd, qe;
+    /** The corresponding thread local class */
+    static final class Participant extends ThreadLocal<Node> {
+        public Node initialValue() { return new Node(); }
     }
 
     /**
-     * Slot array.  Elements are lazily initialized when needed.
-     * Declared volatile to enable double-checked lazy construction.
+     * Per-thread state
      */
-    private volatile Slot[] arena = new Slot[CAPACITY];
+    private final Participant participant;
+
+    /**
+     * Elimination array; null until enabled (within slotExchange).
+     * Element accesses use emulation of volatile gets and CAS.
+     */
+    private volatile Node[] arena;
 
     /**
-     * The maximum slot index being used.  The value sometimes
-     * increases when a thread experiences too many CAS contentions,
-     * and sometimes decreases when a spin-wait elapses.  Changes
-     * are performed only via compareAndSet, to avoid stale values
-     * when a thread happens to stall right before setting.
+     * Slot used until contention detected.
      */
-    private final AtomicInteger max = new AtomicInteger();
+    private volatile Node slot;
 
     /**
-     * Main exchange function, handling the different policy variants.
-     * Uses Object, not "V" as argument and return value to simplify
-     * handling of sentinel values.  Callers from public methods decode
-     * and cast accordingly.
+     * The index of the largest valid arena position, OR'ed with SEQ
+     * number in high bits, incremented on each update.  The initial
+     * update from 0 to SEQ is used to ensure that the arena array is
+     * constructed only once.
+     */
+    private volatile int bound;
+
+    /**
+     * Exchange function when arenas enabled. See above for explanation.
      *
      * @param item the (non-null) item to exchange
      * @param timed true if the wait is timed
-     * @param nanos if timed, the maximum wait time
-     * @return the other thread's item, or CANCEL if interrupted or timed out
+     * @param ns if timed, the maximum wait time, else 0L
+     * @return the other thread's item; or null if interrupted; or
+     * TIMED_OUT if timed and timed out
      */
-    private Object doExchange(Object item, boolean timed, long nanos) {
-        Node me = new Node(item);                 // Create in case occupying
-        int index = hashIndex();                  // Index of current slot
-        int fails = 0;                            // Number of CAS failures
-
-        for (;;) {
-            Object y;                             // Contents of current slot
-            Slot slot = arena[index];
-            if (slot == null)                     // Lazily initialize slots
-                createSlot(index);                // Continue loop to reread
-            else if ((y = slot.get()) != null &&  // Try to fulfill
-                     slot.compareAndSet(y, null)) {
-                Node you = (Node)y;               // Transfer item
-                if (you.compareAndSet(null, item)) {
-                    LockSupport.unpark(you.waiter);
-                    return you.item;
-                }                                 // Else cancelled; continue
+    private final Object arenaExchange(Object item, boolean timed, long ns) {
+        Node[] a = arena;
+        Node p = participant.get();
+        for (int i = p.index;;) {                      // access slot at i
+            int b, m, c; long j;                       // j is raw array offset
+            Node q = (Node)U.getObjectVolatile(a, j = (i << ASHIFT) + ABASE);
+            if (q != null && U.compareAndSwapObject(a, j, q, null)) {
+                Object v = q.item;                     // release
+                q.match = item;
+                Thread w = q.parked;
+                if (w != null)
+                    U.unpark(w);
+                return v;
             }
-            else if (y == null &&                 // Try to occupy
-                     slot.compareAndSet(null, me)) {
-                if (index == 0)                   // Blocking wait for slot 0
-                    return timed ?
-                        awaitNanos(me, slot, nanos) :
-                        await(me, slot);
-                Object v = spinWait(me, slot);    // Spin wait for non-0
-                if (v != CANCEL)
-                    return v;
-                me = new Node(item);              // Throw away cancelled node
-                int m = max.get();
-                if (m > (index >>>= 1))           // Decrease index
-                    max.compareAndSet(m, m - 1);  // Maybe shrink table
+            else if (i <= (m = (b = bound) & MMASK) && q == null) {
+                p.item = item;                         // offer
+                if (U.compareAndSwapObject(a, j, null, p)) {
+                    long end = (timed && m == 0) ? System.nanoTime() + ns : 0L;
+                    Thread t = Thread.currentThread(); // wait
+                    for (int h = p.hash, spins = SPINS;;) {
+                        Object v = p.match;
+                        if (v != null) {
+                            U.putOrderedObject(p, MATCH, null);
+                            p.item = null;             // clear for next use
+                            p.hash = h;
+                            return v;
+                        }
+                        else if (spins > 0) {
+                            h ^= h << 1; h ^= h >>> 3; h ^= h << 10; // xorshift
+                            if (h == 0)                // initialize hash
+                                h = SPINS | (int)t.getId();
+                            else if (h < 0 &&          // approx 50% true
+                                     (--spins & ((SPINS >>> 1) - 1)) == 0)
+                                Thread.yield();        // two yields per wait
+                        }
+                        else if (U.getObjectVolatile(a, j) != p)
+                            spins = SPINS;       // releaser hasn't set match yet
+                        else if (!t.isInterrupted() && m == 0 &&
+                                 (!timed ||
+                                  (ns = end - System.nanoTime()) > 0L)) {
+                            U.putObject(t, BLOCKER, this); // emulate LockSupport
+                            p.parked = t;              // minimize window
+                            if (U.getObjectVolatile(a, j) == p)
+                                U.park(false, ns);
+                            p.parked = null;
+                            U.putObject(t, BLOCKER, null);
+                        }
+                        else if (U.getObjectVolatile(a, j) == p &&
+                                 U.compareAndSwapObject(a, j, p, null)) {
+                            if (m != 0)                // try to shrink
+                                U.compareAndSwapInt(this, BOUND, b, b + SEQ - 1);
+                            p.item = null;
+                            p.hash = h;
+                            i = p.index >>>= 1;        // descend
+                            if (Thread.interrupted())
+                                return null;
+                            if (timed && m == 0 && ns <= 0L)
+                                return TIMED_OUT;
+                            break;                     // expired; restart
+                        }
+                    }
+                }
+                else
+                    p.item = null;                     // clear offer
             }
-            else if (++fails > 1) {               // Allow 2 fails on 1st slot
-                int m = max.get();
-                if (fails > 3 && m < FULL && max.compareAndSet(m, m + 1))
-                    index = m + 1;                // Grow on 3rd failed slot
-                else if (--index < 0)
-                    index = m;                    // Circularly traverse
+            else {
+                if (p.bound != b) {                    // stale; reset
+                    p.bound = b;
+                    p.collides = 0;
+                    i = (i != m || m == 0) ? m : m - 1;
+                }
+                else if ((c = p.collides) < m || m == FULL ||
+                         !U.compareAndSwapInt(this, BOUND, b, b + SEQ + 1)) {
+                    p.collides = c + 1;
+                    i = (i == 0) ? m : i - 1;          // cyclically traverse
+                }
+                else
+                    i = m + 1;                         // grow
+                p.index = i;
             }
         }
     }
 
     /**
-     * Returns a hash index for the current thread.  Uses a one-step
-     * FNV-1a hash code (http://www.isthe.com/chongo/tech/comp/fnv/)
-     * based on the current thread's Thread.getId().  These hash codes
-     * have more uniform distribution properties with respect to small
-     * moduli (here 1-31) than do other simple hashing functions.
-     *
-     * <p>To return an index between 0 and max, we use a cheap
-     * approximation to a mod operation, that also corrects for bias
-     * due to non-power-of-2 remaindering (see {@link
-     * java.util.Random#nextInt}).  Bits of the hashcode are masked
-     * with "nbits", the ceiling power of two of table size (looked up
-     * in a table packed into three ints).  If too large, this is
-     * retried after rotating the hash by nbits bits, while forcing new
-     * top bit to 0, which guarantees eventual termination (although
-     * with a non-random-bias).  This requires an average of less than
-     * 2 tries for all table sizes, and has a maximum 2% difference
-     * from perfectly uniform slot probabilities when applied to all
-     * possible hash codes for sizes less than 32.
+     * Exchange function used until arenas enabled. See above for explanation.
      *
-     * @return a per-thread-random index, 0 <= index < max
-     */
-    private final int hashIndex() {
-        long id = Thread.currentThread().getId();
-        int hash = (((int)(id ^ (id >>> 32))) ^ 0x811c9dc5) * 0x01000193;
-
-        int m = max.get();
-        int nbits = (((0xfffffc00  >> m) & 4) | // Compute ceil(log2(m+1))
-                     ((0x000001f8 >>> m) & 2) | // The constants hold
-                     ((0xffff00f2 >>> m) & 1)); // a lookup table
-        int index;
-        while ((index = hash & ((1 << nbits) - 1)) > m)       // May retry on
-            hash = (hash >>> nbits) | (hash << (33 - nbits)); // non-power-2 m
-        return index;
-    }
-
-    /**
-     * Creates a new slot at given index.  Called only when the slot
-     * appears to be null.  Relies on double-check using builtin
-     * locks, since they rarely contend.  This in turn relies on the
-     * arena array being declared volatile.
-     *
-     * @param index the index to add slot at
+     * @param item the item to exchange
+     * @param timed true if the wait is timed
+     * @param ns if timed, the maximum wait time, else 0L
+     * @return the other thread's item; or null if either the arena
+     * was enabled or the thread was interrupted before completion; or
+     * TIMED_OUT if timed and timed out
      */
-    private void createSlot(int index) {
-        // Create slot outside of lock to narrow sync region
-        Slot newSlot = new Slot();
-        Slot[] a = arena;
-        synchronized (a) {
-            if (a[index] == null)
-                a[index] = newSlot;
-        }
-    }
-
-    /**
-     * Tries to cancel a wait for the given node waiting in the given
-     * slot, if so, helping clear the node from its slot to avoid
-     * garbage retention.
-     *
-     * @param node the waiting node
-     * @param the slot it is waiting in
-     * @return true if successfully cancelled
-     */
-    private static boolean tryCancel(Node node, Slot slot) {
-        if (!node.compareAndSet(null, CANCEL))
-            return false;
-        if (slot.get() == node) // pre-check to minimize contention
-            slot.compareAndSet(node, null);
-        return true;
-    }
-
-    // Three forms of waiting. Each just different enough not to merge
-    // code with others.
-
-    /**
-     * Spin-waits for hole for a non-0 slot.  Fails if spin elapses
-     * before hole filled.  Does not check interrupt, relying on check
-     * in public exchange method to abort if interrupted on entry.
-     *
-     * @param node the waiting node
-     * @return on success, the hole; on failure, CANCEL
-     */
-    private static Object spinWait(Node node, Slot slot) {
-        int spins = SPINS;
-        for (;;) {
-            Object v = node.get();
-            if (v != null)
-                return v;
-            else if (spins > 0)
-                --spins;
-            else
-                tryCancel(node, slot);
-        }
-    }
+    private final Object slotExchange(Object item, boolean timed, long ns) {
+        Node p = participant.get();
+        Thread t = Thread.currentThread();
+        if (t.isInterrupted()) // preserve interrupt status so caller can recheck
+            return null;
 
-    /**
-     * Waits for (by spinning and/or blocking) and gets the hole
-     * filled in by another thread.  Fails if interrupted before
-     * hole filled.
-     *
-     * When a node/thread is about to block, it sets its waiter field
-     * and then rechecks state at least one more time before actually
-     * parking, thus covering race vs fulfiller noticing that waiter
-     * is non-null so should be woken.
-     *
-     * Thread interruption status is checked only surrounding calls to
-     * park.  The caller is assumed to have checked interrupt status
-     * on entry.
-     *
-     * @param node the waiting node
-     * @return on success, the hole; on failure, CANCEL
-     */
-    private static Object await(Node node, Slot slot) {
-        Thread w = Thread.currentThread();
-        int spins = SPINS;
-        for (;;) {
-            Object v = node.get();
-            if (v != null)
-                return v;
-            else if (spins > 0)                 // Spin-wait phase
-                --spins;
-            else if (node.waiter == null)       // Set up to block next
-                node.waiter = w;
-            else if (w.isInterrupted())         // Abort on interrupt
-                tryCancel(node, slot);
-            else                                // Block
-                LockSupport.park(node);
-        }
-    }
-
-    /**
-     * Waits for (at index 0) and gets the hole filled in by another
-     * thread.  Fails if timed out or interrupted before hole filled.
-     * Same basic logic as untimed version, but a bit messier.
-     *
-     * @param node the waiting node
-     * @param nanos the wait time
-     * @return on success, the hole; on failure, CANCEL
-     */
-    private Object awaitNanos(Node node, Slot slot, long nanos) {
-        int spins = TIMED_SPINS;
-        long lastTime = 0;
-        Thread w = null;
-        for (;;) {
-            Object v = node.get();
-            if (v != null)
-                return v;
-            long now = System.nanoTime();
-            if (w == null)
-                w = Thread.currentThread();
-            else
-                nanos -= now - lastTime;
-            lastTime = now;
-            if (nanos > 0) {
-                if (spins > 0)
-                    --spins;
-                else if (node.waiter == null)
-                    node.waiter = w;
-                else if (w.isInterrupted())
-                    tryCancel(node, slot);
-                else
-                    LockSupport.parkNanos(node, nanos);
+        for (Node q;;) {
+            if ((q = slot) != null) {
+                if (U.compareAndSwapObject(this, SLOT, q, null)) {
+                    Object v = q.item;
+                    q.match = item;
+                    Thread w = q.parked;
+                    if (w != null)
+                        U.unpark(w);
+                    return v;
+                }
+                // create arena on contention, but continue until slot null
+                if (NCPU > 1 && bound == 0 &&
+                    U.compareAndSwapInt(this, BOUND, 0, SEQ))
+                    arena = new Node[(FULL + 2) << ASHIFT];
             }
-            else if (tryCancel(node, slot) && !w.isInterrupted())
-                return scanOnTimeout(node);
-        }
-    }
-
-    /**
-     * Sweeps through arena checking for any waiting threads.  Called
-     * only upon return from timeout while waiting in slot 0.  When a
-     * thread gives up on a timed wait, it is possible that a
-     * previously-entered thread is still waiting in some other
-     * slot.  So we scan to check for any.  This is almost always
-     * overkill, but decreases the likelihood of timeouts when there
-     * are other threads present to far less than that in lock-based
-     * exchangers in which earlier-arriving threads may still be
-     * waiting on entry locks.
-     *
-     * @param node the waiting node
-     * @return another thread's item, or CANCEL
-     */
-    private Object scanOnTimeout(Node node) {
-        Object y;
-        for (int j = arena.length - 1; j >= 0; --j) {
-            Slot slot = arena[j];
-            if (slot != null) {
-                while ((y = slot.get()) != null) {
-                    if (slot.compareAndSet(y, null)) {
-                        Node you = (Node)y;
-                        if (you.compareAndSet(null, node.item)) {
-                            LockSupport.unpark(you.waiter);
-                            return you.item;
-                        }
-                    }
-                }
+            else if (arena != null)
+                return null; // caller must reroute to arenaExchange
+            else {
+                p.item = item;
+                if (U.compareAndSwapObject(this, SLOT, null, p))
+                    break;
+                p.item = null;
             }
         }
-        return CANCEL;
+
+        // await release
+        int h = p.hash;
+        long end = timed ? System.nanoTime() + ns : 0L;
+        int spins = (NCPU > 1) ? SPINS : 1;
+        Object v;
+        while ((v = p.match) == null) {
+            if (spins > 0) {
+                h ^= h << 1; h ^= h >>> 3; h ^= h << 10;
+                if (h == 0)
+                    h = SPINS | (int)t.getId();
+                else if (h < 0 && (--spins & ((SPINS >>> 1) - 1)) == 0)
+                    Thread.yield();
+            }
+            else if (slot != p)
+                spins = SPINS;
+            else if (!t.isInterrupted() && arena == null &&
+                     (!timed || (ns = end - System.nanoTime()) > 0L)) {
+                U.putObject(t, BLOCKER, this);
+                p.parked = t;
+                if (slot == p)
+                    U.park(false, ns);
+                p.parked = null;
+                U.putObject(t, BLOCKER, null);
+            }
+            else if (U.compareAndSwapObject(this, SLOT, p, null)) {
+                v = timed && ns <= 0L && !t.isInterrupted() ? TIMED_OUT : null;
+                break;
+            }
+        }
+        U.putOrderedObject(p, MATCH, null);
+        p.item = null;
+        p.hash = h;
+        return v;
     }
 
     /**
      * Creates a new Exchanger.
      */
     public Exchanger() {
+        participant = new Participant();
     }
 
     /**
@@ -620,15 +559,14 @@
      */
     @SuppressWarnings("unchecked")
     public V exchange(V x) throws InterruptedException {
-        if (!Thread.interrupted()) {
-            Object o = doExchange((x == null) ? NULL_ITEM : x, false, 0);
-            if (o == NULL_ITEM)
-                return null;
-            if (o != CANCEL)
-                return (V)o;
-            Thread.interrupted(); // Clear interrupt status on IE throw
-        }
-        throw new InterruptedException();
+        Object v;
+        Object item = (x == null) ? NULL_ITEM : x; // translate null args
+        if ((arena != null ||
+             (v = slotExchange(item, false, 0L)) == null) &&
+            ((Thread.interrupted() || // disambiguates null return
+              (v = arenaExchange(item, false, 0L)) == null)))
+            throw new InterruptedException();
+        return (v == NULL_ITEM) ? null : (V)v;
     }
 
     /**
@@ -666,7 +604,7 @@
      *
      * @param x the object to exchange
      * @param timeout the maximum time to wait
-     * @param unit the time unit of the <tt>timeout</tt> argument
+     * @param unit the time unit of the {@code timeout} argument
      * @return the object provided by the other thread
      * @throws InterruptedException if the current thread was
      *         interrupted while waiting
@@ -676,16 +614,51 @@
     @SuppressWarnings("unchecked")
     public V exchange(V x, long timeout, TimeUnit unit)
         throws InterruptedException, TimeoutException {
-        if (!Thread.interrupted()) {
-            Object o = doExchange((x == null) ? NULL_ITEM : x,
-                                  true, unit.toNanos(timeout));
-            if (o == NULL_ITEM)
-                return null;
-            if (o != CANCEL)
-                return (V)o;
-            if (!Thread.interrupted())
-                throw new TimeoutException();
+        Object v;
+        Object item = (x == null) ? NULL_ITEM : x;
+        long ns = unit.toNanos(timeout);
+        if ((arena != null ||
+             (v = slotExchange(item, true, ns)) == null) &&
+            ((Thread.interrupted() ||
+              (v = arenaExchange(item, true, ns)) == null)))
+            throw new InterruptedException();
+        if (v == TIMED_OUT)
+            throw new TimeoutException();
+        return (v == NULL_ITEM) ? null : (V)v;
+    }
+
+    // Unsafe mechanics
+    private static final sun.misc.Unsafe U;
+    private static final long BOUND;
+    private static final long SLOT;
+    private static final long MATCH;
+    private static final long BLOCKER;
+    private static final int ABASE;
+    static {
+        int s;
+        try {
+            U = sun.misc.Unsafe.getUnsafe();
+            Class<?> ek = Exchanger.class;
+            Class<?> nk = Node.class;
+            Class<?> ak = Node[].class;
+            Class<?> tk = Thread.class;
+            BOUND = U.objectFieldOffset
+                (ek.getDeclaredField("bound"));
+            SLOT = U.objectFieldOffset
+                (ek.getDeclaredField("slot"));
+            MATCH = U.objectFieldOffset
+                (nk.getDeclaredField("match"));
+            BLOCKER = U.objectFieldOffset
+                (tk.getDeclaredField("parkBlocker"));
+            s = U.arrayIndexScale(ak);
+            // ABASE absorbs padding in front of element 0
+            ABASE = U.arrayBaseOffset(ak) + (1 << ASHIFT);
+
+        } catch (Exception e) {
+            throw new Error(e);
         }
-        throw new InterruptedException();
+        if ((s & (s-1)) != 0 || s > (1 << ASHIFT))
+            throw new Error("Unsupported array scale");
     }
+
 }
--- a/src/share/classes/java/util/concurrent/ExecutionException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/ExecutionException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -48,14 +48,14 @@
     private static final long serialVersionUID = 7830266012832686185L;
 
     /**
-     * Constructs an <tt>ExecutionException</tt> with no detail message.
+     * Constructs an {@code ExecutionException} with no detail message.
      * The cause is not initialized, and may subsequently be
      * initialized by a call to {@link #initCause(Throwable) initCause}.
      */
     protected ExecutionException() { }
 
     /**
-     * Constructs an <tt>ExecutionException</tt> with the specified detail
+     * Constructs an {@code ExecutionException} with the specified detail
      * message. The cause is not initialized, and may subsequently be
      * initialized by a call to {@link #initCause(Throwable) initCause}.
      *
@@ -66,7 +66,7 @@
     }
 
     /**
-     * Constructs an <tt>ExecutionException</tt> with the specified detail
+     * Constructs an {@code ExecutionException} with the specified detail
      * message and cause.
      *
      * @param  message the detail message
@@ -78,7 +78,7 @@
     }
 
     /**
-     * Constructs an <tt>ExecutionException</tt> with the specified cause.
+     * Constructs an {@code ExecutionException} with the specified cause.
      * The detail message is set to {@code (cause == null ? null :
      * cause.toString())} (which typically contains the class and
      * detail message of {@code cause}).
--- a/src/share/classes/java/util/concurrent/Executor.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/Executor.java	Mon Jul 22 17:37:15 2013 -0700
@@ -39,9 +39,9 @@
  * An object that executes submitted {@link Runnable} tasks. This
  * interface provides a way of decoupling task submission from the
  * mechanics of how each task will be run, including details of thread
- * use, scheduling, etc.  An <tt>Executor</tt> is normally used
+ * use, scheduling, etc.  An {@code Executor} is normally used
  * instead of explicitly creating threads. For example, rather than
- * invoking <tt>new Thread(new(RunnableTask())).start()</tt> for each
+ * invoking {@code new Thread(new(RunnableTask())).start()} for each
  * of a set of tasks, you might use:
  *
  * <pre>
@@ -51,7 +51,7 @@
  * ...
  * </pre>
  *
- * However, the <tt>Executor</tt> interface does not strictly
+ * However, the {@code Executor} interface does not strictly
  * require that execution be asynchronous. In the simplest case, an
  * executor can run the submitted task immediately in the caller's
  * thread:
@@ -74,7 +74,7 @@
  *   }
  * }}</pre>
  *
- * Many <tt>Executor</tt> implementations impose some sort of
+ * Many {@code Executor} implementations impose some sort of
  * limitation on how and when tasks are scheduled.  The executor below
  * serializes the submission of tasks to a second executor,
  * illustrating a composite executor.
@@ -111,7 +111,7 @@
  *   }
  * }}</pre>
  *
- * The <tt>Executor</tt> implementations provided in this package
+ * The {@code Executor} implementations provided in this package
  * implement {@link ExecutorService}, which is a more extensive
  * interface.  The {@link ThreadPoolExecutor} class provides an
  * extensible thread pool implementation. The {@link Executors} class
@@ -130,11 +130,11 @@
     /**
      * Executes the given command at some time in the future.  The command
      * may execute in a new thread, in a pooled thread, or in the calling
-     * thread, at the discretion of the <tt>Executor</tt> implementation.
+     * thread, at the discretion of the {@code Executor} implementation.
      *
      * @param command the runnable task
      * @throws RejectedExecutionException if this task cannot be
-     * accepted for execution.
+     * accepted for execution
      * @throws NullPointerException if command is null
      */
     void execute(Runnable command);
--- a/src/share/classes/java/util/concurrent/ExecutorService.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/ExecutorService.java	Mon Jul 22 17:37:15 2013 -0700
@@ -42,21 +42,21 @@
  * methods that can produce a {@link Future} for tracking progress of
  * one or more asynchronous tasks.
  *
- * <p> An <tt>ExecutorService</tt> can be shut down, which will cause
+ * <p>An {@code ExecutorService} can be shut down, which will cause
  * it to reject new tasks.  Two different methods are provided for
- * shutting down an <tt>ExecutorService</tt>. The {@link #shutdown}
+ * shutting down an {@code ExecutorService}. The {@link #shutdown}
  * method will allow previously submitted tasks to execute before
  * terminating, while the {@link #shutdownNow} method prevents waiting
  * tasks from starting and attempts to stop currently executing tasks.
  * Upon termination, an executor has no tasks actively executing, no
  * tasks awaiting execution, and no new tasks can be submitted.  An
- * unused <tt>ExecutorService</tt> should be shut down to allow
+ * unused {@code ExecutorService} should be shut down to allow
  * reclamation of its resources.
  *
- * <p> Method <tt>submit</tt> extends base method {@link
- * Executor#execute} by creating and returning a {@link Future} that
- * can be used to cancel execution and/or wait for completion.
- * Methods <tt>invokeAny</tt> and <tt>invokeAll</tt> perform the most
+ * <p>Method {@code submit} extends base method {@link
+ * Executor#execute(Runnable)} by creating and returning a {@link Future}
+ * that can be used to cancel execution and/or wait for completion.
+ * Methods {@code invokeAny} and {@code invokeAll} perform the most
  * commonly useful forms of bulk execution, executing a collection of
  * tasks and then waiting for at least one, or all, to
  * complete. (Class {@link ExecutorCompletionService} can be used to
@@ -101,9 +101,9 @@
  *   }
  * }}</pre>
  *
- * The following method shuts down an <tt>ExecutorService</tt> in two phases,
- * first by calling <tt>shutdown</tt> to reject incoming tasks, and then
- * calling <tt>shutdownNow</tt>, if necessary, to cancel any lingering tasks:
+ * The following method shuts down an {@code ExecutorService} in two phases,
+ * first by calling {@code shutdown} to reject incoming tasks, and then
+ * calling {@code shutdownNow}, if necessary, to cancel any lingering tasks:
  *
  *  <pre> {@code
  * void shutdownAndAwaitTermination(ExecutorService pool) {
@@ -149,8 +149,8 @@
      *         shutting down this ExecutorService may manipulate
      *         threads that the caller is not permitted to modify
      *         because it does not hold {@link
-     *         java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
-     *         or the security manager's <tt>checkAccess</tt> method
+     *         java.lang.RuntimePermission}{@code ("modifyThread")},
+     *         or the security manager's {@code checkAccess} method
      *         denies access.
      */
     void shutdown();
@@ -174,25 +174,25 @@
      *         shutting down this ExecutorService may manipulate
      *         threads that the caller is not permitted to modify
      *         because it does not hold {@link
-     *         java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
-     *         or the security manager's <tt>checkAccess</tt> method
+     *         java.lang.RuntimePermission}{@code ("modifyThread")},
+     *         or the security manager's {@code checkAccess} method
      *         denies access.
      */
     List<Runnable> shutdownNow();
 
     /**
-     * Returns <tt>true</tt> if this executor has been shut down.
+     * Returns {@code true} if this executor has been shut down.
      *
-     * @return <tt>true</tt> if this executor has been shut down
+     * @return {@code true} if this executor has been shut down
      */
     boolean isShutdown();
 
     /**
-     * Returns <tt>true</tt> if all tasks have completed following shut down.
-     * Note that <tt>isTerminated</tt> is never <tt>true</tt> unless
-     * either <tt>shutdown</tt> or <tt>shutdownNow</tt> was called first.
+     * Returns {@code true} if all tasks have completed following shut down.
+     * Note that {@code isTerminated} is never {@code true} unless
+     * either {@code shutdown} or {@code shutdownNow} was called first.
      *
-     * @return <tt>true</tt> if all tasks have completed following shut down
+     * @return {@code true} if all tasks have completed following shut down
      */
     boolean isTerminated();
 
@@ -203,8 +203,8 @@
      *
      * @param timeout the maximum time to wait
      * @param unit the time unit of the timeout argument
-     * @return <tt>true</tt> if this executor terminated and
-     *         <tt>false</tt> if the timeout elapsed before termination
+     * @return {@code true} if this executor terminated and
+     *         {@code false} if the timeout elapsed before termination
      * @throws InterruptedException if interrupted while waiting
      */
     boolean awaitTermination(long timeout, TimeUnit unit)
@@ -213,15 +213,15 @@
     /**
      * Submits a value-returning task for execution and returns a
      * Future representing the pending results of the task. The
-     * Future's <tt>get</tt> method will return the task's result upon
+     * Future's {@code get} method will return the task's result upon
      * successful completion.
      *
      * <p>
      * If you would like to immediately block waiting
      * for a task, you can use constructions of the form
-     * <tt>result = exec.submit(aCallable).get();</tt>
+     * {@code result = exec.submit(aCallable).get();}
      *
-     * <p> Note: The {@link Executors} class includes a set of methods
+     * <p>Note: The {@link Executors} class includes a set of methods
      * that can convert some other common closure-like objects,
      * for example, {@link java.security.PrivilegedAction} to
      * {@link Callable} form so they can be submitted.
@@ -236,7 +236,7 @@
 
     /**
      * Submits a Runnable task for execution and returns a Future
-     * representing that task. The Future's <tt>get</tt> method will
+     * representing that task. The Future's {@code get} method will
      * return the given result upon successful completion.
      *
      * @param task the task to submit
@@ -250,8 +250,8 @@
 
     /**
      * Submits a Runnable task for execution and returns a Future
-     * representing that task. The Future's <tt>get</tt> method will
-     * return <tt>null</tt> upon <em>successful</em> completion.
+     * representing that task. The Future's {@code get} method will
+     * return {@code null} upon <em>successful</em> completion.
      *
      * @param task the task to submit
      * @return a Future representing pending completion of the task
@@ -264,7 +264,7 @@
     /**
      * Executes the given tasks, returning a list of Futures holding
      * their status and results when all complete.
-     * {@link Future#isDone} is <tt>true</tt> for each
+     * {@link Future#isDone} is {@code true} for each
      * element of the returned list.
      * Note that a <em>completed</em> task could have
      * terminated either normally or by throwing an exception.
@@ -272,12 +272,12 @@
      * collection is modified while this operation is in progress.
      *
      * @param tasks the collection of tasks
-     * @return A list of Futures representing the tasks, in the same
+     * @return a list of Futures representing the tasks, in the same
      *         sequential order as produced by the iterator for the
-     *         given task list, each of which has completed.
+     *         given task list, each of which has completed
      * @throws InterruptedException if interrupted while waiting, in
-     *         which case unfinished tasks are cancelled.
-     * @throws NullPointerException if tasks or any of its elements are <tt>null</tt>
+     *         which case unfinished tasks are cancelled
+     * @throws NullPointerException if tasks or any of its elements are {@code null}
      * @throws RejectedExecutionException if any task cannot be
      *         scheduled for execution
      */
@@ -288,7 +288,7 @@
      * Executes the given tasks, returning a list of Futures holding
      * their status and results
      * when all complete or the timeout expires, whichever happens first.
-     * {@link Future#isDone} is <tt>true</tt> for each
+     * {@link Future#isDone} is {@code true} for each
      * element of the returned list.
      * Upon return, tasks that have not completed are cancelled.
      * Note that a <em>completed</em> task could have
@@ -307,7 +307,7 @@
      * @throws InterruptedException if interrupted while waiting, in
      *         which case unfinished tasks are cancelled
      * @throws NullPointerException if tasks, any of its elements, or
-     *         unit are <tt>null</tt>
+     *         unit are {@code null}
      * @throws RejectedExecutionException if any task cannot be scheduled
      *         for execution
      */
@@ -327,7 +327,7 @@
      * @return the result returned by one of the tasks
      * @throws InterruptedException if interrupted while waiting
      * @throws NullPointerException if tasks or any element task
-     *         subject to execution is <tt>null</tt>
+     *         subject to execution is {@code null}
      * @throws IllegalArgumentException if tasks is empty
      * @throws ExecutionException if no task successfully completes
      * @throws RejectedExecutionException if tasks cannot be scheduled
@@ -348,10 +348,10 @@
      * @param tasks the collection of tasks
      * @param timeout the maximum time to wait
      * @param unit the time unit of the timeout argument
-     * @return the result returned by one of the tasks.
+     * @return the result returned by one of the tasks
      * @throws InterruptedException if interrupted while waiting
      * @throws NullPointerException if tasks, or unit, or any element
-     *         task subject to execution is <tt>null</tt>
+     *         task subject to execution is {@code null}
      * @throws TimeoutException if the given timeout elapses before
      *         any task successfully completes
      * @throws ExecutionException if no task successfully completes
--- a/src/share/classes/java/util/concurrent/Executors.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/Executors.java	Mon Jul 22 17:37:15 2013 -0700
@@ -62,7 +62,7 @@
  *        that sets newly created threads to a known state.
  *   <li> Methods that create and return a {@link Callable}
  *        out of other closure-like forms, so they can be used
- *        in execution methods requiring <tt>Callable</tt>.
+ *        in execution methods requiring {@code Callable}.
  * </ul>
  *
  * @since 1.5
@@ -73,7 +73,7 @@
     /**
      * Creates a thread pool that reuses a fixed number of threads
      * operating off a shared unbounded queue.  At any point, at most
-     * <tt>nThreads</tt> threads will be active processing tasks.
+     * {@code nThreads} threads will be active processing tasks.
      * If additional tasks are submitted when all threads are active,
      * they will wait in the queue until a thread is available.
      * If any thread terminates due to a failure during execution
@@ -92,10 +92,47 @@
     }
 
     /**
+     * Creates a thread pool that maintains enough threads to support
+     * the given parallelism level, and may use multiple queues to
+     * reduce contention. The parallelism level corresponds to the
+     * maximum number of threads actively engaged in, or available to
+     * engage in, task processing. The actual number of threads may
+     * grow and shrink dynamically. A work-stealing pool makes no
+     * guarantees about the order in which submitted tasks are
+     * executed.
+     *
+     * @param parallelism the targeted parallelism level
+     * @return the newly created thread pool
+     * @throws IllegalArgumentException if {@code parallelism <= 0}
+     * @since 1.8
+     */
+    public static ExecutorService newWorkStealingPool(int parallelism) {
+        return new ForkJoinPool
+            (parallelism,
+             ForkJoinPool.defaultForkJoinWorkerThreadFactory,
+             null, true);
+    }
+
+    /**
+     * Creates a work-stealing thread pool using all
+     * {@link Runtime#availableProcessors available processors}
+     * as its target parallelism level.
+     * @return the newly created thread pool
+     * @see #newWorkStealingPool(int)
+     * @since 1.8
+     */
+    public static ExecutorService newWorkStealingPool() {
+        return new ForkJoinPool
+            (Runtime.getRuntime().availableProcessors(),
+             ForkJoinPool.defaultForkJoinWorkerThreadFactory,
+             null, true);
+    }
+
+    /**
      * Creates a thread pool that reuses a fixed number of threads
      * operating off a shared unbounded queue, using the provided
      * ThreadFactory to create new threads when needed.  At any point,
-     * at most <tt>nThreads</tt> threads will be active processing
+     * at most {@code nThreads} threads will be active processing
      * tasks.  If additional tasks are submitted when all threads are
      * active, they will wait in the queue until a thread is
      * available.  If any thread terminates due to a failure during
@@ -125,7 +162,7 @@
      * subsequent tasks.)  Tasks are guaranteed to execute
      * sequentially, and no more than one task will be active at any
      * given time. Unlike the otherwise equivalent
-     * <tt>newFixedThreadPool(1)</tt> the returned executor is
+     * {@code newFixedThreadPool(1)} the returned executor is
      * guaranteed not to be reconfigurable to use additional threads.
      *
      * @return the newly created single-threaded Executor
@@ -141,7 +178,7 @@
      * Creates an Executor that uses a single worker thread operating
      * off an unbounded queue, and uses the provided ThreadFactory to
      * create a new thread when needed. Unlike the otherwise
-     * equivalent <tt>newFixedThreadPool(1, threadFactory)</tt> the
+     * equivalent {@code newFixedThreadPool(1, threadFactory)} the
      * returned executor is guaranteed not to be reconfigurable to use
      * additional threads.
      *
@@ -164,7 +201,7 @@
      * will reuse previously constructed threads when they are
      * available.  These pools will typically improve the performance
      * of programs that execute many short-lived asynchronous tasks.
-     * Calls to <tt>execute</tt> will reuse previously constructed
+     * Calls to {@code execute} will reuse previously constructed
      * threads if available. If no existing thread is available, a new
      * thread will be created and added to the pool. Threads that have
      * not been used for sixty seconds are terminated and removed from
@@ -206,7 +243,7 @@
      * subsequent tasks.)  Tasks are guaranteed to execute
      * sequentially, and no more than one task will be active at any
      * given time. Unlike the otherwise equivalent
-     * <tt>newScheduledThreadPool(1)</tt> the returned executor is
+     * {@code newScheduledThreadPool(1)} the returned executor is
      * guaranteed not to be reconfigurable to use additional threads.
      * @return the newly created scheduled executor
      */
@@ -223,7 +260,7 @@
      * place if needed to execute subsequent tasks.)  Tasks are
      * guaranteed to execute sequentially, and no more than one task
      * will be active at any given time. Unlike the otherwise
-     * equivalent <tt>newScheduledThreadPool(1, threadFactory)</tt>
+     * equivalent {@code newScheduledThreadPool(1, threadFactory)}
      * the returned executor is guaranteed not to be reconfigurable to
      * use additional threads.
      * @param threadFactory the factory to use when creating new
@@ -240,7 +277,7 @@
      * Creates a thread pool that can schedule commands to run after a
      * given delay, or to execute periodically.
      * @param corePoolSize the number of threads to keep in the pool,
-     * even if they are idle.
+     * even if they are idle
      * @return a newly created scheduled thread pool
      * @throws IllegalArgumentException if {@code corePoolSize < 0}
      */
@@ -252,9 +289,9 @@
      * Creates a thread pool that can schedule commands to run after a
      * given delay, or to execute periodically.
      * @param corePoolSize the number of threads to keep in the pool,
-     * even if they are idle.
+     * even if they are idle
      * @param threadFactory the factory to use when the executor
-     * creates a new thread.
+     * creates a new thread
      * @return a newly created scheduled thread pool
      * @throws IllegalArgumentException if {@code corePoolSize < 0}
      * @throws NullPointerException if threadFactory is null
@@ -264,7 +301,6 @@
         return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
     }
 
-
     /**
      * Returns an object that delegates all defined {@link
      * ExecutorService} methods to the given executor, but not any
@@ -272,7 +308,7 @@
      * casts. This provides a way to safely "freeze" configuration and
      * disallow tuning of a given concrete implementation.
      * @param executor the underlying implementation
-     * @return an <tt>ExecutorService</tt> instance
+     * @return an {@code ExecutorService} instance
      * @throws NullPointerException if executor null
      */
     public static ExecutorService unconfigurableExecutorService(ExecutorService executor) {
@@ -288,7 +324,7 @@
      * casts. This provides a way to safely "freeze" configuration and
      * disallow tuning of a given concrete implementation.
      * @param executor the underlying implementation
-     * @return a <tt>ScheduledExecutorService</tt> instance
+     * @return a {@code ScheduledExecutorService} instance
      * @throws NullPointerException if executor null
      */
     public static ScheduledExecutorService unconfigurableScheduledExecutorService(ScheduledExecutorService executor) {
@@ -303,9 +339,9 @@
      * same {@link ThreadGroup}. If there is a {@link
      * java.lang.SecurityManager}, it uses the group of {@link
      * System#getSecurityManager}, else the group of the thread
-     * invoking this <tt>defaultThreadFactory</tt> method. Each new
+     * invoking this {@code defaultThreadFactory} method. Each new
      * thread is created as a non-daemon thread with priority set to
-     * the smaller of <tt>Thread.NORM_PRIORITY</tt> and the maximum
+     * the smaller of {@code Thread.NORM_PRIORITY} and the maximum
      * priority permitted in the thread group.  New threads have names
      * accessible via {@link Thread#getName} of
      * <em>pool-N-thread-M</em>, where <em>N</em> is the sequence
@@ -324,30 +360,31 @@
      * Executors#defaultThreadFactory}, additionally setting the
      * AccessControlContext and contextClassLoader of new threads to
      * be the same as the thread invoking this
-     * <tt>privilegedThreadFactory</tt> method.  A new
-     * <tt>privilegedThreadFactory</tt> can be created within an
-     * {@link AccessController#doPrivileged} action setting the
-     * current thread's access control context to create threads with
-     * the selected permission settings holding within that action.
+     * {@code privilegedThreadFactory} method.  A new
+     * {@code privilegedThreadFactory} can be created within an
+     * {@link AccessController#doPrivileged AccessController.doPrivileged}
+     * action setting the current thread's access control context to
+     * create threads with the selected permission settings holding
+     * within that action.
      *
-     * <p> Note that while tasks running within such threads will have
+     * <p>Note that while tasks running within such threads will have
      * the same access control and class loader settings as the
      * current thread, they need not have the same {@link
      * java.lang.ThreadLocal} or {@link
      * java.lang.InheritableThreadLocal} values. If necessary,
      * particular values of thread locals can be set or reset before
      * any task runs in {@link ThreadPoolExecutor} subclasses using
-     * {@link ThreadPoolExecutor#beforeExecute}. Also, if it is
-     * necessary to initialize worker threads to have the same
-     * InheritableThreadLocal settings as some other designated
-     * thread, you can create a custom ThreadFactory in which that
-     * thread waits for and services requests to create others that
-     * will inherit its values.
+     * {@link ThreadPoolExecutor#beforeExecute(Thread, Runnable)}.
+     * Also, if it is necessary to initialize worker threads to have
+     * the same InheritableThreadLocal settings as some other
+     * designated thread, you can create a custom ThreadFactory in
+     * which that thread waits for and services requests to create
+     * others that will inherit its values.
      *
      * @return a thread factory
      * @throws AccessControlException if the current access control
      * context does not have permission to both get and set context
-     * class loader.
+     * class loader
      */
     public static ThreadFactory privilegedThreadFactory() {
         return new PrivilegedThreadFactory();
@@ -357,7 +394,7 @@
      * Returns a {@link Callable} object that, when
      * called, runs the given task and returns the given result.  This
      * can be useful when applying methods requiring a
-     * <tt>Callable</tt> to an otherwise resultless action.
+     * {@code Callable} to an otherwise resultless action.
      * @param task the task to run
      * @param result the result to return
      * @return a callable object
@@ -371,7 +408,7 @@
 
     /**
      * Returns a {@link Callable} object that, when
-     * called, runs the given task and returns <tt>null</tt>.
+     * called, runs the given task and returns {@code null}.
      * @param task the task to run
      * @return a callable object
      * @throws NullPointerException if task null
@@ -412,18 +449,17 @@
     }
 
     /**
-     * Returns a {@link Callable} object that will, when
-     * called, execute the given <tt>callable</tt> under the current
-     * access control context. This method should normally be
-     * invoked within an {@link AccessController#doPrivileged} action
-     * to create callables that will, if possible, execute under the
-     * selected permission settings holding within that action; or if
-     * not possible, throw an associated {@link
+     * Returns a {@link Callable} object that will, when called,
+     * execute the given {@code callable} under the current access
+     * control context. This method should normally be invoked within
+     * an {@link AccessController#doPrivileged AccessController.doPrivileged}
+     * action to create callables that will, if possible, execute
+     * under the selected permission settings holding within that
+     * action; or if not possible, throw an associated {@link
      * AccessControlException}.
      * @param callable the underlying task
      * @return a callable object
      * @throws NullPointerException if callable null
-     *
      */
     public static <T> Callable<T> privilegedCallable(Callable<T> callable) {
         if (callable == null)
@@ -432,22 +468,23 @@
     }
 
     /**
-     * Returns a {@link Callable} object that will, when
-     * called, execute the given <tt>callable</tt> under the current
-     * access control context, with the current context class loader
-     * as the context class loader. This method should normally be
-     * invoked within an {@link AccessController#doPrivileged} action
-     * to create callables that will, if possible, execute under the
-     * selected permission settings holding within that action; or if
-     * not possible, throw an associated {@link
+     * Returns a {@link Callable} object that will, when called,
+     * execute the given {@code callable} under the current access
+     * control context, with the current context class loader as the
+     * context class loader. This method should normally be invoked
+     * within an
+     * {@link AccessController#doPrivileged AccessController.doPrivileged}
+     * action to create callables that will, if possible, execute
+     * under the selected permission settings holding within that
+     * action; or if not possible, throw an associated {@link
      * AccessControlException}.
+     *
      * @param callable the underlying task
-     *
      * @return a callable object
      * @throws NullPointerException if callable null
      * @throws AccessControlException if the current access control
      * context does not have permission to both set and get context
-     * class loader.
+     * class loader
      */
     public static <T> Callable<T> privilegedCallableUsingCurrentClassLoader(Callable<T> callable) {
         if (callable == null)
@@ -699,7 +736,6 @@
         }
     }
 
-
     /** Cannot instantiate. */
     private Executors() {}
 }
--- a/src/share/classes/java/util/concurrent/ForkJoinPool.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/ForkJoinPool.java	Mon Jul 22 17:37:15 2013 -0700
@@ -47,6 +47,7 @@
 import java.util.concurrent.Future;
 import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.RunnableFuture;
+import java.util.concurrent.ThreadLocalRandom;
 import java.util.concurrent.TimeUnit;
 
 /**
@@ -79,9 +80,9 @@
  * level; by default, equal to the number of available processors. The
  * pool attempts to maintain enough active (or available) threads by
  * dynamically adding, suspending, or resuming internal worker
- * threads, even if some tasks are stalled waiting to join
- * others. However, no such adjustments are guaranteed in the face of
- * blocked I/O or other unmanaged synchronization. The nested {@link
+ * threads, even if some tasks are stalled waiting to join others.
+ * However, no such adjustments are guaranteed in the face of blocked
+ * I/O or other unmanaged synchronization. The nested {@link
  * ManagedBlocker} interface enables extension of the kinds of
  * synchronization accommodated.
  *
@@ -157,6 +158,7 @@
  * @since 1.7
  * @author Doug Lea
  */
+@sun.misc.Contended
 public class ForkJoinPool extends AbstractExecutorService {
 
     /*
@@ -189,32 +191,35 @@
      * (http://research.sun.com/scalable/pubs/index.html) and
      * "Idempotent work stealing" by Michael, Saraswat, and Vechev,
      * PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
-     * The main differences ultimately stem from GC requirements that
-     * we null out taken slots as soon as we can, to maintain as small
-     * a footprint as possible even in programs generating huge
-     * numbers of tasks. To accomplish this, we shift the CAS
-     * arbitrating pop vs poll (steal) from being on the indices
-     * ("base" and "top") to the slots themselves.  So, both a
-     * successful pop and poll mainly entail a CAS of a slot from
-     * non-null to null.  Because we rely on CASes of references, we
-     * do not need tag bits on base or top.  They are simple ints as
-     * used in any circular array-based queue (see for example
-     * ArrayDeque).  Updates to the indices must still be ordered in a
-     * way that guarantees that top == base means the queue is empty,
-     * but otherwise may err on the side of possibly making the queue
-     * appear nonempty when a push, pop, or poll have not fully
-     * committed. Note that this means that the poll operation,
-     * considered individually, is not wait-free. One thief cannot
-     * successfully continue until another in-progress one (or, if
-     * previously empty, a push) completes.  However, in the
-     * aggregate, we ensure at least probabilistic non-blockingness.
-     * If an attempted steal fails, a thief always chooses a different
-     * random victim target to try next. So, in order for one thief to
-     * progress, it suffices for any in-progress poll or new push on
-     * any empty queue to complete. (This is why we normally use
-     * method pollAt and its variants that try once at the apparent
-     * base index, else consider alternative actions, rather than
-     * method poll.)
+     * See also "Correct and Efficient Work-Stealing for Weak Memory
+     * Models" by Le, Pop, Cohen, and Nardelli, PPoPP 2013
+     * (http://www.di.ens.fr/~zappa/readings/ppopp13.pdf) for an
+     * analysis of memory ordering (atomic, volatile etc) issues.  The
+     * main differences ultimately stem from GC requirements that we
+     * null out taken slots as soon as we can, to maintain as small a
+     * footprint as possible even in programs generating huge numbers
+     * of tasks. To accomplish this, we shift the CAS arbitrating pop
+     * vs poll (steal) from being on the indices ("base" and "top") to
+     * the slots themselves.  So, both a successful pop and poll
+     * mainly entail a CAS of a slot from non-null to null.  Because
+     * we rely on CASes of references, we do not need tag bits on base
+     * or top.  They are simple ints as used in any circular
+     * array-based queue (see for example ArrayDeque).  Updates to the
+     * indices must still be ordered in a way that guarantees that top
+     * == base means the queue is empty, but otherwise may err on the
+     * side of possibly making the queue appear nonempty when a push,
+     * pop, or poll have not fully committed. Note that this means
+     * that the poll operation, considered individually, is not
+     * wait-free. One thief cannot successfully continue until another
+     * in-progress one (or, if previously empty, a push) completes.
+     * However, in the aggregate, we ensure at least probabilistic
+     * non-blockingness.  If an attempted steal fails, a thief always
+     * chooses a different random victim target to try next. So, in
+     * order for one thief to progress, it suffices for any
+     * in-progress poll or new push on any empty queue to
+     * complete. (This is why we normally use method pollAt and its
+     * variants that try once at the apparent base index, else
+     * consider alternative actions, rather than method poll.)
      *
      * This approach also enables support of a user mode in which local
      * task processing is in FIFO, not LIFO order, simply by using
@@ -334,37 +339,35 @@
      * has not yet entered the wait queue. We solve this by requiring
      * a full sweep of all workers (via repeated calls to method
      * scan()) both before and after a newly waiting worker is added
-     * to the wait queue. During a rescan, the worker might release
-     * some other queued worker rather than itself, which has the same
-     * net effect. Because enqueued workers may actually be rescanning
-     * rather than waiting, we set and clear the "parker" field of
-     * WorkQueues to reduce unnecessary calls to unpark.  (This
-     * requires a secondary recheck to avoid missed signals.)  Note
-     * the unusual conventions about Thread.interrupts surrounding
-     * parking and other blocking: Because interrupts are used solely
-     * to alert threads to check termination, which is checked anyway
-     * upon blocking, we clear status (using Thread.interrupted)
-     * before any call to park, so that park does not immediately
-     * return due to status being set via some other unrelated call to
-     * interrupt in user code.
+     * to the wait queue.  Because enqueued workers may actually be
+     * rescanning rather than waiting, we set and clear the "parker"
+     * field of WorkQueues to reduce unnecessary calls to unpark.
+     * (This requires a secondary recheck to avoid missed signals.)
+     * Note the unusual conventions about Thread.interrupts
+     * surrounding parking and other blocking: Because interrupts are
+     * used solely to alert threads to check termination, which is
+     * checked anyway upon blocking, we clear status (using
+     * Thread.interrupted) before any call to park, so that park does
+     * not immediately return due to status being set via some other
+     * unrelated call to interrupt in user code.
      *
      * Signalling.  We create or wake up workers only when there
      * appears to be at least one task they might be able to find and
-     * execute. However, many other threads may notice the same task
-     * and each signal to wake up a thread that might take it. So in
-     * general, pools will be over-signalled.  When a submission is
-     * added or another worker adds a task to a queue that has fewer
-     * than two tasks, they signal waiting workers (or trigger
-     * creation of new ones if fewer than the given parallelism level
-     * -- signalWork), and may leave a hint to the unparked worker to
-     * help signal others upon wakeup).  These primary signals are
-     * buttressed by others (see method helpSignal) whenever other
-     * threads scan for work or do not have a task to process.  On
-     * most platforms, signalling (unpark) overhead time is noticeably
+     * execute.  When a submission is added or another worker adds a
+     * task to a queue that has fewer than two tasks, they signal
+     * waiting workers (or trigger creation of new ones if fewer than
+     * the given parallelism level -- signalWork).  These primary
+     * signals are buttressed by others whenever other threads remove
+     * a task from a queue and notice that there are other tasks there
+     * as well.  So in general, pools will be over-signalled. On most
+     * platforms, signalling (unpark) overhead time is noticeably
      * long, and the time between signalling a thread and it actually
      * making progress can be very noticeably long, so it is worth
      * offloading these delays from critical paths as much as
-     * possible.
+     * possible. Additionally, workers spin-down gradually, by staying
+     * alive so long as they see the ctl state changing.  Similar
+     * stability-sensing techniques are also used before blocking in
+     * awaitJoin and helpComplete.
      *
      * Trimming workers. To release resources after periods of lack of
      * use, a worker starting to wait when the pool is quiescent will
@@ -477,7 +480,7 @@
      * Common Pool
      * ===========
      *
-     * The static common Pool always exists after static
+     * The static common pool always exists after static
      * initialization.  Since it (or any other created pool) need
      * never be used, we minimize initial construction overhead and
      * footprint to the setup of about a dozen fields, with no nested
@@ -485,8 +488,11 @@
      * fullExternalPush during the first submission to the pool.
      *
      * When external threads submit to the common pool, they can
-     * perform some subtask processing (see externalHelpJoin and
-     * related methods).  We do not need to record whether these
+     * perform subtask processing (see externalHelpJoin and related
+     * methods).  This caller-helps policy makes it sensible to set
+     * common pool parallelism level to one (or more) less than the
+     * total number of available cores, or even zero for pure
+     * caller-runs.  We do not need to record whether external
      * submissions are to the common pool -- if not, externalHelpJoin
      * returns quickly (at the most helping to signal some common pool
      * workers). These submitters would otherwise be blocked waiting
@@ -631,18 +637,10 @@
      * do not want multiple WorkQueue instances or multiple queue
      * arrays sharing cache lines. (It would be best for queue objects
      * and their arrays to share, but there is nothing available to
-     * help arrange that).  Unfortunately, because they are recorded
-     * in a common array, WorkQueue instances are often moved to be
-     * adjacent by garbage collectors. To reduce impact, we use field
-     * padding that works OK on common platforms; this effectively
-     * trades off slightly slower average field access for the sake of
-     * avoiding really bad worst-case access. (Until better JVM
-     * support is in place, this padding is dependent on transient
-     * properties of JVM field layout rules.) We also take care in
-     * allocating, sizing and resizing the array. Non-shared queue
-     * arrays are initialized by workers before use. Others are
-     * allocated on first use.
+     * help arrange that). The @Contended annotation alerts JVMs to
+     * try to keep instances apart.
      */
+    @sun.misc.Contended
     static final class WorkQueue {
         /**
          * Capacity of work-stealing queue array upon initialization.
@@ -664,16 +662,12 @@
          */
         static final int MAXIMUM_QUEUE_CAPACITY = 1 << 26; // 64M
 
-        // Heuristic padding to ameliorate unfortunate memory placements
-        volatile long pad00, pad01, pad02, pad03, pad04, pad05, pad06;
-
-        int seed;                  // for random scanning; initialize nonzero
         volatile int eventCount;   // encoded inactivation count; < 0 if inactive
         int nextWait;              // encoded record of next event waiter
-        int hint;                  // steal or signal hint (index)
-        int poolIndex;             // index of this queue in pool (or 0)
-        final int mode;            // 0: lifo, > 0: fifo, < 0: shared
         int nsteals;               // number of steals
+        int hint;                  // steal index hint
+        short poolIndex;           // index of this queue in pool
+        final short mode;          // 0: lifo, > 0: fifo, < 0: shared
         volatile int qlock;        // 1: locked, -1: terminate; else 0
         volatile int base;         // index of next slot for poll
         int top;                   // index of next slot for push
@@ -684,15 +678,12 @@
         volatile ForkJoinTask<?> currentJoin;  // task being joined in awaitJoin
         ForkJoinTask<?> currentSteal; // current non-local task being executed
 
-        volatile Object pad10, pad11, pad12, pad13, pad14, pad15, pad16, pad17;
-        volatile Object pad18, pad19, pad1a, pad1b, pad1c, pad1d;
-
         WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner, int mode,
                   int seed) {
             this.pool = pool;
             this.owner = owner;
-            this.mode = mode;
-            this.seed = seed;
+            this.mode = (short)mode;
+            this.hint = seed; // store initial seed for runWorker
             // Place indices in the center of array (that is not yet allocated)
             base = top = INITIAL_QUEUE_CAPACITY >>> 1;
         }
@@ -705,7 +696,7 @@
             return (n >= 0) ? 0 : -n; // ignore transient negative
         }
 
-       /**
+        /**
          * Provides a more accurate estimate of whether this queue has
          * any tasks than does queueSize, by checking whether a
          * near-empty queue has at least one unclaimed task.
@@ -730,20 +721,18 @@
          */
         final void push(ForkJoinTask<?> task) {
             ForkJoinTask<?>[] a; ForkJoinPool p;
-            int s = top, m, n;
+            int s = top, n;
             if ((a = array) != null) {    // ignore if queue removed
-                int j = (((m = a.length - 1) & s) << ASHIFT) + ABASE;
-                U.putOrderedObject(a, j, task);
-                if ((n = (top = s + 1) - base) <= 2) {
-                    if ((p = pool) != null)
-                        p.signalWork(this);
-                }
+                int m = a.length - 1;
+                U.putOrderedObject(a, ((m & s) << ASHIFT) + ABASE, task);
+                if ((n = (top = s + 1) - base) <= 2)
+                    (p = pool).signalWork(p.workQueues, this);
                 else if (n >= m)
                     growArray();
             }
         }
 
-       /**
+        /**
          * Initializes or doubles the capacity of array. Call either
          * by owner or with lock held -- it is OK for base, but not
          * top, to move while resizings are in progress.
@@ -801,9 +790,8 @@
             if ((a = array) != null) {
                 int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
                 if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null &&
-                    base == b &&
-                    U.compareAndSwapObject(a, j, t, null)) {
-                    base = b + 1;
+                    base == b && U.compareAndSwapObject(a, j, t, null)) {
+                    U.putOrderedInt(this, QBASE, b + 1);
                     return t;
                 }
             }
@@ -819,9 +807,8 @@
                 int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
                 t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
                 if (t != null) {
-                    if (base == b &&
-                        U.compareAndSwapObject(a, j, t, null)) {
-                        base = b + 1;
+                    if (U.compareAndSwapObject(a, j, t, null)) {
+                        U.putOrderedInt(this, QBASE, b + 1);
                         return t;
                     }
                 }
@@ -878,49 +865,43 @@
                 ForkJoinTask.cancelIgnoringExceptions(t);
         }
 
-        /**
-         * Computes next value for random probes.  Scans don't require
-         * a very high quality generator, but also not a crummy one.
-         * Marsaglia xor-shift is cheap and works well enough.  Note:
-         * This is manually inlined in its usages in ForkJoinPool to
-         * avoid writes inside busy scan loops.
-         */
-        final int nextSeed() {
-            int r = seed;
-            r ^= r << 13;
-            r ^= r >>> 17;
-            return seed = r ^= r << 5;
-        }
-
         // Specialized execution methods
 
         /**
-         * Pops and runs tasks until empty.
-         */
-        private void popAndExecAll() {
-            // A bit faster than repeated pop calls
-            ForkJoinTask<?>[] a; int m, s; long j; ForkJoinTask<?> t;
-            while ((a = array) != null && (m = a.length - 1) >= 0 &&
-                   (s = top - 1) - base >= 0 &&
-                   (t = ((ForkJoinTask<?>)
-                         U.getObject(a, j = ((m & s) << ASHIFT) + ABASE)))
-                   != null) {
-                if (U.compareAndSwapObject(a, j, t, null)) {
-                    top = s;
-                    t.doExec();
-                }
-            }
-        }
-
-        /**
          * Polls and runs tasks until empty.
          */
-        private void pollAndExecAll() {
+        final void pollAndExecAll() {
             for (ForkJoinTask<?> t; (t = poll()) != null;)
                 t.doExec();
         }
 
         /**
+         * Executes a top-level task and any local tasks remaining
+         * after execution.
+         */
+        final void runTask(ForkJoinTask<?> task) {
+            if ((currentSteal = task) != null) {
+                task.doExec();
+                ForkJoinTask<?>[] a = array;
+                int md = mode;
+                ++nsteals;
+                currentSteal = null;
+                if (md != 0)
+                    pollAndExecAll();
+                else if (a != null) {
+                    int s, m = a.length - 1;
+                    ForkJoinTask<?> t;
+                    while ((s = top - 1) - base >= 0 &&
+                           (t = (ForkJoinTask<?>)U.getAndSetObject
+                            (a, ((m & s) << ASHIFT) + ABASE, null)) != null) {
+                        top = s;
+                        t.doExec();
+                    }
+                }
+            }
+        }
+
+        /**
          * If present, removes from queue and executes the given task,
          * or any other cancelled task. Returns (true) on any CAS
          * or consistency check failure so caller can retry.
@@ -928,13 +909,15 @@
          * @return false if no progress can be made, else true
          */
         final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
-            boolean stat = true, removed = false, empty = true;
+            boolean stat;
             ForkJoinTask<?>[] a; int m, s, b, n;
-            if ((a = array) != null && (m = a.length - 1) >= 0 &&
+            if (task != null && (a = array) != null && (m = a.length - 1) >= 0 &&
                 (n = (s = top) - (b = base)) > 0) {
+                boolean removed = false, empty = true;
+                stat = true;
                 for (ForkJoinTask<?> t;;) {           // traverse from s to b
-                    int j = ((--s & m) << ASHIFT) + ABASE;
-                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
+                    long j = ((--s & m) << ASHIFT) + ABASE;
+                    t = (ForkJoinTask<?>)U.getObject(a, j);
                     if (t == null)                    // inconsistent length
                         break;
                     else if (t == task) {
@@ -962,68 +945,95 @@
                         break;
                     }
                 }
+                if (removed)
+                    task.doExec();
             }
-            if (removed)
-                task.doExec();
+            else
+                stat = false;
             return stat;
         }
 
         /**
-         * Polls for and executes the given task or any other task in
-         * its CountedCompleter computation.
+         * Tries to poll for and execute the given task or any other
+         * task in its CountedCompleter computation.
          */
-        final boolean pollAndExecCC(ForkJoinTask<?> root) {
-            ForkJoinTask<?>[] a; int b; Object o;
-            outer: while ((b = base) - top < 0 && (a = array) != null) {
+        final boolean pollAndExecCC(CountedCompleter<?> root) {
+            ForkJoinTask<?>[] a; int b; Object o; CountedCompleter<?> t, r;
+            if ((b = base) - top < 0 && (a = array) != null) {
                 long j = (((a.length - 1) & b) << ASHIFT) + ABASE;
-                if ((o = U.getObject(a, j)) == null ||
-                    !(o instanceof CountedCompleter))
-                    break;
-                for (CountedCompleter<?> t = (CountedCompleter<?>)o, r = t;;) {
-                    if (r == root) {
-                        if (base == b &&
-                            U.compareAndSwapObject(a, j, t, null)) {
-                            base = b + 1;
-                            t.doExec();
+                if ((o = U.getObjectVolatile(a, j)) == null)
+                    return true; // retry
+                if (o instanceof CountedCompleter) {
+                    for (t = (CountedCompleter<?>)o, r = t;;) {
+                        if (r == root) {
+                            if (base == b &&
+                                U.compareAndSwapObject(a, j, t, null)) {
+                                U.putOrderedInt(this, QBASE, b + 1);
+                                t.doExec();
+                            }
                             return true;
                         }
-                        else
-                            break; // restart
+                        else if ((r = r.completer) == null)
+                            break; // not part of root computation
                     }
-                    if ((r = r.completer) == null)
-                        break outer; // not part of root computation
                 }
             }
             return false;
         }
 
         /**
-         * Executes a top-level task and any local tasks remaining
-         * after execution.
+         * Tries to pop and execute the given task or any other task
+         * in its CountedCompleter computation.
          */
-        final void runTask(ForkJoinTask<?> t) {
-            if (t != null) {
-                (currentSteal = t).doExec();
-                currentSteal = null;
-                ++nsteals;
-                if (base - top < 0) {       // process remaining local tasks
-                    if (mode == 0)
-                        popAndExecAll();
-                    else
-                        pollAndExecAll();
+        final boolean externalPopAndExecCC(CountedCompleter<?> root) {
+            ForkJoinTask<?>[] a; int s; Object o; CountedCompleter<?> t, r;
+            if (base - (s = top) < 0 && (a = array) != null) {
+                long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE;
+                if ((o = U.getObject(a, j)) instanceof CountedCompleter) {
+                    for (t = (CountedCompleter<?>)o, r = t;;) {
+                        if (r == root) {
+                            if (U.compareAndSwapInt(this, QLOCK, 0, 1)) {
+                                if (top == s && array == a &&
+                                    U.compareAndSwapObject(a, j, t, null)) {
+                                    top = s - 1;
+                                    qlock = 0;
+                                    t.doExec();
+                                }
+                                else
+                                    qlock = 0;
+                            }
+                            return true;
+                        }
+                        else if ((r = r.completer) == null)
+                            break;
+                    }
                 }
             }
+            return false;
         }
 
         /**
-         * Executes a non-top-level (stolen) task.
+         * Internal version
          */
-        final void runSubtask(ForkJoinTask<?> t) {
-            if (t != null) {
-                ForkJoinTask<?> ps = currentSteal;
-                (currentSteal = t).doExec();
-                currentSteal = ps;
+        final boolean internalPopAndExecCC(CountedCompleter<?> root) {
+            ForkJoinTask<?>[] a; int s; Object o; CountedCompleter<?> t, r;
+            if (base - (s = top) < 0 && (a = array) != null) {
+                long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE;
+                if ((o = U.getObject(a, j)) instanceof CountedCompleter) {
+                    for (t = (CountedCompleter<?>)o, r = t;;) {
+                        if (r == root) {
+                            if (U.compareAndSwapObject(a, j, t, null)) {
+                                top = s - 1;
+                                t.doExec();
+                            }
+                            return true;
+                        }
+                        else if ((r = r.completer) == null)
+                            break;
+                    }
+                }
             }
+            return false;
         }
 
         /**
@@ -1040,6 +1050,7 @@
 
         // Unsafe mechanics
         private static final sun.misc.Unsafe U;
+        private static final long QBASE;
         private static final long QLOCK;
         private static final int ABASE;
         private static final int ASHIFT;
@@ -1048,6 +1059,8 @@
                 U = sun.misc.Unsafe.getUnsafe();
                 Class<?> k = WorkQueue.class;
                 Class<?> ak = ForkJoinTask[].class;
+                QBASE = U.objectFieldOffset
+                    (k.getDeclaredField("base"));
                 QLOCK = U.objectFieldOffset
                     (k.getDeclaredField("qlock"));
                 ABASE = U.arrayBaseOffset(ak);
@@ -1087,7 +1100,7 @@
     /**
      * Common pool parallelism. To allow simpler use and management
      * when common pool threads are disabled, we allow the underlying
-     * common.config field to be zero, but in that case still report
+     * common.parallelism field to be zero, but in that case still report
      * parallelism as 1 to reflect resulting caller-runs mechanics.
      */
     static final int commonParallelism;
@@ -1227,35 +1240,18 @@
     static final int FIFO_QUEUE          =  1;
     static final int SHARED_QUEUE        = -1;
 
-    // bounds for #steps in scan loop -- must be power 2 minus 1
-    private static final int MIN_SCAN    = 0x1ff;   // cover estimation slop
-    private static final int MAX_SCAN    = 0x1ffff; // 4 * max workers
-
     // Instance fields
-
-    /*
-     * Field layout of this class tends to matter more than one would
-     * like. Runtime layout order is only loosely related to
-     * declaration order and may differ across JVMs, but the following
-     * empirically works OK on current JVMs.
-     */
-
-    // Heuristic padding to ameliorate unfortunate memory placements
-    volatile long pad00, pad01, pad02, pad03, pad04, pad05, pad06;
-
     volatile long stealCount;                  // collects worker counts
     volatile long ctl;                         // main pool control
     volatile int plock;                        // shutdown status and seqLock
     volatile int indexSeed;                    // worker/submitter index seed
-    final int config;                          // mode and parallelism level
+    final short parallelism;                   // parallelism level
+    final short mode;                          // LIFO/FIFO
     WorkQueue[] workQueues;                    // main registry
     final ForkJoinWorkerThreadFactory factory;
     final UncaughtExceptionHandler ueh;        // per-worker UEH
     final String workerNamePrefix;             // to create worker name string
 
-    volatile Object pad10, pad11, pad12, pad13, pad14, pad15, pad16, pad17;
-    volatile Object pad18, pad19, pad1a, pad1b;
-
     /**
      * Acquires the plock lock to protect worker array and related
      * updates. This method is called only if an initial CAS on plock
@@ -1307,11 +1303,11 @@
      * parallelism level exist. Adjusts counts etc on failure.
      */
     private void tryAddWorker() {
-        long c; int u;
+        long c; int u, e;
         while ((u = (int)((c = ctl) >>> 32)) < 0 &&
-               (u & SHORT_SIGN) != 0 && (int)c == 0) {
-            long nc = (long)(((u + UTC_UNIT) & UTC_MASK) |
-                             ((u + UAC_UNIT) & UAC_MASK)) << 32;
+               (u & SHORT_SIGN) != 0 && (e = (int)c) >= 0) {
+            long nc = ((long)(((u + UTC_UNIT) & UTC_MASK) |
+                              ((u + UAC_UNIT) & UAC_MASK)) << 32) | (long)e;
             if (U.compareAndSwapLong(this, CTL, c, nc)) {
                 ForkJoinWorkerThreadFactory fac;
                 Throwable ex = null;
@@ -1322,8 +1318,8 @@
                         wt.start();
                         break;
                     }
-                } catch (Throwable e) {
-                    ex = e;
+                } catch (Throwable rex) {
+                    ex = rex;
                 }
                 deregisterWorker(wt, ex);
                 break;
@@ -1351,7 +1347,7 @@
         do {} while (!U.compareAndSwapInt(this, INDEXSEED, s = indexSeed,
                                           s += SEED_INCREMENT) ||
                      s == 0); // skip 0
-        WorkQueue w = new WorkQueue(this, wt, config >>> 16, s);
+        WorkQueue w = new WorkQueue(this, wt, mode, s);
         if (((ps = plock) & PL_LOCK) != 0 ||
             !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
             ps = acquirePlock();
@@ -1371,14 +1367,15 @@
                         }
                     }
                 }
-                w.eventCount = w.poolIndex = r; // volatile write orders
+                w.poolIndex = (short)r;
+                w.eventCount = r; // volatile write orders
                 ws[r] = w;
             }
         } finally {
             if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
                 releasePlock(nps);
         }
-        wt.setName(workerNamePrefix.concat(Integer.toString(w.poolIndex)));
+        wt.setName(workerNamePrefix.concat(Integer.toString(w.poolIndex >>> 1)));
         return w;
     }
 
@@ -1396,9 +1393,7 @@
         if (wt != null && (w = wt.workQueue) != null) {
             int ps;
             w.qlock = -1;                // ensure set
-            long ns = w.nsteals, sc;     // collect steal count
-            do {} while (!U.compareAndSwapLong(this, STEALCOUNT,
-                                               sc = stealCount, sc + ns));
+            U.getAndAddLong(this, STEALCOUNT, w.nsteals); // collect steals
             if (((ps = plock) & PL_LOCK) != 0 ||
                 !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
                 ps = acquirePlock();
@@ -1464,19 +1459,21 @@
      * @param task the task. Caller must ensure non-null.
      */
     final void externalPush(ForkJoinTask<?> task) {
-        WorkQueue[] ws; WorkQueue q; int z, m; ForkJoinTask<?>[] a;
-        if ((z = ThreadLocalRandom.getProbe()) != 0 && plock > 0 &&
-            (ws = workQueues) != null && (m = (ws.length - 1)) >= 0 &&
-            (q = ws[m & z & SQMASK]) != null &&
+        WorkQueue q; int m, s, n, am; ForkJoinTask<?>[] a;
+        int r = ThreadLocalRandom.getProbe();
+        int ps = plock;
+        WorkQueue[] ws = workQueues;
+        if (ps > 0 && ws != null && (m = (ws.length - 1)) >= 0 &&
+            (q = ws[m & r & SQMASK]) != null && r != 0 &&
             U.compareAndSwapInt(q, QLOCK, 0, 1)) { // lock
-            int b = q.base, s = q.top, n, an;
-            if ((a = q.array) != null && (an = a.length) > (n = s + 1 - b)) {
-                int j = (((an - 1) & s) << ASHIFT) + ABASE;
+            if ((a = q.array) != null &&
+                (am = a.length - 1) > (n = (s = q.top) - q.base)) {
+                int j = ((am & s) << ASHIFT) + ABASE;
                 U.putOrderedObject(a, j, task);
                 q.top = s + 1;                     // push on to deque
                 q.qlock = 0;
-                if (n <= 2)
-                    signalWork(q);
+                if (n <= 1)
+                    signalWork(ws, q);
                 return;
             }
             q.qlock = 0;
@@ -1514,7 +1511,7 @@
                 throw new RejectedExecutionException();
             else if (ps == 0 || (ws = workQueues) == null ||
                      (m = ws.length - 1) < 0) { // initialize workQueues
-                int p = config & SMASK;         // find power of two table size
+                int p = parallelism;            // find power of two table size
                 int n = (p > 1) ? p - 1 : 1;    // ensure at least 2 slots
                 n |= n >>> 1; n |= n >>> 2;  n |= n >>> 4;
                 n |= n >>> 8; n |= n >>> 16; n = (n + 1) << 1;
@@ -1546,7 +1543,7 @@
                         q.qlock = 0;  // unlock
                     }
                     if (submitted) {
-                        signalWork(q);
+                        signalWork(ws, q);
                         return;
                     }
                 }
@@ -1554,6 +1551,7 @@
             }
             else if (((ps = plock) & PL_LOCK) == 0) { // create new queue
                 q = new WorkQueue(this, null, SHARED_QUEUE, r);
+                q.poolIndex = (short)k;
                 if (((ps = plock) & PL_LOCK) != 0 ||
                     !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
                     ps = acquirePlock();
@@ -1577,41 +1575,42 @@
      */
     final void incrementActiveCount() {
         long c;
-        do {} while (!U.compareAndSwapLong(this, CTL, c = ctl, c + AC_UNIT));
+        do {} while (!U.compareAndSwapLong
+                     (this, CTL, c = ctl, ((c & ~AC_MASK) |
+                                           ((c & AC_MASK) + AC_UNIT))));
     }
 
     /**
      * Tries to create or activate a worker if too few are active.
      *
-     * @param q the (non-null) queue holding tasks to be signalled
+     * @param ws the worker array to use to find signallees
+     * @param q if non-null, the queue holding tasks to be processed
      */
-    final void signalWork(WorkQueue q) {
-        int hint = q.poolIndex;
-        long c; int e, u, i, n; WorkQueue[] ws; WorkQueue w; Thread p;
-        while ((u = (int)((c = ctl) >>> 32)) < 0) {
-            if ((e = (int)c) > 0) {
-                if ((ws = workQueues) != null && ws.length > (i = e & SMASK) &&
-                    (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
-                    long nc = (((long)(w.nextWait & E_MASK)) |
-                               ((long)(u + UAC_UNIT) << 32));
-                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
-                        w.hint = hint;
-                        w.eventCount = (e + E_SEQ) & E_MASK;
-                        if ((p = w.parker) != null)
-                            U.unpark(p);
-                        break;
-                    }
-                    if (q.top - q.base <= 0)
-                        break;
-                }
-                else
-                    break;
-            }
-            else {
+    final void signalWork(WorkQueue[] ws, WorkQueue q) {
+        for (;;) {
+            long c; int e, u, i; WorkQueue w; Thread p;
+            if ((u = (int)((c = ctl) >>> 32)) >= 0)
+                break;
+            if ((e = (int)c) <= 0) {
                 if ((short)u < 0)
                     tryAddWorker();
                 break;
             }
+            if (ws == null || ws.length <= (i = e & SMASK) ||
+                (w = ws[i]) == null)
+                break;
+            long nc = (((long)(w.nextWait & E_MASK)) |
+                       ((long)(u + UAC_UNIT)) << 32);
+            int ne = (e + E_SEQ) & E_MASK;
+            if (w.eventCount == (e | INT_SIGN) &&
+                U.compareAndSwapLong(this, CTL, c, nc)) {
+                w.eventCount = ne;
+                if ((p = w.parker) != null)
+                    U.unpark(p);
+                break;
+            }
+            if (q != null && q.base >= q.top)
+                break;
         }
     }
 
@@ -1622,215 +1621,152 @@
      */
     final void runWorker(WorkQueue w) {
         w.growArray(); // allocate queue
-        do { w.runTask(scan(w)); } while (w.qlock >= 0);
+        for (int r = w.hint; scan(w, r) == 0; ) {
+            r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
+        }
     }
 
     /**
-     * Scans for and, if found, returns one task, else possibly
+     * Scans for and, if found, runs one task, else possibly
      * inactivates the worker. This method operates on single reads of
      * volatile state and is designed to be re-invoked continuously,
      * in part because it returns upon detecting inconsistencies,
      * contention, or state changes that indicate possible success on
      * re-invocation.
      *
-     * The scan searches for tasks across queues (starting at a random
-     * index, and relying on registerWorker to irregularly scatter
-     * them within array to avoid bias), checking each at least twice.
-     * The scan terminates upon either finding a non-empty queue, or
-     * completing the sweep. If the worker is not inactivated, it
-     * takes and returns a task from this queue. Otherwise, if not
-     * activated, it signals workers (that may include itself) and
-     * returns so caller can retry. Also returns for true if the
-     * worker array may have changed during an empty scan.  On failure
-     * to find a task, we take one of the following actions, after
-     * which the caller will retry calling this method unless
-     * terminated.
-     *
-     * * If pool is terminating, terminate the worker.
-     *
-     * * If not already enqueued, try to inactivate and enqueue the
-     * worker on wait queue. Or, if inactivating has caused the pool
-     * to be quiescent, relay to idleAwaitWork to possibly shrink
-     * pool.
-     *
-     * * If already enqueued and none of the above apply, possibly
-     * park awaiting signal, else lingering to help scan and signal.
-     *
-     * * If a non-empty queue discovered or left as a hint,
-     * help wake up other workers before return.
+     * The scan searches for tasks across queues starting at a random
+     * index, checking each at least twice.  The scan terminates upon
+     * either finding a non-empty queue, or completing the sweep. If
+     * the worker is not inactivated, it takes and runs a task from
+     * this queue. Otherwise, if not activated, it tries to activate
+     * itself or some other worker by signalling. On failure to find a
+     * task, returns (for retry) if pool state may have changed during
+     * an empty scan, or tries to inactivate if active, else possibly
+     * blocks or terminates via method awaitWork.
      *
      * @param w the worker (via its WorkQueue)
-     * @return a task or null if none found
+     * @param r a random seed
+     * @return worker qlock status if would have waited, else 0
      */
-    private final ForkJoinTask<?> scan(WorkQueue w) {
+    private final int scan(WorkQueue w, int r) {
         WorkQueue[] ws; int m;
-        int ps = plock;                          // read plock before ws
-        if (w != null && (ws = workQueues) != null && (m = ws.length - 1) >= 0) {
-            int ec = w.eventCount;               // ec is negative if inactive
-            int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
-            w.hint = -1;                         // update seed and clear hint
-            int j = ((m + m + 1) | MIN_SCAN) & MAX_SCAN;
-            do {
-                WorkQueue q; ForkJoinTask<?>[] a; int b;
-                if ((q = ws[(r + j) & m]) != null && (b = q.base) - q.top < 0 &&
-                    (a = q.array) != null) {     // probably nonempty
-                    int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
-                    ForkJoinTask<?> t = (ForkJoinTask<?>)
-                        U.getObjectVolatile(a, i);
-                    if (q.base == b && ec >= 0 && t != null &&
-                        U.compareAndSwapObject(a, i, t, null)) {
-                        if ((q.base = b + 1) - q.top < 0)
-                            signalWork(q);
-                        return t;                // taken
-                    }
-                    else if ((ec < 0 || j < m) && (int)(ctl >> AC_SHIFT) <= 0) {
-                        w.hint = (r + j) & m;    // help signal below
-                        break;                   // cannot take
+        long c = ctl;                            // for consistency check
+        if ((ws = workQueues) != null && (m = ws.length - 1) >= 0 && w != null) {
+            for (int j = m + m + 1, ec = w.eventCount;;) {
+                WorkQueue q; int b, e; ForkJoinTask<?>[] a; ForkJoinTask<?> t;
+                if ((q = ws[(r - j) & m]) != null &&
+                    (b = q.base) - q.top < 0 && (a = q.array) != null) {
+                    long i = (((a.length - 1) & b) << ASHIFT) + ABASE;
+                    if ((t = ((ForkJoinTask<?>)
+                              U.getObjectVolatile(a, i))) != null) {
+                        if (ec < 0)
+                            helpRelease(c, ws, w, q, b);
+                        else if (q.base == b &&
+                                 U.compareAndSwapObject(a, i, t, null)) {
+                            U.putOrderedInt(q, QBASE, b + 1);
+                            if ((b + 1) - q.top < 0)
+                                signalWork(ws, q);
+                            w.runTask(t);
+                        }
                     }
-                }
-            } while (--j >= 0);
-
-            int h, e, ns; long c, sc; WorkQueue q;
-            if ((ns = w.nsteals) != 0) {
-                if (U.compareAndSwapLong(this, STEALCOUNT,
-                                         sc = stealCount, sc + ns))
-                    w.nsteals = 0;               // collect steals and rescan
-            }
-            else if (plock != ps)                // consistency check
-                ;                                // skip
-            else if ((e = (int)(c = ctl)) < 0)
-                w.qlock = -1;                    // pool is terminating
-            else {
-                if ((h = w.hint) < 0) {
-                    if (ec >= 0) {               // try to enqueue/inactivate
-                        long nc = (((long)ec |
-                                    ((c - AC_UNIT) & (AC_MASK|TC_MASK))));
-                        w.nextWait = e;          // link and mark inactive
-                        w.eventCount = ec | INT_SIGN;
-                        if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc))
-                            w.eventCount = ec;   // unmark on CAS failure
-                        else if ((int)(c >> AC_SHIFT) == 1 - (config & SMASK))
-                            idleAwaitWork(w, nc, c);
-                    }
-                    else if (w.eventCount < 0 && ctl == c) {
-                        Thread wt = Thread.currentThread();
-                        Thread.interrupted();    // clear status
-                        U.putObject(wt, PARKBLOCKER, this);
-                        w.parker = wt;           // emulate LockSupport.park
-                        if (w.eventCount < 0)    // recheck
-                            U.park(false, 0L);   // block
-                        w.parker = null;
-                        U.putObject(wt, PARKBLOCKER, null);
-                    }
+                    break;
                 }
-                if ((h >= 0 || (h = w.hint) >= 0) &&
-                    (ws = workQueues) != null && h < ws.length &&
-                    (q = ws[h]) != null) {      // signal others before retry
-                    WorkQueue v; Thread p; int u, i, s;
-                    for (int n = (config & SMASK) - 1;;) {
-                        int idleCount = (w.eventCount < 0) ? 0 : -1;
-                        if (((s = idleCount - q.base + q.top) <= n &&
-                             (n = s) <= 0) ||
-                            (u = (int)((c = ctl) >>> 32)) >= 0 ||
-                            (e = (int)c) <= 0 || m < (i = e & SMASK) ||
-                            (v = ws[i]) == null)
-                            break;
-                        long nc = (((long)(v.nextWait & E_MASK)) |
-                                   ((long)(u + UAC_UNIT) << 32));
-                        if (v.eventCount != (e | INT_SIGN) ||
-                            !U.compareAndSwapLong(this, CTL, c, nc))
-                            break;
-                        v.hint = h;
-                        v.eventCount = (e + E_SEQ) & E_MASK;
-                        if ((p = v.parker) != null)
-                            U.unpark(p);
-                        if (--n <= 0)
-                            break;
+                else if (--j < 0) {
+                    if ((ec | (e = (int)c)) < 0) // inactive or terminating
+                        return awaitWork(w, c, ec);
+                    else if (ctl == c) {         // try to inactivate and enqueue
+                        long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
+                        w.nextWait = e;
+                        w.eventCount = ec | INT_SIGN;
+                        if (!U.compareAndSwapLong(this, CTL, c, nc))
+                            w.eventCount = ec;   // back out
                     }
-                }
-            }
-        }
-        return null;
-    }
-
-    /**
-     * If inactivating worker w has caused the pool to become
-     * quiescent, checks for pool termination, and, so long as this is
-     * not the only worker, waits for event for up to a given
-     * duration.  On timeout, if ctl has not changed, terminates the
-     * worker, which will in turn wake up another worker to possibly
-     * repeat this process.
-     *
-     * @param w the calling worker
-     * @param currentCtl the ctl value triggering possible quiescence
-     * @param prevCtl the ctl value to restore if thread is terminated
-     */
-    private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
-        if (w != null && w.eventCount < 0 &&
-            !tryTerminate(false, false) && (int)prevCtl != 0 &&
-            ctl == currentCtl) {
-            int dc = -(short)(currentCtl >>> TC_SHIFT);
-            long parkTime = dc < 0 ? FAST_IDLE_TIMEOUT: (dc + 1) * IDLE_TIMEOUT;
-            long deadline = System.nanoTime() + parkTime - TIMEOUT_SLOP;
-            Thread wt = Thread.currentThread();
-            while (ctl == currentCtl) {
-                Thread.interrupted();  // timed variant of version in scan()
-                U.putObject(wt, PARKBLOCKER, this);
-                w.parker = wt;
-                if (ctl == currentCtl)
-                    U.park(false, parkTime);
-                w.parker = null;
-                U.putObject(wt, PARKBLOCKER, null);
-                if (ctl != currentCtl)
-                    break;
-                if (deadline - System.nanoTime() <= 0L &&
-                    U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
-                    w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
-                    w.hint = -1;
-                    w.qlock = -1;   // shrink
                     break;
                 }
             }
         }
+        return 0;
     }
 
     /**
-     * Scans through queues looking for work while joining a task; if
-     * any present, signals. May return early if more signalling is
-     * detectably unneeded.
+     * A continuation of scan(), possibly blocking or terminating
+     * worker w. Returns without blocking if pool state has apparently
+     * changed since last invocation.  Also, if inactivating w has
+     * caused the pool to become quiescent, checks for pool
+     * termination, and, so long as this is not the only worker, waits
+     * for event for up to a given duration.  On timeout, if ctl has
+     * not changed, terminates the worker, which will in turn wake up
+     * another worker to possibly repeat this process.
      *
-     * @param task return early if done
-     * @param origin an index to start scan
+     * @param w the calling worker
+     * @param c the ctl value on entry to scan
+     * @param ec the worker's eventCount on entry to scan
      */
-    private void helpSignal(ForkJoinTask<?> task, int origin) {
-        WorkQueue[] ws; WorkQueue w; Thread p; long c; int m, u, e, i, s;
-        if (task != null && task.status >= 0 &&
-            (u = (int)(ctl >>> 32)) < 0 && (u >> UAC_SHIFT) < 0 &&
-            (ws = workQueues) != null && (m = ws.length - 1) >= 0) {
-            outer: for (int k = origin, j = m; j >= 0; --j) {
-                WorkQueue q = ws[k++ & m];
-                for (int n = m;;) { // limit to at most m signals
-                    if (task.status < 0)
-                        break outer;
-                    if (q == null ||
-                        ((s = -q.base + q.top) <= n && (n = s) <= 0))
-                        break;
-                    if ((u = (int)((c = ctl) >>> 32)) >= 0 ||
-                        (e = (int)c) <= 0 || m < (i = e & SMASK) ||
-                        (w = ws[i]) == null)
-                        break outer;
-                    long nc = (((long)(w.nextWait & E_MASK)) |
-                               ((long)(u + UAC_UNIT) << 32));
-                    if (w.eventCount != (e | INT_SIGN))
-                        break outer;
-                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
-                        w.eventCount = (e + E_SEQ) & E_MASK;
-                        if ((p = w.parker) != null)
-                            U.unpark(p);
-                        if (--n <= 0)
-                            break;
-                    }
+    private final int awaitWork(WorkQueue w, long c, int ec) {
+        int stat, ns; long parkTime, deadline;
+        if ((stat = w.qlock) >= 0 && w.eventCount == ec && ctl == c &&
+            !Thread.interrupted()) {
+            int e = (int)c;
+            int u = (int)(c >>> 32);
+            int d = (u >> UAC_SHIFT) + parallelism; // active count
+
+            if (e < 0 || (d <= 0 && tryTerminate(false, false)))
+                stat = w.qlock = -1;          // pool is terminating
+            else if ((ns = w.nsteals) != 0) { // collect steals and retry
+                w.nsteals = 0;
+                U.getAndAddLong(this, STEALCOUNT, (long)ns);
+            }
+            else {
+                long pc = ((d > 0 || ec != (e | INT_SIGN)) ? 0L :
+                           ((long)(w.nextWait & E_MASK)) | // ctl to restore
+                           ((long)(u + UAC_UNIT)) << 32);
+                if (pc != 0L) {               // timed wait if last waiter
+                    int dc = -(short)(c >>> TC_SHIFT);
+                    parkTime = (dc < 0 ? FAST_IDLE_TIMEOUT:
+                                (dc + 1) * IDLE_TIMEOUT);
+                    deadline = System.nanoTime() + parkTime - TIMEOUT_SLOP;
                 }
+                else
+                    parkTime = deadline = 0L;
+                if (w.eventCount == ec && ctl == c) {
+                    Thread wt = Thread.currentThread();
+                    U.putObject(wt, PARKBLOCKER, this);
+                    w.parker = wt;            // emulate LockSupport.park
+                    if (w.eventCount == ec && ctl == c)
+                        U.park(false, parkTime);  // must recheck before park
+                    w.parker = null;
+                    U.putObject(wt, PARKBLOCKER, null);
+                    if (parkTime != 0L && ctl == c &&
+                        deadline - System.nanoTime() <= 0L &&
+                        U.compareAndSwapLong(this, CTL, c, pc))
+                        stat = w.qlock = -1;  // shrink pool
+                }
+            }
+        }
+        return stat;
+    }
+
+    /**
+     * Possibly releases (signals) a worker. Called only from scan()
+     * when a worker with apparently inactive status finds a non-empty
+     * queue. This requires revalidating all of the associated state
+     * from caller.
+     */
+    private final void helpRelease(long c, WorkQueue[] ws, WorkQueue w,
+                                   WorkQueue q, int b) {
+        WorkQueue v; int e, i; Thread p;
+        if (w != null && w.eventCount < 0 && (e = (int)c) > 0 &&
+            ws != null && ws.length > (i = e & SMASK) &&
+            (v = ws[i]) != null && ctl == c) {
+            long nc = (((long)(v.nextWait & E_MASK)) |
+                       ((long)((int)(c >>> 32) + UAC_UNIT)) << 32);
+            int ne = (e + E_SEQ) & E_MASK;
+            if (q != null && q.base == b && w.eventCount < 0 &&
+                v.eventCount == (e | INT_SIGN) &&
+                U.compareAndSwapLong(this, CTL, c, nc)) {
+                v.eventCount = ne;
+                if ((p = v.parker) != null)
+                    U.unpark(p);
             }
         }
     }
@@ -1855,7 +1791,8 @@
      */
     private int tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
         int stat = 0, steps = 0;                    // bound to avoid cycles
-        if (joiner != null && task != null) {       // hoist null checks
+        if (task != null && joiner != null &&
+            joiner.base - joiner.top >= 0) {        // hoist checks
             restart: for (;;) {
                 ForkJoinTask<?> subtask = task;     // current target
                 for (WorkQueue j = joiner, v;;) {   // v is stealer of subtask
@@ -1882,7 +1819,7 @@
                         }
                     }
                     for (;;) { // help stealer or descend to its stealer
-                        ForkJoinTask[] a;  int b;
+                        ForkJoinTask[] a; int b;
                         if (subtask.status < 0)     // surround probes with
                             continue restart;       //   consistency checks
                         if ((b = v.base) - v.top < 0 && (a = v.array) != null) {
@@ -1893,13 +1830,23 @@
                                 v.currentSteal != subtask)
                                 continue restart;   // stale
                             stat = 1;               // apparent progress
-                            if (t != null && v.base == b &&
-                                U.compareAndSwapObject(a, i, t, null)) {
-                                v.base = b + 1;     // help stealer
-                                joiner.runSubtask(t);
+                            if (v.base == b) {
+                                if (t == null)
+                                    break restart;
+                                if (U.compareAndSwapObject(a, i, t, null)) {
+                                    U.putOrderedInt(v, QBASE, b + 1);
+                                    ForkJoinTask<?> ps = joiner.currentSteal;
+                                    int jt = joiner.top;
+                                    do {
+                                        joiner.currentSteal = t;
+                                        t.doExec(); // clear local tasks too
+                                    } while (task.status >= 0 &&
+                                             joiner.top != jt &&
+                                             (t = joiner.pop()) != null);
+                                    joiner.currentSteal = ps;
+                                    break restart;
+                                }
                             }
-                            else if (v.base == b && ++steps == MAX_HELP)
-                                break restart;      // v apparently stalled
                         }
                         else {                      // empty -- try to descend
                             ForkJoinTask<?> next = v.currentJoin;
@@ -1926,27 +1873,45 @@
      * and run tasks within the target's computation.
      *
      * @param task the task to join
-     * @param mode if shared, exit upon completing any task
-     * if all workers are active
+     * @param maxTasks the maximum number of other tasks to run
      */
-    private int helpComplete(ForkJoinTask<?> task, int mode) {
-        WorkQueue[] ws; WorkQueue q; int m, n, s, u;
-        if (task != null && (ws = workQueues) != null &&
-            (m = ws.length - 1) >= 0) {
-            for (int j = 1, origin = j;;) {
+    final int helpComplete(WorkQueue joiner, CountedCompleter<?> task,
+                           int maxTasks) {
+        WorkQueue[] ws; int m;
+        int s = 0;
+        if ((ws = workQueues) != null && (m = ws.length - 1) >= 0 &&
+            joiner != null && task != null) {
+            int j = joiner.poolIndex;
+            int scans = m + m + 1;
+            long c = 0L;              // for stability check
+            for (int k = scans; ; j += 2) {
+                WorkQueue q;
                 if ((s = task.status) < 0)
-                    return s;
-                if ((q = ws[j & m]) != null && q.pollAndExecCC(task)) {
-                    origin = j;
-                    if (mode == SHARED_QUEUE &&
-                        ((u = (int)(ctl >>> 32)) >= 0 || (u >> UAC_SHIFT) >= 0))
+                    break;
+                else if (joiner.internalPopAndExecCC(task)) {
+                    if (--maxTasks <= 0) {
+                        s = task.status;
                         break;
+                    }
+                    k = scans;
                 }
-                else if ((j = (j + 2) & m) == origin)
+                else if ((s = task.status) < 0)
                     break;
+                else if ((q = ws[j & m]) != null && q.pollAndExecCC(task)) {
+                    if (--maxTasks <= 0) {
+                        s = task.status;
+                        break;
+                    }
+                    k = scans;
+                }
+                else if (--k < 0) {
+                    if (c == (c = ctl))
+                        break;
+                    k = scans;
+                }
             }
         }
-        return 0;
+        return s;
     }
 
     /**
@@ -1955,17 +1920,22 @@
      * for blocking. Fails on contention or termination. Otherwise,
      * adds a new thread if no idle workers are available and pool
      * may become starved.
+     *
+     * @param c the assumed ctl value
      */
-    final boolean tryCompensate() {
-        int pc = config & SMASK, e, i, tc; long c;
-        WorkQueue[] ws; WorkQueue w; Thread p;
-        if ((ws = workQueues) != null && (e = (int)(c = ctl)) >= 0) {
-            if (e != 0 && (i = e & SMASK) < ws.length &&
-                (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
+    final boolean tryCompensate(long c) {
+        WorkQueue[] ws = workQueues;
+        int pc = parallelism, e = (int)c, m, tc;
+        if (ws != null && (m = ws.length - 1) >= 0 && e >= 0 && ctl == c) {
+            WorkQueue w = ws[e & m];
+            if (e != 0 && w != null) {
+                Thread p;
                 long nc = ((long)(w.nextWait & E_MASK) |
                            (c & (AC_MASK|TC_MASK)));
-                if (U.compareAndSwapLong(this, CTL, c, nc)) {
-                    w.eventCount = (e + E_SEQ) & E_MASK;
+                int ne = (e + E_SEQ) & E_MASK;
+                if (w.eventCount == (e | INT_SIGN) &&
+                    U.compareAndSwapLong(this, CTL, c, nc)) {
+                    w.eventCount = ne;
                     if ((p = w.parker) != null)
                         U.unpark(p);
                     return true;   // replace with idle worker
@@ -2008,23 +1978,20 @@
      */
     final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
         int s = 0;
-        if (joiner != null && task != null && (s = task.status) >= 0) {
+        if (task != null && (s = task.status) >= 0 && joiner != null) {
             ForkJoinTask<?> prevJoin = joiner.currentJoin;
             joiner.currentJoin = task;
-            do {} while ((s = task.status) >= 0 && !joiner.isEmpty() &&
-                         joiner.tryRemoveAndExec(task)); // process local tasks
-            if (s >= 0 && (s = task.status) >= 0) {
-                helpSignal(task, joiner.poolIndex);
-                if ((s = task.status) >= 0 &&
-                    (task instanceof CountedCompleter))
-                    s = helpComplete(task, LIFO_QUEUE);
-            }
+            do {} while (joiner.tryRemoveAndExec(task) && // process local tasks
+                         (s = task.status) >= 0);
+            if (s >= 0 && (task instanceof CountedCompleter))
+                s = helpComplete(joiner, (CountedCompleter<?>)task, Integer.MAX_VALUE);
+            long cc = 0;        // for stability checks
             while (s >= 0 && (s = task.status) >= 0) {
-                if ((!joiner.isEmpty() ||           // try helping
-                     (s = tryHelpStealer(joiner, task)) == 0) &&
+                if ((s = tryHelpStealer(joiner, task)) == 0 &&
                     (s = task.status) >= 0) {
-                    helpSignal(task, joiner.poolIndex);
-                    if ((s = task.status) >= 0 && tryCompensate()) {
+                    if (!tryCompensate(cc))
+                        cc = ctl;
+                    else {
                         if (task.trySetSignal() && (s = task.status) >= 0) {
                             synchronized (task) {
                                 if (task.status >= 0) {
@@ -2037,9 +2004,11 @@
                                     task.notifyAll();
                             }
                         }
-                        long c;                          // re-activate
+                        long c; // reactivate
                         do {} while (!U.compareAndSwapLong
-                                     (this, CTL, c = ctl, c + AC_UNIT));
+                                     (this, CTL, c = ctl,
+                                      ((c & ~AC_MASK) |
+                                       ((c & AC_MASK) + AC_UNIT))));
                     }
                 }
             }
@@ -2061,15 +2030,11 @@
         if (joiner != null && task != null && (s = task.status) >= 0) {
             ForkJoinTask<?> prevJoin = joiner.currentJoin;
             joiner.currentJoin = task;
-            do {} while ((s = task.status) >= 0 && !joiner.isEmpty() &&
-                         joiner.tryRemoveAndExec(task));
-            if (s >= 0 && (s = task.status) >= 0) {
-                helpSignal(task, joiner.poolIndex);
-                if ((s = task.status) >= 0 &&
-                    (task instanceof CountedCompleter))
-                    s = helpComplete(task, LIFO_QUEUE);
-            }
-            if (s >= 0 && joiner.isEmpty()) {
+            do {} while (joiner.tryRemoveAndExec(task) && // process local tasks
+                         (s = task.status) >= 0);
+            if (s >= 0) {
+                if (task instanceof CountedCompleter)
+                    helpComplete(joiner, (CountedCompleter<?>)task, Integer.MAX_VALUE);
                 do {} while (task.status >= 0 &&
                              tryHelpStealer(joiner, task) > 0);
             }
@@ -2081,14 +2046,14 @@
      * Returns a (probably) non-empty steal queue, if one is found
      * during a scan, else null.  This method must be retried by
      * caller if, by the time it tries to use the queue, it is empty.
-     * @param r a (random) seed for scanning
      */
-    private WorkQueue findNonEmptyStealQueue(int r) {
+    private WorkQueue findNonEmptyStealQueue() {
+        int r = ThreadLocalRandom.nextSecondarySeed();
         for (;;) {
             int ps = plock, m; WorkQueue[] ws; WorkQueue q;
             if ((ws = workQueues) != null && (m = ws.length - 1) >= 0) {
                 for (int j = (m + 1) << 2; j >= 0; --j) {
-                    if ((q = ws[(((r + j) << 1) | 1) & m]) != null &&
+                    if ((q = ws[(((r - j) << 1) | 1) & m]) != null &&
                         q.base - q.top < 0)
                         return q;
                 }
@@ -2105,35 +2070,36 @@
      * find tasks either.
      */
     final void helpQuiescePool(WorkQueue w) {
+        ForkJoinTask<?> ps = w.currentSteal;
         for (boolean active = true;;) {
             long c; WorkQueue q; ForkJoinTask<?> t; int b;
-            while ((t = w.nextLocalTask()) != null) {
-                if (w.base - w.top < 0)
-                    signalWork(w);
+            while ((t = w.nextLocalTask()) != null)
                 t.doExec();
-            }
-            if ((q = findNonEmptyStealQueue(w.nextSeed())) != null) {
+            if ((q = findNonEmptyStealQueue()) != null) {
                 if (!active) {      // re-establish active count
                     active = true;
                     do {} while (!U.compareAndSwapLong
-                                 (this, CTL, c = ctl, c + AC_UNIT));
+                                 (this, CTL, c = ctl,
+                                  ((c & ~AC_MASK) |
+                                   ((c & AC_MASK) + AC_UNIT))));
                 }
                 if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) {
-                    if (q.base - q.top < 0)
-                        signalWork(q);
-                    w.runSubtask(t);
+                    (w.currentSteal = t).doExec();
+                    w.currentSteal = ps;
                 }
             }
             else if (active) {       // decrement active count without queuing
-                long nc = (c = ctl) - AC_UNIT;
-                if ((int)(nc >> AC_SHIFT) + (config & SMASK) == 0)
-                    return;          // bypass decrement-then-increment
+                long nc = ((c = ctl) & ~AC_MASK) | ((c & AC_MASK) - AC_UNIT);
+                if ((int)(nc >> AC_SHIFT) + parallelism == 0)
+                    break;          // bypass decrement-then-increment
                 if (U.compareAndSwapLong(this, CTL, c, nc))
                     active = false;
             }
-            else if ((int)((c = ctl) >> AC_SHIFT) + (config & SMASK) == 0 &&
-                     U.compareAndSwapLong(this, CTL, c, c + AC_UNIT))
-                return;
+            else if ((int)((c = ctl) >> AC_SHIFT) + parallelism <= 0 &&
+                     U.compareAndSwapLong
+                     (this, CTL, c, ((c & ~AC_MASK) |
+                                     ((c & AC_MASK) + AC_UNIT))))
+                break;
         }
     }
 
@@ -2147,13 +2113,10 @@
             WorkQueue q; int b;
             if ((t = w.nextLocalTask()) != null)
                 return t;
-            if ((q = findNonEmptyStealQueue(w.nextSeed())) == null)
+            if ((q = findNonEmptyStealQueue()) == null)
                 return null;
-            if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) {
-                if (q.base - q.top < 0)
-                    signalWork(q);
+            if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
                 return t;
-            }
         }
     }
 
@@ -2206,7 +2169,7 @@
     static int getSurplusQueuedTaskCount() {
         Thread t; ForkJoinWorkerThread wt; ForkJoinPool pool; WorkQueue q;
         if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)) {
-            int p = (pool = (wt = (ForkJoinWorkerThread)t).pool).config & SMASK;
+            int p = (pool = (wt = (ForkJoinWorkerThread)t).pool).parallelism;
             int n = (q = wt.workQueue).top - q.base;
             int a = (int)(pool.ctl >> AC_SHIFT) + p;
             return n - (a > (p >>>= 1) ? 0 :
@@ -2236,7 +2199,7 @@
      */
     private boolean tryTerminate(boolean now, boolean enable) {
         int ps;
-        if (this == common)                    // cannot shut down
+        if (this == common)                        // cannot shut down
             return false;
         if ((ps = plock) >= 0) {                   // enable by setting plock
             if (!enable)
@@ -2250,7 +2213,7 @@
         }
         for (long c;;) {
             if (((c = ctl) & STOP_BIT) != 0) {     // already terminating
-                if ((short)(c >>> TC_SHIFT) == -(config & SMASK)) {
+                if ((short)(c >>> TC_SHIFT) + parallelism <= 0) {
                     synchronized (this) {
                         notifyAll();               // signal when 0 workers
                     }
@@ -2259,17 +2222,15 @@
             }
             if (!now) {                            // check if idle & no tasks
                 WorkQueue[] ws; WorkQueue w;
-                if ((int)(c >> AC_SHIFT) != -(config & SMASK))
+                if ((int)(c >> AC_SHIFT) + parallelism > 0)
                     return false;
                 if ((ws = workQueues) != null) {
                     for (int i = 0; i < ws.length; ++i) {
-                        if ((w = ws[i]) != null) {
-                            if (!w.isEmpty()) {    // signal unprocessed tasks
-                                signalWork(w);
-                                return false;
-                            }
-                            if ((i & 1) != 0 && w.eventCount >= 0)
-                                return false;      // unqueued inactive worker
+                        if ((w = ws[i]) != null &&
+                            (!w.isEmpty() ||
+                             ((i & 1) != 0 && w.eventCount >= 0))) {
+                            signalWork(ws, w);
+                            return false;
                         }
                     }
                 }
@@ -2336,116 +2297,67 @@
     /**
      * Tries to pop the given task from submitter's queue in common pool.
      */
-    static boolean tryExternalUnpush(ForkJoinTask<?> t) {
-        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
-        ForkJoinTask<?>[] a;  int m, s, z;
-        if (t != null &&
-            (z = ThreadLocalRandom.getProbe()) != 0 &&
-            (p = common) != null &&
-            (ws = p.workQueues) != null &&
-            (m = ws.length - 1) >= 0 &&
-            (q = ws[m & z & SQMASK]) != null &&
-            (s = q.top) != q.base &&
-            (a = q.array) != null) {
+    final boolean tryExternalUnpush(ForkJoinTask<?> task) {
+        WorkQueue joiner; ForkJoinTask<?>[] a; int m, s;
+        WorkQueue[] ws = workQueues;
+        int z = ThreadLocalRandom.getProbe();
+        boolean popped = false;
+        if (ws != null && (m = ws.length - 1) >= 0 &&
+            (joiner = ws[z & m & SQMASK]) != null &&
+            joiner.base != (s = joiner.top) &&
+            (a = joiner.array) != null) {
             long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE;
-            if (U.getObject(a, j) == t &&
-                U.compareAndSwapInt(q, QLOCK, 0, 1)) {
-                if (q.array == a && q.top == s && // recheck
-                    U.compareAndSwapObject(a, j, t, null)) {
-                    q.top = s - 1;
-                    q.qlock = 0;
-                    return true;
+            if (U.getObject(a, j) == task &&
+                U.compareAndSwapInt(joiner, QLOCK, 0, 1)) {
+                if (joiner.top == s && joiner.array == a &&
+                    U.compareAndSwapObject(a, j, task, null)) {
+                    joiner.top = s - 1;
+                    popped = true;
                 }
-                q.qlock = 0;
+                joiner.qlock = 0;
             }
         }
-        return false;
+        return popped;
     }
 
-    /**
-     * Tries to pop and run local tasks within the same computation
-     * as the given root. On failure, tries to help complete from
-     * other queues via helpComplete.
-     */
-    private void externalHelpComplete(WorkQueue q, ForkJoinTask<?> root) {
-        ForkJoinTask<?>[] a; int m;
-        if (q != null && (a = q.array) != null && (m = (a.length - 1)) >= 0 &&
-            root != null && root.status >= 0) {
-            for (;;) {
-                int s, u; Object o; CountedCompleter<?> task = null;
-                if ((s = q.top) - q.base > 0) {
-                    long j = ((m & (s - 1)) << ASHIFT) + ABASE;
-                    if ((o = U.getObject(a, j)) != null &&
-                        (o instanceof CountedCompleter)) {
-                        CountedCompleter<?> t = (CountedCompleter<?>)o, r = t;
-                        do {
-                            if (r == root) {
-                                if (U.compareAndSwapInt(q, QLOCK, 0, 1)) {
-                                    if (q.array == a && q.top == s &&
-                                        U.compareAndSwapObject(a, j, t, null)) {
-                                        q.top = s - 1;
-                                        task = t;
-                                    }
-                                    q.qlock = 0;
-                                }
-                                break;
-                            }
-                        } while ((r = r.completer) != null);
+    final int externalHelpComplete(CountedCompleter<?> task, int maxTasks) {
+        WorkQueue joiner; int m;
+        WorkQueue[] ws = workQueues;
+        int j = ThreadLocalRandom.getProbe();
+        int s = 0;
+        if (ws != null && (m = ws.length - 1) >= 0 &&
+            (joiner = ws[j & m & SQMASK]) != null && task != null) {
+            int scans = m + m + 1;
+            long c = 0L;             // for stability check
+            j |= 1;                  // poll odd queues
+            for (int k = scans; ; j += 2) {
+                WorkQueue q;
+                if ((s = task.status) < 0)
+                    break;
+                else if (joiner.externalPopAndExecCC(task)) {
+                    if (--maxTasks <= 0) {
+                        s = task.status;
+                        break;
                     }
+                    k = scans;
                 }
-                if (task != null)
-                    task.doExec();
-                if (root.status < 0 ||
-                    (config != 0 &&
-                     ((u = (int)(ctl >>> 32)) >= 0 || (u >> UAC_SHIFT) >= 0)))
+                else if ((s = task.status) < 0)
                     break;
-               if (task == null) {
-                    helpSignal(root, q.poolIndex);
-                    if (root.status >= 0)
-                        helpComplete(root, SHARED_QUEUE);
-                    break;
+                else if ((q = ws[j & m]) != null && q.pollAndExecCC(task)) {
+                    if (--maxTasks <= 0) {
+                        s = task.status;
+                        break;
+                    }
+                    k = scans;
+                }
+                else if (--k < 0) {
+                    if (c == (c = ctl))
+                        break;
+                    k = scans;
                 }
             }
         }
-    }
-
-    /**
-     * Tries to help execute or signal availability of the given task
-     * from submitter's queue in common pool.
-     */
-    static void externalHelpJoin(ForkJoinTask<?> t) {
-        // Some hard-to-avoid overlap with tryExternalUnpush
-        ForkJoinPool p; WorkQueue[] ws; WorkQueue q, w;
-        ForkJoinTask<?>[] a;  int m, s, n, z;
-        if (t != null &&
-            (z = ThreadLocalRandom.getProbe()) != 0 &&
-            (p = common) != null &&
-            (ws = p.workQueues) != null &&
-            (m = ws.length - 1) >= 0 &&
-            (q = ws[m & z & SQMASK]) != null &&
-            (a = q.array) != null) {
-            int am = a.length - 1;
-            if ((s = q.top) != q.base) {
-                long j = ((am & (s - 1)) << ASHIFT) + ABASE;
-                if (U.getObject(a, j) == t &&
-                    U.compareAndSwapInt(q, QLOCK, 0, 1)) {
-                    if (q.array == a && q.top == s &&
-                        U.compareAndSwapObject(a, j, t, null)) {
-                        q.top = s - 1;
-                        q.qlock = 0;
-                        t.doExec();
-                    }
-                    else
-                        q.qlock = 0;
-                }
-            }
-            if (t.status >= 0) {
-                if (t instanceof CountedCompleter)
-                    p.externalHelpComplete(q, t);
-                else
-                    p.helpSignal(t, q.poolIndex);
-            }
-        }
+        return s;
     }
 
     // Exported methods
@@ -2517,7 +2429,7 @@
         this(checkParallelism(parallelism),
              checkFactory(factory),
              handler,
-             asyncMode,
+             (asyncMode ? FIFO_QUEUE : LIFO_QUEUE),
              "ForkJoinPool-" + nextPoolId() + "-worker-");
         checkPermission();
     }
@@ -2543,12 +2455,13 @@
     private ForkJoinPool(int parallelism,
                          ForkJoinWorkerThreadFactory factory,
                          UncaughtExceptionHandler handler,
-                         boolean asyncMode,
+                         int mode,
                          String workerNamePrefix) {
         this.workerNamePrefix = workerNamePrefix;
         this.factory = factory;
         this.ueh = handler;
-        this.config = parallelism | (asyncMode ? (FIFO_QUEUE << 16) : 0);
+        this.mode = (short)mode;
+        this.parallelism = (short)parallelism;
         long np = (long)(-parallelism); // offset ctl counts
         this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
     }
@@ -2736,8 +2649,8 @@
      * @return the targeted parallelism level of this pool
      */
     public int getParallelism() {
-        int par = (config & SMASK);
-        return (par > 0) ? par : 1;
+        int par;
+        return ((par = parallelism) > 0) ? par : 1;
     }
 
     /**
@@ -2759,7 +2672,7 @@
      * @return the number of worker threads
      */
     public int getPoolSize() {
-        return (config & SMASK) + (short)(ctl >>> TC_SHIFT);
+        return parallelism + (short)(ctl >>> TC_SHIFT);
     }
 
     /**
@@ -2769,7 +2682,7 @@
      * @return {@code true} if this pool uses async mode
      */
     public boolean getAsyncMode() {
-        return (config >>> 16) == FIFO_QUEUE;
+        return mode == FIFO_QUEUE;
     }
 
     /**
@@ -2800,7 +2713,7 @@
      * @return the number of active threads
      */
     public int getActiveThreadCount() {
-        int r = (config & SMASK) + (int)(ctl >> AC_SHIFT);
+        int r = parallelism + (int)(ctl >> AC_SHIFT);
         return (r <= 0) ? 0 : r; // suppress momentarily negative values
     }
 
@@ -2816,7 +2729,7 @@
      * @return {@code true} if all threads are currently idle
      */
     public boolean isQuiescent() {
-        return (int)(ctl >> AC_SHIFT) + (config & SMASK) == 0;
+        return parallelism + (int)(ctl >> AC_SHIFT) <= 0;
     }
 
     /**
@@ -2979,7 +2892,7 @@
                 }
             }
         }
-        int pc = (config & SMASK);
+        int pc = parallelism;
         int tc = pc + (short)(c >>> TC_SHIFT);
         int ac = pc + (int)(c >> AC_SHIFT);
         if (ac < 0) // ignore transient negative
@@ -3052,7 +2965,7 @@
     public boolean isTerminated() {
         long c = ctl;
         return ((c & STOP_BIT) != 0L &&
-                (short)(c >>> TC_SHIFT) == -(config & SMASK));
+                (short)(c >>> TC_SHIFT) + parallelism <= 0);
     }
 
     /**
@@ -3071,7 +2984,7 @@
     public boolean isTerminating() {
         long c = ctl;
         return ((c & STOP_BIT) != 0L &&
-                (short)(c >>> TC_SHIFT) != -(config & SMASK));
+                (short)(c >>> TC_SHIFT) + parallelism > 0);
     }
 
     /**
@@ -3108,19 +3021,20 @@
         long nanos = unit.toNanos(timeout);
         if (isTerminated())
             return true;
-        long startTime = System.nanoTime();
-        boolean terminated = false;
+        if (nanos <= 0L)
+            return false;
+        long deadline = System.nanoTime() + nanos;
         synchronized (this) {
-            for (long waitTime = nanos, millis = 0L;;) {
-                if (terminated = isTerminated() ||
-                    waitTime <= 0L ||
-                    (millis = unit.toMillis(waitTime)) <= 0L)
-                    break;
-                wait(millis);
-                waitTime = nanos - (System.nanoTime() - startTime);
+            for (;;) {
+                if (isTerminated())
+                    return true;
+                if (nanos <= 0L)
+                    return false;
+                long millis = TimeUnit.NANOSECONDS.toMillis(nanos);
+                wait(millis > 0L ? millis : 1L);
+                nanos = deadline - System.nanoTime();
             }
         }
-        return terminated;
     }
 
     /**
@@ -3159,11 +3073,8 @@
                 ForkJoinTask<?> t; WorkQueue q; int b;
                 if ((q = ws[r++ & m]) != null && (b = q.base) - q.top < 0) {
                     found = true;
-                    if ((t = q.pollAt(b)) != null) {
-                        if (q.base - q.top < 0)
-                            signalWork(q);
+                    if ((t = q.pollAt(b)) != null)
                         t.doExec();
-                    }
                     break;
                 }
             }
@@ -3278,21 +3189,8 @@
         Thread t = Thread.currentThread();
         if (t instanceof ForkJoinWorkerThread) {
             ForkJoinPool p = ((ForkJoinWorkerThread)t).pool;
-            while (!blocker.isReleasable()) { // variant of helpSignal
-                WorkQueue[] ws; WorkQueue q; int m, u;
-                if ((ws = p.workQueues) != null && (m = ws.length - 1) >= 0) {
-                    for (int i = 0; i <= m; ++i) {
-                        if (blocker.isReleasable())
-                            return;
-                        if ((q = ws[i]) != null && q.base - q.top < 0) {
-                            p.signalWork(q);
-                            if ((u = (int)(p.ctl >>> 32)) >= 0 ||
-                                (u >> UAC_SHIFT) >= 0)
-                                break;
-                        }
-                    }
-                }
-                if (p.tryCompensate()) {
+            while (!blocker.isReleasable()) {
+                if (p.tryCompensate(p.ctl)) {
                     try {
                         do {} while (!blocker.isReleasable() &&
                                      !blocker.block());
@@ -3330,6 +3228,7 @@
     private static final long STEALCOUNT;
     private static final long PLOCK;
     private static final long INDEXSEED;
+    private static final long QBASE;
     private static final long QLOCK;
 
     static {
@@ -3349,6 +3248,8 @@
             PARKBLOCKER = U.objectFieldOffset
                 (tk.getDeclaredField("parkBlocker"));
             Class<?> wk = WorkQueue.class;
+            QBASE = U.objectFieldOffset
+                (wk.getDeclaredField("base"));
             QLOCK = U.objectFieldOffset
                 (wk.getDeclaredField("qlock"));
             Class<?> ak = ForkJoinTask[].class;
@@ -3368,7 +3269,7 @@
         common = java.security.AccessController.doPrivileged
             (new java.security.PrivilegedAction<ForkJoinPool>() {
                 public ForkJoinPool run() { return makeCommonPool(); }});
-        int par = common.config; // report 1 even if threads disabled
+        int par = common.parallelism; // report 1 even if threads disabled
         commonParallelism = par > 0 ? par : 1;
     }
 
@@ -3381,7 +3282,7 @@
         ForkJoinWorkerThreadFactory factory
             = defaultForkJoinWorkerThreadFactory;
         UncaughtExceptionHandler handler = null;
-        try {  // ignore exceptions in accesing/parsing properties
+        try {  // ignore exceptions in accessing/parsing properties
             String pp = System.getProperty
                 ("java.util.concurrent.ForkJoinPool.common.parallelism");
             String fp = System.getProperty
@@ -3399,11 +3300,12 @@
         } catch (Exception ignore) {
         }
 
-        if (parallelism < 0)
-            parallelism = Runtime.getRuntime().availableProcessors();
+        if (parallelism < 0 && // default 1 less than #cores
+            (parallelism = Runtime.getRuntime().availableProcessors() - 1) < 0)
+            parallelism = 0;
         if (parallelism > MAX_CAP)
             parallelism = MAX_CAP;
-        return new ForkJoinPool(parallelism, factory, handler, false,
+        return new ForkJoinPool(parallelism, factory, handler, LIFO_QUEUE,
                                 "ForkJoinPool.commonPool-worker-");
     }
 
--- a/src/share/classes/java/util/concurrent/ForkJoinTask.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/ForkJoinTask.java	Mon Jul 22 17:37:15 2013 -0700
@@ -165,7 +165,7 @@
  * supports other methods and techniques (for example the use of
  * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
  * may be of use in constructing custom subclasses for problems that
- * are not statically structured as DAGs. To support such usages a
+ * are not statically structured as DAGs. To support such usages, a
  * ForkJoinTask may be atomically <em>tagged</em> with a {@code short}
  * value using {@link #setForkJoinTaskTag} or {@link
  * #compareAndSetForkJoinTaskTag} and checked using {@link
@@ -314,25 +314,35 @@
      */
     private int externalAwaitDone() {
         int s;
-        ForkJoinPool.externalHelpJoin(this);
-        boolean interrupted = false;
-        while ((s = status) >= 0) {
-            if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
-                synchronized (this) {
-                    if (status >= 0) {
-                        try {
-                            wait();
-                        } catch (InterruptedException ie) {
-                            interrupted = true;
+        ForkJoinPool cp = ForkJoinPool.common;
+        if ((s = status) >= 0) {
+            if (cp != null) {
+                if (this instanceof CountedCompleter)
+                    s = cp.externalHelpComplete((CountedCompleter<?>)this, Integer.MAX_VALUE);
+                else if (cp.tryExternalUnpush(this))
+                    s = doExec();
+            }
+            if (s >= 0 && (s = status) >= 0) {
+                boolean interrupted = false;
+                do {
+                    if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
+                        synchronized (this) {
+                            if (status >= 0) {
+                                try {
+                                    wait();
+                                } catch (InterruptedException ie) {
+                                    interrupted = true;
+                                }
+                            }
+                            else
+                                notifyAll();
                         }
                     }
-                    else
-                        notifyAll();
-                }
+                } while ((s = status) >= 0);
+                if (interrupted)
+                    Thread.currentThread().interrupt();
             }
         }
-        if (interrupted)
-            Thread.currentThread().interrupt();
         return s;
     }
 
@@ -341,9 +351,15 @@
      */
     private int externalInterruptibleAwaitDone() throws InterruptedException {
         int s;
+        ForkJoinPool cp = ForkJoinPool.common;
         if (Thread.interrupted())
             throw new InterruptedException();
-        ForkJoinPool.externalHelpJoin(this);
+        if ((s = status) >= 0 && cp != null) {
+            if (this instanceof CountedCompleter)
+                cp.externalHelpComplete((CountedCompleter<?>)this, Integer.MAX_VALUE);
+            else if (cp.tryExternalUnpush(this))
+                doExec();
+        }
         while ((s = status) >= 0) {
             if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
                 synchronized (this) {
@@ -357,7 +373,6 @@
         return s;
     }
 
-
     /**
      * Implementation for join, get, quietlyJoin. Directly handles
      * only cases of already-completed, external wait, and
@@ -629,14 +644,9 @@
     /**
      * A version of "sneaky throw" to relay exceptions
      */
-    static void rethrow(final Throwable ex) {
-        if (ex != null) {
-            if (ex instanceof Error)
-                throw (Error)ex;
-            if (ex instanceof RuntimeException)
-                throw (RuntimeException)ex;
+    static void rethrow(Throwable ex) {
+        if (ex != null)
             ForkJoinTask.<RuntimeException>uncheckedThrow(ex);
-        }
     }
 
     /**
@@ -646,8 +656,7 @@
      */
     @SuppressWarnings("unchecked") static <T extends Throwable>
         void uncheckedThrow(Throwable t) throws T {
-        if (t != null)
-            throw (T)t; // rely on vacuous cast
+        throw (T)t; // rely on vacuous cast
     }
 
     /**
@@ -1010,6 +1019,7 @@
         // Messy in part because we measure in nanosecs, but wait in millisecs
         int s; long ms;
         long ns = unit.toNanos(timeout);
+        ForkJoinPool cp;
         if ((s = status) >= 0 && ns > 0L) {
             long deadline = System.nanoTime() + ns;
             ForkJoinPool p = null;
@@ -1021,8 +1031,12 @@
                 w = wt.workQueue;
                 p.helpJoinOnce(w, this); // no retries on failure
             }
-            else
-                ForkJoinPool.externalHelpJoin(this);
+            else if ((cp = ForkJoinPool.common) != null) {
+                if (this instanceof CountedCompleter)
+                    cp.externalHelpComplete((CountedCompleter<?>)this, Integer.MAX_VALUE);
+                else if (cp.tryExternalUnpush(this))
+                    doExec();
+            }
             boolean canBlock = false;
             boolean interrupted = false;
             try {
@@ -1030,7 +1044,7 @@
                     if (w != null && w.qlock < 0)
                         cancelIgnoringExceptions(this);
                     else if (!canBlock) {
-                        if (p == null || p.tryCompensate())
+                        if (p == null || p.tryCompensate(p.ctl))
                             canBlock = true;
                     }
                     else {
@@ -1171,7 +1185,7 @@
         Thread t;
         return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
                 ((ForkJoinWorkerThread)t).workQueue.tryUnpush(this) :
-                ForkJoinPool.tryExternalUnpush(this));
+                ForkJoinPool.common.tryExternalUnpush(this));
     }
 
     /**
@@ -1340,7 +1354,7 @@
      *
      * @param e the expected tag value
      * @param tag the new tag value
-     * @return true if successful; i.e., the current value was
+     * @return {@code true} if successful; i.e., the current value was
      * equal to e and is now tag.
      * @since 1.8
      */
--- a/src/share/classes/java/util/concurrent/ForkJoinWorkerThread.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/ForkJoinWorkerThread.java	Mon Jul 22 17:37:15 2013 -0700
@@ -43,8 +43,8 @@
  * scheduling or execution.  However, you can override initialization
  * and termination methods surrounding the main task processing loop.
  * If you do create such a subclass, you will also need to supply a
- * custom {@link ForkJoinPool.ForkJoinWorkerThreadFactory} to use it
- * in a {@code ForkJoinPool}.
+ * custom {@link ForkJoinPool.ForkJoinWorkerThreadFactory} to
+ * {@linkplain ForkJoinPool#ForkJoinPool use it} in a {@code ForkJoinPool}.
  *
  * @since 1.7
  * @author Doug Lea
@@ -89,16 +89,17 @@
     }
 
     /**
-     * Returns the index number of this thread in its pool.  The
-     * returned value ranges from zero to the maximum number of
-     * threads (minus one) that have ever been created in the pool.
-     * This method may be useful for applications that track status or
-     * collect results per-worker rather than per-task.
+     * Returns the unique index number of this thread in its pool.
+     * The returned value ranges from zero to the maximum number of
+     * threads (minus one) that may exist in the pool, and does not
+     * change during the lifetime of the thread.  This method may be
+     * useful for applications that track status or collect results
+     * per-worker-thread rather than per-task.
      *
      * @return the index number
      */
     public int getPoolIndex() {
-        return workQueue.poolIndex;
+        return workQueue.poolIndex >>> 1; // ignore odd/even tag bit
     }
 
     /**
--- a/src/share/classes/java/util/concurrent/Future.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/Future.java	Mon Jul 22 17:37:15 2013 -0700
@@ -36,19 +36,19 @@
 package java.util.concurrent;
 
 /**
- * A <tt>Future</tt> represents the result of an asynchronous
+ * A {@code Future} represents the result of an asynchronous
  * computation.  Methods are provided to check if the computation is
  * complete, to wait for its completion, and to retrieve the result of
  * the computation.  The result can only be retrieved using method
- * <tt>get</tt> when the computation has completed, blocking if
+ * {@code get} when the computation has completed, blocking if
  * necessary until it is ready.  Cancellation is performed by the
- * <tt>cancel</tt> method.  Additional methods are provided to
+ * {@code cancel} method.  Additional methods are provided to
  * determine if the task completed normally or was cancelled. Once a
  * computation has completed, the computation cannot be cancelled.
- * If you would like to use a <tt>Future</tt> for the sake
+ * If you would like to use a {@code Future} for the sake
  * of cancellability but not provide a usable result, you can
  * declare types of the form {@code Future<?>} and
- * return <tt>null</tt> as a result of the underlying task.
+ * return {@code null} as a result of the underlying task.
  *
  * <p>
  * <b>Sample Usage</b> (Note that the following classes are all
@@ -72,9 +72,9 @@
  *   }
  * }}</pre>
  *
- * The {@link FutureTask} class is an implementation of <tt>Future</tt> that
- * implements <tt>Runnable</tt>, and so may be executed by an <tt>Executor</tt>.
- * For example, the above construction with <tt>submit</tt> could be replaced by:
+ * The {@link FutureTask} class is an implementation of {@code Future} that
+ * implements {@code Runnable}, and so may be executed by an {@code Executor}.
+ * For example, the above construction with {@code submit} could be replaced by:
  *  <pre> {@code
  * FutureTask<String> future =
  *   new FutureTask<String>(new Callable<String>() {
@@ -91,7 +91,7 @@
  * @see Executor
  * @since 1.5
  * @author Doug Lea
- * @param <V> The result type returned by this Future's <tt>get</tt> method
+ * @param <V> The result type returned by this Future's {@code get} method
  */
 public interface Future<V> {
 
@@ -99,41 +99,41 @@
      * Attempts to cancel execution of this task.  This attempt will
      * fail if the task has already completed, has already been cancelled,
      * or could not be cancelled for some other reason. If successful,
-     * and this task has not started when <tt>cancel</tt> is called,
+     * and this task has not started when {@code cancel} is called,
      * this task should never run.  If the task has already started,
-     * then the <tt>mayInterruptIfRunning</tt> parameter determines
+     * then the {@code mayInterruptIfRunning} parameter determines
      * whether the thread executing this task should be interrupted in
      * an attempt to stop the task.
      *
      * <p>After this method returns, subsequent calls to {@link #isDone} will
-     * always return <tt>true</tt>.  Subsequent calls to {@link #isCancelled}
-     * will always return <tt>true</tt> if this method returned <tt>true</tt>.
+     * always return {@code true}.  Subsequent calls to {@link #isCancelled}
+     * will always return {@code true} if this method returned {@code true}.
      *
-     * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
+     * @param mayInterruptIfRunning {@code true} if the thread executing this
      * task should be interrupted; otherwise, in-progress tasks are allowed
      * to complete
-     * @return <tt>false</tt> if the task could not be cancelled,
+     * @return {@code false} if the task could not be cancelled,
      * typically because it has already completed normally;
-     * <tt>true</tt> otherwise
+     * {@code true} otherwise
      */
     boolean cancel(boolean mayInterruptIfRunning);
 
     /**
-     * Returns <tt>true</tt> if this task was cancelled before it completed
+     * Returns {@code true} if this task was cancelled before it completed
      * normally.
      *
-     * @return <tt>true</tt> if this task was cancelled before it completed
+     * @return {@code true} if this task was cancelled before it completed
      */
     boolean isCancelled();
 
     /**
-     * Returns <tt>true</tt> if this task completed.
+     * Returns {@code true} if this task completed.
      *
      * Completion may be due to normal termination, an exception, or
      * cancellation -- in all of these cases, this method will return
-     * <tt>true</tt>.
+     * {@code true}.
      *
-     * @return <tt>true</tt> if this task completed
+     * @return {@code true} if this task completed
      */
     boolean isDone();
 
--- a/src/share/classes/java/util/concurrent/FutureTask.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/FutureTask.java	Mon Jul 22 17:37:15 2013 -0700
@@ -162,19 +162,23 @@
     }
 
     public boolean cancel(boolean mayInterruptIfRunning) {
-        if (state != NEW)
+        if (!(state == NEW &&
+              UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
+                  mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
             return false;
-        if (mayInterruptIfRunning) {
-            if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
-                return false;
-            Thread t = runner;
-            if (t != null)
-                t.interrupt();
-            UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
+        try {    // in case call to interrupt throws exception
+            if (mayInterruptIfRunning) {
+                try {
+                    Thread t = runner;
+                    if (t != null)
+                        t.interrupt();
+                } finally { // final state
+                    UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
+                }
+            }
+        } finally {
+            finishCompletion();
         }
-        else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
-            return false;
-        finishCompletion();
         return true;
     }
 
@@ -288,7 +292,7 @@
      * designed for use with tasks that intrinsically execute more
      * than once.
      *
-     * @return true if successfully run and reset
+     * @return {@code true} if successfully run and reset
      */
     protected boolean runAndReset() {
         if (state != NEW ||
--- a/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java	Mon Jul 22 17:37:15 2013 -0700
@@ -41,12 +41,15 @@
 import java.util.NoSuchElementException;
 import java.util.concurrent.locks.Condition;
 import java.util.concurrent.locks.ReentrantLock;
+import java.util.Spliterator;
+import java.util.Spliterators;
+import java.util.function.Consumer;
 
 /**
  * An optionally-bounded {@linkplain BlockingDeque blocking deque} based on
  * linked nodes.
  *
- * <p> The optional capacity bound constructor argument serves as a
+ * <p>The optional capacity bound constructor argument serves as a
  * way to prevent excessive expansion. The capacity, if unspecified,
  * is equal to {@link Integer#MAX_VALUE}.  Linked nodes are
  * dynamically created upon each insertion unless this would bring the
@@ -315,8 +318,8 @@
     // BlockingDeque methods
 
     /**
-     * @throws IllegalStateException {@inheritDoc}
-     * @throws NullPointerException  {@inheritDoc}
+     * @throws IllegalStateException if this deque is full
+     * @throws NullPointerException {@inheritDoc}
      */
     public void addFirst(E e) {
         if (!offerFirst(e))
@@ -324,7 +327,7 @@
     }
 
     /**
-     * @throws IllegalStateException {@inheritDoc}
+     * @throws IllegalStateException if this deque is full
      * @throws NullPointerException  {@inheritDoc}
      */
     public void addLast(E e) {
@@ -623,8 +626,7 @@
      *
      * <p>This method is equivalent to {@link #addLast}.
      *
-     * @throws IllegalStateException if the element cannot be added at this
-     *         time due to capacity restrictions
+     * @throws IllegalStateException if this deque is full
      * @throws NullPointerException if the specified element is null
      */
     public boolean add(E e) {
@@ -761,8 +763,8 @@
     // Stack methods
 
     /**
-     * @throws IllegalStateException {@inheritDoc}
-     * @throws NullPointerException  {@inheritDoc}
+     * @throws IllegalStateException if this deque is full
+     * @throws NullPointerException {@inheritDoc}
      */
     public void push(E e) {
         addFirst(e);
@@ -852,7 +854,7 @@
 //      * @throws ClassCastException            {@inheritDoc}
 //      * @throws NullPointerException          {@inheritDoc}
 //      * @throws IllegalArgumentException      {@inheritDoc}
-//      * @throws IllegalStateException         {@inheritDoc}
+//      * @throws IllegalStateException if this deque is full
 //      * @see #add(Object)
 //      */
 //     public boolean addAll(Collection<? extends E> c) {
@@ -1151,6 +1153,127 @@
         Node<E> nextNode(Node<E> n) { return n.prev; }
     }
 
+    /** A customized variant of Spliterators.IteratorSpliterator */
+    static final class LBDSpliterator<E> implements Spliterator<E> {
+        static final int MAX_BATCH = 1 << 25;  // max batch array size;
+        final LinkedBlockingDeque<E> queue;
+        Node<E> current;    // current node; null until initialized
+        int batch;          // batch size for splits
+        boolean exhausted;  // true when no more nodes
+        long est;           // size estimate
+        LBDSpliterator(LinkedBlockingDeque<E> queue) {
+            this.queue = queue;
+            this.est = queue.size();
+        }
+
+        public long estimateSize() { return est; }
+
+        public Spliterator<E> trySplit() {
+            Node<E> h;
+            final LinkedBlockingDeque<E> q = this.queue;
+            int b = batch;
+            int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
+            if (!exhausted &&
+                ((h = current) != null || (h = q.first) != null) &&
+                h.next != null) {
+                Object[] a = new Object[n];
+                final ReentrantLock lock = q.lock;
+                int i = 0;
+                Node<E> p = current;
+                lock.lock();
+                try {
+                    if (p != null || (p = q.first) != null) {
+                        do {
+                            if ((a[i] = p.item) != null)
+                                ++i;
+                        } while ((p = p.next) != null && i < n);
+                    }
+                } finally {
+                    lock.unlock();
+                }
+                if ((current = p) == null) {
+                    est = 0L;
+                    exhausted = true;
+                }
+                else if ((est -= i) < 0L)
+                    est = 0L;
+                if (i > 0) {
+                    batch = i;
+                    return Spliterators.spliterator
+                        (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
+                         Spliterator.CONCURRENT);
+                }
+            }
+            return null;
+        }
+
+        public void forEachRemaining(Consumer<? super E> action) {
+            if (action == null) throw new NullPointerException();
+            final LinkedBlockingDeque<E> q = this.queue;
+            final ReentrantLock lock = q.lock;
+            if (!exhausted) {
+                exhausted = true;
+                Node<E> p = current;
+                do {
+                    E e = null;
+                    lock.lock();
+                    try {
+                        if (p == null)
+                            p = q.first;
+                        while (p != null) {
+                            e = p.item;
+                            p = p.next;
+                            if (e != null)
+                                break;
+                        }
+                    } finally {
+                        lock.unlock();
+                    }
+                    if (e != null)
+                        action.accept(e);
+                } while (p != null);
+            }
+        }
+
+        public boolean tryAdvance(Consumer<? super E> action) {
+            if (action == null) throw new NullPointerException();
+            final LinkedBlockingDeque<E> q = this.queue;
+            final ReentrantLock lock = q.lock;
+            if (!exhausted) {
+                E e = null;
+                lock.lock();
+                try {
+                    if (current == null)
+                        current = q.first;
+                    while (current != null) {
+                        e = current.item;
+                        current = current.next;
+                        if (e != null)
+                            break;
+                    }
+                } finally {
+                    lock.unlock();
+                }
+                if (current == null)
+                    exhausted = true;
+                if (e != null) {
+                    action.accept(e);
+                    return true;
+                }
+            }
+            return false;
+        }
+
+        public int characteristics() {
+            return Spliterator.ORDERED | Spliterator.NONNULL |
+                Spliterator.CONCURRENT;
+        }
+    }
+
+    public Spliterator<E> spliterator() {
+        return new LBDSpliterator<E>(this);
+    }
+
     /**
      * Saves this deque to a stream (that is, serializes it).
      *
--- a/src/share/classes/java/util/concurrent/LinkedBlockingQueue.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/LinkedBlockingQueue.java	Mon Jul 22 17:37:15 2013 -0700
@@ -42,6 +42,9 @@
 import java.util.Collection;
 import java.util.Iterator;
 import java.util.NoSuchElementException;
+import java.util.Spliterator;
+import java.util.Spliterators;
+import java.util.function.Consumer;
 
 /**
  * An optionally-bounded {@linkplain BlockingQueue blocking queue} based on
@@ -56,7 +59,7 @@
  * Linked queues typically have higher throughput than array-based queues but
  * less predictable performance in most concurrent applications.
  *
- * <p> The optional capacity bound constructor argument serves as a
+ * <p>The optional capacity bound constructor argument serves as a
  * way to prevent excessive queue expansion. The capacity, if unspecified,
  * is equal to {@link Integer#MAX_VALUE}.  Linked nodes are
  * dynamically created upon each insertion unless this would bring the
@@ -216,7 +219,7 @@
     }
 
     /**
-     * Lock to prevent both puts and takes.
+     * Locks to prevent both puts and takes.
      */
     void fullyLock() {
         putLock.lock();
@@ -224,7 +227,7 @@
     }
 
     /**
-     * Unlock to allow both puts and takes.
+     * Unlocks to allow both puts and takes.
      */
     void fullyUnlock() {
         takeLock.unlock();
@@ -362,7 +365,7 @@
      * necessary up to the specified wait time for space to become available.
      *
      * @return {@code true} if successful, or {@code false} if
-     *         the specified waiting time elapses before space is available.
+     *         the specified waiting time elapses before space is available
      * @throws InterruptedException {@inheritDoc}
      * @throws NullPointerException {@inheritDoc}
      */
@@ -782,6 +785,7 @@
          * item to hand out so that if hasNext() reports true, we will
          * still have it to return even if lost race with a take etc.
          */
+
         private Node<E> current;
         private Node<E> lastRet;
         private E currentElement;
@@ -855,6 +859,124 @@
         }
     }
 
+    /** A customized variant of Spliterators.IteratorSpliterator */
+    static final class LBQSpliterator<E> implements Spliterator<E> {
+        static final int MAX_BATCH = 1 << 25;  // max batch array size;
+        final LinkedBlockingQueue<E> queue;
+        Node<E> current;    // current node; null until initialized
+        int batch;          // batch size for splits
+        boolean exhausted;  // true when no more nodes
+        long est;           // size estimate
+        LBQSpliterator(LinkedBlockingQueue<E> queue) {
+            this.queue = queue;
+            this.est = queue.size();
+        }
+
+        public long estimateSize() { return est; }
+
+        public Spliterator<E> trySplit() {
+            Node<E> h;
+            final LinkedBlockingQueue<E> q = this.queue;
+            int b = batch;
+            int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
+            if (!exhausted &&
+                ((h = current) != null || (h = q.head.next) != null) &&
+                h.next != null) {
+                Object[] a = new Object[n];
+                int i = 0;
+                Node<E> p = current;
+                q.fullyLock();
+                try {
+                    if (p != null || (p = q.head.next) != null) {
+                        do {
+                            if ((a[i] = p.item) != null)
+                                ++i;
+                        } while ((p = p.next) != null && i < n);
+                    }
+                } finally {
+                    q.fullyUnlock();
+                }
+                if ((current = p) == null) {
+                    est = 0L;
+                    exhausted = true;
+                }
+                else if ((est -= i) < 0L)
+                    est = 0L;
+                if (i > 0) {
+                    batch = i;
+                    return Spliterators.spliterator
+                        (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
+                         Spliterator.CONCURRENT);
+                }
+            }
+            return null;
+        }
+
+        public void forEachRemaining(Consumer<? super E> action) {
+            if (action == null) throw new NullPointerException();
+            final LinkedBlockingQueue<E> q = this.queue;
+            if (!exhausted) {
+                exhausted = true;
+                Node<E> p = current;
+                do {
+                    E e = null;
+                    q.fullyLock();
+                    try {
+                        if (p == null)
+                            p = q.head.next;
+                        while (p != null) {
+                            e = p.item;
+                            p = p.next;
+                            if (e != null)
+                                break;
+                        }
+                    } finally {
+                        q.fullyUnlock();
+                    }
+                    if (e != null)
+                        action.accept(e);
+                } while (p != null);
+            }
+        }
+
+        public boolean tryAdvance(Consumer<? super E> action) {
+            if (action == null) throw new NullPointerException();
+            final LinkedBlockingQueue<E> q = this.queue;
+            if (!exhausted) {
+                E e = null;
+                q.fullyLock();
+                try {
+                    if (current == null)
+                        current = q.head.next;
+                    while (current != null) {
+                        e = current.item;
+                        current = current.next;
+                        if (e != null)
+                            break;
+                    }
+                } finally {
+                    q.fullyUnlock();
+                }
+                if (current == null)
+                    exhausted = true;
+                if (e != null) {
+                    action.accept(e);
+                    return true;
+                }
+            }
+            return false;
+        }
+
+        public int characteristics() {
+            return Spliterator.ORDERED | Spliterator.NONNULL |
+                Spliterator.CONCURRENT;
+        }
+    }
+
+    public Spliterator<E> spliterator() {
+        return new LBQSpliterator<E>(this);
+    }
+
     /**
      * Saves this queue to a stream (that is, serializes it).
      *
--- a/src/share/classes/java/util/concurrent/LinkedTransferQueue.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/LinkedTransferQueue.java	Mon Jul 22 17:37:15 2013 -0700
@@ -40,8 +40,10 @@
 import java.util.Iterator;
 import java.util.NoSuchElementException;
 import java.util.Queue;
-import java.util.concurrent.TimeUnit;
 import java.util.concurrent.locks.LockSupport;
+import java.util.Spliterator;
+import java.util.Spliterators;
+import java.util.function.Consumer;
 
 /**
  * An unbounded {@link TransferQueue} based on linked nodes.
@@ -777,6 +779,24 @@
     }
 
     /**
+     * Version of firstOfMode used by Spliterator
+     */
+    final Node firstDataNode() {
+        for (Node p = head; p != null;) {
+            Object item = p.item;
+            if (p.isData) {
+                if (item != null && item != p)
+                    return p;
+            }
+            else if (item == null)
+                break;
+            if (p == (p = p.next))
+                p = head;
+        }
+        return null;
+    }
+
+    /**
      * Returns the item in the first unmatched node with isData; or
      * null if none.  Used by peek.
      */
@@ -910,6 +930,98 @@
         }
     }
 
+    /** A customized variant of Spliterators.IteratorSpliterator */
+    static final class LTQSpliterator<E> implements Spliterator<E> {
+        static final int MAX_BATCH = 1 << 25;  // max batch array size;
+        final LinkedTransferQueue<E> queue;
+        Node current;    // current node; null until initialized
+        int batch;          // batch size for splits
+        boolean exhausted;  // true when no more nodes
+        LTQSpliterator(LinkedTransferQueue<E> queue) {
+            this.queue = queue;
+        }
+
+        public Spliterator<E> trySplit() {
+            Node p;
+            final LinkedTransferQueue<E> q = this.queue;
+            int b = batch;
+            int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
+            if (!exhausted &&
+                ((p = current) != null || (p = q.firstDataNode()) != null) &&
+                p.next != null) {
+                Object[] a = new Object[n];
+                int i = 0;
+                do {
+                    if ((a[i] = p.item) != null)
+                        ++i;
+                    if (p == (p = p.next))
+                        p = q.firstDataNode();
+                } while (p != null && i < n);
+                if ((current = p) == null)
+                    exhausted = true;
+                if (i > 0) {
+                    batch = i;
+                    return Spliterators.spliterator
+                        (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
+                         Spliterator.CONCURRENT);
+                }
+            }
+            return null;
+        }
+
+        @SuppressWarnings("unchecked")
+        public void forEachRemaining(Consumer<? super E> action) {
+            Node p;
+            if (action == null) throw new NullPointerException();
+            final LinkedTransferQueue<E> q = this.queue;
+            if (!exhausted &&
+                ((p = current) != null || (p = q.firstDataNode()) != null)) {
+                exhausted = true;
+                do {
+                    Object e = p.item;
+                    if (p == (p = p.next))
+                        p = q.firstDataNode();
+                    if (e != null)
+                        action.accept((E)e);
+                } while (p != null);
+            }
+        }
+
+        @SuppressWarnings("unchecked")
+        public boolean tryAdvance(Consumer<? super E> action) {
+            Node p;
+            if (action == null) throw new NullPointerException();
+            final LinkedTransferQueue<E> q = this.queue;
+            if (!exhausted &&
+                ((p = current) != null || (p = q.firstDataNode()) != null)) {
+                Object e;
+                do {
+                    e = p.item;
+                    if (p == (p = p.next))
+                        p = q.firstDataNode();
+                } while (e == null && p != null);
+                if ((current = p) == null)
+                    exhausted = true;
+                if (e != null) {
+                    action.accept((E)e);
+                    return true;
+                }
+            }
+            return false;
+        }
+
+        public long estimateSize() { return Long.MAX_VALUE; }
+
+        public int characteristics() {
+            return Spliterator.ORDERED | Spliterator.NONNULL |
+                Spliterator.CONCURRENT;
+        }
+    }
+
+    public Spliterator<E> spliterator() {
+        return new LTQSpliterator<E>(this);
+    }
+
     /* -------------- Removal methods -------------- */
 
     /**
--- a/src/share/classes/java/util/concurrent/Phaser.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/Phaser.java	Mon Jul 22 17:37:15 2013 -0700
@@ -46,7 +46,7 @@
  * {@link java.util.concurrent.CountDownLatch CountDownLatch}
  * but supporting more flexible usage.
  *
- * <p> <b>Registration.</b> Unlike the case for other barriers, the
+ * <p><b>Registration.</b> Unlike the case for other barriers, the
  * number of parties <em>registered</em> to synchronize on a phaser
  * may vary over time.  Tasks may be registered at any time (using
  * methods {@link #register}, {@link #bulkRegister}, or forms of
@@ -59,7 +59,7 @@
  * (However, you can introduce such bookkeeping by subclassing this
  * class.)
  *
- * <p> <b>Synchronization.</b> Like a {@code CyclicBarrier}, a {@code
+ * <p><b>Synchronization.</b> Like a {@code CyclicBarrier}, a {@code
  * Phaser} may be repeatedly awaited.  Method {@link
  * #arriveAndAwaitAdvance} has effect analogous to {@link
  * java.util.concurrent.CyclicBarrier#await CyclicBarrier.await}. Each
@@ -103,7 +103,7 @@
  *
  * </ul>
  *
- * <p> <b>Termination.</b> A phaser may enter a <em>termination</em>
+ * <p><b>Termination.</b> A phaser may enter a <em>termination</em>
  * state, that may be checked using method {@link #isTerminated}. Upon
  * termination, all synchronization methods immediately return without
  * waiting for advance, as indicated by a negative return value.
@@ -118,7 +118,7 @@
  * also available to abruptly release waiting threads and allow them
  * to terminate.
  *
- * <p> <b>Tiering.</b> Phasers may be <em>tiered</em> (i.e.,
+ * <p><b>Tiering.</b> Phasers may be <em>tiered</em> (i.e.,
  * constructed in tree structures) to reduce contention. Phasers with
  * large numbers of parties that would otherwise experience heavy
  * synchronization contention costs may instead be set up so that
@@ -300,18 +300,20 @@
     private static final int  PHASE_SHIFT     = 32;
     private static final int  UNARRIVED_MASK  = 0xffff;      // to mask ints
     private static final long PARTIES_MASK    = 0xffff0000L; // to mask longs
+    private static final long COUNTS_MASK     = 0xffffffffL;
     private static final long TERMINATION_BIT = 1L << 63;
 
     // some special values
     private static final int  ONE_ARRIVAL     = 1;
     private static final int  ONE_PARTY       = 1 << PARTIES_SHIFT;
+    private static final int  ONE_DEREGISTER  = ONE_ARRIVAL|ONE_PARTY;
     private static final int  EMPTY           = 1;
 
     // The following unpacking methods are usually manually inlined
 
     private static int unarrivedOf(long s) {
         int counts = (int)s;
-        return (counts == EMPTY) ? 0 : counts & UNARRIVED_MASK;
+        return (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK);
     }
 
     private static int partiesOf(long s) {
@@ -372,37 +374,44 @@
      * Manually tuned to speed up and minimize race windows for the
      * common case of just decrementing unarrived field.
      *
-     * @param deregister false for arrive, true for arriveAndDeregister
+     * @param adjust value to subtract from state;
+     *               ONE_ARRIVAL for arrive,
+     *               ONE_DEREGISTER for arriveAndDeregister
      */
-    private int doArrive(boolean deregister) {
-        int adj = deregister ? ONE_ARRIVAL|ONE_PARTY : ONE_ARRIVAL;
+    private int doArrive(int adjust) {
         final Phaser root = this.root;
         for (;;) {
             long s = (root == this) ? state : reconcileState();
             int phase = (int)(s >>> PHASE_SHIFT);
-            int counts = (int)s;
-            int unarrived = (counts & UNARRIVED_MASK) - 1;
             if (phase < 0)
                 return phase;
-            else if (counts == EMPTY || unarrived < 0) {
-                if (root == this || reconcileState() == s)
-                    throw new IllegalStateException(badArrive(s));
-            }
-            else if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s-=adj)) {
-                if (unarrived == 0) {
+            int counts = (int)s;
+            int unarrived = (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK);
+            if (unarrived <= 0)
+                throw new IllegalStateException(badArrive(s));
+            if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s-=adjust)) {
+                if (unarrived == 1) {
                     long n = s & PARTIES_MASK;  // base of next state
                     int nextUnarrived = (int)n >>> PARTIES_SHIFT;
-                    if (root != this)
-                        return parent.doArrive(nextUnarrived == 0);
-                    if (onAdvance(phase, nextUnarrived))
-                        n |= TERMINATION_BIT;
-                    else if (nextUnarrived == 0)
-                        n |= EMPTY;
+                    if (root == this) {
+                        if (onAdvance(phase, nextUnarrived))
+                            n |= TERMINATION_BIT;
+                        else if (nextUnarrived == 0)
+                            n |= EMPTY;
+                        else
+                            n |= nextUnarrived;
+                        int nextPhase = (phase + 1) & MAX_PHASE;
+                        n |= (long)nextPhase << PHASE_SHIFT;
+                        UNSAFE.compareAndSwapLong(this, stateOffset, s, n);
+                        releaseWaiters(phase);
+                    }
+                    else if (nextUnarrived == 0) { // propagate deregistration
+                        phase = parent.doArrive(ONE_DEREGISTER);
+                        UNSAFE.compareAndSwapLong(this, stateOffset,
+                                                  s, s | EMPTY);
+                    }
                     else
-                        n |= nextUnarrived;
-                    n |= (long)((phase + 1) & MAX_PHASE) << PHASE_SHIFT;
-                    UNSAFE.compareAndSwapLong(this, stateOffset, s, n);
-                    releaseWaiters(phase);
+                        phase = parent.doArrive(ONE_ARRIVAL);
                 }
                 return phase;
             }
@@ -417,42 +426,49 @@
      */
     private int doRegister(int registrations) {
         // adjustment to state
-        long adj = ((long)registrations << PARTIES_SHIFT) | registrations;
+        long adjust = ((long)registrations << PARTIES_SHIFT) | registrations;
         final Phaser parent = this.parent;
         int phase;
         for (;;) {
-            long s = state;
+            long s = (parent == null) ? state : reconcileState();
             int counts = (int)s;
             int parties = counts >>> PARTIES_SHIFT;
             int unarrived = counts & UNARRIVED_MASK;
             if (registrations > MAX_PARTIES - parties)
                 throw new IllegalStateException(badRegister(s));
-            else if ((phase = (int)(s >>> PHASE_SHIFT)) < 0)
+            phase = (int)(s >>> PHASE_SHIFT);
+            if (phase < 0)
                 break;
-            else if (counts != EMPTY) {             // not 1st registration
+            if (counts != EMPTY) {                  // not 1st registration
                 if (parent == null || reconcileState() == s) {
                     if (unarrived == 0)             // wait out advance
                         root.internalAwaitAdvance(phase, null);
                     else if (UNSAFE.compareAndSwapLong(this, stateOffset,
-                                                       s, s + adj))
+                                                       s, s + adjust))
                         break;
                 }
             }
             else if (parent == null) {              // 1st root registration
-                long next = ((long)phase << PHASE_SHIFT) | adj;
+                long next = ((long)phase << PHASE_SHIFT) | adjust;
                 if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next))
                     break;
             }
             else {
                 synchronized (this) {               // 1st sub registration
                     if (state == s) {               // recheck under lock
-                        parent.doRegister(1);
-                        do {                        // force current phase
+                        phase = parent.doRegister(1);
+                        if (phase < 0)
+                            break;
+                        // finish registration whenever parent registration
+                        // succeeded, even when racing with termination,
+                        // since these are part of the same "transaction".
+                        while (!UNSAFE.compareAndSwapLong
+                               (this, stateOffset, s,
+                                ((long)phase << PHASE_SHIFT) | adjust)) {
+                            s = state;
                             phase = (int)(root.state >>> PHASE_SHIFT);
-                            // assert phase < 0 || (int)state == EMPTY;
-                        } while (!UNSAFE.compareAndSwapLong
-                                 (this, stateOffset, state,
-                                  ((long)phase << PHASE_SHIFT) | adj));
+                            // assert (int)s == EMPTY;
+                        }
                         break;
                     }
                 }
@@ -467,10 +483,6 @@
      * subphasers have not yet done so, in which case they must finish
      * their own advance by setting unarrived to parties (or if
      * parties is zero, resetting to unregistered EMPTY state).
-     * However, this method may also be called when "floating"
-     * subphasers with possibly some unarrived parties are merely
-     * catching up to current phase, in which case counts are
-     * unaffected.
      *
      * @return reconciled state
      */
@@ -478,16 +490,16 @@
         final Phaser root = this.root;
         long s = state;
         if (root != this) {
-            int phase, u, p;
-            // CAS root phase with current parties; possibly trip unarrived
+            int phase, p;
+            // CAS to root phase with current parties, tripping unarrived
             while ((phase = (int)(root.state >>> PHASE_SHIFT)) !=
                    (int)(s >>> PHASE_SHIFT) &&
                    !UNSAFE.compareAndSwapLong
                    (this, stateOffset, s,
                     s = (((long)phase << PHASE_SHIFT) |
-                         (s & PARTIES_MASK) |
-                         ((p = (int)s >>> PARTIES_SHIFT) == 0 ? EMPTY :
-                          (u = (int)s & UNARRIVED_MASK) == 0 ? p : u))))
+                         ((phase < 0) ? (s & COUNTS_MASK) :
+                          (((p = (int)s >>> PARTIES_SHIFT) == 0) ? EMPTY :
+                           ((s & PARTIES_MASK) | p))))))
                 s = state;
         }
         return s;
@@ -619,7 +631,7 @@
      * of unarrived parties would become negative
      */
     public int arrive() {
-        return doArrive(false);
+        return doArrive(ONE_ARRIVAL);
     }
 
     /**
@@ -639,7 +651,7 @@
      * of registered or unarrived parties would become negative
      */
     public int arriveAndDeregister() {
-        return doArrive(true);
+        return doArrive(ONE_DEREGISTER);
     }
 
     /**
@@ -666,17 +678,15 @@
         for (;;) {
             long s = (root == this) ? state : reconcileState();
             int phase = (int)(s >>> PHASE_SHIFT);
-            int counts = (int)s;
-            int unarrived = (counts & UNARRIVED_MASK) - 1;
             if (phase < 0)
                 return phase;
-            else if (counts == EMPTY || unarrived < 0) {
-                if (reconcileState() == s)
-                    throw new IllegalStateException(badArrive(s));
-            }
-            else if (UNSAFE.compareAndSwapLong(this, stateOffset, s,
-                                               s -= ONE_ARRIVAL)) {
-                if (unarrived != 0)
+            int counts = (int)s;
+            int unarrived = (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK);
+            if (unarrived <= 0)
+                throw new IllegalStateException(badArrive(s));
+            if (UNSAFE.compareAndSwapLong(this, stateOffset, s,
+                                          s -= ONE_ARRIVAL)) {
+                if (unarrived > 1)
                     return root.internalAwaitAdvance(phase, null);
                 if (root != this)
                     return parent.arriveAndAwaitAdvance();
@@ -809,8 +819,8 @@
             if (UNSAFE.compareAndSwapLong(root, stateOffset,
                                           s, s | TERMINATION_BIT)) {
                 // signal all threads
-                releaseWaiters(0);
-                releaseWaiters(1);
+                releaseWaiters(0); // Waiters on evenQ
+                releaseWaiters(1); // Waiters on oddQ
                 return;
             }
         }
@@ -1016,7 +1026,7 @@
 
     /**
      * Possibly blocks and waits for phase to advance unless aborted.
-     * Call only from root node.
+     * Call only on root phaser.
      *
      * @param phase current phase
      * @param node if non-null, the wait node to track interrupt and timeout;
@@ -1024,6 +1034,7 @@
      * @return current phase
      */
     private int internalAwaitAdvance(int phase, QNode node) {
+        // assert root == this;
         releaseWaiters(phase-1);          // ensure old queue clean
         boolean queued = false;           // true when node is enqueued
         int lastUnarrived = 0;            // to increase spins upon change
@@ -1082,7 +1093,7 @@
         final boolean timed;
         boolean wasInterrupted;
         long nanos;
-        long lastTime;
+        final long deadline;
         volatile Thread thread; // nulled to cancel wait
         QNode next;
 
@@ -1093,7 +1104,7 @@
             this.interruptible = interruptible;
             this.nanos = nanos;
             this.timed = timed;
-            this.lastTime = timed ? System.nanoTime() : 0L;
+            this.deadline = timed ? System.nanoTime() + nanos : 0L;
             thread = Thread.currentThread();
         }
 
@@ -1112,9 +1123,7 @@
             }
             if (timed) {
                 if (nanos > 0L) {
-                    long now = System.nanoTime();
-                    nanos -= now - lastTime;
-                    lastTime = now;
+                    nanos = deadline - System.nanoTime();
                 }
                 if (nanos <= 0L) {
                     thread = null;
@@ -1129,7 +1138,7 @@
                 return true;
             else if (!timed)
                 LockSupport.park(this);
-            else if (nanos > 0)
+            else if (nanos > 0L)
                 LockSupport.parkNanos(this, nanos);
             return isReleasable();
         }
--- a/src/share/classes/java/util/concurrent/PriorityBlockingQueue.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/PriorityBlockingQueue.java	Mon Jul 22 17:37:15 2013 -0700
@@ -37,7 +37,17 @@
 
 import java.util.concurrent.locks.Condition;
 import java.util.concurrent.locks.ReentrantLock;
-import java.util.*;
+import java.util.AbstractQueue;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.PriorityQueue;
+import java.util.Queue;
+import java.util.SortedSet;
+import java.util.Spliterator;
+import java.util.function.Consumer;
 
 /**
  * An unbounded {@linkplain BlockingQueue blocking queue} that uses
@@ -342,7 +352,6 @@
      * @param k the position to fill
      * @param x the item to insert
      * @param array the heap array
-     * @param n heap size
      */
     private static <T> void siftUpComparable(int k, T x, Object[] array) {
         Comparable<? super T> key = (Comparable<? super T>) x;
@@ -936,6 +945,70 @@
         }
     }
 
+    // Similar to Collections.ArraySnapshotSpliterator but avoids
+    // commitment to toArray until needed
+    static final class PBQSpliterator<E> implements Spliterator<E> {
+        final PriorityBlockingQueue<E> queue;
+        Object[] array;
+        int index;
+        int fence;
+
+        PBQSpliterator(PriorityBlockingQueue<E> queue, Object[] array,
+                       int index, int fence) {
+            this.queue = queue;
+            this.array = array;
+            this.index = index;
+            this.fence = fence;
+        }
+
+        final int getFence() {
+            int hi;
+            if ((hi = fence) < 0)
+                hi = fence = (array = queue.toArray()).length;
+            return hi;
+        }
+
+        public Spliterator<E> trySplit() {
+            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
+            return (lo >= mid) ? null :
+                new PBQSpliterator<E>(queue, array, lo, index = mid);
+        }
+
+        @SuppressWarnings("unchecked")
+        public void forEachRemaining(Consumer<? super E> action) {
+            Object[] a; int i, hi; // hoist accesses and checks from loop
+            if (action == null)
+                throw new NullPointerException();
+            if ((a = array) == null)
+                fence = (a = queue.toArray()).length;
+            if ((hi = fence) <= a.length &&
+                (i = index) >= 0 && i < (index = hi)) {
+                do { action.accept((E)a[i]); } while (++i < hi);
+            }
+        }
+
+        public boolean tryAdvance(Consumer<? super E> action) {
+            if (action == null)
+                throw new NullPointerException();
+            if (getFence() > index && index >= 0) {
+                @SuppressWarnings("unchecked") E e = (E) array[index++];
+                action.accept(e);
+                return true;
+            }
+            return false;
+        }
+
+        public long estimateSize() { return (long)(getFence() - index); }
+
+        public int characteristics() {
+            return Spliterator.NONNULL | Spliterator.SIZED | Spliterator.SUBSIZED;
+        }
+    }
+
+    public Spliterator<E> spliterator() {
+        return new PBQSpliterator<E>(this, null, 0, -1);
+    }
+
     // Unsafe mechanics
     private static final sun.misc.Unsafe UNSAFE;
     private static final long allocationSpinLockOffset;
--- a/src/share/classes/java/util/concurrent/RecursiveAction.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/RecursiveAction.java	Mon Jul 22 17:37:15 2013 -0700
@@ -63,7 +63,7 @@
  *     }
  *   }
  *   // implementation details follow:
- *   final static int THRESHOLD = 1000;
+ *   static final int THRESHOLD = 1000;
  *   void sortSequentially(int lo, int hi) {
  *     Arrays.sort(array, lo, hi);
  *   }
@@ -140,21 +140,21 @@
  *     int h = hi;
  *     Applyer right = null;
  *     while (h - l > 1 && getSurplusQueuedTaskCount() <= 3) {
- *        int mid = (l + h) >>> 1;
- *        right = new Applyer(array, mid, h, right);
- *        right.fork();
- *        h = mid;
+ *       int mid = (l + h) >>> 1;
+ *       right = new Applyer(array, mid, h, right);
+ *       right.fork();
+ *       h = mid;
  *     }
  *     double sum = atLeaf(l, h);
  *     while (right != null) {
- *        if (right.tryUnfork()) // directly calculate if not stolen
- *          sum += right.atLeaf(right.lo, right.hi);
+ *       if (right.tryUnfork()) // directly calculate if not stolen
+ *         sum += right.atLeaf(right.lo, right.hi);
  *       else {
- *          right.join();
- *          sum += right.result;
- *        }
- *        right = right.next;
- *      }
+ *         right.join();
+ *         sum += right.result;
+ *       }
+ *       right = right.next;
+ *     }
  *     result = sum;
  *   }
  * }}</pre>
--- a/src/share/classes/java/util/concurrent/RecursiveTask.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/RecursiveTask.java	Mon Jul 22 17:37:15 2013 -0700
@@ -46,7 +46,7 @@
  *   Fibonacci(int n) { this.n = n; }
  *   Integer compute() {
  *     if (n <= 1)
- *        return n;
+ *       return n;
  *     Fibonacci f1 = new Fibonacci(n - 1);
  *     f1.fork();
  *     Fibonacci f2 = new Fibonacci(n - 2);
@@ -75,6 +75,7 @@
 
     /**
      * The main computation performed by this task.
+     * @return the result of the computation
      */
     protected abstract V compute();
 
--- a/src/share/classes/java/util/concurrent/RejectedExecutionException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/RejectedExecutionException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -46,14 +46,14 @@
     private static final long serialVersionUID = -375805702767069545L;
 
     /**
-     * Constructs a <tt>RejectedExecutionException</tt> with no detail message.
+     * Constructs a {@code RejectedExecutionException} with no detail message.
      * The cause is not initialized, and may subsequently be
      * initialized by a call to {@link #initCause(Throwable) initCause}.
      */
     public RejectedExecutionException() { }
 
     /**
-     * Constructs a <tt>RejectedExecutionException</tt> with the
+     * Constructs a {@code RejectedExecutionException} with the
      * specified detail message. The cause is not initialized, and may
      * subsequently be initialized by a call to {@link
      * #initCause(Throwable) initCause}.
@@ -65,7 +65,7 @@
     }
 
     /**
-     * Constructs a <tt>RejectedExecutionException</tt> with the
+     * Constructs a {@code RejectedExecutionException} with the
      * specified detail message and cause.
      *
      * @param  message the detail message
@@ -77,10 +77,10 @@
     }
 
     /**
-     * Constructs a <tt>RejectedExecutionException</tt> with the
+     * Constructs a {@code RejectedExecutionException} with the
      * specified cause.  The detail message is set to {@code (cause ==
      * null ? null : cause.toString())} (which typically contains
-     * the class and detail message of <tt>cause</tt>).
+     * the class and detail message of {@code cause}).
      *
      * @param  cause the cause (which is saved for later retrieval by the
      *         {@link #getCause()} method)
--- a/src/share/classes/java/util/concurrent/RunnableFuture.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/RunnableFuture.java	Mon Jul 22 17:37:15 2013 -0700
@@ -37,13 +37,13 @@
 
 /**
  * A {@link Future} that is {@link Runnable}. Successful execution of
- * the <tt>run</tt> method causes completion of the <tt>Future</tt>
+ * the {@code run} method causes completion of the {@code Future}
  * and allows access to its results.
  * @see FutureTask
  * @see Executor
  * @since 1.6
  * @author Doug Lea
- * @param <V> The result type returned by this Future's <tt>get</tt> method
+ * @param <V> The result type returned by this Future's {@code get} method
  */
 public interface RunnableFuture<V> extends Runnable, Future<V> {
     /**
--- a/src/share/classes/java/util/concurrent/RunnableScheduledFuture.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/RunnableScheduledFuture.java	Mon Jul 22 17:37:15 2013 -0700
@@ -37,22 +37,22 @@
 
 /**
  * A {@link ScheduledFuture} that is {@link Runnable}. Successful
- * execution of the <tt>run</tt> method causes completion of the
- * <tt>Future</tt> and allows access to its results.
+ * execution of the {@code run} method causes completion of the
+ * {@code Future} and allows access to its results.
  * @see FutureTask
  * @see Executor
  * @since 1.6
  * @author Doug Lea
- * @param <V> The result type returned by this Future's <tt>get</tt> method
+ * @param <V> The result type returned by this Future's {@code get} method
  */
 public interface RunnableScheduledFuture<V> extends RunnableFuture<V>, ScheduledFuture<V> {
 
     /**
-     * Returns true if this is a periodic task. A periodic task may
+     * Returns {@code true} if this task is periodic. A periodic task may
      * re-run according to some schedule. A non-periodic task can be
      * run only once.
      *
-     * @return true if this task is periodic
+     * @return {@code true} if this task is periodic
      */
     boolean isPeriodic();
 }
--- a/src/share/classes/java/util/concurrent/ScheduledExecutorService.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/ScheduledExecutorService.java	Mon Jul 22 17:37:15 2013 -0700
@@ -39,30 +39,30 @@
  * An {@link ExecutorService} that can schedule commands to run after a given
  * delay, or to execute periodically.
  *
- * <p> The <tt>schedule</tt> methods create tasks with various delays
+ * <p>The {@code schedule} methods create tasks with various delays
  * and return a task object that can be used to cancel or check
- * execution. The <tt>scheduleAtFixedRate</tt> and
- * <tt>scheduleWithFixedDelay</tt> methods create and execute tasks
+ * execution. The {@code scheduleAtFixedRate} and
+ * {@code scheduleWithFixedDelay} methods create and execute tasks
  * that run periodically until cancelled.
  *
- * <p> Commands submitted using the {@link Executor#execute} and
- * {@link ExecutorService} <tt>submit</tt> methods are scheduled with
- * a requested delay of zero. Zero and negative delays (but not
- * periods) are also allowed in <tt>schedule</tt> methods, and are
+ * <p>Commands submitted using the {@link Executor#execute(Runnable)}
+ * and {@link ExecutorService} {@code submit} methods are scheduled
+ * with a requested delay of zero. Zero and negative delays (but not
+ * periods) are also allowed in {@code schedule} methods, and are
  * treated as requests for immediate execution.
  *
- * <p>All <tt>schedule</tt> methods accept <em>relative</em> delays and
+ * <p>All {@code schedule} methods accept <em>relative</em> delays and
  * periods as arguments, not absolute times or dates. It is a simple
  * matter to transform an absolute time represented as a {@link
  * java.util.Date} to the required form. For example, to schedule at
- * a certain future <tt>date</tt>, you can use: <tt>schedule(task,
+ * a certain future {@code date}, you can use: {@code schedule(task,
  * date.getTime() - System.currentTimeMillis(),
- * TimeUnit.MILLISECONDS)</tt>. Beware however that expiration of a
- * relative delay need not coincide with the current <tt>Date</tt> at
+ * TimeUnit.MILLISECONDS)}. Beware however that expiration of a
+ * relative delay need not coincide with the current {@code Date} at
  * which the task is enabled due to network time synchronization
  * protocols, clock drift, or other factors.
  *
- * The {@link Executors} class provides convenient factory methods for
+ * <p>The {@link Executors} class provides convenient factory methods for
  * the ScheduledExecutorService implementations provided in this package.
  *
  * <h3>Usage Example</h3>
@@ -101,8 +101,8 @@
      * @param delay the time from now to delay execution
      * @param unit the time unit of the delay parameter
      * @return a ScheduledFuture representing pending completion of
-     *         the task and whose <tt>get()</tt> method will return
-     *         <tt>null</tt> upon completion
+     *         the task and whose {@code get()} method will return
+     *         {@code null} upon completion
      * @throws RejectedExecutionException if the task cannot be
      *         scheduled for execution
      * @throws NullPointerException if command is null
@@ -129,8 +129,8 @@
      * Creates and executes a periodic action that becomes enabled first
      * after the given initial delay, and subsequently with the given
      * period; that is executions will commence after
-     * <tt>initialDelay</tt> then <tt>initialDelay+period</tt>, then
-     * <tt>initialDelay + 2 * period</tt>, and so on.
+     * {@code initialDelay} then {@code initialDelay+period}, then
+     * {@code initialDelay + 2 * period}, and so on.
      * If any execution of the task
      * encounters an exception, subsequent executions are suppressed.
      * Otherwise, the task will only terminate via cancellation or
@@ -143,7 +143,7 @@
      * @param period the period between successive executions
      * @param unit the time unit of the initialDelay and period parameters
      * @return a ScheduledFuture representing pending completion of
-     *         the task, and whose <tt>get()</tt> method will throw an
+     *         the task, and whose {@code get()} method will throw an
      *         exception upon cancellation
      * @throws RejectedExecutionException if the task cannot be
      *         scheduled for execution
@@ -170,7 +170,7 @@
      * execution and the commencement of the next
      * @param unit the time unit of the initialDelay and delay parameters
      * @return a ScheduledFuture representing pending completion of
-     *         the task, and whose <tt>get()</tt> method will throw an
+     *         the task, and whose {@code get()} method will throw an
      *         exception upon cancellation
      * @throws RejectedExecutionException if the task cannot be
      *         scheduled for execution
--- a/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java	Mon Jul 22 17:37:15 2013 -0700
@@ -81,7 +81,7 @@
  * without threads to handle tasks once they become eligible to run.
  *
  * <p><b>Extension notes:</b> This class overrides the
- * {@link ThreadPoolExecutor#execute execute} and
+ * {@link ThreadPoolExecutor#execute(Runnable) execute} and
  * {@link AbstractExecutorService#submit(Runnable) submit}
  * methods to generate internal {@link ScheduledFuture} objects to
  * control per-task delays and scheduling.  To preserve
@@ -256,9 +256,9 @@
         }
 
         /**
-         * Returns true if this is a periodic (not a one-shot) action.
+         * Returns {@code true} if this is a periodic (not a one-shot) action.
          *
-         * @return true if periodic
+         * @return {@code true} if periodic
          */
         public boolean isPeriodic() {
             return period != 0;
@@ -315,7 +315,7 @@
      * is shut down, rejects the task. Otherwise adds task to queue
      * and starts a thread, if necessary, to run it.  (We cannot
      * prestart the thread to run the task because the task (probably)
-     * shouldn't be run yet,) If the pool is shut down while the task
+     * shouldn't be run yet.)  If the pool is shut down while the task
      * is being added, cancel and remove it if required by state and
      * run-after-shutdown parameters.
      *
@@ -654,7 +654,7 @@
      * {@code false} when already shutdown.
      * This value is by default {@code false}.
      *
-     * @param value if {@code true}, continue after shutdown, else don't.
+     * @param value if {@code true}, continue after shutdown, else don't
      * @see #getContinueExistingPeriodicTasksAfterShutdownPolicy
      */
     public void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value) {
@@ -686,7 +686,7 @@
      * {@code false} when already shutdown.
      * This value is by default {@code true}.
      *
-     * @param value if {@code true}, execute after shutdown, else don't.
+     * @param value if {@code true}, execute after shutdown, else don't
      * @see #getExecuteExistingDelayedTasksAfterShutdownPolicy
      */
     public void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value) {
@@ -1081,7 +1081,8 @@
                         long delay = first.getDelay(NANOSECONDS);
                         if (delay <= 0)
                             return finishPoll(first);
-                        else if (leader != null)
+                        first = null; // don't retain ref while waiting
+                        if (leader != null)
                             available.await();
                         else {
                             Thread thisThread = Thread.currentThread();
@@ -1121,6 +1122,7 @@
                             return finishPoll(first);
                         if (nanos <= 0)
                             return null;
+                        first = null; // don't retain ref while waiting
                         if (nanos < delay || leader != null)
                             nanos = available.awaitNanos(nanos);
                         else {
--- a/src/share/classes/java/util/concurrent/SynchronousQueue.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/SynchronousQueue.java	Mon Jul 22 17:37:15 2013 -0700
@@ -44,17 +44,17 @@
  * operation must wait for a corresponding remove operation by another
  * thread, and vice versa.  A synchronous queue does not have any
  * internal capacity, not even a capacity of one.  You cannot
- * <tt>peek</tt> at a synchronous queue because an element is only
+ * {@code peek} at a synchronous queue because an element is only
  * present when you try to remove it; you cannot insert an element
  * (using any method) unless another thread is trying to remove it;
  * you cannot iterate as there is nothing to iterate.  The
  * <em>head</em> of the queue is the element that the first queued
  * inserting thread is trying to add to the queue; if there is no such
  * queued thread then no element is available for removal and
- * <tt>poll()</tt> will return <tt>null</tt>.  For purposes of other
- * <tt>Collection</tt> methods (for example <tt>contains</tt>), a
- * <tt>SynchronousQueue</tt> acts as an empty collection.  This queue
- * does not permit <tt>null</tt> elements.
+ * {@code poll()} will return {@code null}.  For purposes of other
+ * {@code Collection} methods (for example {@code contains}), a
+ * {@code SynchronousQueue} acts as an empty collection.  This queue
+ * does not permit {@code null} elements.
  *
  * <p>Synchronous queues are similar to rendezvous channels used in
  * CSP and Ada. They are well suited for handoff designs, in which an
@@ -62,10 +62,10 @@
  * in another thread in order to hand it some information, event, or
  * task.
  *
- * <p> This class supports an optional fairness policy for ordering
+ * <p>This class supports an optional fairness policy for ordering
  * waiting producer and consumer threads.  By default, this ordering
  * is not guaranteed. However, a queue constructed with fairness set
- * to <tt>true</tt> grants threads access in FIFO order.
+ * to {@code true} grants threads access in FIFO order.
  *
  * <p>This class and its iterator implement all of the
  * <em>optional</em> methods of the {@link Collection} and {@link
@@ -599,7 +599,7 @@
         /**
          * Reference to a cancelled node that might not yet have been
          * unlinked from queue because it was the last inserted node
-         * when it cancelled.
+         * when it was cancelled.
          */
         transient volatile QNode cleanMe;
 
@@ -847,14 +847,14 @@
     private transient volatile Transferer<E> transferer;
 
     /**
-     * Creates a <tt>SynchronousQueue</tt> with nonfair access policy.
+     * Creates a {@code SynchronousQueue} with nonfair access policy.
      */
     public SynchronousQueue() {
         this(false);
     }
 
     /**
-     * Creates a <tt>SynchronousQueue</tt> with the specified fairness policy.
+     * Creates a {@code SynchronousQueue} with the specified fairness policy.
      *
      * @param fair if true, waiting threads contend in FIFO order for
      *        access; otherwise the order is unspecified.
@@ -882,8 +882,8 @@
      * Inserts the specified element into this queue, waiting if necessary
      * up to the specified wait time for another thread to receive it.
      *
-     * @return <tt>true</tt> if successful, or <tt>false</tt> if the
-     *         specified waiting time elapses before a consumer appears.
+     * @return {@code true} if successful, or {@code false} if the
+     *         specified waiting time elapses before a consumer appears
      * @throws InterruptedException {@inheritDoc}
      * @throws NullPointerException {@inheritDoc}
      */
@@ -902,8 +902,8 @@
      * waiting to receive it.
      *
      * @param e the element to add
-     * @return <tt>true</tt> if the element was added to this queue, else
-     *         <tt>false</tt>
+     * @return {@code true} if the element was added to this queue, else
+     *         {@code false}
      * @throws NullPointerException if the specified element is null
      */
     public boolean offer(E e) {
@@ -931,8 +931,8 @@
      * if necessary up to the specified wait time, for another thread
      * to insert it.
      *
-     * @return the head of this queue, or <tt>null</tt> if the
-     *         specified waiting time elapses before an element is present.
+     * @return the head of this queue, or {@code null} if the
+     *         specified waiting time elapses before an element is present
      * @throws InterruptedException {@inheritDoc}
      */
     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
@@ -946,18 +946,18 @@
      * Retrieves and removes the head of this queue, if another thread
      * is currently making an element available.
      *
-     * @return the head of this queue, or <tt>null</tt> if no
-     *         element is available.
+     * @return the head of this queue, or {@code null} if no
+     *         element is available
      */
     public E poll() {
         return transferer.transfer(null, true, 0);
     }
 
     /**
-     * Always returns <tt>true</tt>.
-     * A <tt>SynchronousQueue</tt> has no internal capacity.
+     * Always returns {@code true}.
+     * A {@code SynchronousQueue} has no internal capacity.
      *
-     * @return <tt>true</tt>
+     * @return {@code true}
      */
     public boolean isEmpty() {
         return true;
@@ -965,9 +965,9 @@
 
     /**
      * Always returns zero.
-     * A <tt>SynchronousQueue</tt> has no internal capacity.
+     * A {@code SynchronousQueue} has no internal capacity.
      *
-     * @return zero.
+     * @return zero
      */
     public int size() {
         return 0;
@@ -975,9 +975,9 @@
 
     /**
      * Always returns zero.
-     * A <tt>SynchronousQueue</tt> has no internal capacity.
+     * A {@code SynchronousQueue} has no internal capacity.
      *
-     * @return zero.
+     * @return zero
      */
     public int remainingCapacity() {
         return 0;
@@ -985,80 +985,80 @@
 
     /**
      * Does nothing.
-     * A <tt>SynchronousQueue</tt> has no internal capacity.
+     * A {@code SynchronousQueue} has no internal capacity.
      */
     public void clear() {
     }
 
     /**
-     * Always returns <tt>false</tt>.
-     * A <tt>SynchronousQueue</tt> has no internal capacity.
+     * Always returns {@code false}.
+     * A {@code SynchronousQueue} has no internal capacity.
      *
      * @param o the element
-     * @return <tt>false</tt>
+     * @return {@code false}
      */
     public boolean contains(Object o) {
         return false;
     }
 
     /**
-     * Always returns <tt>false</tt>.
-     * A <tt>SynchronousQueue</tt> has no internal capacity.
+     * Always returns {@code false}.
+     * A {@code SynchronousQueue} has no internal capacity.
      *
      * @param o the element to remove
-     * @return <tt>false</tt>
+     * @return {@code false}
      */
     public boolean remove(Object o) {
         return false;
     }
 
     /**
-     * Returns <tt>false</tt> unless the given collection is empty.
-     * A <tt>SynchronousQueue</tt> has no internal capacity.
+     * Returns {@code false} unless the given collection is empty.
+     * A {@code SynchronousQueue} has no internal capacity.
      *
      * @param c the collection
-     * @return <tt>false</tt> unless given collection is empty
+     * @return {@code false} unless given collection is empty
      */
     public boolean containsAll(Collection<?> c) {
         return c.isEmpty();
     }
 
     /**
-     * Always returns <tt>false</tt>.
-     * A <tt>SynchronousQueue</tt> has no internal capacity.
+     * Always returns {@code false}.
+     * A {@code SynchronousQueue} has no internal capacity.
      *
      * @param c the collection
-     * @return <tt>false</tt>
+     * @return {@code false}
      */
     public boolean removeAll(Collection<?> c) {
         return false;
     }
 
     /**
-     * Always returns <tt>false</tt>.
-     * A <tt>SynchronousQueue</tt> has no internal capacity.
+     * Always returns {@code false}.
+     * A {@code SynchronousQueue} has no internal capacity.
      *
      * @param c the collection
-     * @return <tt>false</tt>
+     * @return {@code false}
      */
     public boolean retainAll(Collection<?> c) {
         return false;
     }
 
     /**
-     * Always returns <tt>null</tt>.
-     * A <tt>SynchronousQueue</tt> does not return elements
+     * Always returns {@code null}.
+     * A {@code SynchronousQueue} does not return elements
      * unless actively waited on.
      *
-     * @return <tt>null</tt>
+     * @return {@code null}
      */
     public E peek() {
         return null;
     }
 
     /**
-     * Returns an empty iterator in which <tt>hasNext</tt> always returns
-     * <tt>false</tt>.
+     * Returns an empty iterator in which {@code hasNext} always returns
+     * {@code false}.
      *
      * @return an empty iterator
      */
@@ -1077,6 +1077,10 @@
         public void remove() { throw new IllegalStateException(); }
     }
 
+    public Spliterator<E> spliterator() {
+        return Spliterators.emptySpliterator();
+    }
+
     /**
      * Returns a zero-length array.
      * @return a zero-length array
@@ -1086,7 +1090,7 @@
     }
 
     /**
-     * Sets the zeroeth element of the specified array to <tt>null</tt>
+     * Sets the zeroeth element of the specified array to {@code null}
      * (if the array has non-zero length) and returns it.
      *
      * @param a the array
--- a/src/share/classes/java/util/concurrent/ThreadPoolExecutor.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/ThreadPoolExecutor.java	Mon Jul 22 17:37:15 2013 -0700
@@ -75,22 +75,23 @@
  * corePoolSize (see {@link #getCorePoolSize}) and
  * maximumPoolSize (see {@link #getMaximumPoolSize}).
  *
- * When a new task is submitted in method {@link #execute}, and fewer
- * than corePoolSize threads are running, a new thread is created to
- * handle the request, even if other worker threads are idle.  If
- * there are more than corePoolSize but less than maximumPoolSize
- * threads running, a new thread will be created only if the queue is
- * full.  By setting corePoolSize and maximumPoolSize the same, you
- * create a fixed-size thread pool. By setting maximumPoolSize to an
- * essentially unbounded value such as {@code Integer.MAX_VALUE}, you
- * allow the pool to accommodate an arbitrary number of concurrent
- * tasks. Most typically, core and maximum pool sizes are set only
- * upon construction, but they may also be changed dynamically using
- * {@link #setCorePoolSize} and {@link #setMaximumPoolSize}. </dd>
+ * When a new task is submitted in method {@link #execute(Runnable)},
+ * and fewer than corePoolSize threads are running, a new thread is
+ * created to handle the request, even if other worker threads are
+ * idle.  If there are more than corePoolSize but less than
+ * maximumPoolSize threads running, a new thread will be created only
+ * if the queue is full.  By setting corePoolSize and maximumPoolSize
+ * the same, you create a fixed-size thread pool. By setting
+ * maximumPoolSize to an essentially unbounded value such as {@code
+ * Integer.MAX_VALUE}, you allow the pool to accommodate an arbitrary
+ * number of concurrent tasks. Most typically, core and maximum pool
+ * sizes are set only upon construction, but they may also be changed
+ * dynamically using {@link #setCorePoolSize} and {@link
+ * #setMaximumPoolSize}. </dd>
  *
  * <dt>On-demand construction</dt>
  *
- * <dd> By default, even core threads are initially created and
+ * <dd>By default, even core threads are initially created and
  * started only when new tasks arrive, but this can be overridden
  * dynamically using method {@link #prestartCoreThread} or {@link
  * #prestartAllCoreThreads}.  You probably want to prestart threads if
@@ -117,17 +118,17 @@
  *
  * <dd>If the pool currently has more than corePoolSize threads,
  * excess threads will be terminated if they have been idle for more
- * than the keepAliveTime (see {@link #getKeepAliveTime}). This
- * provides a means of reducing resource consumption when the pool is
- * not being actively used. If the pool becomes more active later, new
- * threads will be constructed. This parameter can also be changed
- * dynamically using method {@link #setKeepAliveTime}. Using a value
- * of {@code Long.MAX_VALUE} {@link TimeUnit#NANOSECONDS} effectively
- * disables idle threads from ever terminating prior to shut down. By
- * default, the keep-alive policy applies only when there are more
- * than corePoolSizeThreads. But method {@link
- * #allowCoreThreadTimeOut(boolean)} can be used to apply this
- * time-out policy to core threads as well, so long as the
+ * than the keepAliveTime (see {@link #getKeepAliveTime(TimeUnit)}).
+ * This provides a means of reducing resource consumption when the
+ * pool is not being actively used. If the pool becomes more active
+ * later, new threads will be constructed. This parameter can also be
+ * changed dynamically using method {@link #setKeepAliveTime(long,
+ * TimeUnit)}.  Using a value of {@code Long.MAX_VALUE} {@link
+ * TimeUnit#NANOSECONDS} effectively disables idle threads from ever
+ * terminating prior to shut down. By default, the keep-alive policy
+ * applies only when there are more than corePoolSize threads. But
+ * method {@link #allowCoreThreadTimeOut(boolean)} can be used to
+ * apply this time-out policy to core threads as well, so long as the
  * keepAliveTime value is non-zero. </dd>
  *
  * <dt>Queuing</dt>
@@ -197,14 +198,14 @@
  *
  * <dt>Rejected tasks</dt>
  *
- * <dd> New tasks submitted in method {@link #execute} will be
- * <em>rejected</em> when the Executor has been shut down, and also
- * when the Executor uses finite bounds for both maximum threads and
- * work queue capacity, and is saturated.  In either case, the {@code
- * execute} method invokes the {@link
- * RejectedExecutionHandler#rejectedExecution} method of its {@link
- * RejectedExecutionHandler}.  Four predefined handler policies are
- * provided:
+ * <dd>New tasks submitted in method {@link #execute(Runnable)} will be
+ * <em>rejected</em> when the Executor has been shut down, and also when
+ * the Executor uses finite bounds for both maximum threads and work queue
+ * capacity, and is saturated.  In either case, the {@code execute} method
+ * invokes the {@link
+ * RejectedExecutionHandler#rejectedExecution(Runnable, ThreadPoolExecutor)}
+ * method of its {@link RejectedExecutionHandler}.  Four predefined handler
+ * policies are provided:
  *
  * <ol>
  *
@@ -234,30 +235,31 @@
  *
  * <dt>Hook methods</dt>
  *
- * <dd>This class provides {@code protected} overridable {@link
- * #beforeExecute} and {@link #afterExecute} methods that are called
+ * <dd>This class provides {@code protected} overridable
+ * {@link #beforeExecute(Thread, Runnable)} and
+ * {@link #afterExecute(Runnable, Throwable)} methods that are called
  * before and after execution of each task.  These can be used to
  * manipulate the execution environment; for example, reinitializing
- * ThreadLocals, gathering statistics, or adding log
- * entries. Additionally, method {@link #terminated} can be overridden
- * to perform any special processing that needs to be done once the
- * Executor has fully terminated.
+ * ThreadLocals, gathering statistics, or adding log entries.
+ * Additionally, method {@link #terminated} can be overridden to perform
+ * any special processing that needs to be done once the Executor has
+ * fully terminated.
  *
  * <p>If hook or callback methods throw exceptions, internal worker
  * threads may in turn fail and abruptly terminate.</dd>
  *
  * <dt>Queue maintenance</dt>
  *
- * <dd> Method {@link #getQueue} allows access to the work queue for
- * purposes of monitoring and debugging.  Use of this method for any
- * other purpose is strongly discouraged.  Two supplied methods,
- * {@link #remove} and {@link #purge} are available to assist in
- * storage reclamation when large numbers of queued tasks become
- * cancelled.</dd>
+ * <dd>Method {@link #getQueue()} allows access to the work queue
+ * for purposes of monitoring and debugging.  Use of this method for
+ * any other purpose is strongly discouraged.  Two supplied methods,
+ * {@link #remove(Runnable)} and {@link #purge} are available to
+ * assist in storage reclamation when large numbers of queued tasks
+ * become cancelled.</dd>
  *
  * <dt>Finalization</dt>
  *
- * <dd> A pool that is no longer referenced in a program <em>AND</em>
+ * <dd>A pool that is no longer referenced in a program <em>AND</em>
  * has no remaining threads will be {@code shutdown} automatically. If
  * you would like to ensure that unreferenced pools are reclaimed even
  * if users forget to call {@link #shutdown}, then you must arrange
@@ -267,7 +269,7 @@
  *
  * </dl>
  *
- * <p> <b>Extension example</b>. Most extensions of this class
+ * <p><b>Extension example</b>. Most extensions of this class
  * override one or more of the protected hook methods. For example,
  * here is a subclass that adds a simple pause/resume feature:
  *
@@ -336,7 +338,7 @@
      * bookkeeping before terminating. The user-visible pool size is
      * reported as the current size of the workers set.
      *
-     * The runState provides the main lifecyle control, taking on values:
+     * The runState provides the main lifecycle control, taking on values:
      *
      *   RUNNING:  Accept new tasks and process queued tasks
      *   SHUTDOWN: Don't accept new tasks, but process queued tasks
@@ -406,14 +408,14 @@
     }
 
     /**
-     * Attempt to CAS-increment the workerCount field of ctl.
+     * Attempts to CAS-increment the workerCount field of ctl.
      */
     private boolean compareAndIncrementWorkerCount(int expect) {
         return ctl.compareAndSet(expect, expect + 1);
     }
 
     /**
-     * Attempt to CAS-decrement the workerCount field of ctl.
+     * Attempts to CAS-decrement the workerCount field of ctl.
      */
     private boolean compareAndDecrementWorkerCount(int expect) {
         return ctl.compareAndSet(expect, expect - 1);
@@ -498,7 +500,7 @@
      * We go further and preserve pool invariants even in the face of
      * errors such as OutOfMemoryError, that might be thrown while
      * trying to create threads.  Such errors are rather common due to
-     * the need to allocate a native stack in Thread#start, and users
+     * the need to allocate a native stack in Thread.start, and users
      * will want to perform clean pool shutdown to clean up.  There
      * will likely be enough memory available for the cleanup code to
      * complete without encountering yet another OutOfMemoryError.
@@ -848,7 +850,7 @@
      */
     private List<Runnable> drainQueue() {
         BlockingQueue<Runnable> q = workQueue;
-        List<Runnable> taskList = new ArrayList<Runnable>();
+        ArrayList<Runnable> taskList = new ArrayList<Runnable>();
         q.drainTo(taskList);
         if (!q.isEmpty()) {
             for (Runnable r : q.toArray(new Runnable[0])) {
@@ -873,7 +875,7 @@
      * factory fails to create a thread when asked.  If the thread
      * creation fails, either due to the thread factory returning
      * null, or due to an exception (typically OutOfMemoryError in
-     * Thread#start), we roll back cleanly.
+     * Thread.start()), we roll back cleanly.
      *
      * @param firstTask the task the new thread should run first (or
      * null if none). Workers are created with an initial first task
@@ -920,17 +922,16 @@
         boolean workerAdded = false;
         Worker w = null;
         try {
-            final ReentrantLock mainLock = this.mainLock;
             w = new Worker(firstTask);
             final Thread t = w.thread;
             if (t != null) {
+                final ReentrantLock mainLock = this.mainLock;
                 mainLock.lock();
                 try {
                     // Recheck while holding lock.
                     // Back out on ThreadFactory failure or if
                     // shut down before lock acquired.
-                    int c = ctl.get();
-                    int rs = runStateOf(c);
+                    int rs = runStateOf(ctl.get());
 
                     if (rs < SHUTDOWN ||
                         (rs == SHUTDOWN && firstTask == null)) {
@@ -1029,7 +1030,8 @@
      * 4. This worker timed out waiting for a task, and timed-out
      *    workers are subject to termination (that is,
      *    {@code allowCoreThreadTimeOut || workerCount > corePoolSize})
-     *    both before and after the timed wait.
+     *    both before and after the timed wait, and if the queue is
+     *    non-empty, this worker is not the last thread in the pool.
      *
      * @return task, or null if the worker must exit, in which case
      *         workerCount is decremented
@@ -1037,7 +1039,6 @@
     private Runnable getTask() {
         boolean timedOut = false; // Did the last poll() time out?
 
-        retry:
         for (;;) {
             int c = ctl.get();
             int rs = runStateOf(c);
@@ -1048,20 +1049,16 @@
                 return null;
             }
 
-            boolean timed;      // Are workers subject to culling?
+            int wc = workerCountOf(c);
 
-            for (;;) {
-                int wc = workerCountOf(c);
-                timed = allowCoreThreadTimeOut || wc > corePoolSize;
+            // Are workers subject to culling?
+            boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
 
-                if (wc <= maximumPoolSize && ! (timedOut && timed))
-                    break;
+            if ((wc > maximumPoolSize || (timed && timedOut))
+                && (wc > 1 || workQueue.isEmpty())) {
                 if (compareAndDecrementWorkerCount(c))
                     return null;
-                c = ctl.get();  // Re-read ctl
-                if (runStateOf(c) != rs)
-                    continue retry;
-                // else CAS failed due to workerCount change; retry inner loop
+                continue;
             }
 
             try {
@@ -1090,9 +1087,9 @@
      * usually leads processWorkerExit to replace this thread.
      *
      * 2. Before running any task, the lock is acquired to prevent
-     * other pool interrupts while the task is executing, and
-     * clearInterruptsForTaskRun called to ensure that unless pool is
-     * stopping, this thread does not have its interrupt set.
+     * other pool interrupts while the task is executing, and then we
+     * ensure that unless pool is stopping, this thread does not have
+     * its interrupt set.
      *
      * 3. Each task run is preceded by a call to beforeExecute, which
      * might throw an exception, in which case we cause thread to die
@@ -1100,12 +1097,12 @@
      * the task.
      *
      * 4. Assuming beforeExecute completes normally, we run the task,
-     * gathering any of its thrown exceptions to send to
-     * afterExecute. We separately handle RuntimeException, Error
-     * (both of which the specs guarantee that we trap) and arbitrary
-     * Throwables.  Because we cannot rethrow Throwables within
-     * Runnable.run, we wrap them within Errors on the way out (to the
-     * thread's UncaughtExceptionHandler).  Any thrown exception also
+     * gathering any of its thrown exceptions to send to afterExecute.
+     * We separately handle RuntimeException, Error (both of which the
+     * specs guarantee that we trap) and arbitrary Throwables.
+     * Because we cannot rethrow Throwables within Runnable.run, we
+     * wrap them within Errors on the way out (to the thread's
+     * UncaughtExceptionHandler).  Any thrown exception also
      * conservatively causes thread to die.
      *
      * 5. After task.run completes, we call afterExecute, which may
@@ -1443,7 +1440,7 @@
      * ignored or suppressed interruption, causing this executor not
      * to properly terminate.
      *
-     * @return true if terminating but not yet terminated
+     * @return {@code true} if terminating but not yet terminated
      */
     public boolean isTerminating() {
         int c = ctl.get();
@@ -1497,7 +1494,7 @@
      * Returns the thread factory used to create new threads.
      *
      * @return the current thread factory
-     * @see #setThreadFactory
+     * @see #setThreadFactory(ThreadFactory)
      */
     public ThreadFactory getThreadFactory() {
         return threadFactory;
@@ -1520,7 +1517,7 @@
      * Returns the current handler for unexecutable tasks.
      *
      * @return the current handler
-     * @see #setRejectedExecutionHandler
+     * @see #setRejectedExecutionHandler(RejectedExecutionHandler)
      */
     public RejectedExecutionHandler getRejectedExecutionHandler() {
         return handler;
@@ -1692,7 +1689,7 @@
      * @param unit the time unit of the {@code time} argument
      * @throws IllegalArgumentException if {@code time} less than zero or
      *         if {@code time} is zero and {@code allowsCoreThreadTimeOut}
-     * @see #getKeepAliveTime
+     * @see #getKeepAliveTime(TimeUnit)
      */
     public void setKeepAliveTime(long time, TimeUnit unit) {
         if (time < 0)
@@ -1713,7 +1710,7 @@
      *
      * @param unit the desired time unit of the result
      * @return the time limit
-     * @see #setKeepAliveTime
+     * @see #setKeepAliveTime(long, TimeUnit)
      */
     public long getKeepAliveTime(TimeUnit unit) {
         return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
@@ -1738,7 +1735,7 @@
      * present, thus causing it not to be run if it has not already
      * started.
      *
-     * <p> This method may be useful as one part of a cancellation
+     * <p>This method may be useful as one part of a cancellation
      * scheme.  It may fail to remove tasks that have been converted
      * into other forms before being placed on the internal queue. For
      * example, a task entered using {@code submit} might be
@@ -1747,7 +1744,7 @@
      * remove those Futures that have been cancelled.
      *
      * @param task the task to remove
-     * @return true if the task was removed
+     * @return {@code true} if the task was removed
      */
     public boolean remove(Runnable task) {
         boolean removed = workQueue.remove(task);
@@ -2042,7 +2039,7 @@
          *
          * @param r the runnable task requested to be executed
          * @param e the executor attempting to execute this task
-         * @throws RejectedExecutionException always.
+         * @throws RejectedExecutionException always
          */
         public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
             throw new RejectedExecutionException("Task " + r.toString() +
@@ -2099,4 +2096,3 @@
         }
     }
 }
-
--- a/src/share/classes/java/util/concurrent/TimeUnit.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/TimeUnit.java	Mon Jul 22 17:37:15 2013 -0700
@@ -36,10 +36,10 @@
 package java.util.concurrent;
 
 /**
- * A <tt>TimeUnit</tt> represents time durations at a given unit of
+ * A {@code TimeUnit} represents time durations at a given unit of
  * granularity and provides utility methods to convert across units,
  * and to perform timing and delay operations in these units.  A
- * <tt>TimeUnit</tt> does not maintain time information, but only
+ * {@code TimeUnit} does not maintain time information, but only
  * helps organize and use time representations that may be maintained
  * separately across various contexts.  A nanosecond is defined as one
  * thousandth of a microsecond, a microsecond as one thousandth of a
@@ -47,7 +47,7 @@
  * as sixty seconds, an hour as sixty minutes, and a day as twenty four
  * hours.
  *
- * <p>A <tt>TimeUnit</tt> is mainly used to inform time-based methods
+ * <p>A {@code TimeUnit} is mainly used to inform time-based methods
  * how a given timing parameter should be interpreted. For example,
  * the following code will timeout in 50 milliseconds if the {@link
  * java.util.concurrent.locks.Lock lock} is not available:
@@ -63,7 +63,7 @@
  *
  * Note however, that there is no guarantee that a particular timeout
  * implementation will be able to notice the passage of time at the
- * same granularity as the given <tt>TimeUnit</tt>.
+ * same granularity as the given {@code TimeUnit}.
  *
  * @since 1.5
  * @author Doug Lea
@@ -174,83 +174,82 @@
     // etc. are not declared abstract but otherwise act as abstract methods.
 
     /**
-     * Convert the given time duration in the given unit to this
-     * unit.  Conversions from finer to coarser granularities
-     * truncate, so lose precision. For example converting
-     * <tt>999</tt> milliseconds to seconds results in
-     * <tt>0</tt>. Conversions from coarser to finer granularities
-     * with arguments that would numerically overflow saturate to
-     * <tt>Long.MIN_VALUE</tt> if negative or <tt>Long.MAX_VALUE</tt>
-     * if positive.
+     * Converts the given time duration in the given unit to this unit.
+     * Conversions from finer to coarser granularities truncate, so
+     * lose precision. For example, converting {@code 999} milliseconds
+     * to seconds results in {@code 0}. Conversions from coarser to
+     * finer granularities with arguments that would numerically
+     * overflow saturate to {@code Long.MIN_VALUE} if negative or
+     * {@code Long.MAX_VALUE} if positive.
      *
      * <p>For example, to convert 10 minutes to milliseconds, use:
-     * <tt>TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES)</tt>
+     * {@code TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES)}
      *
-     * @param sourceDuration the time duration in the given <tt>sourceUnit</tt>
-     * @param sourceUnit the unit of the <tt>sourceDuration</tt> argument
+     * @param sourceDuration the time duration in the given {@code sourceUnit}
+     * @param sourceUnit the unit of the {@code sourceDuration} argument
      * @return the converted duration in this unit,
-     * or <tt>Long.MIN_VALUE</tt> if conversion would negatively
-     * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
+     * or {@code Long.MIN_VALUE} if conversion would negatively
+     * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
      */
     public long convert(long sourceDuration, TimeUnit sourceUnit) {
         throw new AbstractMethodError();
     }
 
     /**
-     * Equivalent to <tt>NANOSECONDS.convert(duration, this)</tt>.
+     * Equivalent to
+     * {@link #convert(long, TimeUnit) NANOSECONDS.convert(duration, this)}.
      * @param duration the duration
      * @return the converted duration,
-     * or <tt>Long.MIN_VALUE</tt> if conversion would negatively
-     * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
-     * @see #convert
+     * or {@code Long.MIN_VALUE} if conversion would negatively
+     * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
      */
     public long toNanos(long duration) {
         throw new AbstractMethodError();
     }
 
     /**
-     * Equivalent to <tt>MICROSECONDS.convert(duration, this)</tt>.
+     * Equivalent to
+     * {@link #convert(long, TimeUnit) MICROSECONDS.convert(duration, this)}.
      * @param duration the duration
      * @return the converted duration,
-     * or <tt>Long.MIN_VALUE</tt> if conversion would negatively
-     * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
-     * @see #convert
+     * or {@code Long.MIN_VALUE} if conversion would negatively
+     * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
      */
     public long toMicros(long duration) {
         throw new AbstractMethodError();
     }
 
     /**
-     * Equivalent to <tt>MILLISECONDS.convert(duration, this)</tt>.
+     * Equivalent to
+     * {@link #convert(long, TimeUnit) MILLISECONDS.convert(duration, this)}.
      * @param duration the duration
      * @return the converted duration,
-     * or <tt>Long.MIN_VALUE</tt> if conversion would negatively
-     * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
-     * @see #convert
+     * or {@code Long.MIN_VALUE} if conversion would negatively
+     * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
      */
     public long toMillis(long duration) {
         throw new AbstractMethodError();
     }
 
     /**
-     * Equivalent to <tt>SECONDS.convert(duration, this)</tt>.
+     * Equivalent to
+     * {@link #convert(long, TimeUnit) SECONDS.convert(duration, this)}.
      * @param duration the duration
      * @return the converted duration,
-     * or <tt>Long.MIN_VALUE</tt> if conversion would negatively
-     * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
-     * @see #convert
+     * or {@code Long.MIN_VALUE} if conversion would negatively
+     * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
      */
     public long toSeconds(long duration) {
         throw new AbstractMethodError();
     }
 
     /**
-     * Equivalent to <tt>MINUTES.convert(duration, this)</tt>.
+     * Equivalent to
+     * {@link #convert(long, TimeUnit) MINUTES.convert(duration, this)}.
      * @param duration the duration
      * @return the converted duration,
-     * or <tt>Long.MIN_VALUE</tt> if conversion would negatively
-     * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
-     * @see #convert
+     * or {@code Long.MIN_VALUE} if conversion would negatively
+     * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
      * @since 1.6
      */
     public long toMinutes(long duration) {
@@ -258,12 +257,12 @@
     }
 
     /**
-     * Equivalent to <tt>HOURS.convert(duration, this)</tt>.
+     * Equivalent to
+     * {@link #convert(long, TimeUnit) HOURS.convert(duration, this)}.
      * @param duration the duration
      * @return the converted duration,
-     * or <tt>Long.MIN_VALUE</tt> if conversion would negatively
-     * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
-     * @see #convert
+     * or {@code Long.MIN_VALUE} if conversion would negatively
+     * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
      * @since 1.6
      */
     public long toHours(long duration) {
@@ -271,10 +270,10 @@
     }
 
     /**
-     * Equivalent to <tt>DAYS.convert(duration, this)</tt>.
+     * Equivalent to
+     * {@link #convert(long, TimeUnit) DAYS.convert(duration, this)}.
      * @param duration the duration
      * @return the converted duration
-     * @see #convert
      * @since 1.6
      */
     public long toDays(long duration) {
@@ -294,9 +293,9 @@
      * Performs a timed {@link Object#wait(long, int) Object.wait}
      * using this time unit.
      * This is a convenience method that converts timeout arguments
-     * into the form required by the <tt>Object.wait</tt> method.
+     * into the form required by the {@code Object.wait} method.
      *
-     * <p>For example, you could implement a blocking <tt>poll</tt>
+     * <p>For example, you could implement a blocking {@code poll}
      * method (see {@link BlockingQueue#poll BlockingQueue.poll})
      * using:
      *
@@ -327,7 +326,7 @@
      * Performs a timed {@link Thread#join(long, int) Thread.join}
      * using this time unit.
      * This is a convenience method that converts time arguments into the
-     * form required by the <tt>Thread.join</tt> method.
+     * form required by the {@code Thread.join} method.
      *
      * @param thread the thread to wait for
      * @param timeout the maximum time to wait. If less than
@@ -347,7 +346,7 @@
      * Performs a {@link Thread#sleep(long, int) Thread.sleep} using
      * this time unit.
      * This is a convenience method that converts time arguments into the
-     * form required by the <tt>Thread.sleep</tt> method.
+     * form required by the {@code Thread.sleep} method.
      *
      * @param timeout the minimum time to sleep. If less than
      * or equal to zero, do not sleep at all.
--- a/src/share/classes/java/util/concurrent/TimeoutException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/TimeoutException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -40,7 +40,7 @@
  * operations for which a timeout is specified need a means to
  * indicate that the timeout has occurred. For many such operations it
  * is possible to return a value that indicates timeout; when that is
- * not possible or desirable then <tt>TimeoutException</tt> should be
+ * not possible or desirable then {@code TimeoutException} should be
  * declared and thrown.
  *
  * @since 1.5
@@ -50,13 +50,13 @@
     private static final long serialVersionUID = 1900926677490660714L;
 
     /**
-     * Constructs a <tt>TimeoutException</tt> with no specified detail
+     * Constructs a {@code TimeoutException} with no specified detail
      * message.
      */
     public TimeoutException() {}
 
     /**
-     * Constructs a <tt>TimeoutException</tt> with the specified detail
+     * Constructs a {@code TimeoutException} with the specified detail
      * message.
      *
      * @param message the detail message
--- a/src/share/classes/java/util/concurrent/package-info.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/concurrent/package-info.java	Mon Jul 22 17:37:15 2013 -0700
@@ -48,7 +48,7 @@
  *
  * {@link java.util.concurrent.Executor} is a simple standardized
  * interface for defining custom thread-like subsystems, including
- * thread pools, asynchronous IO, and lightweight task frameworks.
+ * thread pools, asynchronous I/O, and lightweight task frameworks.
  * Depending on which concrete Executor class is being used, tasks may
  * execute in a newly created thread, an existing task-execution thread,
  * or the thread calling {@link java.util.concurrent.Executor#execute
@@ -102,8 +102,10 @@
  * <h2>Queues</h2>
  *
  * The {@link java.util.concurrent.ConcurrentLinkedQueue} class
- * supplies an efficient scalable thread-safe non-blocking FIFO
- * queue.
+ * supplies an efficient scalable thread-safe non-blocking FIFO queue.
+ * The {@link java.util.concurrent.ConcurrentLinkedDeque} class is
+ * similar, but additionally supports the {@link java.util.Deque}
+ * interface.
  *
  * <p>Five implementations in {@code java.util.concurrent} support
  * the extended {@link java.util.concurrent.BlockingQueue}
@@ -117,7 +119,7 @@
  * for producer-consumer, messaging, parallel tasking, and
  * related concurrent designs.
  *
- * <p> Extended interface {@link java.util.concurrent.TransferQueue},
+ * <p>Extended interface {@link java.util.concurrent.TransferQueue},
  * and implementation {@link java.util.concurrent.LinkedTransferQueue}
  * introduce a synchronous {@code transfer} method (along with related
  * features) in which a producer may optionally block awaiting its
@@ -216,9 +218,9 @@
  * it may (or may not) reflect any updates since the iterator was
  * created.
  *
- * <h2><a name="MemoryVisibility">Memory Consistency Properties</a></h2>
+ * <h2 id="MemoryVisibility">Memory Consistency Properties</h2>
  *
- * <a href="http://docs.oracle.com/javase/specs/jls/se7/html/index.html">
+ * <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.5">
  * Chapter 17 of the Java Language Specification</a> defines the
  * <i>happens-before</i> relation on memory operations such as reads and
  * writes of shared variables.  The results of a write by one thread are
--- a/src/share/classes/java/util/jar/JarFile.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/jar/JarFile.java	Mon Jul 22 17:37:15 2013 -0700
@@ -272,7 +272,7 @@
         return StreamSupport.stream(Spliterators.spliterator(
                 new JarEntryIterator(), size(),
                 Spliterator.ORDERED | Spliterator.DISTINCT |
-                        Spliterator.IMMUTABLE | Spliterator.NONNULL));
+                        Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
     }
 
     private class JarFileEntry extends JarEntry {
--- a/src/share/classes/java/util/regex/MatchResult.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/regex/MatchResult.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -77,7 +77,7 @@
     public int start(int group);
 
     /**
-     * Returns the offset after the last character matched.  </p>
+     * Returns the offset after the last character matched.
      *
      * @return  The offset after the last character matched
      *
--- a/src/share/classes/java/util/regex/Matcher.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/regex/Matcher.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,8 +28,8 @@
 import java.util.Objects;
 
 /**
- * An engine that performs match operations on a {@link java.lang.CharSequence
- * </code>character sequence<code>} by interpreting a {@link Pattern}.
+ * An engine that performs match operations on a {@linkplain java.lang.CharSequence
+ * character sequence} by interpreting a {@link Pattern}.
  *
  * <p> A matcher is created from a pattern by invoking the pattern's {@link
  * Pattern#matcher matcher} method.  Once created, a matcher can be used to
@@ -330,7 +330,7 @@
     }
 
     /**
-     * Returns the start index of the previous match.  </p>
+     * Returns the start index of the previous match.
      *
      * @return  The index of the first character matched
      *
@@ -402,7 +402,7 @@
     }
 
     /**
-     * Returns the offset after the last character matched.  </p>
+     * Returns the offset after the last character matched.
      *
      * @return  The offset after the last character matched
      *
@@ -647,6 +647,7 @@
      * invocations of the {@link #find()} method will start at the first
      * character not matched by this match.  </p>
      *
+     * @param start the index to start searching for a match
      * @throws  IndexOutOfBoundsException
      *          If start is less than zero or if start is greater than the
      *          length of the input sequence.
@@ -736,8 +737,8 @@
      * captured during the previous match: Each occurrence of
      * <tt>${</tt><i>name</i><tt>}</tt> or <tt>$</tt><i>g</i>
      * will be replaced by the result of evaluating the corresponding
-     * {@link #group(String) group(name)} or {@link #group(int) group(g)</tt>}
-     * respectively. For  <tt>$</tt><i>g</i><tt></tt>,
+     * {@link #group(String) group(name)} or {@link #group(int) group(g)}
+     * respectively. For  <tt>$</tt><i>g</i>,
      * the first number after the <tt>$</tt> is always treated as part of
      * the group reference. Subsequent numbers are incorporated into g if
      * they would form a legal group reference. Only the numerals '0'
--- a/src/share/classes/java/util/regex/Pattern.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/regex/Pattern.java	Mon Jul 22 17:37:15 2013 -0700
@@ -45,8 +45,8 @@
  *
  * <p> A regular expression, specified as a string, must first be compiled into
  * an instance of this class.  The resulting pattern can then be used to create
- * a {@link Matcher} object that can match arbitrary {@link
- * java.lang.CharSequence </code>character sequences<code>} against the regular
+ * a {@link Matcher} object that can match arbitrary {@linkplain
+ * java.lang.CharSequence character sequences} against the regular
  * expression.  All of the state involved in performing a match resides in the
  * matcher, so many matchers can share the same pattern.
  *
@@ -73,15 +73,14 @@
  * such use.
  *
  *
- * <a name="sum">
- * <h4> Summary of regular-expression constructs </h4>
+ * <h3><a name="sum">Summary of regular-expression constructs</a></h3>
  *
  * <table border="0" cellpadding="1" cellspacing="0"
  *  summary="Regular expression constructs, and what they match">
  *
  * <tr align="left">
- * <th bgcolor="#CCCCFF" align="left" id="construct">Construct</th>
- * <th bgcolor="#CCCCFF" align="left" id="matches">Matches</th>
+ * <th align="left" id="construct">Construct</th>
+ * <th align="left" id="matches">Matches</th>
  * </tr>
  *
  * <tr><th>&nbsp;</th></tr>
@@ -128,24 +127,24 @@
  * <tr><th>&nbsp;</th></tr>
  * <tr align="left"><th colspan="2" id="classes">Character classes</th></tr>
  *
- * <tr><td valign="top" headers="construct classes"><tt>[abc]</tt></td>
- *     <td headers="matches"><tt>a</tt>, <tt>b</tt>, or <tt>c</tt> (simple class)</td></tr>
- * <tr><td valign="top" headers="construct classes"><tt>[^abc]</tt></td>
- *     <td headers="matches">Any character except <tt>a</tt>, <tt>b</tt>, or <tt>c</tt> (negation)</td></tr>
- * <tr><td valign="top" headers="construct classes"><tt>[a-zA-Z]</tt></td>
- *     <td headers="matches"><tt>a</tt> through <tt>z</tt>
- *         or <tt>A</tt> through <tt>Z</tt>, inclusive (range)</td></tr>
- * <tr><td valign="top" headers="construct classes"><tt>[a-d[m-p]]</tt></td>
- *     <td headers="matches"><tt>a</tt> through <tt>d</tt>,
- *      or <tt>m</tt> through <tt>p</tt>: <tt>[a-dm-p]</tt> (union)</td></tr>
- * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[def]]</tt></td>
- *     <td headers="matches"><tt>d</tt>, <tt>e</tt>, or <tt>f</tt> (intersection)</tr>
- * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[^bc]]</tt></td>
- *     <td headers="matches"><tt>a</tt> through <tt>z</tt>,
- *         except for <tt>b</tt> and <tt>c</tt>: <tt>[ad-z]</tt> (subtraction)</td></tr>
- * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[^m-p]]</tt></td>
- *     <td headers="matches"><tt>a</tt> through <tt>z</tt>,
- *          and not <tt>m</tt> through <tt>p</tt>: <tt>[a-lq-z]</tt>(subtraction)</td></tr>
+ * <tr><td valign="top" headers="construct classes">{@code [abc]}</td>
+ *     <td headers="matches">{@code a}, {@code b}, or {@code c} (simple class)</td></tr>
+ * <tr><td valign="top" headers="construct classes">{@code [^abc]}</td>
+ *     <td headers="matches">Any character except {@code a}, {@code b}, or {@code c} (negation)</td></tr>
+ * <tr><td valign="top" headers="construct classes">{@code [a-zA-Z]}</td>
+ *     <td headers="matches">{@code a} through {@code z}
+ *         or {@code A} through {@code Z}, inclusive (range)</td></tr>
+ * <tr><td valign="top" headers="construct classes">{@code [a-d[m-p]]}</td>
+ *     <td headers="matches">{@code a} through {@code d},
+ *      or {@code m} through {@code p}: {@code [a-dm-p]} (union)</td></tr>
+ * <tr><td valign="top" headers="construct classes">{@code [a-z&&[def]]}</td>
+ *     <td headers="matches">{@code d}, {@code e}, or {@code f} (intersection)</tr>
+ * <tr><td valign="top" headers="construct classes">{@code [a-z&&[^bc]]}</td>
+ *     <td headers="matches">{@code a} through {@code z},
+ *         except for {@code b} and {@code c}: {@code [ad-z]} (subtraction)</td></tr>
+ * <tr><td valign="top" headers="construct classes">{@code [a-z&&[^m-p]]}</td>
+ *     <td headers="matches">{@code a} through {@code z},
+ *          and not {@code m} through {@code p}: {@code [a-lq-z]}(subtraction)</td></tr>
  * <tr><th>&nbsp;</th></tr>
  *
  * <tr align="left"><th colspan="2" id="predef">Predefined character classes</th></tr>
@@ -175,36 +174,36 @@
  * <tr><td valign="top" headers="construct predef"><tt>\W</tt></td>
  *     <td headers="matches">A non-word character: <tt>[^\w]</tt></td></tr>
  * <tr><th>&nbsp;</th></tr>
- * <tr align="left"><th colspan="2" id="posix">POSIX character classes</b> (US-ASCII only)<b></th></tr>
+ * <tr align="left"><th colspan="2" id="posix"><b>POSIX character classes (US-ASCII only)</b></th></tr>
  *
- * <tr><td valign="top" headers="construct posix"><tt>\p{Lower}</tt></td>
- *     <td headers="matches">A lower-case alphabetic character: <tt>[a-z]</tt></td></tr>
- * <tr><td valign="top" headers="construct posix"><tt>\p{Upper}</tt></td>
- *     <td headers="matches">An upper-case alphabetic character:<tt>[A-Z]</tt></td></tr>
- * <tr><td valign="top" headers="construct posix"><tt>\p{ASCII}</tt></td>
- *     <td headers="matches">All ASCII:<tt>[\x00-\x7F]</tt></td></tr>
- * <tr><td valign="top" headers="construct posix"><tt>\p{Alpha}</tt></td>
- *     <td headers="matches">An alphabetic character:<tt>[\p{Lower}\p{Upper}]</tt></td></tr>
- * <tr><td valign="top" headers="construct posix"><tt>\p{Digit}</tt></td>
- *     <td headers="matches">A decimal digit: <tt>[0-9]</tt></td></tr>
- * <tr><td valign="top" headers="construct posix"><tt>\p{Alnum}</tt></td>
- *     <td headers="matches">An alphanumeric character:<tt>[\p{Alpha}\p{Digit}]</tt></td></tr>
- * <tr><td valign="top" headers="construct posix"><tt>\p{Punct}</tt></td>
- *     <td headers="matches">Punctuation: One of <tt>!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~</tt></td></tr>
- *     <!-- <tt>[\!"#\$%&'\(\)\*\+,\-\./:;\<=\>\?@\[\\\]\^_`\{\|\}~]</tt>
- *          <tt>[\X21-\X2F\X31-\X40\X5B-\X60\X7B-\X7E]</tt> -->
- * <tr><td valign="top" headers="construct posix"><tt>\p{Graph}</tt></td>
- *     <td headers="matches">A visible character: <tt>[\p{Alnum}\p{Punct}]</tt></td></tr>
- * <tr><td valign="top" headers="construct posix"><tt>\p{Print}</tt></td>
- *     <td headers="matches">A printable character: <tt>[\p{Graph}\x20]</tt></td></tr>
- * <tr><td valign="top" headers="construct posix"><tt>\p{Blank}</tt></td>
- *     <td headers="matches">A space or a tab: <tt>[ \t]</tt></td></tr>
- * <tr><td valign="top" headers="construct posix"><tt>\p{Cntrl}</tt></td>
- *     <td headers="matches">A control character: <tt>[\x00-\x1F\x7F]</tt></td></tr>
- * <tr><td valign="top" headers="construct posix"><tt>\p{XDigit}</tt></td>
- *     <td headers="matches">A hexadecimal digit: <tt>[0-9a-fA-F]</tt></td></tr>
- * <tr><td valign="top" headers="construct posix"><tt>\p{Space}</tt></td>
- *     <td headers="matches">A whitespace character: <tt>[ \t\n\x0B\f\r]</tt></td></tr>
+ * <tr><td valign="top" headers="construct posix">{@code \p{Lower}}</td>
+ *     <td headers="matches">A lower-case alphabetic character: {@code [a-z]}</td></tr>
+ * <tr><td valign="top" headers="construct posix">{@code \p{Upper}}</td>
+ *     <td headers="matches">An upper-case alphabetic character:{@code [A-Z]}</td></tr>
+ * <tr><td valign="top" headers="construct posix">{@code \p{ASCII}}</td>
+ *     <td headers="matches">All ASCII:{@code [\x00-\x7F]}</td></tr>
+ * <tr><td valign="top" headers="construct posix">{@code \p{Alpha}}</td>
+ *     <td headers="matches">An alphabetic character:{@code [\p{Lower}\p{Upper}]}</td></tr>
+ * <tr><td valign="top" headers="construct posix">{@code \p{Digit}}</td>
+ *     <td headers="matches">A decimal digit: {@code [0-9]}</td></tr>
+ * <tr><td valign="top" headers="construct posix">{@code \p{Alnum}}</td>
+ *     <td headers="matches">An alphanumeric character:{@code [\p{Alpha}\p{Digit}]}</td></tr>
+ * <tr><td valign="top" headers="construct posix">{@code \p{Punct}}</td>
+ *     <td headers="matches">Punctuation: One of {@code !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~}</td></tr>
+ *     <!-- {@code [\!"#\$%&'\(\)\*\+,\-\./:;\<=\>\?@\[\\\]\^_`\{\|\}~]}
+ *          {@code [\X21-\X2F\X31-\X40\X5B-\X60\X7B-\X7E]} -->
+ * <tr><td valign="top" headers="construct posix">{@code \p{Graph}}</td>
+ *     <td headers="matches">A visible character: {@code [\p{Alnum}\p{Punct}]}</td></tr>
+ * <tr><td valign="top" headers="construct posix">{@code \p{Print}}</td>
+ *     <td headers="matches">A printable character: {@code [\p{Graph}\x20]}</td></tr>
+ * <tr><td valign="top" headers="construct posix">{@code \p{Blank}}</td>
+ *     <td headers="matches">A space or a tab: {@code [ \t]}</td></tr>
+ * <tr><td valign="top" headers="construct posix">{@code \p{Cntrl}}</td>
+ *     <td headers="matches">A control character: {@code [\x00-\x1F\x7F]}</td></tr>
+ * <tr><td valign="top" headers="construct posix">{@code \p{XDigit}}</td>
+ *     <td headers="matches">A hexadecimal digit: {@code [0-9a-fA-F]}</td></tr>
+ * <tr><td valign="top" headers="construct posix">{@code \p{Space}}</td>
+ *     <td headers="matches">A whitespace character: {@code [ \t\n\x0B\f\r]}</td></tr>
  *
  * <tr><th>&nbsp;</th></tr>
  * <tr align="left"><th colspan="2">java.lang.Character classes (simple <a href="#jcc">java character type</a>)</th></tr>
@@ -220,19 +219,19 @@
  *
  * <tr><th>&nbsp;</th></tr>
  * <tr align="left"><th colspan="2" id="unicode">Classes for Unicode scripts, blocks, categories and binary properties</th></tr>
- * * <tr><td valign="top" headers="construct unicode"><tt>\p{IsLatin}</tt></td>
+ * * <tr><td valign="top" headers="construct unicode">{@code \p{IsLatin}}</td>
  *     <td headers="matches">A Latin&nbsp;script character (<a href="#usc">script</a>)</td></tr>
- * <tr><td valign="top" headers="construct unicode"><tt>\p{InGreek}</tt></td>
+ * <tr><td valign="top" headers="construct unicode">{@code \p{InGreek}}</td>
  *     <td headers="matches">A character in the Greek&nbsp;block (<a href="#ubc">block</a>)</td></tr>
- * <tr><td valign="top" headers="construct unicode"><tt>\p{Lu}</tt></td>
+ * <tr><td valign="top" headers="construct unicode">{@code \p{Lu}}</td>
  *     <td headers="matches">An uppercase letter (<a href="#ucc">category</a>)</td></tr>
- * <tr><td valign="top" headers="construct unicode"><tt>\p{IsAlphabetic}</tt></td>
+ * <tr><td valign="top" headers="construct unicode">{@code \p{IsAlphabetic}}</td>
  *     <td headers="matches">An alphabetic character (<a href="#ubpc">binary property</a>)</td></tr>
- * <tr><td valign="top" headers="construct unicode"><tt>\p{Sc}</tt></td>
+ * <tr><td valign="top" headers="construct unicode">{@code \p{Sc}}</td>
  *     <td headers="matches">A currency symbol</td></tr>
- * <tr><td valign="top" headers="construct unicode"><tt>\P{InGreek}</tt></td>
+ * <tr><td valign="top" headers="construct unicode">{@code \P{InGreek}}</td>
  *     <td headers="matches">Any character except one in the Greek block (negation)</td></tr>
- * <tr><td valign="top" headers="construct unicode"><tt>[\p{L}&&[^\p{Lu}]]&nbsp;</tt></td>
+ * <tr><td valign="top" headers="construct unicode">{@code [\p{L}&&[^\p{Lu}]]}</td>
  *     <td headers="matches">Any letter except an uppercase letter (subtraction)</td></tr>
  *
  * <tr><th>&nbsp;</th></tr>
@@ -376,8 +375,7 @@
  * <hr>
  *
  *
- * <a name="bs">
- * <h4> Backslashes, escapes, and quoting </h4>
+ * <h3><a name="bs">Backslashes, escapes, and quoting</a></h3>
  *
  * <p> The backslash character (<tt>'\'</tt>) serves to introduce escaped
  * constructs, as defined in the table above, as well as to quote characters
@@ -405,8 +403,7 @@
  * <tt>(hello)</tt> the string literal <tt>"&#92;&#92;(hello&#92;&#92;)"</tt>
  * must be used.
  *
- * <a name="cc">
- * <h4> Character Classes </h4>
+ * <h3><a name="cc">Character Classes</a></h3>
  *
  *    <p> Character classes may appear within other character classes, and
  *    may be composed by the union operator (implicit) and the intersection
@@ -435,7 +432,7 @@
  *        <td><tt>[a-e][i-u]</tt></td></tr>
  *      <tr><th>5&nbsp;&nbsp;&nbsp;&nbsp;</th>
  *        <td>Intersection</td>
- *        <td><tt>[a-z&&[aeiou]]</tt></td></tr>
+ *        <td>{@code [a-z&&[aeiou]]}</td></tr>
  *    </table></blockquote>
  *
  *    <p> Note that a different set of metacharacters are in effect inside
@@ -444,8 +441,7 @@
  *    character class, while the expression <tt>-</tt> becomes a range
  *    forming metacharacter.
  *
- * <a name="lt">
- * <h4> Line terminators </h4>
+ * <h3><a name="lt">Line terminators</a></h3>
  *
  * <p> A <i>line terminator</i> is a one- or two-character sequence that marks
  * the end of a line of the input character sequence.  The following are
@@ -480,11 +476,9 @@
  * except at the end of input. When in {@link #MULTILINE} mode <tt>$</tt>
  * matches just before a line terminator or the end of the input sequence.
  *
- * <a name="cg">
- * <h4> Groups and capturing </h4>
+ * <h3><a name="cg">Groups and capturing</a></h3>
  *
- * <a name="gnumber">
- * <h5> Group number </h5>
+ * <h4><a name="gnumber">Group number</a></h4>
  * <p> Capturing groups are numbered by counting their opening parentheses from
  * left to right.  In the expression <tt>((A)(B(C)))</tt>, for example, there
  * are four such groups: </p>
@@ -507,8 +501,7 @@
  * subsequence may be used later in the expression, via a back reference, and
  * may also be retrieved from the matcher once the match operation is complete.
  *
- * <a name="groupname">
- * <h5> Group name </h5>
+ * <h4><a name="groupname">Group name</a></h4>
  * <p>A capturing group can also be assigned a "name", a <tt>named-capturing group</tt>,
  * and then be back-referenced later by the "name". Group names are composed of
  * the following characters. The first character must be a <tt>letter</tt>.
@@ -537,7 +530,7 @@
  * that do not capture text and do not count towards the group total, or
  * <i>named-capturing</i> group.
  *
- * <h4> Unicode support </h4>
+ * <h3> Unicode support </h3>
  *
  * <p> This class is in conformance with Level 1 of <a
  * href="http://www.unicode.org/reports/tr18/"><i>Unicode Technical
@@ -568,18 +561,18 @@
  * <p>
  * Scripts, blocks, categories and binary properties can be used both inside
  * and outside of a character class.
- * <a name="usc">
+ *
  * <p>
- * <b>Scripts</b> are specified either with the prefix {@code Is}, as in
+ * <b><a name="usc">Scripts</a></b> are specified either with the prefix {@code Is}, as in
  * {@code IsHiragana}, or by using  the {@code script} keyword (or its short
  * form {@code sc})as in {@code script=Hiragana} or {@code sc=Hiragana}.
  * <p>
  * The script names supported by <code>Pattern</code> are the valid script names
  * accepted and defined by
  * {@link java.lang.Character.UnicodeScript#forName(String) UnicodeScript.forName}.
- * <a name="ubc">
+ *
  * <p>
- * <b>Blocks</b> are specified with the prefix {@code In}, as in
+ * <b><a name="ubc">Blocks</a></b> are specified with the prefix {@code In}, as in
  * {@code InMongolian}, or by using the keyword {@code block} (or its short
  * form {@code blk}) as in {@code block=Mongolian} or {@code blk=Mongolian}.
  * <p>
@@ -587,8 +580,8 @@
  * accepted and defined by
  * {@link java.lang.Character.UnicodeBlock#forName(String) UnicodeBlock.forName}.
  * <p>
- * <a name="ucc">
- * <b>Categories</b> may be specified with the optional prefix {@code Is}:
+ *
+ * <b><a name="ucc">Categories</a></b> may be specified with the optional prefix {@code Is}:
  * Both {@code \p{L}} and {@code \p{IsL}} denote the category of Unicode
  * letters. Same as scripts and blocks, categories can also be specified
  * by using the keyword {@code general_category} (or its short form
@@ -600,8 +593,8 @@
  * {@link java.lang.Character Character} class. The category names are those
  * defined in the Standard, both normative and informative.
  * <p>
- * <a name="ubpc">
- * <b>Binary properties</b> are specified with the prefix {@code Is}, as in
+ *
+ * <b><a name="ubpc">Binary properties</a></b> are specified with the prefix {@code Is}, as in
  * {@code IsAlphabetic}. The supported binary properties by <code>Pattern</code>
  * are
  * <ul>
@@ -629,8 +622,8 @@
  * <table border="0" cellpadding="1" cellspacing="0"
  *  summary="predefined and posix character classes in Unicode mode">
  * <tr align="left">
- * <th bgcolor="#CCCCFF" align="left" id="classes">Classes</th>
- * <th bgcolor="#CCCCFF" align="left" id="matches">Matches</th>
+ * <th align="left" id="predef_classes">Classes</th>
+ * <th align="left" id="predef_matches">Matches</th>
  *</tr>
  * <tr><td><tt>\p{Lower}</tt></td>
  *     <td>A lowercase character:<tt>\p{IsLowercase}</tt></td></tr>
@@ -649,9 +642,9 @@
  * <tr><td><tt>\p{Graph}</tt></td>
  *     <td>A visible character: <tt>[^\p{IsWhite_Space}\p{gc=Cc}\p{gc=Cs}\p{gc=Cn}]</tt></td></tr>
  * <tr><td><tt>\p{Print}</tt></td>
- *     <td>A printable character: <tt>[\p{Graph}\p{Blank}&&[^\p{Cntrl}]]</tt></td></tr>
+ *     <td>A printable character: {@code [\p{Graph}\p{Blank}&&[^\p{Cntrl}]]}</td></tr>
  * <tr><td><tt>\p{Blank}</tt></td>
- *     <td>A space or a tab: <tt>[\p{IsWhite_Space}&&[^\p{gc=Zl}\p{gc=Zp}\x0a\x0b\x0c\x0d\x85]]</tt></td></tr>
+ *     <td>A space or a tab: {@code [\p{IsWhite_Space}&&[^\p{gc=Zl}\p{gc=Zp}\x0a\x0b\x0c\x0d\x85]]}</td></tr>
  * <tr><td><tt>\p{Cntrl}</tt></td>
  *     <td>A control character: <tt>\p{gc=Cc}</tt></td></tr>
  * <tr><td><tt>\p{XDigit}</tt></td>
@@ -676,9 +669,9 @@
  * Categories that behave like the java.lang.Character
  * boolean is<i>methodname</i> methods (except for the deprecated ones) are
  * available through the same <tt>\p{</tt><i>prop</i><tt>}</tt> syntax where
- * the specified property has the name <tt>java<i>methodname</i></tt>.
+ * the specified property has the name <tt>java<i>methodname</i></tt></a>.
  *
- * <h4> Comparison to Perl 5 </h4>
+ * <h3> Comparison to Perl 5 </h3>
  *
  * <p>The <code>Pattern</code> engine performs traditional NFA-based matching
  * with ordered alternation as occurs in Perl 5.
@@ -1023,11 +1016,11 @@
     private transient boolean hasSupplementary;
 
     /**
-     * Compiles the given regular expression into a pattern.  </p>
+     * Compiles the given regular expression into a pattern.
      *
      * @param  regex
      *         The expression to be compiled
-     *
+     * @return the given regular expression compiled into a pattern
      * @throws  PatternSyntaxException
      *          If the expression's syntax is invalid
      */
@@ -1037,7 +1030,7 @@
 
     /**
      * Compiles the given regular expression into a pattern with the given
-     * flags.  </p>
+     * flags.
      *
      * @param  regex
      *         The expression to be compiled
@@ -1049,6 +1042,7 @@
      *         {@link #LITERAL}, {@link #UNICODE_CHARACTER_CLASS}
      *         and {@link #COMMENTS}
      *
+     * @return the given regular expression compiled into a pattern with the given flags
      * @throws  IllegalArgumentException
      *          If bit values other than those corresponding to the defined
      *          match flags are set in <tt>flags</tt>
@@ -1062,7 +1056,6 @@
 
     /**
      * Returns the regular expression from which this pattern was compiled.
-     * </p>
      *
      * @return  The source of this pattern
      */
@@ -1084,7 +1077,6 @@
 
     /**
      * Creates a matcher that will match the given input against this pattern.
-     * </p>
      *
      * @param  input
      *         The character sequence to be matched
@@ -1103,7 +1095,7 @@
     }
 
     /**
-     * Returns this pattern's match flags.  </p>
+     * Returns this pattern's match flags.
      *
      * @return  The match flags specified when this pattern was compiled
      */
@@ -1133,7 +1125,7 @@
      *
      * @param  input
      *         The character sequence to be matched
-     *
+     * @return whether or not the regular expression matches on the input
      * @throws  PatternSyntaxException
      *          If the expression's syntax is invalid
      */
@@ -1170,9 +1162,9 @@
      *
      * <blockquote><table cellpadding=1 cellspacing=0
      *              summary="Split examples showing regex, limit, and result">
-     * <tr><th><P align="left"><i>Regex&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
-     *     <th><P align="left"><i>Limit&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
-     *     <th><P align="left"><i>Result&nbsp;&nbsp;&nbsp;&nbsp;</i></th></tr>
+     * <tr><th align="left"><i>Regex&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
+     *     <th align="left"><i>Limit&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
+     *     <th align="left"><i>Result&nbsp;&nbsp;&nbsp;&nbsp;</i></th></tr>
      * <tr><td align=center>:</td>
      *     <td align=center>2</td>
      *     <td><tt>{ "boo", "and:foo" }</tt></td></tr>
@@ -1253,8 +1245,8 @@
      *
      * <blockquote><table cellpadding=1 cellspacing=0
      *              summary="Split examples showing regex and result">
-     * <tr><th><P align="left"><i>Regex&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
-     *     <th><P align="left"><i>Result</i></th></tr>
+     * <tr><th align="left"><i>Regex&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
+     *     <th align="left"><i>Result</i></th></tr>
      * <tr><td align=center>:</td>
      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
      * <tr><td align=center>o</td>
@@ -5823,6 +5815,6 @@
             }
         }
         return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
-                new MatcherIterator(), Spliterator.ORDERED | Spliterator.NONNULL));
+                new MatcherIterator(), Spliterator.ORDERED | Spliterator.NONNULL), false);
     }
 }
--- a/src/share/classes/java/util/stream/AbstractPipeline.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/stream/AbstractPipeline.java	Mon Jul 22 17:37:15 2013 -0700
@@ -53,11 +53,6 @@
  * operation, the stream is considered to be consumed, and no more intermediate
  * or terminal operations are permitted on this stream instance.
  *
- * <p>{@code AbstractPipeline} implements a number of methods that are
- * specified in {@link BaseStream}, though it does not implement
- * {@code BaseStream} directly.  Subclasses of {@code AbstractPipeline}
- * will generally implement {@code BaseStream}.
- *
  * @implNote
  * <p>For sequential streams, and parallel streams without
  * <a href="package-summary.html#StreamOps">stateful intermediate
@@ -75,7 +70,7 @@
  * @since 1.8
  */
 abstract class AbstractPipeline<E_IN, E_OUT, S extends BaseStream<E_OUT, S>>
-        extends PipelineHelper<E_OUT> {
+        extends PipelineHelper<E_OUT> implements BaseStream<E_OUT, S> {
     /**
      * Backlink to the head of the pipeline chain (self if this is the source
      * stage).
@@ -286,26 +281,20 @@
 
     // BaseStream
 
-    /**
-     * Implements {@link BaseStream#sequential()}
-     */
+    @Override
     public final S sequential() {
         sourceStage.parallel = false;
         return (S) this;
     }
 
-    /**
-     * Implements {@link BaseStream#parallel()}
-     */
+    @Override
     public final S parallel() {
         sourceStage.parallel = true;
         return (S) this;
     }
 
     // Primitive specialization use co-variant overrides, hence is not final
-    /**
-     * Implements {@link BaseStream#spliterator()}
-     */
+    @Override
     public Spliterator<E_OUT> spliterator() {
         if (linkedOrConsumed)
             throw new IllegalStateException("stream has already been operated upon");
@@ -331,9 +320,7 @@
         }
     }
 
-    /**
-     * Implements {@link BaseStream#isParallel()}
-     */
+    @Override
     public final boolean isParallel() {
         return sourceStage.parallel;
     }
--- a/src/share/classes/java/util/stream/AbstractShortCircuitTask.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/stream/AbstractShortCircuitTask.java	Mon Jul 22 17:37:15 2013 -0700
@@ -92,22 +92,51 @@
      */
     protected abstract R getEmptyResult();
 
+    /**
+     * Overrides AbstractTask version to include checks for early
+     * exits while splitting or computing.
+     */
     @Override
-    protected boolean canCompute() {
-        // Have we already found an answer?
-        if (sharedResult.get() != null) {
-            tryComplete();
-            return false;
-        } else if (taskCanceled()) {
-            setLocalResult(getEmptyResult());
-            tryComplete();
-            return false;
+    public void compute() {
+        Spliterator<P_IN> rs = spliterator, ls;
+        long sizeEstimate = rs.estimateSize();
+        long sizeThreshold = getTargetSize(sizeEstimate);
+        boolean forkRight = false;
+        @SuppressWarnings("unchecked") K task = (K) this;
+        AtomicReference<R> sr = sharedResult;
+        R result;
+        while ((result = sr.get()) == null) {
+            if (task.taskCanceled()) {
+                result = task.getEmptyResult();
+                break;
+            }
+            if (sizeEstimate <= sizeThreshold || (ls = rs.trySplit()) == null) {
+                result = task.doLeaf();
+                break;
+            }
+            K leftChild, rightChild, taskToFork;
+            task.leftChild  = leftChild = task.makeChild(ls);
+            task.rightChild = rightChild = task.makeChild(rs);
+            task.setPendingCount(1);
+            if (forkRight) {
+                forkRight = false;
+                rs = ls;
+                task = leftChild;
+                taskToFork = rightChild;
+            }
+            else {
+                forkRight = true;
+                task = rightChild;
+                taskToFork = leftChild;
+            }
+            taskToFork.fork();
+            sizeEstimate = rs.estimateSize();
         }
-        else {
-            return true;
-        }
+        task.setLocalResult(result);
+        task.tryComplete();
     }
 
+
     /**
      * Declares that a globally valid result has been found.  If another task has
      * not already found the answer, the result is installed in
--- a/src/share/classes/java/util/stream/AbstractTask.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/stream/AbstractTask.java	Mon Jul 22 17:37:15 2013 -0700
@@ -102,7 +102,7 @@
     protected Spliterator<P_IN> spliterator;
 
     /** Target leaf size, common to all tasks in a computation */
-    protected final long targetSize;
+    protected long targetSize; // may be laziliy initialized
 
     /**
      * The left child.
@@ -134,7 +134,7 @@
         super(null);
         this.helper = helper;
         this.spliterator = spliterator;
-        this.targetSize = suggestTargetSize(spliterator.estimateSize());
+        this.targetSize = 0L;
     }
 
     /**
@@ -182,27 +182,13 @@
     }
 
     /**
-     * Returns a suggestion whether it is advisable to split the provided
-     * spliterator based on target size and other considerations, such as pool
-     * state.
-      *
-     * @return {@code true} if a split is advised otherwise {@code false}
+     * Returns the targetSize, initializing it via the supplied
+     * size estimate if not already initialized.
      */
-    public static boolean suggestSplit(Spliterator spliterator,
-                                       long targetSize) {
-        long remaining = spliterator.estimateSize();
-        return (remaining > targetSize);
-        // @@@ May additionally want to fold in pool characteristics such as surplus task count
-    }
-
-    /**
-     * Returns a suggestion whether it is adviseable to split this task based on
-     * target size and other considerations.
-      *
-     *  @return {@code true} if a split is advised otherwise {@code false}
-     */
-    public boolean suggestSplit() {
-        return suggestSplit(spliterator, targetSize);
+    protected final long getTargetSize(long sizeEstimate) {
+        long s;
+        return ((s = targetSize) != 0 ? s :
+                (targetSize = suggestTargetSize(sizeEstimate)));
     }
 
     /**
@@ -285,43 +271,46 @@
     }
 
     /**
-     * Decides whether or not to split a task further or compute it directly. If
-     * computing directly, call {@code doLeaf} and pass the result to
-     * {@code setRawResult}.  If splitting, set up the child-related fields,
-     * create the child tasks, fork the leftmost (prefix) child tasks, and
-     * compute the rightmost (remaining) child tasks.
+     * Decides whether or not to split a task further or compute it
+     * directly. If computing directly, calls {@code doLeaf} and pass
+     * the result to {@code setRawResult}. Otherwise splits off
+     * subtasks, forking one and continuing as the other.
      *
-     * <p>
-     * Computing will continue for rightmost tasks while a task can be computed
-     * as determined by {@link #canCompute()} and that task should and can be
-     * split into left and right tasks.
-     *
-     * <p>
-     * The rightmost tasks are computed in a loop rather than recursively to
-     * avoid potential stack overflows when computing with a right-balanced
-     * tree, such as that produced when splitting with a {@link Spliterator}
-     * created from an {@link java.util.Iterator}.
+     * <p> The method is structured to conserve resources across a
+     * range of uses.  The loop continues with one of the child tasks
+     * when split, to avoid deep recursion. To cope with spliterators
+     * that may be systematically biased toward left-heavy or
+     * right-heavy splits, we alternate which child is forked versus
+     * continued in the loop.
      */
     @Override
-    public final void compute() {
-        @SuppressWarnings("unchecked")
-        K task = (K) this;
-        while (task.canCompute()) {
-            Spliterator<P_IN> split;
-            if (!task.suggestSplit() || (split = task.spliterator.trySplit()) == null) {
-                task.setLocalResult(task.doLeaf());
-                task.tryComplete();
-                return;
+    public void compute() {
+        Spliterator<P_IN> rs = spliterator, ls; // right, left spliterators
+        long sizeEstimate = rs.estimateSize();
+        long sizeThreshold = getTargetSize(sizeEstimate);
+        boolean forkRight = false;
+        @SuppressWarnings("unchecked") K task = (K) this;
+        while (sizeEstimate > sizeThreshold && (ls = rs.trySplit()) != null) {
+            K leftChild, rightChild, taskToFork;
+            task.leftChild  = leftChild = task.makeChild(ls);
+            task.rightChild = rightChild = task.makeChild(rs);
+            task.setPendingCount(1);
+            if (forkRight) {
+                forkRight = false;
+                rs = ls;
+                task = leftChild;
+                taskToFork = rightChild;
             }
             else {
-                K l = task.leftChild = task.makeChild(split);
-                K r = task.rightChild = task.makeChild(task.spliterator);
-                task.spliterator = null;
-                task.setPendingCount(1);
-                l.fork();
-                task = r;
+                forkRight = true;
+                task = rightChild;
+                taskToFork = leftChild;
             }
+            taskToFork.fork();
+            sizeEstimate = rs.estimateSize();
         }
+        task.setLocalResult(task.doLeaf());
+        task.tryComplete();
     }
 
     /**
@@ -339,21 +328,6 @@
     }
 
     /**
-     * Determines if the task can be computed.
-     *
-     * @implSpec The default always returns true
-     *
-     * @return {@code true} if this task can be computed to either calculate the
-     *         leaf via {@link #doLeaf()} or split, otherwise false if this task
-     *         cannot be computed, for example if this task has been canceled
-     *         and/or a result for the computation has been found by another
-     *         task.
-     */
-    protected boolean canCompute() {
-        return true;
-    }
-
-    /**
      * Returns whether this node is a "leftmost" node -- whether the path from
      * the root to this node involves only traversing leftmost child links.  For
      * a leaf node, this means it is the first leaf node in the encounter order.
--- a/src/share/classes/java/util/stream/BaseStream.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/stream/BaseStream.java	Mon Jul 22 17:37:15 2013 -0700
@@ -29,15 +29,13 @@
 
 /**
  * Base interface for stream types such as {@link Stream}, {@link IntStream},
- * etc.  Contains methods common to all stream types.  Many of these methods
- * are implemented by {@link AbstractPipeline}, even though
- * {@code AbstractPipeline} does not directly implement {@code BaseStream}.
+ * etc.  Contains methods common to all stream types.
  *
  * @param <T> type of stream elements
  * @param <S> type of stream implementing {@code BaseStream}
  * @since 1.8
  */
-interface BaseStream<T, S extends BaseStream<T, S>> {
+public interface BaseStream<T, S extends BaseStream<T, S>> {
     /**
      * Returns an iterator for the elements of this stream.
      *
--- a/src/share/classes/java/util/stream/DoubleStream.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/stream/DoubleStream.java	Mon Jul 22 17:37:15 2013 -0700
@@ -662,7 +662,7 @@
      *
      * @return a stream builder
      */
-    public static StreamBuilder.OfDouble builder() {
+    public static Builder builder() {
         return new Streams.DoubleStreamBuilderImpl();
     }
 
@@ -672,7 +672,7 @@
      * @return an empty sequential stream
      */
     public static DoubleStream empty() {
-        return StreamSupport.doubleStream(Spliterators.emptyDoubleSpliterator());
+        return StreamSupport.doubleStream(Spliterators.emptyDoubleSpliterator(), false);
     }
 
     /**
@@ -682,7 +682,7 @@
      * @return a singleton sequential stream
      */
     public static DoubleStream of(double t) {
-        return StreamSupport.doubleStream(new Streams.DoubleStreamBuilderImpl(t));
+        return StreamSupport.doubleStream(new Streams.DoubleStreamBuilderImpl(t), false);
     }
 
     /**
@@ -730,7 +730,7 @@
         };
         return StreamSupport.doubleStream(Spliterators.spliteratorUnknownSize(
                 iterator,
-                Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL));
+                Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
     }
 
     /**
@@ -744,6 +744,83 @@
     public static DoubleStream generate(DoubleSupplier s) {
         Objects.requireNonNull(s);
         return StreamSupport.doubleStream(
-                new StreamSpliterators.InfiniteSupplyingSpliterator.OfDouble(Long.MAX_VALUE, s));
+                new StreamSpliterators.InfiniteSupplyingSpliterator.OfDouble(Long.MAX_VALUE, s), false);
+    }
+
+    /**
+     * Creates a lazy concatenated {@code DoubleStream} whose elements are all the
+     * elements of a first {@code DoubleStream} succeeded by all the elements of the
+     * second {@code DoubleStream}. The resulting stream is ordered if both
+     * of the input streams are ordered, and parallel if either of the input
+     * streams is parallel.
+     *
+     * @param a the first stream
+     * @param b the second stream to concatenate on to end of the first stream
+     * @return the concatenation of the two streams
+     */
+    public static DoubleStream concat(DoubleStream a, DoubleStream b) {
+        Objects.requireNonNull(a);
+        Objects.requireNonNull(b);
+
+        Spliterator.OfDouble split = new Streams.ConcatSpliterator.OfDouble(
+                a.spliterator(), b.spliterator());
+        return StreamSupport.doubleStream(split, a.isParallel() || b.isParallel());
+    }
+
+    /**
+     * A mutable builder for a {@code DoubleStream}.
+     *
+     * <p>A stream builder has a lifecycle, where it starts in a building
+     * phase, during which elements can be added, and then transitions to a
+     * built phase, after which elements may not be added.  The built phase
+     * begins when the {@link #build()} method is called, which creates an
+     * ordered stream whose elements are the elements that were added to the
+     * stream builder, in the order they were added.
+     *
+     * @see DoubleStream#builder()
+     * @since 1.8
+     */
+    public interface Builder extends DoubleConsumer {
+
+        /**
+         * Adds an element to the stream being built.
+         *
+         * @throws IllegalStateException if the builder has already transitioned
+         * to the built state
+         */
+        @Override
+        void accept(double t);
+
+        /**
+         * Adds an element to the stream being built.
+         *
+         * @implSpec
+         * The default implementation behaves as if:
+         * <pre>{@code
+         *     accept(t)
+         *     return this;
+         * }</pre>
+         *
+         * @param t the element to add
+         * @return {@code this} builder
+         * @throws IllegalStateException if the builder has already transitioned
+         * to the built state
+         */
+        default Builder add(double t) {
+            accept(t);
+            return this;
+        }
+
+        /**
+         * Builds the stream, transitioning this builder to the built state.
+         * An {@code IllegalStateException} is thrown if there are further
+         * attempts to operate on the builder after it has entered the built
+         * state.
+         *
+         * @return the built stream
+         * @throws IllegalStateException if the builder has already transitioned
+         * to the built state
+         */
+        DoubleStream build();
     }
 }
--- a/src/share/classes/java/util/stream/ForEachOps.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/stream/ForEachOps.java	Mon Jul 22 17:37:15 2013 -0700
@@ -28,6 +28,7 @@
 import java.util.Spliterator;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.CountedCompleter;
+import java.util.concurrent.ForkJoinTask;
 import java.util.function.Consumer;
 import java.util.function.DoubleConsumer;
 import java.util.function.IntConsumer;
@@ -128,7 +129,7 @@
      *
      * @param <T> the output type of the stream pipeline
      */
-    private static abstract class ForEachOp<T>
+    static abstract class ForEachOp<T>
             implements TerminalOp<T, Void>, TerminalSink<T, Void> {
         private final boolean ordered;
 
@@ -169,7 +170,7 @@
         // Implementations
 
         /** Implementation class for reference streams */
-        private static class OfRef<T> extends ForEachOp<T> {
+        static final class OfRef<T> extends ForEachOp<T> {
             final Consumer<? super T> consumer;
 
             OfRef(Consumer<? super T> consumer, boolean ordered) {
@@ -184,7 +185,7 @@
         }
 
         /** Implementation class for {@code IntStream} */
-        private static class OfInt extends ForEachOp<Integer>
+        static final class OfInt extends ForEachOp<Integer>
                 implements Sink.OfInt {
             final IntConsumer consumer;
 
@@ -205,7 +206,7 @@
         }
 
         /** Implementation class for {@code LongStream} */
-        private static class OfLong extends ForEachOp<Long>
+        static final class OfLong extends ForEachOp<Long>
                 implements Sink.OfLong {
             final LongConsumer consumer;
 
@@ -226,7 +227,7 @@
         }
 
         /** Implementation class for {@code DoubleStream} */
-        private static class OfDouble extends ForEachOp<Double>
+        static final class OfDouble extends ForEachOp<Double>
                 implements Sink.OfDouble {
             final DoubleConsumer consumer;
 
@@ -248,20 +249,20 @@
     }
 
     /** A {@code ForkJoinTask} for performing a parallel for-each operation */
-    private static class ForEachTask<S, T> extends CountedCompleter<Void> {
+    static final class ForEachTask<S, T> extends CountedCompleter<Void> {
         private Spliterator<S> spliterator;
         private final Sink<S> sink;
         private final PipelineHelper<T> helper;
-        private final long targetSize;
+        private long targetSize;
 
         ForEachTask(PipelineHelper<T> helper,
                     Spliterator<S> spliterator,
                     Sink<S> sink) {
             super(null);
+            this.sink = sink;
+            this.helper = helper;
             this.spliterator = spliterator;
-            this.sink = sink;
-            this.targetSize = AbstractTask.suggestTargetSize(spliterator.estimateSize());
-            this.helper = helper;
+            this.targetSize = 0L;
         }
 
         ForEachTask(ForEachTask<S, T> parent, Spliterator<S> spliterator) {
@@ -272,28 +273,40 @@
             this.helper = parent.helper;
         }
 
+        // Similar to AbstractTask but doesn't need to track child tasks
         public void compute() {
+            Spliterator<S> rightSplit = spliterator, leftSplit;
+            long sizeEstimate = rightSplit.estimateSize(), sizeThreshold;
+            if ((sizeThreshold = targetSize) == 0L)
+                targetSize = sizeThreshold = AbstractTask.suggestTargetSize(sizeEstimate);
             boolean isShortCircuit = StreamOpFlag.SHORT_CIRCUIT.isKnown(helper.getStreamAndOpFlags());
-            while (true) {
-                if (isShortCircuit && sink.cancellationRequested()) {
-                    propagateCompletion();
-                    spliterator = null;
-                    return;
+            boolean forkRight = false;
+            Sink<S> taskSink = sink;
+            ForEachTask<S, T> task = this;
+            while (!isShortCircuit || !taskSink.cancellationRequested()) {
+                if (sizeEstimate <= sizeThreshold ||
+                    (leftSplit = rightSplit.trySplit()) == null) {
+                    task.helper.copyInto(taskSink, rightSplit);
+                    break;
                 }
-
-                Spliterator<S> split;
-                if (!AbstractTask.suggestSplit(spliterator, targetSize)
-                    || (split = spliterator.trySplit()) == null) {
-                    helper.copyInto(sink, spliterator);
-                    propagateCompletion();
-                    spliterator = null;
-                    return;
+                ForEachTask<S, T> leftTask = new ForEachTask<>(task, leftSplit);
+                task.addToPendingCount(1);
+                ForEachTask<S, T> taskToFork;
+                if (forkRight) {
+                    forkRight = false;
+                    rightSplit = leftSplit;
+                    taskToFork = task;
+                    task = leftTask;
                 }
                 else {
-                    addToPendingCount(1);
-                    new ForEachTask<>(this, split).fork();
+                    forkRight = true;
+                    taskToFork = leftTask;
                 }
+                taskToFork.fork();
+                sizeEstimate = rightSplit.estimateSize();
             }
+            task.spliterator = null;
+            task.propagateCompletion();
         }
     }
 
@@ -301,7 +314,7 @@
      * A {@code ForkJoinTask} for performing a parallel for-each operation
      * which visits the elements in encounter order
      */
-    private static class ForEachOrderedTask<S, T> extends CountedCompleter<Void> {
+    static final class ForEachOrderedTask<S, T> extends CountedCompleter<Void> {
         private final PipelineHelper<T> helper;
         private Spliterator<S> spliterator;
         private final long targetSize;
@@ -343,39 +356,49 @@
         }
 
         private static <S, T> void doCompute(ForEachOrderedTask<S, T> task) {
-            while (true) {
-                Spliterator<S> split;
-                if (!AbstractTask.suggestSplit(task.spliterator, task.targetSize)
-                    || (split = task.spliterator.trySplit()) == null) {
-                    if (task.getPendingCount() == 0) {
-                        task.helper.wrapAndCopyInto(task.action, task.spliterator);
-                    }
-                    else {
-                        Node.Builder<T> nb = task.helper.makeNodeBuilder(
-                                task.helper.exactOutputSizeIfKnown(task.spliterator),
-                                size -> (T[]) new Object[size]);
-                        task.node = task.helper.wrapAndCopyInto(nb, task.spliterator).build();
-                    }
-                    task.tryComplete();
-                    return;
+            Spliterator<S> rightSplit = task.spliterator, leftSplit;
+            long sizeThreshold = task.targetSize;
+            boolean forkRight = false;
+            while (rightSplit.estimateSize() > sizeThreshold &&
+                   (leftSplit = rightSplit.trySplit()) != null) {
+                ForEachOrderedTask<S, T> leftChild =
+                    new ForEachOrderedTask<>(task, leftSplit, task.leftPredecessor);
+                ForEachOrderedTask<S, T> rightChild =
+                    new ForEachOrderedTask<>(task, rightSplit, leftChild);
+                task.completionMap.put(leftChild, rightChild);
+                task.addToPendingCount(1); // forking
+                rightChild.addToPendingCount(1); // right pending on left child
+                if (task.leftPredecessor != null) {
+                    leftChild.addToPendingCount(1); // left pending on previous subtree, except left spine
+                    if (task.completionMap.replace(task.leftPredecessor, task, leftChild))
+                        task.addToPendingCount(-1); // transfer my "right child" count to my left child
+                    else
+                        leftChild.addToPendingCount(-1); // left child is ready to go when ready
+                }
+                ForEachOrderedTask<S, T> taskToFork;
+                if (forkRight) {
+                    forkRight = false;
+                    rightSplit = leftSplit;
+                    task = leftChild;
+                    taskToFork = rightChild;
                 }
                 else {
-                    ForEachOrderedTask<S, T> leftChild = new ForEachOrderedTask<>(task, split, task.leftPredecessor);
-                    ForEachOrderedTask<S, T> rightChild = new ForEachOrderedTask<>(task, task.spliterator, leftChild);
-                    task.completionMap.put(leftChild, rightChild);
-                    task.addToPendingCount(1); // forking
-                    rightChild.addToPendingCount(1); // right pending on left child
-                    if (task.leftPredecessor != null) {
-                        leftChild.addToPendingCount(1); // left pending on previous subtree, except left spine
-                        if (task.completionMap.replace(task.leftPredecessor, task, leftChild))
-                            task.addToPendingCount(-1);      // transfer my "right child" count to my left child
-                        else
-                            leftChild.addToPendingCount(-1); // left child is ready to go when ready
-                    }
-                    leftChild.fork();
+                    forkRight = true;
                     task = rightChild;
+                    taskToFork = leftChild;
                 }
+                taskToFork.fork();
             }
+            if (task.getPendingCount() == 0) {
+                task.helper.wrapAndCopyInto(task.action, rightSplit);
+            }
+            else {
+                Node.Builder<T> nb = task.helper.makeNodeBuilder(
+                  task.helper.exactOutputSizeIfKnown(rightSplit),
+                  size -> (T[]) new Object[size]);
+                task.node = task.helper.wrapAndCopyInto(nb, rightSplit).build();
+            }
+            task.tryComplete();
         }
 
         @Override
--- a/src/share/classes/java/util/stream/IntStream.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/stream/IntStream.java	Mon Jul 22 17:37:15 2013 -0700
@@ -664,7 +664,7 @@
      *
      * @return a stream builder
      */
-    public static StreamBuilder.OfInt builder() {
+    public static Builder builder() {
         return new Streams.IntStreamBuilderImpl();
     }
 
@@ -674,7 +674,7 @@
      * @return an empty sequential stream
      */
     public static IntStream empty() {
-        return StreamSupport.intStream(Spliterators.emptyIntSpliterator());
+        return StreamSupport.intStream(Spliterators.emptyIntSpliterator(), false);
     }
 
     /**
@@ -684,7 +684,7 @@
      * @return a singleton sequential stream
      */
     public static IntStream of(int t) {
-        return StreamSupport.intStream(new Streams.IntStreamBuilderImpl(t));
+        return StreamSupport.intStream(new Streams.IntStreamBuilderImpl(t), false);
     }
 
     /**
@@ -732,7 +732,7 @@
         };
         return StreamSupport.intStream(Spliterators.spliteratorUnknownSize(
                 iterator,
-                Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL));
+                Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
     }
 
     /**
@@ -746,7 +746,7 @@
     public static IntStream generate(IntSupplier s) {
         Objects.requireNonNull(s);
         return StreamSupport.intStream(
-                new StreamSpliterators.InfiniteSupplyingSpliterator.OfInt(Long.MAX_VALUE, s));
+                new StreamSpliterators.InfiniteSupplyingSpliterator.OfInt(Long.MAX_VALUE, s), false);
     }
 
     /**
@@ -771,7 +771,7 @@
             return empty();
         } else {
             return StreamSupport.intStream(
-                    new Streams.RangeIntSpliterator(startInclusive, endExclusive, false));
+                    new Streams.RangeIntSpliterator(startInclusive, endExclusive, false), false);
         }
     }
 
@@ -797,7 +797,84 @@
             return empty();
         } else {
             return StreamSupport.intStream(
-                    new Streams.RangeIntSpliterator(startInclusive, endInclusive, true));
+                    new Streams.RangeIntSpliterator(startInclusive, endInclusive, true), false);
         }
     }
+
+    /**
+     * Creates a lazy concatenated {@code IntStream} whose elements are all the
+     * elements of a first {@code IntStream} succeeded by all the elements of the
+     * second {@code IntStream}. The resulting stream is ordered if both
+     * of the input streams are ordered, and parallel if either of the input
+     * streams is parallel.
+     *
+     * @param a the first stream
+     * @param b the second stream to concatenate on to end of the first stream
+     * @return the concatenation of the two streams
+     */
+    public static IntStream concat(IntStream a, IntStream b) {
+        Objects.requireNonNull(a);
+        Objects.requireNonNull(b);
+
+        Spliterator.OfInt split = new Streams.ConcatSpliterator.OfInt(
+                a.spliterator(), b.spliterator());
+        return StreamSupport.intStream(split, a.isParallel() || b.isParallel());
+    }
+
+    /**
+     * A mutable builder for an {@code IntStream}.
+     *
+     * <p>A stream builder has a lifecycle, where it starts in a building
+     * phase, during which elements can be added, and then transitions to a
+     * built phase, after which elements may not be added.  The built phase
+     * begins when the {@link #build()} method is called, which creates an
+     * ordered stream whose elements are the elements that were added to the
+     * stream builder, in the order they were added.
+     *
+     * @see IntStream#builder()
+     * @since 1.8
+     */
+    public interface Builder extends IntConsumer {
+
+        /**
+         * Adds an element to the stream being built.
+         *
+         * @throws IllegalStateException if the builder has already transitioned
+         * to the built state
+         */
+        @Override
+        void accept(int t);
+
+        /**
+         * Adds an element to the stream being built.
+         *
+         * @implSpec
+         * The default implementation behaves as if:
+         * <pre>{@code
+         *     accept(t)
+         *     return this;
+         * }</pre>
+         *
+         * @param t the element to add
+         * @return {@code this} builder
+         * @throws IllegalStateException if the builder has already transitioned
+         * to the built state
+         */
+        default Builder add(int t) {
+            accept(t);
+            return this;
+        }
+
+        /**
+         * Builds the stream, transitioning this builder to the built state.
+         * An {@code IllegalStateException} is thrown if there are further
+         * attempts to operate on the builder after it has entered the built
+         * state.
+         *
+         * @return the built stream
+         * @throws IllegalStateException if the builder has already transitioned to
+         * the built state
+         */
+        IntStream build();
+    }
 }
--- a/src/share/classes/java/util/stream/LongStream.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/stream/LongStream.java	Mon Jul 22 17:37:15 2013 -0700
@@ -655,7 +655,7 @@
      *
      * @return a stream builder
      */
-    public static StreamBuilder.OfLong builder() {
+    public static Builder builder() {
         return new Streams.LongStreamBuilderImpl();
     }
 
@@ -665,7 +665,7 @@
      * @return an empty sequential stream
      */
     public static LongStream empty() {
-        return StreamSupport.longStream(Spliterators.emptyLongSpliterator());
+        return StreamSupport.longStream(Spliterators.emptyLongSpliterator(), false);
     }
 
     /**
@@ -675,7 +675,7 @@
      * @return a singleton sequential stream
      */
     public static LongStream of(long t) {
-        return StreamSupport.longStream(new Streams.LongStreamBuilderImpl(t));
+        return StreamSupport.longStream(new Streams.LongStreamBuilderImpl(t), false);
     }
 
     /**
@@ -723,7 +723,7 @@
         };
         return StreamSupport.longStream(Spliterators.spliteratorUnknownSize(
                 iterator,
-                Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL));
+                Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
     }
 
     /**
@@ -737,7 +737,7 @@
     public static LongStream generate(LongSupplier s) {
         Objects.requireNonNull(s);
         return StreamSupport.longStream(
-                new StreamSpliterators.InfiniteSupplyingSpliterator.OfLong(Long.MAX_VALUE, s));
+                new StreamSpliterators.InfiniteSupplyingSpliterator.OfLong(Long.MAX_VALUE, s), false);
     }
 
     /**
@@ -765,13 +765,11 @@
             // Split the range in two and concatenate
             // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE) then
             // the lower range, [Long.MIN_VALUE, 0) will be further split in two
-//            long m = startInclusive + Long.divideUnsigned(endExclusive - startInclusive, 2) + 1;
-//            return Streams.concat(range(startInclusive, m), range(m, endExclusive));
-            // This is temporary until Streams.concat is supported
-            throw new UnsupportedOperationException();
+            long m = startInclusive + Long.divideUnsigned(endExclusive - startInclusive, 2) + 1;
+            return concat(range(startInclusive, m), range(m, endExclusive));
         } else {
             return StreamSupport.longStream(
-                    new Streams.RangeLongSpliterator(startInclusive, endExclusive, false));
+                    new Streams.RangeLongSpliterator(startInclusive, endExclusive, false), false);
         }
     }
 
@@ -801,13 +799,88 @@
             // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE] then
             // the lower range, [Long.MIN_VALUE, 0), and upper range,
             // [0, Long.MAX_VALUE], will both be further split in two
-//            long m = startInclusive + Long.divideUnsigned(endInclusive - startInclusive, 2) + 1;
-//            return Streams.concat(range(startInclusive, m), rangeClosed(m, endInclusive));
-            // This is temporary until Streams.concat is supported
-            throw new UnsupportedOperationException();
+            long m = startInclusive + Long.divideUnsigned(endInclusive - startInclusive, 2) + 1;
+            return concat(range(startInclusive, m), rangeClosed(m, endInclusive));
         } else {
             return StreamSupport.longStream(
-                    new Streams.RangeLongSpliterator(startInclusive, endInclusive, true));
+                    new Streams.RangeLongSpliterator(startInclusive, endInclusive, true), false);
         }
     }
+
+    /**
+     * Creates a lazy concatenated {@code LongStream} whose elements are all the
+     * elements of a first {@code LongStream} succeeded by all the elements of the
+     * second {@code LongStream}. The resulting stream is ordered if both
+     * of the input streams are ordered, and parallel if either of the input
+     * streams is parallel.
+     *
+     * @param a the first stream
+     * @param b the second stream to concatenate on to end of the first stream
+     * @return the concatenation of the two streams
+     */
+    public static LongStream concat(LongStream a, LongStream b) {
+        Objects.requireNonNull(a);
+        Objects.requireNonNull(b);
+
+        Spliterator.OfLong split = new Streams.ConcatSpliterator.OfLong(
+                a.spliterator(), b.spliterator());
+        return StreamSupport.longStream(split, a.isParallel() || b.isParallel());
+    }
+
+    /**
+     * A mutable builder for a {@code LongStream}.
+     *
+     * <p>A stream builder has a lifecycle, where it starts in a building
+     * phase, during which elements can be added, and then transitions to a
+     * built phase, after which elements may not be added.  The built phase
+     * begins when the {@link #build()} method is called, which creates an
+     * ordered stream whose elements are the elements that were added to the
+     * stream builder, in the order they were added.
+     *
+     * @see LongStream#builder()
+     * @since 1.8
+     */
+    public interface Builder extends LongConsumer {
+
+        /**
+         * Adds an element to the stream being built.
+         *
+         * @throws IllegalStateException if the builder has already transitioned
+         * to the built state
+         */
+        @Override
+        void accept(long t);
+
+        /**
+         * Adds an element to the stream being built.
+         *
+         * @implSpec
+         * The default implementation behaves as if:
+         * <pre>{@code
+         *     accept(t)
+         *     return this;
+         * }</pre>
+         *
+         * @param t the element to add
+         * @return {@code this} builder
+         * @throws IllegalStateException if the builder has already transitioned
+         * to the built state
+         */
+        default Builder add(long t) {
+            accept(t);
+            return this;
+        }
+
+        /**
+         * Builds the stream, transitioning this builder to the built state.
+         * An {@code IllegalStateException} is thrown if there are further
+         * attempts to operate on the builder after it has entered the built
+         * state.
+         *
+         * @return the built stream
+         * @throws IllegalStateException if the builder has already transitioned
+         * to the built state
+         */
+        LongStream build();
+    }
 }
--- a/src/share/classes/java/util/stream/Nodes.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/stream/Nodes.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1829,25 +1829,20 @@
         @Override
         public void compute() {
             SizedCollectorTask<P_IN, P_OUT, T_SINK, K> task = this;
-            while (true) {
-                Spliterator<P_IN> leftSplit;
-                if (!AbstractTask.suggestSplit(task.spliterator, task.targetSize)
-                    || ((leftSplit = task.spliterator.trySplit()) == null)) {
-                    if (task.offset + task.length >= MAX_ARRAY_SIZE)
-                        throw new IllegalArgumentException("Stream size exceeds max array size");
-                    T_SINK sink = (T_SINK) task;
-                    task.helper.wrapAndCopyInto(sink, task.spliterator);
-                    task.propagateCompletion();
-                    return;
-                }
-                else {
-                    task.setPendingCount(1);
-                    long leftSplitSize = leftSplit.estimateSize();
-                    task.makeChild(leftSplit, task.offset, leftSplitSize).fork();
-                    task = task.makeChild(task.spliterator, task.offset + leftSplitSize,
-                                          task.length - leftSplitSize);
-                }
+            Spliterator<P_IN> rightSplit = spliterator, leftSplit;
+            while (rightSplit.estimateSize() > task.targetSize &&
+                   (leftSplit = rightSplit.trySplit()) != null) {
+                task.setPendingCount(1);
+                long leftSplitSize = leftSplit.estimateSize();
+                task.makeChild(leftSplit, task.offset, leftSplitSize).fork();
+                task = task.makeChild(rightSplit, task.offset + leftSplitSize,
+                                      task.length - leftSplitSize);
             }
+            if (task.offset + task.length >= MAX_ARRAY_SIZE)
+                throw new IllegalArgumentException("Stream size exceeds max array size");
+            T_SINK sink = (T_SINK) task;
+            task.helper.wrapAndCopyInto(sink, rightSplit);
+            task.propagateCompletion();
         }
 
         abstract K makeChild(Spliterator<P_IN> spliterator, long offset, long size);
--- a/src/share/classes/java/util/stream/SliceOps.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/stream/SliceOps.java	Mon Jul 22 17:37:15 2013 -0700
@@ -598,9 +598,9 @@
                 final Node.Builder<P_OUT> nb = op.makeNodeBuilder(sizeIfKnown, generator);
                 Sink<P_OUT> opSink = op.opWrapSink(helper.getStreamAndOpFlags(), nb);
                 helper.copyIntoWithCancel(helper.wrapSink(opSink), spliterator);
-                // It is necessary to truncate here since the result at the root
-                // can only be set once
-                return doTruncate(nb.build());
+                // There is no need to truncate since the op performs the
+                // skipping and limiting of elements
+                return nb.build();
             }
             else {
                 Node<P_OUT> node = helper.wrapAndCopyInto(helper.makeNodeBuilder(-1, generator),
--- a/src/share/classes/java/util/stream/Stream.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/stream/Stream.java	Mon Jul 22 17:37:15 2013 -0700
@@ -794,7 +794,7 @@
      * @param <T> type of elements
      * @return a stream builder
      */
-    public static<T> StreamBuilder<T> builder() {
+    public static<T> Builder<T> builder() {
         return new Streams.StreamBuilderImpl<>();
     }
 
@@ -805,7 +805,7 @@
      * @return an empty sequential stream
      */
     public static<T> Stream<T> empty() {
-        return StreamSupport.stream(Spliterators.<T>emptySpliterator());
+        return StreamSupport.stream(Spliterators.<T>emptySpliterator(), false);
     }
 
     /**
@@ -816,7 +816,7 @@
      * @return a singleton sequential stream
      */
     public static<T> Stream<T> of(T t) {
-        return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t));
+        return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
     }
 
     /**
@@ -866,7 +866,7 @@
         };
         return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
                 iterator,
-                Spliterator.ORDERED | Spliterator.IMMUTABLE));
+                Spliterator.ORDERED | Spliterator.IMMUTABLE), false);
     }
 
     /**
@@ -881,6 +881,90 @@
     public static<T> Stream<T> generate(Supplier<T> s) {
         Objects.requireNonNull(s);
         return StreamSupport.stream(
-                new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s));
+                new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s), false);
+    }
+
+    /**
+     * Creates a lazy concatenated {@code Stream} whose elements are all the
+     * elements of a first {@code Stream} succeeded by all the elements of the
+     * second {@code Stream}. The resulting stream is ordered if both
+     * of the input streams are ordered, and parallel if either of the input
+     * streams is parallel.
+     *
+     * @param <T> The type of stream elements
+     * @param a the first stream
+     * @param b the second stream to concatenate on to end of the first
+     *        stream
+     * @return the concatenation of the two input streams
+     */
+    public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) {
+        Objects.requireNonNull(a);
+        Objects.requireNonNull(b);
+
+        @SuppressWarnings("unchecked")
+        Spliterator<T> split = new Streams.ConcatSpliterator.OfRef<>(
+                (Spliterator<T>) a.spliterator(), (Spliterator<T>) b.spliterator());
+        return StreamSupport.stream(split, a.isParallel() || b.isParallel());
+    }
+
+    /**
+     * A mutable builder for a {@code Stream}.  This allows the creation of a
+     * {@code Stream} by generating elements individually and adding them to the
+     * {@code Builder} (without the copying overhead that comes from using
+     * an {@code ArrayList} as a temporary buffer.)
+     *
+     * <p>A {@code Stream.Builder} has a lifecycle, where it starts in a building
+     * phase, during which elements can be added, and then transitions to a built
+     * phase, after which elements may not be added.  The built phase begins
+     * when the {@link #build()} method is called, which creates an ordered
+     * {@code Stream} whose elements are the elements that were added to the stream
+     * builder, in the order they were added.
+     *
+     * @param <T> the type of stream elements
+     * @see Stream#builder()
+     * @since 1.8
+     */
+    public interface Builder<T> extends Consumer<T> {
+
+        /**
+         * Adds an element to the stream being built.
+         *
+         * @throws IllegalStateException if the builder has already transitioned to
+         * the built state
+         */
+        @Override
+        void accept(T t);
+
+        /**
+         * Adds an element to the stream being built.
+         *
+         * @implSpec
+         * The default implementation behaves as if:
+         * <pre>{@code
+         *     accept(t)
+         *     return this;
+         * }</pre>
+         *
+         * @param t the element to add
+         * @return {@code this} builder
+         * @throws IllegalStateException if the builder has already transitioned to
+         * the built state
+         */
+        default Builder<T> add(T t) {
+            accept(t);
+            return this;
+        }
+
+        /**
+         * Builds the stream, transitioning this builder to the built state.
+         * An {@code IllegalStateException} is thrown if there are further attempts
+         * to operate on the builder after it has entered the built state.
+         *
+         * @return the built stream
+         * @throws IllegalStateException if the builder has already transitioned to
+         * the built state
+         */
+        Stream<T> build();
+
     }
 }
--- a/src/share/classes/java/util/stream/StreamBuilder.java	Thu Jul 18 03:38:49 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,265 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-package java.util.stream;
-
-import java.util.function.Consumer;
-import java.util.function.DoubleConsumer;
-import java.util.function.IntConsumer;
-import java.util.function.LongConsumer;
-
-/**
- * A mutable builder for a {@code Stream}.  This allows the creation of a
- * {@code Stream} by generating elements individually and adding them to the
- * {@code StreamBuilder} (without the copying overhead that comes from using
- * an {@code ArrayList} as a temporary buffer.)
- *
- * <p>A {@code StreamBuilder} has a lifecycle, where it starts in a building
- * phase, during which elements can be added, and then transitions to a built
- * phase, after which elements may not be added.  The built phase begins
- * when the {@link #build()} method is called, which creates an ordered
- * {@code Stream} whose elements are the elements that were added to the stream
- * builder, in the order they were added.
- *
- * <p>Primitive specializations of {@code StreamBuilder} are provided
- * for {@link OfInt int}, {@link OfLong long}, and {@link OfDouble double}
- * values.
- *
- * @param <T> the type of stream elements
- * @see Stream#builder()
- * @since 1.8
- */
-public interface StreamBuilder<T> extends Consumer<T> {
-
-    /**
-     * Adds an element to the stream being built.
-     *
-     * @throws IllegalStateException if the builder has already transitioned to
-     * the built state
-     */
-    @Override
-    void accept(T t);
-
-    /**
-     * Adds an element to the stream being built.
-     *
-     * @implSpec
-     * The default implementation behaves as if:
-     * <pre>{@code
-     *     accept(t)
-     *     return this;
-     * }</pre>
-     *
-     * @param t the element to add
-     * @return {@code this} builder
-     * @throws IllegalStateException if the builder has already transitioned to
-     * the built state
-     */
-    default StreamBuilder<T> add(T t) {
-        accept(t);
-        return this;
-    }
-
-    /**
-     * Builds the stream, transitioning this builder to the built state.
-     * An {@code IllegalStateException} is thrown if there are further attempts
-     * to operate on the builder after it has entered the built state.
-     *
-     * @return the built stream
-     * @throws IllegalStateException if the builder has already transitioned to
-     * the built state
-     */
-    Stream<T> build();
-
-    /**
-     * A mutable builder for an {@code IntStream}.
-     *
-     * <p>A stream builder has a lifecycle, where it starts in a building
-     * phase, during which elements can be added, and then transitions to a
-     * built phase, after which elements may not be added.  The built phase
-     * begins when the {@link #build()} method is called, which creates an
-     * ordered stream whose elements are the elements that were added to the
-     * stream builder, in the order they were added.
-     *
-     * @see IntStream#builder()
-     * @since 1.8
-     */
-    interface OfInt extends IntConsumer {
-
-        /**
-         * Adds an element to the stream being built.
-         *
-         * @throws IllegalStateException if the builder has already transitioned
-         * to the built state
-         */
-        @Override
-        void accept(int t);
-
-        /**
-         * Adds an element to the stream being built.
-         *
-         * @implSpec
-         * The default implementation behaves as if:
-         * <pre>{@code
-         *     accept(t)
-         *     return this;
-         * }</pre>
-         *
-         * @param t the element to add
-         * @return {@code this} builder
-         * @throws IllegalStateException if the builder has already transitioned
-         * to the built state
-         */
-        default StreamBuilder.OfInt add(int t) {
-            accept(t);
-            return this;
-        }
-
-        /**
-         * Builds the stream, transitioning this builder to the built state.
-         * An {@code IllegalStateException} is thrown if there are further
-         * attempts to operate on the builder after it has entered the built
-         * state.
-         *
-         * @return the built stream
-         * @throws IllegalStateException if the builder has already transitioned to
-         * the built state
-         */
-        IntStream build();
-    }
-
-    /**
-     * A mutable builder for a {@code LongStream}.
-     *
-     * <p>A stream builder has a lifecycle, where it starts in a building
-     * phase, during which elements can be added, and then transitions to a
-     * built phase, after which elements may not be added.  The built phase
-     * begins when the {@link #build()} method is called, which creates an
-     * ordered stream whose elements are the elements that were added to the
-     * stream builder, in the order they were added.
-     *
-     * @see LongStream#builder()
-     * @since 1.8
-     */
-    interface OfLong extends LongConsumer {
-
-        /**
-         * Adds an element to the stream being built.
-         *
-         * @throws IllegalStateException if the builder has already transitioned
-         * to the built state
-         */
-        @Override
-        void accept(long t);
-
-        /**
-         * Adds an element to the stream being built.
-         *
-         * @implSpec
-         * The default implementation behaves as if:
-         * <pre>{@code
-         *     accept(t)
-         *     return this;
-         * }</pre>
-         *
-         * @param t the element to add
-         * @return {@code this} builder
-         * @throws IllegalStateException if the builder has already transitioned
-         * to the built state
-         */
-        default StreamBuilder.OfLong add(long t) {
-            accept(t);
-            return this;
-        }
-
-        /**
-         * Builds the stream, transitioning this builder to the built state.
-         * An {@code IllegalStateException} is thrown if there are further
-         * attempts to operate on the builder after it has entered the built
-         * state.
-         *
-         * @return the built stream
-         * @throws IllegalStateException if the builder has already transitioned
-         * to the built state
-         */
-        LongStream build();
-    }
-
-    /**
-     * A mutable builder for a {@code DoubleStream}.
-     *
-     * <p>A stream builder has a lifecycle, where it starts in a building
-     * phase, during which elements can be added, and then transitions to a
-     * built phase, after which elements may not be added.  The built phase
-     * begins when the {@link #build()} method is called, which creates an
-     * ordered stream whose elements are the elements that were added to the
-     * stream builder, in the order they were added.
-     *
-     * @see LongStream#builder()
-     * @since 1.8
-     */
-    interface OfDouble extends DoubleConsumer {
-
-        /**
-         * Adds an element to the stream being built.
-         *
-         * @throws IllegalStateException if the builder has already transitioned
-         * to the built state
-         */
-        @Override
-        void accept(double t);
-
-        /**
-         * Adds an element to the stream being built.
-         *
-         * @implSpec
-         * The default implementation behaves as if:
-         * <pre>{@code
-         *     accept(t)
-         *     return this;
-         * }</pre>
-         *
-         * @param t the element to add
-         * @return {@code this} builder
-         * @throws IllegalStateException if the builder has already transitioned
-         * to the built state
-         */
-        default StreamBuilder.OfDouble add(double t) {
-            accept(t);
-            return this;
-        }
-
-        /**
-         * Builds the stream, transitioning this builder to the built state.
-         * An {@code IllegalStateException} is thrown if there are further
-         * attempts to operate on the builder after it has entered the built
-         * state.
-         *
-         * @return the built stream
-         * @throws IllegalStateException if the builder has already transitioned
-         * to the built state
-         */
-        DoubleStream build();
-    }
-}
--- a/src/share/classes/java/util/stream/StreamSupport.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/stream/StreamSupport.java	Mon Jul 22 17:37:15 2013 -0700
@@ -47,7 +47,8 @@
     private StreamSupport() {}
 
     /**
-     * Creates a new sequential {@code Stream} from a {@code Spliterator}.
+     * Creates a new sequential or parallel {@code Stream} from a
+     * {@code Spliterator}.
      *
      * <p>The spliterator is only traversed, split, or queried for estimated
      * size after the terminal operation of the stream pipeline commences.
@@ -55,50 +56,28 @@
      * <p>It is strongly recommended the spliterator report a characteristic of
      * {@code IMMUTABLE} or {@code CONCURRENT}, or be
      * <a href="../Spliterator.html#binding">late-binding</a>.  Otherwise,
-     * {@link #stream(Supplier, int)} should be used to
-     * reduce the scope of potential interference with the source.  See
+     * {@link #stream(java.util.function.Supplier, int, boolean)} should be used
+     * to reduce the scope of potential interference with the source.  See
      * <a href="package-summary.html#Non-Interference">Non-Interference</a> for
      * more details.
      *
      * @param <T> the type of stream elements
      * @param spliterator a {@code Spliterator} describing the stream elements
-     * @return a new sequential {@code Stream}
+     * @param parallel if {@code true} then the returned stream is a parallel
+     *        stream; if {@code false} the returned stream is a sequential
+     *        stream.
+     * @return a new sequential or parallel {@code Stream}
      */
-    public static <T> Stream<T> stream(Spliterator<T> spliterator) {
+    public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel) {
         Objects.requireNonNull(spliterator);
         return new ReferencePipeline.Head<>(spliterator,
                                             StreamOpFlag.fromCharacteristics(spliterator),
-                                            false);
+                                            parallel);
     }
 
     /**
-     * Creates a new parallel {@code Stream} from a {@code Spliterator}.
-     *
-     * <p>The spliterator is only traversed, split, or queried for estimated
-     * size after the terminal operation of the stream pipeline commences.
-     *
-     * <p>It is strongly recommended the spliterator report a characteristic of
-     * {@code IMMUTABLE} or {@code CONCURRENT}, or be
-     * <a href="../Spliterator.html#binding">late-binding</a>.  Otherwise,
-     * {@link #stream(Supplier, int)} should be used to
-     * reduce the scope of potential interference with the source.  See
-     * <a href="package-summary.html#Non-Interference">Non-Interference</a> for
-     * more details.
-     *
-     * @param <T> the type of stream elements
-     * @param spliterator a {@code Spliterator} describing the stream elements
-     * @return a new parallel {@code Stream}
-     */
-    public static <T> Stream<T> parallelStream(Spliterator<T> spliterator) {
-        Objects.requireNonNull(spliterator);
-        return new ReferencePipeline.Head<>(spliterator,
-                                            StreamOpFlag.fromCharacteristics(spliterator),
-                                            true);
-    }
-
-    /**
-     * Creates a new sequential {@code Stream} from a {@code Supplier} of
-     * {@code Spliterator}.
+     * Creates a new sequential or parallel {@code Stream} from a
+     * {@code Supplier} of {@code Spliterator}.
      *
      * <p>The {@link Supplier#get()} method will be invoked on the supplier no
      * more than once, and after the terminal operation of the stream pipeline
@@ -107,43 +86,8 @@
      * <p>For spliterators that report a characteristic of {@code IMMUTABLE}
      * or {@code CONCURRENT}, or that are
      * <a href="../Spliterator.html#binding">late-binding</a>, it is likely
-     * more efficient to use {@link #stream(java.util.Spliterator)} instead.
-     * The use of a {@code Supplier} in this form provides a level of
-     * indirection that reduces the scope of potential interference with the
-     * source.  Since the supplier is only invoked after the terminal operation
-     * commences, any modifications to the source up to the start of the
-     * terminal operation are reflected in the stream result.  See
-     * <a href="package-summary.html#Non-Interference">Non-Interference</a> for
-     * more details.
-     *
-     * @param <T> the type of stream elements
-     * @param supplier a {@code Supplier} of a {@code Spliterator}
-     * @param characteristics Spliterator characteristics of the supplied
-     *        {@code Spliterator}.  The characteristics must be equal to
-     *        {@code source.get().getCharacteristics()}.
-     * @return a new sequential {@code Stream}
-     * @see #stream(Spliterator)
-     */
-    public static <T> Stream<T> stream(Supplier<? extends Spliterator<T>> supplier,
-                                      int characteristics) {
-        Objects.requireNonNull(supplier);
-        return new ReferencePipeline.Head<>(supplier,
-                                            StreamOpFlag.fromCharacteristics(characteristics),
-                                            false);
-    }
-
-    /**
-     * Creates a new parallel {@code Stream} from a {@code Supplier} of
-     * {@code Spliterator}.
-     *
-     * <p>The {@link Supplier#get()} method will be invoked on the supplier no
-     * more than once, and after the terminal operation of the stream pipeline
-     * commences.
-     *
-     * <p>For spliterators that report a characteristic of {@code IMMUTABLE}
-     * or {@code CONCURRENT}, or that are
-     * <a href="../Spliterator.html#binding">late-binding</a>, it is likely
-     * more efficient to use {@link #stream(Spliterator)} instead.
+     * more efficient to use {@link #stream(java.util.Spliterator, boolean)}
+     * instead.
      * The use of a {@code Supplier} in this form provides a level of
      * indirection that reduces the scope of potential interference with the
      * source.  Since the supplier is only invoked after the terminal operation
@@ -152,24 +96,28 @@
      * <a href="package-summary.html#Non-Interference">Non-Interference</a> for
      * more details.
      *
-     * @param <T> the type of stream elements
      * @param supplier a {@code Supplier} of a {@code Spliterator}
      * @param characteristics Spliterator characteristics of the supplied
      *        {@code Spliterator}.  The characteristics must be equal to
-     *        {@code source.get().getCharacteristics()}
-     * @return a new parallel {@code Stream}
-     * @see #parallelStream(Spliterator)
+     *        {@code supplier.get().characteristics()}.
+     * @param parallel if {@code true} then the returned stream is a parallel
+     *        stream; if {@code false} the returned stream is a sequential
+     *        stream.
+     * @return a new sequential or parallel {@code Stream}
+     * @see #stream(java.util.Spliterator, boolean)
      */
-    public static <T> Stream<T> parallelStream(Supplier<? extends Spliterator<T>> supplier,
-                                              int characteristics) {
+    public static <T> Stream<T> stream(Supplier<? extends Spliterator<T>> supplier,
+                                       int characteristics,
+                                       boolean parallel) {
         Objects.requireNonNull(supplier);
         return new ReferencePipeline.Head<>(supplier,
                                             StreamOpFlag.fromCharacteristics(characteristics),
-                                            true);
+                                            parallel);
     }
 
     /**
-     * Creates a new sequential {@code IntStream} from a {@code Spliterator.OfInt}.
+     * Creates a new sequential or parallel {@code IntStream} from a
+     * {@code Spliterator.OfInt}.
      *
      * <p>The spliterator is only traversed, split, or queried for estimated size
      * after the terminal operation of the stream pipeline commences.
@@ -177,46 +125,26 @@
      * <p>It is strongly recommended the spliterator report a characteristic of
      * {@code IMMUTABLE} or {@code CONCURRENT}, or be
      * <a href="../Spliterator.html#binding">late-binding</a>.  Otherwise,
-     * {@link #stream(Supplier, int)}} should be used to
-     * reduce the scope of potential interference with the source.  See
+     * {@link #intStream(java.util.function.Supplier, int, boolean)} should be
+     * used to reduce the scope of potential interference with the source.  See
      * <a href="package-summary.html#Non-Interference">Non-Interference</a> for
      * more details.
      *
      * @param spliterator a {@code Spliterator.OfInt} describing the stream elements
-     * @return a new sequential {@code IntStream}
+     * @param parallel if {@code true} then the returned stream is a parallel
+     *        stream; if {@code false} the returned stream is a sequential
+     *        stream.
+     * @return a new sequential or parallel {@code IntStream}
      */
-    public static IntStream intStream(Spliterator.OfInt spliterator) {
+    public static IntStream intStream(Spliterator.OfInt spliterator, boolean parallel) {
         return new IntPipeline.Head<>(spliterator,
                                       StreamOpFlag.fromCharacteristics(spliterator),
-                                      false);
+                                      parallel);
     }
 
     /**
-     * Creates a new parallel {@code IntStream} from a {@code Spliterator.OfInt}.
-     *
-     * <p>he spliterator is only traversed, split, or queried for estimated size
-     * after the terminal operation of the stream pipeline commences.
-     *
-     * <p>It is strongly recommended the spliterator report a characteristic of
-     * {@code IMMUTABLE} or {@code CONCURRENT}, or be
-     * <a href="../Spliterator.html#binding">late-binding</a>.  Otherwise,
-     * {@link #stream(Supplier, int)}} should be used to
-     * reduce the scope of potential interference with the source.  See
-     * <a href="package-summary.html#Non-Interference">Non-Interference</a> for
-     * more details.
-     *
-     * @param spliterator a {@code Spliterator.OfInt} describing the stream elements
-     * @return a new parallel {@code IntStream}
-     */
-    public static IntStream intParallelStream(Spliterator.OfInt spliterator) {
-        return new IntPipeline.Head<>(spliterator,
-                                      StreamOpFlag.fromCharacteristics(spliterator),
-                                      true);
-    }
-
-    /**
-     * Creates a new sequential {@code IntStream} from a {@code Supplier} of
-     * {@code Spliterator.OfInt}.
+     * Creates a new sequential or parallel {@code IntStream} from a
+     * {@code Supplier} of {@code Spliterator.OfInt}.
      *
      * <p>The {@link Supplier#get()} method will be invoked on the supplier no
      * more than once, and after the terminal operation of the stream pipeline
@@ -225,41 +153,8 @@
      * <p>For spliterators that report a characteristic of {@code IMMUTABLE}
      * or {@code CONCURRENT}, or that are
      * <a href="../Spliterator.html#binding">late-binding</a>, it is likely
-     * more efficient to use {@link #intStream(Spliterator.OfInt)} instead.
-     * The use of a {@code Supplier} in this form provides a level of
-     * indirection that reduces the scope of potential interference with the
-     * source.  Since the supplier is only invoked after the terminal operation
-     * commences, any modifications to the source up to the start of the
-     * terminal operation are reflected in the stream result.  See
-     * <a href="package-summary.html#Non-Interference">Non-Interference</a> for
-     * more details.
-     *
-     * @param supplier a {@code Supplier} of a {@code Spliterator.OfInt}
-     * @param characteristics Spliterator characteristics of the supplied
-     *        {@code Spliterator.OfInt}.  The characteristics must be equal to
-     *        {@code source.get().getCharacteristics()}
-     * @return a new sequential {@code IntStream}
-     * @see #intStream(Spliterator.OfInt)
-     */
-    public static IntStream intStream(Supplier<? extends Spliterator.OfInt> supplier,
-                                      int characteristics) {
-        return new IntPipeline.Head<>(supplier,
-                                      StreamOpFlag.fromCharacteristics(characteristics),
-                                      false);
-    }
-
-    /**
-     * Creates a new parallel {@code IntStream} from a {@code Supplier} of
-     * {@code Spliterator.OfInt}.
-     *
-     * <p>The {@link Supplier#get()} method will be invoked on the supplier no
-     * more than once, and after the terminal operation of the stream pipeline
-     * commences.
-     *
-     * <p>For spliterators that report a characteristic of {@code IMMUTABLE}
-     * or {@code CONCURRENT}, or that are
-     * <a href="../Spliterator.html#binding">late-binding</a>, it is likely
-     * more efficient to use {@link #intStream(Spliterator.OfInt)} instead.
+     * more efficient to use {@link #intStream(java.util.Spliterator.OfInt, boolean)}
+     * instead.
      * The use of a {@code Supplier} in this form provides a level of
      * indirection that reduces the scope of potential interference with the
      * source.  Since the supplier is only invoked after the terminal operation
@@ -271,19 +166,24 @@
      * @param supplier a {@code Supplier} of a {@code Spliterator.OfInt}
      * @param characteristics Spliterator characteristics of the supplied
      *        {@code Spliterator.OfInt}.  The characteristics must be equal to
-     *        {@code source.get().getCharacteristics()}
-     * @return a new parallel {@code IntStream}
-     * @see #intParallelStream(Spliterator.OfInt)
+     *        {@code supplier.get().characteristics()}
+     * @param parallel if {@code true} then the returned stream is a parallel
+     *        stream; if {@code false} the returned stream is a sequential
+     *        stream.
+     * @return a new sequential or parallel {@code IntStream}
+     * @see #intStream(java.util.Spliterator.OfInt, boolean)
      */
-    public static IntStream intParallelStream(Supplier<? extends Spliterator.OfInt> supplier,
-                                              int characteristics) {
+    public static IntStream intStream(Supplier<? extends Spliterator.OfInt> supplier,
+                                      int characteristics,
+                                      boolean parallel) {
         return new IntPipeline.Head<>(supplier,
                                       StreamOpFlag.fromCharacteristics(characteristics),
-                                      true);
+                                      parallel);
     }
 
     /**
-     * Creates a new sequential {@code LongStream} from a {@code Spliterator.OfLong}.
+     * Creates a new sequential or parallel {@code LongStream} from a
+     * {@code Spliterator.OfLong}.
      *
      * <p>The spliterator is only traversed, split, or queried for estimated
      * size after the terminal operation of the stream pipeline commences.
@@ -291,47 +191,27 @@
      * <p>It is strongly recommended the spliterator report a characteristic of
      * {@code IMMUTABLE} or {@code CONCURRENT}, or be
      * <a href="../Spliterator.html#binding">late-binding</a>.  Otherwise,
-     * {@link #stream(Supplier, int)} should be used to
-     * reduce the scope of potential interference with the source.  See
-     * <a href="package-summary.html#Non-Interference">Non-Interference</a> for
-     * more details.
-     *
-     * @param spliterator a {@code Spliterator.OfLong} describing the stream
-     * elements
-     * @return a new sequential {@code LongStream}
-     */
-    public static LongStream longStream(Spliterator.OfLong spliterator) {
-        return new LongPipeline.Head<>(spliterator,
-                                       StreamOpFlag.fromCharacteristics(spliterator),
-                                       false);
-    }
-
-    /**
-     * Creates a new parallel {@code LongStream} from a {@code Spliterator.OfLong}.
-     *
-     * <p>The spliterator is only traversed, split, or queried for estimated
-     * size after the terminal operation of the stream pipeline commences.
-     *
-     * <p>It is strongly recommended the spliterator report a characteristic of
-     * {@code IMMUTABLE} or {@code CONCURRENT}, or be
-     * <a href="../Spliterator.html#binding">late-binding</a>.  Otherwise,
-     * {@link #stream(Supplier, int)} should be used to
-     * reduce the scope of potential interference with the source.  See
+     * {@link #longStream(java.util.function.Supplier, int, boolean)} should be
+     * used to reduce the scope of potential interference with the source.  See
      * <a href="package-summary.html#Non-Interference">Non-Interference</a> for
      * more details.
      *
      * @param spliterator a {@code Spliterator.OfLong} describing the stream elements
-     * @return a new parallel {@code LongStream}
+     * @param parallel if {@code true} then the returned stream is a parallel
+     *        stream; if {@code false} the returned stream is a sequential
+     *        stream.
+     * @return a new sequential or parallel {@code LongStream}
      */
-    public static LongStream longParallelStream(Spliterator.OfLong spliterator) {
+    public static LongStream longStream(Spliterator.OfLong spliterator,
+                                        boolean parallel) {
         return new LongPipeline.Head<>(spliterator,
                                        StreamOpFlag.fromCharacteristics(spliterator),
-                                       true);
+                                       parallel);
     }
 
     /**
-     * Creates a new sequential {@code LongStream} from a {@code Supplier} of
-     * {@code Spliterator.OfLong}.
+     * Creates a new sequential or parallel {@code LongStream} from a
+     * {@code Supplier} of {@code Spliterator.OfLong}.
      *
      * <p>The {@link Supplier#get()} method will be invoked on the supplier no
      * more than once, and after the terminal operation of the stream pipeline
@@ -340,7 +220,8 @@
      * <p>For spliterators that report a characteristic of {@code IMMUTABLE}
      * or {@code CONCURRENT}, or that are
      * <a href="../Spliterator.html#binding">late-binding</a>, it is likely
-     * more efficient to use {@link #longStream(Spliterator.OfLong)} instead.
+     * more efficient to use {@link #longStream(java.util.Spliterator.OfLong, boolean)}
+     * instead.
      * The use of a {@code Supplier} in this form provides a level of
      * indirection that reduces the scope of potential interference with the
      * source.  Since the supplier is only invoked after the terminal operation
@@ -352,20 +233,52 @@
      * @param supplier a {@code Supplier} of a {@code Spliterator.OfLong}
      * @param characteristics Spliterator characteristics of the supplied
      *        {@code Spliterator.OfLong}.  The characteristics must be equal to
-     *        {@code source.get().getCharacteristics()}
-     * @return a new sequential {@code LongStream}
-     * @see #longStream(Spliterator.OfLong)
+     *        {@code supplier.get().characteristics()}
+     * @param parallel if {@code true} then the returned stream is a parallel
+     *        stream; if {@code false} the returned stream is a sequential
+     *        stream.
+     * @return a new sequential or parallel {@code LongStream}
+     * @see #longStream(java.util.Spliterator.OfLong, boolean)
      */
     public static LongStream longStream(Supplier<? extends Spliterator.OfLong> supplier,
-                                        int characteristics) {
+                                        int characteristics,
+                                        boolean parallel) {
         return new LongPipeline.Head<>(supplier,
                                        StreamOpFlag.fromCharacteristics(characteristics),
-                                       false);
+                                       parallel);
     }
 
     /**
-     * Creates a new parallel {@code LongStream} from a {@code Supplier} of
-     * {@code Spliterator.OfLong}.
+     * Creates a new sequential or parallel {@code DoubleStream} from a
+     * {@code Spliterator.OfDouble}.
+     *
+     * <p>The spliterator is only traversed, split, or queried for estimated size
+     * after the terminal operation of the stream pipeline commences.
+     *
+     * <p>It is strongly recommended the spliterator report a characteristic of
+     * {@code IMMUTABLE} or {@code CONCURRENT}, or be
+     * <a href="../Spliterator.html#binding">late-binding</a>.  Otherwise,
+     * {@link #doubleStream(java.util.function.Supplier, int, boolean)} should
+     * be used to reduce the scope of potential interference with the source.  See
+     * <a href="package-summary.html#Non-Interference">Non-Interference</a> for
+     * more details.
+     *
+     * @param spliterator A {@code Spliterator.OfDouble} describing the stream elements
+     * @param parallel if {@code true} then the returned stream is a parallel
+     *        stream; if {@code false} the returned stream is a sequential
+     *        stream.
+     * @return a new sequential or parallel {@code DoubleStream}
+     */
+    public static DoubleStream doubleStream(Spliterator.OfDouble spliterator,
+                                            boolean parallel) {
+        return new DoublePipeline.Head<>(spliterator,
+                                         StreamOpFlag.fromCharacteristics(spliterator),
+                                         parallel);
+    }
+
+    /**
+     * Creates a new sequential or parallel {@code DoubleStream} from a
+     * {@code Supplier} of {@code Spliterator.OfDouble}.
      *
      * <p>The {@link Supplier#get()} method will be invoked on the supplier no
      * more than once, and after the terminal operation of the stream pipeline
@@ -374,89 +287,8 @@
      * <p>For spliterators that report a characteristic of {@code IMMUTABLE}
      * or {@code CONCURRENT}, or that are
      * <a href="../Spliterator.html#binding">late-binding</a>, it is likely
-     * more efficient to use {@link #longStream(Spliterator.OfLong)} instead.
-     * The use of a {@code Supplier} in this form provides a level of
-     * indirection that reduces the scope of potential interference with the
-     * source.  Since the supplier is only invoked after the terminal operation
-     * commences, any modifications to the source up to the start of the
-     * terminal operation are reflected in the stream result.  See
-     * <a href="package-summary.html#Non-Interference">Non-Interference</a> for
-     * more details.
-     *
-     * @param supplier A {@code Supplier} of a {@code Spliterator.OfLong}
-     * @param characteristics Spliterator characteristics of the supplied
-     *        {@code Spliterator.OfLong}.  The characteristics must be equal to
-     *        {@code source.get().getCharacteristics()}
-     * @return A new parallel {@code LongStream}
-     * @see #longParallelStream(Spliterator.OfLong)
-     */
-    public static LongStream longParallelStream(Supplier<? extends Spliterator.OfLong> supplier,
-                                                int characteristics) {
-        return new LongPipeline.Head<>(supplier,
-                                       StreamOpFlag.fromCharacteristics(characteristics),
-                                       true);
-    }
-
-    /**
-     * Creates a new sequential {@code DoubleStream} from a
-     * {@code Spliterator.OfDouble}.
-     *
-     * <p>The spliterator is only traversed, split, or queried for estimated size
-     * after the terminal operation of the stream pipeline commences.
-     *
-     * <p>It is strongly recommended the spliterator report a characteristic of
-     * {@code IMMUTABLE} or {@code CONCURRENT}, or be
-     * <a href="../Spliterator.html#binding">late-binding</a>.  Otherwise,
-     * {@link #stream(Supplier, int)} should be used to
-     * reduce the scope of potential interference with the source.  See
-     * <a href="package-summary.html#Non-Interference">Non-Interference</a> for
-     * more details.
-     *
-     * @param spliterator A {@code Spliterator.OfDouble} describing the stream elements
-     * @return A new sequential {@code DoubleStream}
-     */
-    public static DoubleStream doubleStream(Spliterator.OfDouble spliterator) {
-        return new DoublePipeline.Head<>(spliterator,
-                                         StreamOpFlag.fromCharacteristics(spliterator),
-                                         false);
-    }
-
-    /**
-     * Creates a new parallel {@code DoubleStream} from a
-     * {@code Spliterator.OfDouble}.
-     *
-     * <p>The spliterator is only traversed, split, or queried for estimated size
-     * after the terminal operation of the stream pipeline commences.
-     *
-     * <p>It is strongly recommended the spliterator report a characteristic of
-     * {@code IMMUTABLE} or {@code CONCURRENT}, or be
-     * <a href="../Spliterator.html#binding">late-binding</a>.  Otherwise,
-     * {@link #stream(Supplier, int)} should be used to
-     * reduce the scope of potential interference with the source.  See
-     * <a href="package-summary.html#Non-Interference">Non-Interference</a> for
-     * more details.
-     *
-     * @param spliterator A {@code Spliterator.OfDouble} describing the stream elements
-     * @return A new parallel {@code DoubleStream}
-     */
-    public static DoubleStream doubleParallelStream(Spliterator.OfDouble spliterator) {
-        return new DoublePipeline.Head<>(spliterator,
-                                         StreamOpFlag.fromCharacteristics(spliterator),
-                                         true);
-    }
-
-    /**
-     * Creates a new sequential {@code DoubleStream} from a {@code Supplier} of
-     * {@code Spliterator.OfDouble}.
-     * <p>
-     * The {@link Supplier#get()} method will be invoked on the supplier no
-     * more than once, and after the terminal operation of the stream pipeline
-     * commences.
-     * <p>
-     * For spliterators that report a characteristic of {@code IMMUTABLE}
-     * or {@code CONCURRENT}, or that are
-     * <a href="../Spliterator.html#binding">late-binding</a>, it is likely
-     * more efficient to use {@link #doubleStream(Spliterator.OfDouble)} instead.
+     * more efficient to use {@link #doubleStream(java.util.Spliterator.OfDouble, boolean)}
+     * instead.
      * The use of a {@code Supplier} in this form provides a level of
      * indirection that reduces the scope of potential interference with the
      * source.  Since the supplier is only invoked after the terminal operation
@@ -468,48 +300,18 @@
      * @param supplier A {@code Supplier} of a {@code Spliterator.OfDouble}
      * @param characteristics Spliterator characteristics of the supplied
      *        {@code Spliterator.OfDouble}.  The characteristics must be equal to
-     *        {@code source.get().getCharacteristics()}
-     * @return A new sequential {@code DoubleStream}
-     * @see #doubleStream(Spliterator.OfDouble)
+     *        {@code supplier.get().characteristics()}
+     * @param parallel if {@code true} then the returned stream is a parallel
+     *        stream; if {@code false} the returned stream is a sequential
+     *        stream.
+     * @return a new sequential or parallel {@code DoubleStream}
+     * @see #doubleStream(java.util.Spliterator.OfDouble, boolean)
      */
     public static DoubleStream doubleStream(Supplier<? extends Spliterator.OfDouble> supplier,
-                                            int characteristics) {
+                                            int characteristics,
+                                            boolean parallel) {
         return new DoublePipeline.Head<>(supplier,
                                          StreamOpFlag.fromCharacteristics(characteristics),
-                                         false);
-    }
-
-    /**
-     * Creates a new parallel {@code DoubleStream} from a {@code Supplier} of
-     * {@code Spliterator.OfDouble}.
-     *
-     * <p>The {@link Supplier#get()} method will be invoked on the supplier no
-     * more than once, and after the terminal operation of the stream pipeline
-     * commences.
-     *
-     * <p>For spliterators that report a characteristic of {@code IMMUTABLE}
-     * or {@code CONCURRENT}, or that are
-     * <a href="../Spliterator.html#binding">late-binding</a>, it is likely
-     * more efficient to use {@link #doubleStream(Spliterator.OfDouble)} instead.
-     * The use of a {@code Supplier} in this form provides a level of
-     * indirection that reduces the scope of potential interference with the
-     * source.  Since the supplier is only invoked after the terminal operation
-     * commences, any modifications to the source up to the start of the
-     * terminal operation are reflected in the stream result.  See
-     * <a href="package-summary.html#Non-Interference">Non-Interference</a> for
-     * more details.
-     *
-     * @param supplier a {@code Supplier} of a {@code Spliterator.OfDouble}
-     * @param characteristics Spliterator characteristics of the supplied
-     *        {@code Spliterator.OfDouble}.  The characteristics must be equal to
-     *        {@code source.get().getCharacteristics()}
-     * @return a new parallel {@code DoubleStream}
-     * @see #doubleParallelStream(Spliterator.OfDouble)
-     */
-    public static DoubleStream doubleParallelStream(Supplier<? extends Spliterator.OfDouble> supplier,
-                                                    int characteristics) {
-        return new DoublePipeline.Head<>(supplier,
-                                         StreamOpFlag.fromCharacteristics(characteristics),
-                                         true);
+                                         parallel);
     }
 }
--- a/src/share/classes/java/util/stream/Streams.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/stream/Streams.java	Mon Jul 22 17:37:15 2013 -0700
@@ -25,10 +25,7 @@
 package java.util.stream;
 
 import java.util.Comparator;
-import java.util.Objects;
 import java.util.Spliterator;
-import java.util.Spliterators;
-import java.util.function.BiFunction;
 import java.util.function.Consumer;
 import java.util.function.DoubleConsumer;
 import java.util.function.IntConsumer;
@@ -43,7 +40,7 @@
  *
  * @since 1.8
  */
-class Streams {
+final class Streams {
 
     private Streams() {
         throw new Error("no instances");
@@ -320,7 +317,7 @@
 
     static final class StreamBuilderImpl<T>
             extends AbstractStreamBuilderImpl<T, Spliterator<T>>
-            implements StreamBuilder<T> {
+            implements Stream.Builder<T> {
         // The first element in the stream
         // valid if count == 1
         T first;
@@ -366,7 +363,7 @@
             }
         }
 
-        public StreamBuilder<T> add(T t) {
+        public Stream.Builder<T> add(T t) {
             accept(t);
             return this;
         }
@@ -379,7 +376,7 @@
                 count = -count - 1;
                 // Use this spliterator if 0 or 1 elements, otherwise use
                 // the spliterator of the spined buffer
-                return (c < 2) ? StreamSupport.stream(this) : StreamSupport.stream(buffer.spliterator());
+                return (c < 2) ? StreamSupport.stream(this, false) : StreamSupport.stream(buffer.spliterator(), false);
             }
 
             throw new IllegalStateException();
@@ -412,7 +409,7 @@
 
     static final class IntStreamBuilderImpl
             extends AbstractStreamBuilderImpl<Integer, Spliterator.OfInt>
-            implements StreamBuilder.OfInt, Spliterator.OfInt {
+            implements IntStream.Builder, Spliterator.OfInt {
         // The first element in the stream
         // valid if count == 1
         int first;
@@ -466,7 +463,7 @@
                 count = -count - 1;
                 // Use this spliterator if 0 or 1 elements, otherwise use
                 // the spliterator of the spined buffer
-                return (c < 2) ? StreamSupport.intStream(this) : StreamSupport.intStream(buffer.spliterator());
+                return (c < 2) ? StreamSupport.intStream(this, false) : StreamSupport.intStream(buffer.spliterator(), false);
             }
 
             throw new IllegalStateException();
@@ -499,7 +496,7 @@
 
     static final class LongStreamBuilderImpl
             extends AbstractStreamBuilderImpl<Long, Spliterator.OfLong>
-            implements StreamBuilder.OfLong, Spliterator.OfLong {
+            implements LongStream.Builder, Spliterator.OfLong {
         // The first element in the stream
         // valid if count == 1
         long first;
@@ -553,7 +550,7 @@
                 count = -count - 1;
                 // Use this spliterator if 0 or 1 elements, otherwise use
                 // the spliterator of the spined buffer
-                return (c < 2) ? StreamSupport.longStream(this) : StreamSupport.longStream(buffer.spliterator());
+                return (c < 2) ? StreamSupport.longStream(this, false) : StreamSupport.longStream(buffer.spliterator(), false);
             }
 
             throw new IllegalStateException();
@@ -586,7 +583,7 @@
 
     static final class DoubleStreamBuilderImpl
             extends AbstractStreamBuilderImpl<Double, Spliterator.OfDouble>
-            implements StreamBuilder.OfDouble, Spliterator.OfDouble {
+            implements DoubleStream.Builder, Spliterator.OfDouble {
         // The first element in the stream
         // valid if count == 1
         double first;
@@ -640,7 +637,7 @@
                 count = -count - 1;
                 // Use this spliterator if 0 or 1 elements, otherwise use
                 // the spliterator of the spined buffer
-                return (c < 2) ? StreamSupport.doubleStream(this) : StreamSupport.doubleStream(buffer.spliterator());
+                return (c < 2) ? StreamSupport.doubleStream(this, false) : StreamSupport.doubleStream(buffer.spliterator(), false);
             }
 
             throw new IllegalStateException();
@@ -670,4 +667,147 @@
             }
         }
     }
+
+    abstract static class ConcatSpliterator<T, T_SPLITR extends Spliterator<T>>
+            implements Spliterator<T> {
+        protected final T_SPLITR aSpliterator;
+        protected final T_SPLITR bSpliterator;
+        // True when no split has occurred, otherwise false
+        boolean beforeSplit;
+        // Never read after splitting
+        final boolean unsized;
+
+        public ConcatSpliterator(T_SPLITR aSpliterator, T_SPLITR bSpliterator) {
+            this.aSpliterator = aSpliterator;
+            this.bSpliterator = bSpliterator;
+            beforeSplit = true;
+            // The spliterator is unsized before splitting if a and b are
+            // sized and the sum of the estimates overflows
+            unsized = aSpliterator.hasCharacteristics(SIZED)
+                      && aSpliterator.hasCharacteristics(SIZED)
+                      && aSpliterator.estimateSize() + bSpliterator.estimateSize() < 0;
+        }
+
+        @Override
+        public T_SPLITR trySplit() {
+            T_SPLITR ret = beforeSplit ? aSpliterator : (T_SPLITR) bSpliterator.trySplit();
+            beforeSplit = false;
+            return ret;
+        }
+
+        @Override
+        public boolean tryAdvance(Consumer<? super T> consumer) {
+            boolean hasNext;
+            if (beforeSplit) {
+                hasNext = aSpliterator.tryAdvance(consumer);
+                if (!hasNext) {
+                    beforeSplit = false;
+                    hasNext = bSpliterator.tryAdvance(consumer);
+                }
+            }
+            else
+                hasNext = bSpliterator.tryAdvance(consumer);
+            return hasNext;
+        }
+
+        @Override
+        public void forEachRemaining(Consumer<? super T> consumer) {
+            if (beforeSplit)
+                aSpliterator.forEachRemaining(consumer);
+            bSpliterator.forEachRemaining(consumer);
+        }
+
+        @Override
+        public long estimateSize() {
+            if (beforeSplit) {
+                // If one or both estimates are Long.MAX_VALUE then the sum
+                // will either be Long.MAX_VALUE or overflow to a negative value
+                long size = aSpliterator.estimateSize() + bSpliterator.estimateSize();
+                return (size >= 0) ? size : Long.MAX_VALUE;
+            }
+            else {
+                return bSpliterator.estimateSize();
+            }
+        }
+
+        @Override
+        public int characteristics() {
+            if (beforeSplit) {
+                // Concatenation loses DISTINCT and SORTED characteristics
+                return aSpliterator.characteristics() & bSpliterator.characteristics()
+                       & ~(Spliterator.DISTINCT | Spliterator.SORTED
+                           | (unsized ? Spliterator.SIZED | Spliterator.SUBSIZED : 0));
+            }
+            else {
+                return bSpliterator.characteristics();
+            }
+        }
+
+        @Override
+        public Comparator<? super T> getComparator() {
+            if (beforeSplit)
+                throw new IllegalStateException();
+            return bSpliterator.getComparator();
+        }
+
+        static class OfRef<T> extends ConcatSpliterator<T, Spliterator<T>> {
+            OfRef(Spliterator<T> aSpliterator, Spliterator<T> bSpliterator) {
+                super(aSpliterator, bSpliterator);
+            }
+        }
+
+        private static abstract class OfPrimitive<T, T_CONS, T_SPLITR extends Spliterator.OfPrimitive<T, T_CONS, T_SPLITR>>
+                extends ConcatSpliterator<T, T_SPLITR>
+                implements Spliterator.OfPrimitive<T, T_CONS, T_SPLITR> {
+            private OfPrimitive(T_SPLITR aSpliterator, T_SPLITR bSpliterator) {
+                super(aSpliterator, bSpliterator);
+            }
+
+            @Override
+            public boolean tryAdvance(T_CONS action) {
+                boolean hasNext;
+                if (beforeSplit) {
+                    hasNext = aSpliterator.tryAdvance(action);
+                    if (!hasNext) {
+                        beforeSplit = false;
+                        hasNext = bSpliterator.tryAdvance(action);
+                    }
+                }
+                else
+                    hasNext = bSpliterator.tryAdvance(action);
+                return hasNext;
+            }
+
+            @Override
+            public void forEachRemaining(T_CONS action) {
+                if (beforeSplit)
+                    aSpliterator.forEachRemaining(action);
+                bSpliterator.forEachRemaining(action);
+            }
+        }
+
+        static class OfInt
+                extends ConcatSpliterator.OfPrimitive<Integer, IntConsumer, Spliterator.OfInt>
+                implements Spliterator.OfInt {
+            OfInt(Spliterator.OfInt aSpliterator, Spliterator.OfInt bSpliterator) {
+                super(aSpliterator, bSpliterator);
+            }
+        }
+
+        static class OfLong
+                extends ConcatSpliterator.OfPrimitive<Long, LongConsumer, Spliterator.OfLong>
+                implements Spliterator.OfLong {
+            OfLong(Spliterator.OfLong aSpliterator, Spliterator.OfLong bSpliterator) {
+                super(aSpliterator, bSpliterator);
+            }
+        }
+
+        static class OfDouble
+                extends ConcatSpliterator.OfPrimitive<Double, DoubleConsumer, Spliterator.OfDouble>
+                implements Spliterator.OfDouble {
+            OfDouble(Spliterator.OfDouble aSpliterator, Spliterator.OfDouble bSpliterator) {
+                super(aSpliterator, bSpliterator);
+            }
+        }
+    }
 }
--- a/src/share/classes/java/util/zip/ZipFile.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/java/util/zip/ZipFile.java	Mon Jul 22 17:37:15 2013 -0700
@@ -551,7 +551,7 @@
         return StreamSupport.stream(Spliterators.spliterator(
                 new ZipEntryIterator(), size(),
                 Spliterator.ORDERED | Spliterator.DISTINCT |
-                        Spliterator.IMMUTABLE | Spliterator.NONNULL));
+                        Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
     }
 
     private ZipEntry getZipEntry(String name, long jzentry) {
--- a/src/share/classes/javax/accessibility/AccessibleAction.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/accessibility/AccessibleAction.java	Mon Jul 22 17:37:15 2013 -0700
@@ -54,7 +54,7 @@
      * @since 1.5
      */
     public static final String TOGGLE_EXPAND =
-        new String ("toggle expand");
+        new String ("toggleexpand");
 
     /**
      * An action which increments a value.
--- a/src/share/classes/javax/crypto/Cipher.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/crypto/Cipher.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1135,7 +1135,7 @@
      *
      * <p>If this cipher (including its underlying feedback or padding scheme)
      * requires any random bytes (e.g., for parameter generation), it will get
-     * them using the {@link SecureRandom <code>SecureRandom</code>}
+     * them using the {@link java.security.SecureRandom}
      * implementation of the highest-priority
      * installed provider as the source of randomness.
      * (If none of the installed providers supply an implementation of
@@ -1263,7 +1263,7 @@
      *
      * <p>If this cipher (including its underlying feedback or padding scheme)
      * requires any random bytes (e.g., for parameter generation), it will get
-     * them using the {@link SecureRandom <code>SecureRandom</code>}
+     * them using the {@link java.security.SecureRandom}
      * implementation of the highest-priority
      * installed provider as the source of randomness.
      * (If none of the installed providers supply an implementation of
@@ -1400,7 +1400,7 @@
      *
      * <p>If this cipher (including its underlying feedback or padding scheme)
      * requires any random bytes (e.g., for parameter generation), it will get
-     * them using the {@link SecureRandom <code>SecureRandom</code>}
+     * them using the {@link java.security.SecureRandom}
      * implementation of the highest-priority
      * installed provider as the source of randomness.
      * (If none of the installed providers supply an implementation of
--- a/src/share/classes/javax/crypto/CipherInputStream.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/crypto/CipherInputStream.java	Mon Jul 22 17:37:15 2013 -0700
@@ -245,7 +245,7 @@
      * <p>Fewer bytes than requested might be skipped.
      * The actual number of bytes skipped is equal to <code>n</code> or
      * the result of a call to
-     * {@link #available() <code>available</code>},
+     * {@link #available() available},
      * whichever is smaller.
      * If <code>n</code> is less than zero, no bytes are skipped.
      *
@@ -303,7 +303,9 @@
         input.close();
         try {
             // throw away the unprocessed data
-            cipher.doFinal();
+            if (!done) {
+                cipher.doFinal();
+            }
         }
         catch (BadPaddingException | IllegalBlockSizeException ex) {
         }
--- a/src/share/classes/javax/crypto/ExemptionMechanism.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/crypto/ExemptionMechanism.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -116,7 +116,7 @@
      * mechanism.
      * See the ExemptionMechanism section in the
      * <a href=
-     *   "{docRoot}/../technotes/guides/security/StandardNames.html#Exemption">
+     *   "{@docRoot}/../technotes/guides/security/StandardNames.html#Exemption">
      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
      * for information about standard exemption mechanism names.
      *
@@ -155,7 +155,7 @@
      * @param algorithm the standard name of the requested exemption mechanism.
      * See the ExemptionMechanism section in the
      * <a href=
-     *   "{docRoot}/../technotes/guides/security/StandardNames.html#Exemption">
+     *   "{@docRoot}/../technotes/guides/security/StandardNames.html#Exemption">
      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
      * for information about standard exemption mechanism names.
      *
@@ -199,7 +199,7 @@
      * @param algorithm the standard name of the requested exemption mechanism.
      * See the ExemptionMechanism section in the
      * <a href=
-     *   "{docRoot}/../technotes/guides/security/StandardNames.html#Exemption">
+     *   "{@docRoot}/../technotes/guides/security/StandardNames.html#Exemption">
      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
      * for information about standard exemption mechanism names.
      *
--- a/src/share/classes/javax/crypto/KeyAgreement.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/crypto/KeyAgreement.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -149,7 +149,7 @@
      * algorithm.
      * See the KeyAgreement section in the <a href=
      * "{@docRoot}/../technotes/guides/security/StandardNames.html#KeyAgreement">
-     * Java Cryptography Architecture Standard Algorithm Name Documentation
+     * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
      * for information about standard algorithm names.
      *
      * @return the new <code>KeyAgreement</code> object.
@@ -196,7 +196,7 @@
      * algorithm.
      * See the KeyAgreement section in the <a href=
      * "{@docRoot}/../technotes/guides/security/StandardNames.html#KeyAgreement">
-     * Java Cryptography Architecture Standard Algorithm Name Documentation
+     * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
      * for information about standard algorithm names.
      *
      * @param provider the name of the provider.
@@ -240,7 +240,7 @@
      * algorithm.
      * See the KeyAgreement section in the <a href=
      * "{@docRoot}/../technotes/guides/security/StandardNames.html#KeyAgreement">
-     * Java Cryptography Architecture Standard Algorithm Name Documentation
+     * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
      * for information about standard algorithm names.
      *
      * @param provider the provider.
@@ -418,7 +418,7 @@
      *
      * <p> If this key agreement requires any random bytes, it will get
      * them using the
-     * {@link SecureRandom <code>SecureRandom</code>}
+     * {@link java.security.SecureRandom}
      * implementation of the highest-priority
      * installed provider as the source of randomness.
      * (If none of the installed providers supply an implementation of
@@ -476,7 +476,7 @@
      *
      * <p> If this key agreement requires any random bytes, it will get
      * them using the
-     * {@link SecureRandom <code>SecureRandom</code>}
+     * {@link java.security.SecureRandom}
      * implementation of the highest-priority
      * installed provider as the source of randomness.
      * (If none of the installed providers supply an implementation of
--- a/src/share/classes/javax/crypto/KeyGenerator.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/crypto/KeyGenerator.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -398,7 +398,7 @@
      *
      * <p> If this key generator requires any random bytes, it will get them
      * using the
-     * {@link SecureRandom <code>SecureRandom</code>}
+     * {@link java.security.SecureRandom}
      * implementation of the highest-priority installed
      * provider as the source of randomness.
      * (If none of the installed providers supply an implementation of
@@ -463,7 +463,7 @@
      *
      * <p> If this key generator requires any random bytes, it will get them
      * using the
-     * {@link SecureRandom <code>SecureRandom</code>}
+     * {@link java.security.SecureRandom}
      * implementation of the highest-priority installed
      * provider as the source of randomness.
      * (If none of the installed providers supply an implementation of
--- a/src/share/classes/javax/crypto/NullCipher.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/crypto/NullCipher.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -38,6 +38,9 @@
 
 public class NullCipher extends Cipher {
 
+    /**
+     * Creates a NullCipher object.
+     */
     public NullCipher() {
         super(new NullCipherSpi(), null);
     }
--- a/src/share/classes/javax/management/JMX.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/management/JMX.java	Mon Jul 22 17:37:15 2013 -0700
@@ -160,6 +160,10 @@
      * example, then the return type is {@code MyMBean}.
      *
      * @return the new proxy instance.
+     *
+     * @throws IllegalArgumentException if {@code interfaceClass} is not
+     * a <a href="package-summary.html#mgIface">compliant MBean
+     * interface</a>
      */
     public static <T> T newMBeanProxy(MBeanServerConnection connection,
                                       ObjectName objectName,
@@ -200,6 +204,10 @@
      * example, then the return type is {@code MyMBean}.
      *
      * @return the new proxy instance.
+     *
+     * @throws IllegalArgumentException if {@code interfaceClass} is not
+     * a <a href="package-summary.html#mgIface">compliant MBean
+     * interface</a>
      */
     public static <T> T newMBeanProxy(MBeanServerConnection connection,
                                       ObjectName objectName,
@@ -298,6 +306,9 @@
      * example, then the return type is {@code MyMXBean}.
      *
      * @return the new proxy instance.
+     *
+     * @throws IllegalArgumentException if {@code interfaceClass} is not
+     * a {@link javax.management.MXBean compliant MXBean interface}
      */
     public static <T> T newMXBeanProxy(MBeanServerConnection connection,
                                        ObjectName objectName,
@@ -338,6 +349,9 @@
      * example, then the return type is {@code MyMXBean}.
      *
      * @return the new proxy instance.
+     *
+     * @throws IllegalArgumentException if {@code interfaceClass} is not
+     * a {@link javax.management.MXBean compliant MXBean interface}
      */
     public static <T> T newMXBeanProxy(MBeanServerConnection connection,
                                        ObjectName objectName,
@@ -348,21 +362,25 @@
 
     /**
      * <p>Test whether an interface is an MXBean interface.
-     * An interface is an MXBean interface if it is annotated
-     * {@link MXBean &#64;MXBean} or {@code @MXBean(true)}
+     * An interface is an MXBean interface if it is public,
+     * annotated {@link MXBean &#64;MXBean} or {@code @MXBean(true)}
      * or if it does not have an {@code @MXBean} annotation
      * and its name ends with "{@code MXBean}".</p>
      *
      * @param interfaceClass The candidate interface.
      *
-     * @return true if {@code interfaceClass} is an interface and
-     * meets the conditions described.
+     * @return true if {@code interfaceClass} is a
+     * {@link javax.management.MXBean compliant MXBean interface}
      *
      * @throws NullPointerException if {@code interfaceClass} is null.
      */
     public static boolean isMXBeanInterface(Class<?> interfaceClass) {
         if (!interfaceClass.isInterface())
             return false;
+        if (!Modifier.isPublic(interfaceClass.getModifiers()) &&
+            !Introspector.ALLOW_NONPUBLIC_MBEAN) {
+            return false;
+        }
         MXBean a = interfaceClass.getAnnotation(MXBean.class);
         if (a != null)
             return a.value();
@@ -389,9 +407,6 @@
                                      boolean notificationEmitter,
                                      boolean isMXBean) {
 
-        if (System.getSecurityManager() != null) {
-            checkProxyInterface(interfaceClass);
-        }
         try {
             if (isMXBean) {
                 // Check interface for MXBean compliance
@@ -419,17 +434,4 @@
                 handler);
         return interfaceClass.cast(proxy);
     }
-
-    /**
-     * Checks for the M(X)Bean proxy interface being public and not restricted
-     * @param interfaceClass MBean proxy interface
-     * @throws SecurityException when the proxy interface comes from a restricted
-     *                           package or is not public
-     */
-    private static void checkProxyInterface(Class<?> interfaceClass) {
-        if (!Modifier.isPublic(interfaceClass.getModifiers())) {
-            throw new SecurityException("mbean proxy interface non-public");
-        }
-        ReflectUtil.checkPackageAccess(interfaceClass);
-    }
 }
--- a/src/share/classes/javax/management/MBeanServerInvocationHandler.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/management/MBeanServerInvocationHandler.java	Mon Jul 22 17:37:15 2013 -0700
@@ -225,7 +225,7 @@
      *
      * @return the new proxy instance.
      *
-     * @see JMX#newMBeanProxy(MBeanServerConnection, ObjectName, Class)
+     * @see JMX#newMBeanProxy(MBeanServerConnection, ObjectName, Class, boolean)
      */
     public static <T> T newProxyInstance(MBeanServerConnection connection,
                                          ObjectName objectName,
--- a/src/share/classes/javax/management/MXBean.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/management/MXBean.java	Mon Jul 22 17:37:15 2013 -0700
@@ -54,9 +54,9 @@
 /**
     <p>Annotation to mark an interface explicitly as being an MXBean
     interface, or as not being an MXBean interface.  By default, an
-    interface is an MXBean interface if its name ends with {@code
-    MXBean}, as in {@code SomethingMXBean}.  The following interfaces
-    are MXBean interfaces:</p>
+    interface is an MXBean interface if it is public and its name ends
+    with {@code MXBean}, as in {@code SomethingMXBean}.  The following
+    interfaces are MXBean interfaces:</p>
 
     <pre>
     public interface WhatsitMXBean {}
@@ -71,6 +71,8 @@
     <p>The following interfaces are not MXBean interfaces:</p>
 
     <pre>
+    interface NonPublicInterfaceNotMXBean{}
+
     public interface Whatsit3Interface{}
 
     &#64;MXBean(false)
--- a/src/share/classes/javax/management/package.html	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/management/package.html	Mon Jul 22 17:37:15 2013 -0700
@@ -53,8 +53,8 @@
 
         <p>The fundamental notion of the JMX API is the <em>MBean</em>.
             An MBean is a named <em>managed object</em> representing a
-            resource.  It has a <em>management interface</em> consisting
-        of:</p>
+            resource.  It has a <em id="mgIface">management interface</em>
+            which must be <em>public</em> and consist of:</p>
 
         <ul>
             <li>named and typed attributes that can be read and/or
--- a/src/share/classes/javax/script/ScriptEngineFactory.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/script/ScriptEngineFactory.java	Mon Jul 22 17:37:15 2013 -0700
@@ -196,18 +196,17 @@
 
 
     /**
-     * Returns A valid scripting language executable progam with given statements.
+     * Returns a valid scripting language executable progam with given statements.
      * For instance an implementation for a PHP engine might be:
      * <p>
      * <pre>{@code
      * public String getProgram(String... statements) {
-     *      $retval = "<?\n";
+     *      String retval = "<?\n";
      *      int len = statements.length;
      *      for (int i = 0; i < len; i++) {
-     *          $retval += statements[i] + ";\n";
+     *          retval += statements[i] + ";\n";
      *      }
-     *      $retval += "?>";
-     *
+     *      return retval += "?>";
      * }
      * }</pre>
      *
--- a/src/share/classes/javax/security/auth/AuthPermission.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/AuthPermission.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -41,10 +41,10 @@
  *
  * <pre>
  *      doAs -                  allow the caller to invoke the
- *                              <code>Subject.doAs</code> methods.
+ *                              {@code Subject.doAs} methods.
  *
  *      doAsPrivileged -        allow the caller to invoke the
- *                              <code>Subject.doAsPrivileged</code> methods.
+ *                              {@code Subject.doAsPrivileged} methods.
  *
  *      getSubject -            allow for the retrieval of the
  *                              Subject(s) associated with the
@@ -52,39 +52,39 @@
  *
  *      getSubjectFromDomainCombiner -  allow for the retrieval of the
  *                              Subject associated with the
- *                              a <code>SubjectDomainCombiner</code>.
+ *                              a {@code SubjectDomainCombiner}.
  *
  *      setReadOnly -           allow the caller to set a Subject
  *                              to be read-only.
  *
- *      modifyPrincipals -      allow the caller to modify the <code>Set</code>
+ *      modifyPrincipals -      allow the caller to modify the {@code Set}
  *                              of Principals associated with a
- *                              <code>Subject</code>
+ *                              {@code Subject}
  *
  *      modifyPublicCredentials - allow the caller to modify the
- *                              <code>Set</code> of public credentials
- *                              associated with a <code>Subject</code>
+ *                              {@code Set} of public credentials
+ *                              associated with a {@code Subject}
  *
  *      modifyPrivateCredentials - allow the caller to modify the
- *                              <code>Set</code> of private credentials
- *                              associated with a <code>Subject</code>
+ *                              {@code Set} of private credentials
+ *                              associated with a {@code Subject}
  *
- *      refreshCredential -     allow code to invoke the <code>refresh</code>
+ *      refreshCredential -     allow code to invoke the {@code refresh}
  *                              method on a credential which implements
- *                              the <code>Refreshable</code> interface.
+ *                              the {@code Refreshable} interface.
  *
- *      destroyCredential -     allow code to invoke the <code>destroy</code>
- *                              method on a credential <code>object</code>
- *                              which implements the <code>Destroyable</code>
+ *      destroyCredential -     allow code to invoke the {@code destroy}
+ *                              method on a credential {@code object}
+ *                              which implements the {@code Destroyable}
  *                              interface.
  *
  *      createLoginContext.{name} -  allow code to instantiate a
- *                              <code>LoginContext</code> with the
+ *                              {@code LoginContext} with the
  *                              specified <i>name</i>.  <i>name</i>
  *                              is used as the index into the installed login
- *                              <code>Configuration</code>
+ *                              {@code Configuration}
  *                              (that returned by
- *                              <code>Configuration.getConfiguration()</code>).
+ *                              {@code Configuration.getConfiguration()}).
  *                              <i>name</i> can be wildcarded (set to '*')
  *                              to allow for any name.
  *
@@ -93,7 +93,7 @@
  *
  *      createLoginConfiguration.{type} - allow code to obtain a Configuration
  *                              object via
- *                              <code>Configuration.getInstance</code>.
+ *                              {@code Configuration.getInstance}.
  *
  *      setLoginConfiguration - allow for the setting of the system-wide
  *                              login Configuration.
@@ -103,15 +103,15 @@
  * </pre>
  *
  * <p> The following target name has been deprecated in favor of
- * <code>createLoginContext.{name}</code>.
+ * {@code createLoginContext.{name}}.
  *
  * <pre>
  *      createLoginContext -    allow code to instantiate a
- *                              <code>LoginContext</code>.
+ *                              {@code LoginContext}.
  * </pre>
  *
- * <p> <code>javax.security.auth.Policy</code> has been
- * deprecated in favor of <code>java.security.Policy</code>.
+ * <p> {@code javax.security.auth.Policy} has been
+ * deprecated in favor of {@code java.security.Policy}.
  * Therefore, the following target names have also been deprecated:
  *
  * <pre>
@@ -139,8 +139,8 @@
      *
      * @param name the name of the AuthPermission
      *
-     * @throws NullPointerException if <code>name</code> is <code>null</code>.
-     * @throws IllegalArgumentException if <code>name</code> is empty.
+     * @throws NullPointerException if {@code name} is {@code null}.
+     * @throws IllegalArgumentException if {@code name} is empty.
      */
     public AuthPermission(String name) {
         // for backwards compatibility --
@@ -160,8 +160,8 @@
      *
      * @param actions should be null.
      *
-     * @throws NullPointerException if <code>name</code> is <code>null</code>.
-     * @throws IllegalArgumentException if <code>name</code> is empty.
+     * @throws NullPointerException if {@code name} is {@code null}.
+     * @throws IllegalArgumentException if {@code name} is empty.
      */
     public AuthPermission(String name, String actions) {
         // for backwards compatibility --
--- a/src/share/classes/javax/security/auth/DestroyFailedException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/DestroyFailedException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,10 @@
 package javax.security.auth;
 
 /**
- * Signals that a <code>destroy</code> operation failed.
+ * Signals that a {@code destroy} operation failed.
  *
  * <p> This exception is thrown by credentials implementing
- * the <code>Destroyable</code> interface when the <code>destroy</code>
+ * the {@code Destroyable} interface when the {@code destroy}
  * method fails.
  *
  */
--- a/src/share/classes/javax/security/auth/Destroyable.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/Destroyable.java	Mon Jul 22 17:37:15 2013 -0700
@@ -34,12 +34,12 @@
 public interface Destroyable {
 
     /**
-     * Destroy this <code>Object</code>.
+     * Destroy this {@code Object}.
      *
-     * <p> Sensitive information associated with this <code>Object</code>
+     * <p> Sensitive information associated with this {@code Object}
      * is destroyed or cleared.  Subsequent calls to certain methods
-     * on this <code>Object</code> will result in an
-     * <code>IllegalStateException</code> being thrown.
+     * on this {@code Object} will result in an
+     * {@code IllegalStateException} being thrown.
      *
      * <p>
      * The default implementation throws {@code DestroyFailedException}.
@@ -47,19 +47,19 @@
      * @exception DestroyFailedException if the destroy operation fails. <p>
      *
      * @exception SecurityException if the caller does not have permission
-     *          to destroy this <code>Object</code>.
+     *          to destroy this {@code Object}.
      */
     public default void destroy() throws DestroyFailedException {
         throw new DestroyFailedException();
     }
 
     /**
-     * Determine if this <code>Object</code> has been destroyed.
+     * Determine if this {@code Object} has been destroyed.
      *
      * <p>
      * The default implementation returns false.
      *
-     * @return true if this <code>Object</code> has been destroyed,
+     * @return true if this {@code Object} has been destroyed,
      *          false otherwise.
      */
     public default boolean isDestroyed() {
--- a/src/share/classes/javax/security/auth/Policy.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/Policy.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,11 +32,11 @@
  * <p> This is an abstract class for representing the system policy for
  * Subject-based authorization.  A subclass implementation
  * of this class provides a means to specify a Subject-based
- * access control <code>Policy</code>.
+ * access control {@code Policy}.
  *
- * <p> A <code>Policy</code> object can be queried for the set of
+ * <p> A {@code Policy} object can be queried for the set of
  * Permissions granted to code running as a
- * <code>Principal</code> in the following manner:
+ * {@code Principal} in the following manner:
  *
  * <pre>
  *      policy = Policy.getPolicy();
@@ -44,20 +44,20 @@
  *                                                      codeSource);
  * </pre>
  *
- * The <code>Policy</code> object consults the local policy and returns
- * and appropriate <code>Permissions</code> object with the
+ * The {@code Policy} object consults the local policy and returns
+ * and appropriate {@code Permissions} object with the
  * Permissions granted to the Principals associated with the
  * provided <i>subject</i>, and granted to the code specified
  * by the provided <i>codeSource</i>.
  *
- * <p> A <code>Policy</code> contains the following information.
+ * <p> A {@code Policy} contains the following information.
  * Note that this example only represents the syntax for the default
- * <code>Policy</code> implementation. Subclass implementations of this class
+ * {@code Policy} implementation. Subclass implementations of this class
  * may implement alternative syntaxes and may retrieve the
- * <code>Policy</code> from any source such as files, databases,
+ * {@code Policy} from any source such as files, databases,
  * or servers.
  *
- * <p> Each entry in the <code>Policy</code> is represented as
+ * <p> Each entry in the {@code Policy} is represented as
  * a <b><i>grant</i></b> entry.  Each <b><i>grant</i></b> entry
  * specifies a codebase, code signers, and Principals triplet,
  * as well as the Permissions granted to that triplet.
@@ -84,23 +84,23 @@
  * </pre>
  *
  * This <b><i>grant</i></b> entry specifies that code from "foo.com",
- * signed by "foo', and running as a <code>SolarisPrincipal</code> with the
- * name, duke, has one <code>Permission</code>.  This <code>Permission</code>
+ * signed by "foo', and running as a {@code SolarisPrincipal} with the
+ * name, duke, has one {@code Permission}.  This {@code Permission}
  * permits the executing code to read and write files in the directory,
  * "/home/duke".
  *
- * <p> To "run" as a particular <code>Principal</code>,
- * code invokes the <code>Subject.doAs(subject, ...)</code> method.
+ * <p> To "run" as a particular {@code Principal},
+ * code invokes the {@code Subject.doAs(subject, ...)} method.
  * After invoking that method, the code runs as all the Principals
- * associated with the specified <code>Subject</code>.
- * Note that this <code>Policy</code> (and the Permissions
- * granted in this <code>Policy</code>) only become effective
- * after the call to <code>Subject.doAs</code> has occurred.
+ * associated with the specified {@code Subject}.
+ * Note that this {@code Policy} (and the Permissions
+ * granted in this {@code Policy}) only become effective
+ * after the call to {@code Subject.doAs} has occurred.
  *
  * <p> Multiple Principals may be listed within one <b><i>grant</i></b> entry.
  * All the Principals in the grant entry must be associated with
- * the <code>Subject</code> provided to <code>Subject.doAs</code>
- * for that <code>Subject</code> to be granted the specified Permissions.
+ * the {@code Subject} provided to {@code Subject.doAs}
+ * for that {@code Subject} to be granted the specified Permissions.
  *
  * <pre>
  *      grant Principal com.sun.security.auth.SolarisPrincipal "duke",
@@ -115,7 +115,7 @@
  * as well as permission to make socket connections to "duke.com".
  *
  * <p> Note that non Principal-based grant entries are not permitted
- * in this <code>Policy</code>.  Therefore, grant entries such as:
+ * in this {@code Policy}.  Therefore, grant entries such as:
  *
  * <pre>
  *      grant CodeBase "foo.com", Signedby "foo" {
@@ -124,7 +124,7 @@
  * </pre>
  *
  * are rejected.  Such permission must be listed in the
- * <code>java.security.Policy</code>.
+ * {@code java.security.Policy}.
  *
  * <p> The default {@code Policy} implementation can be changed by
  * setting the value of the {@code auth.policy.provider} security property to
@@ -179,14 +179,14 @@
     /**
      * Returns the installed Policy object.
      * This method first calls
-     * <code>SecurityManager.checkPermission</code> with the
-     * <code>AuthPermission("getPolicy")</code> permission
+     * {@code SecurityManager.checkPermission} with the
+     * {@code AuthPermission("getPolicy")} permission
      * to ensure the caller has permission to get the Policy object.
      *
      * <p>
      *
      * @return the installed Policy.  The return value cannot be
-     *          <code>null</code>.
+     *          {@code null}.
      *
      * @exception java.lang.SecurityException if the current thread does not
      *      have permission to get the Policy object.
@@ -252,8 +252,8 @@
 
     /**
      * Sets the system-wide Policy object. This method first calls
-     * <code>SecurityManager.checkPermission</code> with the
-     * <code>AuthPermission("setPolicy")</code>
+     * {@code SecurityManager.checkPermission} with the
+     * {@code AuthPermission("setPolicy")}
      * permission to ensure the caller has permission to set the Policy.
      *
      * <p>
@@ -313,25 +313,25 @@
 
     /**
      * Retrieve the Permissions granted to the Principals associated with
-     * the specified <code>CodeSource</code>.
+     * the specified {@code CodeSource}.
      *
      * <p>
      *
-     * @param subject the <code>Subject</code>
+     * @param subject the {@code Subject}
      *                  whose associated Principals,
      *                  in conjunction with the provided
-     *                  <code>CodeSource</code>, determines the Permissions
+     *                  {@code CodeSource}, determines the Permissions
      *                  returned by this method.  This parameter
-     *                  may be <code>null</code>. <p>
+     *                  may be {@code null}. <p>
      *
-     * @param cs the code specified by its <code>CodeSource</code>
+     * @param cs the code specified by its {@code CodeSource}
      *                  that determines, in conjunction with the provided
-     *                  <code>Subject</code>, the Permissions
+     *                  {@code Subject}, the Permissions
      *                  returned by this method.  This parameter may be
-     *                  <code>null</code>.
+     *                  {@code null}.
      *
      * @return the Collection of Permissions granted to all the
-     *                  <code>Subject</code> and code specified in
+     *                  {@code Subject} and code specified in
      *                  the provided <i>subject</i> and <i>cs</i>
      *                  parameters.
      */
@@ -345,7 +345,7 @@
      * <p>This method causes this object to refresh/reload its current
      * Policy. This is implementation-dependent.
      * For example, if the Policy object is stored in
-     * a file, calling <code>refresh</code> will cause the file to be re-read.
+     * a file, calling {@code refresh} will cause the file to be re-read.
      *
      * <p>
      *
--- a/src/share/classes/javax/security/auth/PrivateCredentialPermission.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/PrivateCredentialPermission.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,10 +34,10 @@
 
 /**
  * This class is used to protect access to private Credentials
- * belonging to a particular <code>Subject</code>.  The <code>Subject</code>
+ * belonging to a particular {@code Subject}.  The {@code Subject}
  * is represented by a Set of Principals.
  *
- * <p> The target name of this <code>Permission</code> specifies
+ * <p> The target name of this {@code Permission} specifies
  * a Credential class name, and a Set of Principals.
  * The only valid value for this Permission's actions is, "read".
  * The target name must abide by the following syntax:
@@ -65,12 +65,12 @@
  *
  * If CredentialClass is "*", then access is granted to
  * all private Credentials belonging to the specified
- * <code>Subject</code>.
+ * {@code Subject}.
  * If "PrincipalName" is "*", then access is granted to the
- * specified Credential owned by any <code>Subject</code> that has the
- * specified <code>Principal</code> (the actual PrincipalName doesn't matter).
+ * specified Credential owned by any {@code Subject} that has the
+ * specified {@code Principal} (the actual PrincipalName doesn't matter).
  * For example, the following grants access to the
- * a.b.Credential owned by any <code>Subject</code> that has
+ * a.b.Credential owned by any {@code Subject} that has
  * an a.b.Principal.
  *
  * <pre>
@@ -83,7 +83,7 @@
  *
  * If both the PrincipalClass and "PrincipalName" are "*",
  * then access is granted to the specified Credential owned by
- * any <code>Subject</code>.
+ * any {@code Subject}.
  *
  * <p> In addition, the PrincipalClass/PrincipalName pairing may be repeated:
  *
@@ -96,7 +96,7 @@
  * </pre>
  *
  * The above grants access to the private Credential, "a.b.Credential",
- * belonging to a <code>Subject</code> with at least two associated Principals:
+ * belonging to a {@code Subject} with at least two associated Principals:
  * "a.b.Principal" with the name, "duke", and "c.d.Principal", with the name,
  * "dukette".
  *
@@ -115,7 +115,7 @@
     /**
      * @serial The Principals associated with this permission.
      *          The set contains elements of type,
-     *          <code>PrivateCredentialPermission.CredOwner</code>.
+     *          {@code PrivateCredentialPermission.CredOwner}.
      */
     private Set<Principal> principals;  // ignored - kept around for compatibility
     private transient CredOwner[] credOwners;
@@ -126,8 +126,8 @@
     private boolean testing = false;
 
     /**
-     * Create a new <code>PrivateCredentialPermission</code>
-     * with the specified <code>credentialClass</code> and Principals.
+     * Create a new {@code PrivateCredentialPermission}
+     * with the specified {@code credentialClass} and Principals.
      */
     PrivateCredentialPermission(String credentialClass,
                         Set<Principal> principals) {
@@ -153,19 +153,19 @@
     }
 
     /**
-     * Creates a new <code>PrivateCredentialPermission</code>
-     * with the specified <code>name</code>.  The <code>name</code>
-     * specifies both a Credential class and a <code>Principal</code> Set.
+     * Creates a new {@code PrivateCredentialPermission}
+     * with the specified {@code name}.  The {@code name}
+     * specifies both a Credential class and a {@code Principal} Set.
      *
      * <p>
      *
      * @param name the name specifying the Credential class and
-     *          <code>Principal</code> Set. <p>
+     *          {@code Principal} Set. <p>
      *
      * @param actions the actions specifying that the Credential can be read.
      *
-     * @throws IllegalArgumentException if <code>name</code> does not conform
-     *          to the correct syntax or if <code>actions</code> is not "read".
+     * @throws IllegalArgumentException if {@code name} does not conform
+     *          to the correct syntax or if {@code actions} is not "read".
      */
     public PrivateCredentialPermission(String name, String actions) {
         super(name);
@@ -178,34 +178,34 @@
 
     /**
      * Returns the Class name of the Credential associated with this
-     * <code>PrivateCredentialPermission</code>.
+     * {@code PrivateCredentialPermission}.
      *
      * <p>
      *
      * @return the Class name of the Credential associated with this
-     *          <code>PrivateCredentialPermission</code>.
+     *          {@code PrivateCredentialPermission}.
      */
     public String getCredentialClass() {
         return credentialClass;
     }
 
     /**
-     * Returns the <code>Principal</code> classes and names
-     * associated with this <code>PrivateCredentialPermission</code>.
+     * Returns the {@code Principal} classes and names
+     * associated with this {@code PrivateCredentialPermission}.
      * The information is returned as a two-dimensional array (array[x][y]).
-     * The 'x' value corresponds to the number of <code>Principal</code>
+     * The 'x' value corresponds to the number of {@code Principal}
      * class and name pairs.  When (y==0), it corresponds to
-     * the <code>Principal</code> class value, and when (y==1),
-     * it corresponds to the <code>Principal</code> name value.
+     * the {@code Principal} class value, and when (y==1),
+     * it corresponds to the {@code Principal} name value.
      * For example, array[0][0] corresponds to the class name of
-     * the first <code>Principal</code> in the array.  array[0][1]
-     * corresponds to the <code>Principal</code> name of the
-     * first <code>Principal</code> in the array.
+     * the first {@code Principal} in the array.  array[0][1]
+     * corresponds to the {@code Principal} name of the
+     * first {@code Principal} in the array.
      *
      * <p>
      *
-     * @return the <code>Principal</code> class and names associated
-     *          with this <code>PrivateCredentialPermission</code>.
+     * @return the {@code Principal} class and names associated
+     *          with this {@code PrivateCredentialPermission}.
      */
     public String[][] getPrincipals() {
 
@@ -222,8 +222,8 @@
     }
 
     /**
-     * Checks if this <code>PrivateCredentialPermission</code> implies
-     * the specified <code>Permission</code>.
+     * Checks if this {@code PrivateCredentialPermission} implies
+     * the specified {@code Permission}.
      *
      * <p>
      *
@@ -241,10 +241,10 @@
      *
      * <p>
      *
-     * @param p the <code>Permission</code> to check against.
+     * @param p the {@code Permission} to check against.
      *
-     * @return true if this <code>PrivateCredentialPermission</code> implies
-     * the specified <code>Permission</code>, false if not.
+     * @return true if this {@code PrivateCredentialPermission} implies
+     * the specified {@code Permission}, false if not.
      */
     public boolean implies(Permission p) {
 
@@ -260,9 +260,9 @@
     }
 
     /**
-     * Checks two <code>PrivateCredentialPermission</code> objects for
+     * Checks two {@code PrivateCredentialPermission} objects for
      * equality.  Checks that <i>obj</i> is a
-     * <code>PrivateCredentialPermission</code>,
+     * {@code PrivateCredentialPermission},
      * and has the same credential class as this object,
      * as well as the same Principals as this object.
      * The order of the Principals in the respective Permission's
@@ -272,7 +272,7 @@
      *
      * @param obj the object we are testing for equality with this object.
      *
-     * @return true if obj is a <code>PrivateCredentialPermission</code>,
+     * @return true if obj is a {@code PrivateCredentialPermission},
      *          has the same credential class as this object,
      *          and has the same Principals as this object.
      */
@@ -311,9 +311,9 @@
 
     /**
      * Return a homogeneous collection of PrivateCredentialPermissions
-     * in a <code>PermissionCollection</code>.
-     * No such <code>PermissionCollection</code> is defined,
-     * so this method always returns <code>null</code>.
+     * in a {@code PermissionCollection}.
+     * No such {@code PermissionCollection} is defined,
+     * so this method always returns {@code null}.
      *
      * <p>
      *
--- a/src/share/classes/javax/security/auth/RefreshFailedException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/RefreshFailedException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,10 @@
 package javax.security.auth;
 
 /**
- * Signals that a <code>refresh</code> operation failed.
+ * Signals that a {@code refresh} operation failed.
  *
  * <p> This exception is thrown by credentials implementing
- * the <code>Refreshable</code> interface when the <code>refresh</code>
+ * the {@code Refreshable} interface when the {@code refresh}
  * method fails.
  *
  */
--- a/src/share/classes/javax/security/auth/Refreshable.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/Refreshable.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -37,24 +37,24 @@
 public interface Refreshable {
 
     /**
-     * Determine if this <code>Object</code> is current.
+     * Determine if this {@code Object} is current.
      *
      * <p>
      *
-     * @return true if this <code>Object</code> is currently current,
+     * @return true if this {@code Object} is currently current,
      *          false otherwise.
      */
     boolean isCurrent();
 
     /**
      * Update or extend the validity period for this
-     * <code>Object</code>.
+     * {@code Object}.
      *
      * <p>
      *
      * @exception SecurityException if the caller does not have permission
      *          to update or extend the validity period for this
-     *          <code>Object</code>. <p>
+     *          {@code Object}. <p>
      *
      * @exception RefreshFailedException if the refresh attempt failed.
      */
--- a/src/share/classes/javax/security/auth/Subject.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/Subject.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,39 +42,39 @@
 import sun.security.util.ResourcesMgr;
 
 /**
- * <p> A <code>Subject</code> represents a grouping of related information
+ * <p> A {@code Subject} represents a grouping of related information
  * for a single entity, such as a person.
  * Such information includes the Subject's identities as well as
  * its security-related attributes
  * (passwords and cryptographic keys, for example).
  *
  * <p> Subjects may potentially have multiple identities.
- * Each identity is represented as a <code>Principal</code>
- * within the <code>Subject</code>.  Principals simply bind names to a
- * <code>Subject</code>.  For example, a <code>Subject</code> that happens
+ * Each identity is represented as a {@code Principal}
+ * within the {@code Subject}.  Principals simply bind names to a
+ * {@code Subject}.  For example, a {@code Subject} that happens
  * to be a person, Alice, might have two Principals:
  * one which binds "Alice Bar", the name on her driver license,
- * to the <code>Subject</code>, and another which binds,
+ * to the {@code Subject}, and another which binds,
  * "999-99-9999", the number on her student identification card,
- * to the <code>Subject</code>.  Both Principals refer to the same
- * <code>Subject</code> even though each has a different name.
+ * to the {@code Subject}.  Both Principals refer to the same
+ * {@code Subject} even though each has a different name.
  *
- * <p> A <code>Subject</code> may also own security-related attributes,
+ * <p> A {@code Subject} may also own security-related attributes,
  * which are referred to as credentials.
  * Sensitive credentials that require special protection, such as
  * private cryptographic keys, are stored within a private credential
- * <code>Set</code>.  Credentials intended to be shared, such as
+ * {@code Set}.  Credentials intended to be shared, such as
  * public key certificates or Kerberos server tickets are stored
- * within a public credential <code>Set</code>.  Different permissions
+ * within a public credential {@code Set}.  Different permissions
  * are required to access and modify the different credential Sets.
  *
- * <p> To retrieve all the Principals associated with a <code>Subject</code>,
- * invoke the <code>getPrincipals</code> method.  To retrieve
- * all the public or private credentials belonging to a <code>Subject</code>,
- * invoke the <code>getPublicCredentials</code> method or
- * <code>getPrivateCredentials</code> method, respectively.
- * To modify the returned <code>Set</code> of Principals and credentials,
- * use the methods defined in the <code>Set</code> class.
+ * <p> To retrieve all the Principals associated with a {@code Subject},
+ * invoke the {@code getPrincipals} method.  To retrieve
+ * all the public or private credentials belonging to a {@code Subject},
+ * invoke the {@code getPublicCredentials} method or
+ * {@code getPrivateCredentials} method, respectively.
+ * To modify the returned {@code Set} of Principals and credentials,
+ * use the methods defined in the {@code Set} class.
  * For example:
  * <pre>
  *      Subject subject;
@@ -86,13 +86,13 @@
  *      subject.getPublicCredentials().add(credential);
  * </pre>
  *
- * <p> This <code>Subject</code> class implements <code>Serializable</code>.
- * While the Principals associated with the <code>Subject</code> are serialized,
- * the credentials associated with the <code>Subject</code> are not.
- * Note that the <code>java.security.Principal</code> class
- * does not implement <code>Serializable</code>.  Therefore all concrete
- * <code>Principal</code> implementations associated with Subjects
- * must implement <code>Serializable</code>.
+ * <p> This {@code Subject} class implements {@code Serializable}.
+ * While the Principals associated with the {@code Subject} are serialized,
+ * the credentials associated with the {@code Subject} are not.
+ * Note that the {@code java.security.Principal} class
+ * does not implement {@code Serializable}.  Therefore all concrete
+ * {@code Principal} implementations associated with Subjects
+ * must implement {@code Serializable}.
  *
  * @see java.security.Principal
  * @see java.security.DomainCombiner
@@ -102,14 +102,14 @@
     private static final long serialVersionUID = -8308522755600156056L;
 
     /**
-     * A <code>Set</code> that provides a view of all of this
+     * A {@code Set} that provides a view of all of this
      * Subject's Principals
      *
      * <p>
      *
      * @serial Each element in this set is a
-     *          <code>java.security.Principal</code>.
-     *          The set is a <code>Subject.SecureSet</code>.
+     *          {@code java.security.Principal}.
+     *          The set is a {@code Subject.SecureSet}.
      */
     Set<Principal> principals;
 
@@ -135,21 +135,21 @@
         = new ProtectionDomain[0];
 
     /**
-     * Create an instance of a <code>Subject</code>
-     * with an empty <code>Set</code> of Principals and empty
+     * Create an instance of a {@code Subject}
+     * with an empty {@code Set} of Principals and empty
      * Sets of public and private credentials.
      *
-     * <p> The newly constructed Sets check whether this <code>Subject</code>
+     * <p> The newly constructed Sets check whether this {@code Subject}
      * has been set read-only before permitting subsequent modifications.
      * The newly created Sets also prevent illegal modifications
      * by ensuring that callers have sufficient permissions.
      *
      * <p> To modify the Principals Set, the caller must have
-     * <code>AuthPermission("modifyPrincipals")</code>.
+     * {@code AuthPermission("modifyPrincipals")}.
      * To modify the public credential Set, the caller must have
-     * <code>AuthPermission("modifyPublicCredentials")</code>.
+     * {@code AuthPermission("modifyPublicCredentials")}.
      * To modify the private credential Set, the caller must have
-     * <code>AuthPermission("modifyPrivateCredentials")</code>.
+     * {@code AuthPermission("modifyPrivateCredentials")}.
      */
     public Subject() {
 
@@ -162,39 +162,39 @@
     }
 
     /**
-     * Create an instance of a <code>Subject</code> with
+     * Create an instance of a {@code Subject} with
      * Principals and credentials.
      *
      * <p> The Principals and credentials from the specified Sets
      * are copied into newly constructed Sets.
-     * These newly created Sets check whether this <code>Subject</code>
+     * These newly created Sets check whether this {@code Subject}
      * has been set read-only before permitting subsequent modifications.
      * The newly created Sets also prevent illegal modifications
      * by ensuring that callers have sufficient permissions.
      *
      * <p> To modify the Principals Set, the caller must have
-     * <code>AuthPermission("modifyPrincipals")</code>.
+     * {@code AuthPermission("modifyPrincipals")}.
      * To modify the public credential Set, the caller must have
-     * <code>AuthPermission("modifyPublicCredentials")</code>.
+     * {@code AuthPermission("modifyPublicCredentials")}.
      * To modify the private credential Set, the caller must have
-     * <code>AuthPermission("modifyPrivateCredentials")</code>.
+     * {@code AuthPermission("modifyPrivateCredentials")}.
      * <p>
      *
-     * @param readOnly true if the <code>Subject</code> is to be read-only,
+     * @param readOnly true if the {@code Subject} is to be read-only,
      *          and false otherwise. <p>
      *
-     * @param principals the <code>Set</code> of Principals
-     *          to be associated with this <code>Subject</code>. <p>
+     * @param principals the {@code Set} of Principals
+     *          to be associated with this {@code Subject}. <p>
      *
-     * @param pubCredentials the <code>Set</code> of public credentials
-     *          to be associated with this <code>Subject</code>. <p>
+     * @param pubCredentials the {@code Set} of public credentials
+     *          to be associated with this {@code Subject}. <p>
      *
-     * @param privCredentials the <code>Set</code> of private credentials
-     *          to be associated with this <code>Subject</code>.
+     * @param privCredentials the {@code Set} of private credentials
+     *          to be associated with this {@code Subject}.
      *
      * @exception NullPointerException if the specified
-     *          <code>principals</code>, <code>pubCredentials</code>,
-     *          or <code>privCredentials</code> are <code>null</code>.
+     *          {@code principals}, {@code pubCredentials},
+     *          or {@code privCredentials} are {@code null}.
      */
     public Subject(boolean readOnly, Set<? extends Principal> principals,
                    Set<?> pubCredentials, Set<?> privCredentials)
@@ -216,24 +216,24 @@
     }
 
     /**
-     * Set this <code>Subject</code> to be read-only.
+     * Set this {@code Subject} to be read-only.
      *
      * <p> Modifications (additions and removals) to this Subject's
-     * <code>Principal</code> <code>Set</code> and
+     * {@code Principal} {@code Set} and
      * credential Sets will be disallowed.
-     * The <code>destroy</code> operation on this Subject's credentials will
+     * The {@code destroy} operation on this Subject's credentials will
      * still be permitted.
      *
-     * <p> Subsequent attempts to modify the Subject's <code>Principal</code>
+     * <p> Subsequent attempts to modify the Subject's {@code Principal}
      * and credential Sets will result in an
-     * <code>IllegalStateException</code> being thrown.
-     * Also, once a <code>Subject</code> is read-only,
+     * {@code IllegalStateException} being thrown.
+     * Also, once a {@code Subject} is read-only,
      * it can not be reset to being writable again.
      *
      * <p>
      *
      * @exception SecurityException if the caller does not have permission
-     *          to set this <code>Subject</code> to be read-only.
+     *          to set this {@code Subject} to be read-only.
      */
     public void setReadOnly() {
         java.lang.SecurityManager sm = System.getSecurityManager();
@@ -245,40 +245,40 @@
     }
 
     /**
-     * Query whether this <code>Subject</code> is read-only.
+     * Query whether this {@code Subject} is read-only.
      *
      * <p>
      *
-     * @return true if this <code>Subject</code> is read-only, false otherwise.
+     * @return true if this {@code Subject} is read-only, false otherwise.
      */
     public boolean isReadOnly() {
         return this.readOnly;
     }
 
     /**
-     * Get the <code>Subject</code> associated with the provided
-     * <code>AccessControlContext</code>.
+     * Get the {@code Subject} associated with the provided
+     * {@code AccessControlContext}.
      *
-     * <p> The <code>AccessControlContext</code> may contain many
-     * Subjects (from nested <code>doAs</code> calls).
-     * In this situation, the most recent <code>Subject</code> associated
-     * with the <code>AccessControlContext</code> is returned.
+     * <p> The {@code AccessControlContext} may contain many
+     * Subjects (from nested {@code doAs} calls).
+     * In this situation, the most recent {@code Subject} associated
+     * with the {@code AccessControlContext} is returned.
      *
      * <p>
      *
-     * @param  acc the <code>AccessControlContext</code> from which to retrieve
-     *          the <code>Subject</code>.
+     * @param  acc the {@code AccessControlContext} from which to retrieve
+     *          the {@code Subject}.
      *
-     * @return  the <code>Subject</code> associated with the provided
-     *          <code>AccessControlContext</code>, or <code>null</code>
-     *          if no <code>Subject</code> is associated
-     *          with the provided <code>AccessControlContext</code>.
+     * @return  the {@code Subject} associated with the provided
+     *          {@code AccessControlContext}, or {@code null}
+     *          if no {@code Subject} is associated
+     *          with the provided {@code AccessControlContext}.
      *
      * @exception SecurityException if the caller does not have permission
-     *          to get the <code>Subject</code>. <p>
+     *          to get the {@code Subject}. <p>
      *
      * @exception NullPointerException if the provided
-     *          <code>AccessControlContext</code> is <code>null</code>.
+     *          {@code AccessControlContext} is {@code null}.
      */
     public static Subject getSubject(final AccessControlContext acc) {
 
@@ -306,33 +306,36 @@
     }
 
     /**
-     * Perform work as a particular <code>Subject</code>.
+     * Perform work as a particular {@code Subject}.
      *
      * <p> This method first retrieves the current Thread's
-     * <code>AccessControlContext</code> via
-     * <code>AccessController.getContext</code>,
-     * and then instantiates a new <code>AccessControlContext</code>
+     * {@code AccessControlContext} via
+     * {@code AccessController.getContext},
+     * and then instantiates a new {@code AccessControlContext}
      * using the retrieved context along with a new
-     * <code>SubjectDomainCombiner</code> (constructed using
-     * the provided <code>Subject</code>).
-     * Finally, this method invokes <code>AccessController.doPrivileged</code>,
-     * passing it the provided <code>PrivilegedAction</code>,
-     * as well as the newly constructed <code>AccessControlContext</code>.
+     * {@code SubjectDomainCombiner} (constructed using
+     * the provided {@code Subject}).
+     * Finally, this method invokes {@code AccessController.doPrivileged},
+     * passing it the provided {@code PrivilegedAction},
+     * as well as the newly constructed {@code AccessControlContext}.
      *
      * <p>
      *
-     * @param subject the <code>Subject</code> that the specified
-     *                  <code>action</code> will run as.  This parameter
-     *                  may be <code>null</code>. <p>
+     * @param subject the {@code Subject} that the specified
+     *                  {@code action} will run as.  This parameter
+     *                  may be {@code null}. <p>
+     *
+     * @param <T> the type of the value returned by the PrivilegedAction's
+     *                  {@code run} method.
      *
      * @param action the code to be run as the specified
-     *                  <code>Subject</code>. <p>
+     *                  {@code Subject}. <p>
      *
      * @return the value returned by the PrivilegedAction's
-     *                  <code>run</code> method.
+     *                  {@code run} method.
      *
-     * @exception NullPointerException if the <code>PrivilegedAction</code>
-     *                  is <code>null</code>. <p>
+     * @exception NullPointerException if the {@code PrivilegedAction}
+     *                  is {@code null}. <p>
      *
      * @exception SecurityException if the caller does not have permission
      *                  to invoke this method.
@@ -359,38 +362,41 @@
     }
 
     /**
-     * Perform work as a particular <code>Subject</code>.
+     * Perform work as a particular {@code Subject}.
      *
      * <p> This method first retrieves the current Thread's
-     * <code>AccessControlContext</code> via
-     * <code>AccessController.getContext</code>,
-     * and then instantiates a new <code>AccessControlContext</code>
+     * {@code AccessControlContext} via
+     * {@code AccessController.getContext},
+     * and then instantiates a new {@code AccessControlContext}
      * using the retrieved context along with a new
-     * <code>SubjectDomainCombiner</code> (constructed using
-     * the provided <code>Subject</code>).
-     * Finally, this method invokes <code>AccessController.doPrivileged</code>,
-     * passing it the provided <code>PrivilegedExceptionAction</code>,
-     * as well as the newly constructed <code>AccessControlContext</code>.
+     * {@code SubjectDomainCombiner} (constructed using
+     * the provided {@code Subject}).
+     * Finally, this method invokes {@code AccessController.doPrivileged},
+     * passing it the provided {@code PrivilegedExceptionAction},
+     * as well as the newly constructed {@code AccessControlContext}.
      *
      * <p>
      *
-     * @param subject the <code>Subject</code> that the specified
-     *                  <code>action</code> will run as.  This parameter
-     *                  may be <code>null</code>. <p>
+     * @param subject the {@code Subject} that the specified
+     *                  {@code action} will run as.  This parameter
+     *                  may be {@code null}. <p>
+     *
+     * @param <T> the type of the value returned by the
+     *                  PrivilegedExceptionAction's {@code run} method.
      *
      * @param action the code to be run as the specified
-     *                  <code>Subject</code>. <p>
+     *                  {@code Subject}. <p>
      *
      * @return the value returned by the
-     *                  PrivilegedExceptionAction's <code>run</code> method.
+     *                  PrivilegedExceptionAction's {@code run} method.
      *
      * @exception PrivilegedActionException if the
-     *                  <code>PrivilegedExceptionAction.run</code>
+     *                  {@code PrivilegedExceptionAction.run}
      *                  method throws a checked exception. <p>
      *
      * @exception NullPointerException if the specified
-     *                  <code>PrivilegedExceptionAction</code> is
-     *                  <code>null</code>. <p>
+     *                  {@code PrivilegedExceptionAction} is
+     *                  {@code null}. <p>
      *
      * @exception SecurityException if the caller does not have permission
      *                  to invoke this method.
@@ -418,33 +424,36 @@
     }
 
     /**
-     * Perform privileged work as a particular <code>Subject</code>.
+     * Perform privileged work as a particular {@code Subject}.
      *
-     * <p> This method behaves exactly as <code>Subject.doAs</code>,
+     * <p> This method behaves exactly as {@code Subject.doAs},
      * except that instead of retrieving the current Thread's
-     * <code>AccessControlContext</code>, it uses the provided
-     * <code>AccessControlContext</code>.  If the provided
-     * <code>AccessControlContext</code> is <code>null</code>,
-     * this method instantiates a new <code>AccessControlContext</code>
+     * {@code AccessControlContext}, it uses the provided
+     * {@code AccessControlContext}.  If the provided
+     * {@code AccessControlContext} is {@code null},
+     * this method instantiates a new {@code AccessControlContext}
      * with an empty collection of ProtectionDomains.
      *
      * <p>
      *
-     * @param subject the <code>Subject</code> that the specified
-     *                  <code>action</code> will run as.  This parameter
-     *                  may be <code>null</code>. <p>
+     * @param subject the {@code Subject} that the specified
+     *                  {@code action} will run as.  This parameter
+     *                  may be {@code null}. <p>
+     *
+     * @param <T> the type of the value returned by the PrivilegedAction's
+     *                  {@code run} method.
      *
      * @param action the code to be run as the specified
-     *                  <code>Subject</code>. <p>
+     *                  {@code Subject}. <p>
      *
-     * @param acc the <code>AccessControlContext</code> to be tied to the
+     * @param acc the {@code AccessControlContext} to be tied to the
      *                  specified <i>subject</i> and <i>action</i>. <p>
      *
      * @return the value returned by the PrivilegedAction's
-     *                  <code>run</code> method.
+     *                  {@code run} method.
      *
-     * @exception NullPointerException if the <code>PrivilegedAction</code>
-     *                  is <code>null</code>. <p>
+     * @exception NullPointerException if the {@code PrivilegedAction}
+     *                  is {@code null}. <p>
      *
      * @exception SecurityException if the caller does not have permission
      *                  to invoke this method.
@@ -476,38 +485,41 @@
     }
 
     /**
-     * Perform privileged work as a particular <code>Subject</code>.
+     * Perform privileged work as a particular {@code Subject}.
      *
-     * <p> This method behaves exactly as <code>Subject.doAs</code>,
+     * <p> This method behaves exactly as {@code Subject.doAs},
      * except that instead of retrieving the current Thread's
-     * <code>AccessControlContext</code>, it uses the provided
-     * <code>AccessControlContext</code>.  If the provided
-     * <code>AccessControlContext</code> is <code>null</code>,
-     * this method instantiates a new <code>AccessControlContext</code>
+     * {@code AccessControlContext}, it uses the provided
+     * {@code AccessControlContext}.  If the provided
+     * {@code AccessControlContext} is {@code null},
+     * this method instantiates a new {@code AccessControlContext}
      * with an empty collection of ProtectionDomains.
      *
      * <p>
      *
-     * @param subject the <code>Subject</code> that the specified
-     *                  <code>action</code> will run as.  This parameter
-     *                  may be <code>null</code>. <p>
+     * @param subject the {@code Subject} that the specified
+     *                  {@code action} will run as.  This parameter
+     *                  may be {@code null}. <p>
+     *
+     * @param <T> the type of the value returned by the
+     *                  PrivilegedExceptionAction's {@code run} method.
      *
      * @param action the code to be run as the specified
-     *                  <code>Subject</code>. <p>
+     *                  {@code Subject}. <p>
      *
-     * @param acc the <code>AccessControlContext</code> to be tied to the
+     * @param acc the {@code AccessControlContext} to be tied to the
      *                  specified <i>subject</i> and <i>action</i>. <p>
      *
      * @return the value returned by the
-     *                  PrivilegedExceptionAction's <code>run</code> method.
+     *                  PrivilegedExceptionAction's {@code run} method.
      *
      * @exception PrivilegedActionException if the
-     *                  <code>PrivilegedExceptionAction.run</code>
+     *                  {@code PrivilegedExceptionAction.run}
      *                  method throws a checked exception. <p>
      *
      * @exception NullPointerException if the specified
-     *                  <code>PrivilegedExceptionAction</code> is
-     *                  <code>null</code>. <p>
+     *                  {@code PrivilegedExceptionAction} is
+     *                  {@code null}. <p>
      *
      * @exception SecurityException if the caller does not have permission
      *                  to invoke this method.
@@ -556,19 +568,19 @@
     }
 
     /**
-     * Return the <code>Set</code> of Principals associated with this
-     * <code>Subject</code>.  Each <code>Principal</code> represents
-     * an identity for this <code>Subject</code>.
+     * Return the {@code Set} of Principals associated with this
+     * {@code Subject}.  Each {@code Principal} represents
+     * an identity for this {@code Subject}.
      *
-     * <p> The returned <code>Set</code> is backed by this Subject's
-     * internal <code>Principal</code> <code>Set</code>.  Any modification
-     * to the returned <code>Set</code> affects the internal
-     * <code>Principal</code> <code>Set</code> as well.
+     * <p> The returned {@code Set} is backed by this Subject's
+     * internal {@code Principal} {@code Set}.  Any modification
+     * to the returned {@code Set} affects the internal
+     * {@code Principal} {@code Set} as well.
      *
      * <p>
      *
-     * @return  The <code>Set</code> of Principals associated with this
-     *          <code>Subject</code>.
+     * @return  The {@code Set} of Principals associated with this
+     *          {@code Subject}.
      */
     public Set<Principal> getPrincipals() {
 
@@ -578,26 +590,28 @@
     }
 
     /**
-     * Return a <code>Set</code> of Principals associated with this
-     * <code>Subject</code> that are instances or subclasses of the specified
-     * <code>Class</code>.
+     * Return a {@code Set} of Principals associated with this
+     * {@code Subject} that are instances or subclasses of the specified
+     * {@code Class}.
      *
-     * <p> The returned <code>Set</code> is not backed by this Subject's
-     * internal <code>Principal</code> <code>Set</code>.  A new
-     * <code>Set</code> is created and returned for each method invocation.
-     * Modifications to the returned <code>Set</code>
-     * will not affect the internal <code>Principal</code> <code>Set</code>.
+     * <p> The returned {@code Set} is not backed by this Subject's
+     * internal {@code Principal} {@code Set}.  A new
+     * {@code Set} is created and returned for each method invocation.
+     * Modifications to the returned {@code Set}
+     * will not affect the internal {@code Principal} {@code Set}.
      *
      * <p>
      *
-     * @param c the returned <code>Set</code> of Principals will all be
+     * @param <T> the type of the class modeled by {@code c}
+     *
+     * @param c the returned {@code Set} of Principals will all be
      *          instances of this class.
      *
-     * @return a <code>Set</code> of Principals that are instances of the
-     *          specified <code>Class</code>.
+     * @return a {@code Set} of Principals that are instances of the
+     *          specified {@code Class}.
      *
-     * @exception NullPointerException if the specified <code>Class</code>
-     *                  is <code>null</code>.
+     * @exception NullPointerException if the specified {@code Class}
+     *                  is {@code null}.
      */
     public <T extends Principal> Set<T> getPrincipals(Class<T> c) {
 
@@ -611,18 +625,18 @@
     }
 
     /**
-     * Return the <code>Set</code> of public credentials held by this
-     * <code>Subject</code>.
+     * Return the {@code Set} of public credentials held by this
+     * {@code Subject}.
      *
-     * <p> The returned <code>Set</code> is backed by this Subject's
-     * internal public Credential <code>Set</code>.  Any modification
-     * to the returned <code>Set</code> affects the internal public
-     * Credential <code>Set</code> as well.
+     * <p> The returned {@code Set} is backed by this Subject's
+     * internal public Credential {@code Set}.  Any modification
+     * to the returned {@code Set} affects the internal public
+     * Credential {@code Set} as well.
      *
      * <p>
      *
-     * @return  A <code>Set</code> of public credentials held by this
-     *          <code>Subject</code>.
+     * @return  A {@code Set} of public credentials held by this
+     *          {@code Subject}.
      */
     public Set<Object> getPublicCredentials() {
 
@@ -632,29 +646,29 @@
     }
 
     /**
-     * Return the <code>Set</code> of private credentials held by this
-     * <code>Subject</code>.
+     * Return the {@code Set} of private credentials held by this
+     * {@code Subject}.
      *
-     * <p> The returned <code>Set</code> is backed by this Subject's
-     * internal private Credential <code>Set</code>.  Any modification
-     * to the returned <code>Set</code> affects the internal private
-     * Credential <code>Set</code> as well.
+     * <p> The returned {@code Set} is backed by this Subject's
+     * internal private Credential {@code Set}.  Any modification
+     * to the returned {@code Set} affects the internal private
+     * Credential {@code Set} as well.
      *
      * <p> A caller requires permissions to access the Credentials
-     * in the returned <code>Set</code>, or to modify the
-     * <code>Set</code> itself.  A <code>SecurityException</code>
+     * in the returned {@code Set}, or to modify the
+     * {@code Set} itself.  A {@code SecurityException}
      * is thrown if the caller does not have the proper permissions.
      *
-     * <p> While iterating through the <code>Set</code>,
-     * a <code>SecurityException</code> is thrown
+     * <p> While iterating through the {@code Set},
+     * a {@code SecurityException} is thrown
      * if the caller does not have permission to access a
-     * particular Credential.  The <code>Iterator</code>
-     * is nevertheless advanced to next element in the <code>Set</code>.
+     * particular Credential.  The {@code Iterator}
+     * is nevertheless advanced to next element in the {@code Set}.
      *
      * <p>
      *
-     * @return  A <code>Set</code> of private credentials held by this
-     *          <code>Subject</code>.
+     * @return  A {@code Set} of private credentials held by this
+     *          {@code Subject}.
      */
     public Set<Object> getPrivateCredentials() {
 
@@ -672,26 +686,28 @@
     }
 
     /**
-     * Return a <code>Set</code> of public credentials associated with this
-     * <code>Subject</code> that are instances or subclasses of the specified
-     * <code>Class</code>.
+     * Return a {@code Set} of public credentials associated with this
+     * {@code Subject} that are instances or subclasses of the specified
+     * {@code Class}.
      *
-     * <p> The returned <code>Set</code> is not backed by this Subject's
-     * internal public Credential <code>Set</code>.  A new
-     * <code>Set</code> is created and returned for each method invocation.
-     * Modifications to the returned <code>Set</code>
-     * will not affect the internal public Credential <code>Set</code>.
+     * <p> The returned {@code Set} is not backed by this Subject's
+     * internal public Credential {@code Set}.  A new
+     * {@code Set} is created and returned for each method invocation.
+     * Modifications to the returned {@code Set}
+     * will not affect the internal public Credential {@code Set}.
      *
      * <p>
      *
-     * @param c the returned <code>Set</code> of public credentials will all be
+     * @param <T> the type of the class modeled by {@code c}
+     *
+     * @param c the returned {@code Set} of public credentials will all be
      *          instances of this class.
      *
-     * @return a <code>Set</code> of public credentials that are instances
-     *          of the  specified <code>Class</code>.
+     * @return a {@code Set} of public credentials that are instances
+     *          of the  specified {@code Class}.
      *
-     * @exception NullPointerException if the specified <code>Class</code>
-     *          is <code>null</code>.
+     * @exception NullPointerException if the specified {@code Class}
+     *          is {@code null}.
      */
     public <T> Set<T> getPublicCredentials(Class<T> c) {
 
@@ -705,30 +721,32 @@
     }
 
     /**
-     * Return a <code>Set</code> of private credentials associated with this
-     * <code>Subject</code> that are instances or subclasses of the specified
-     * <code>Class</code>.
+     * Return a {@code Set} of private credentials associated with this
+     * {@code Subject} that are instances or subclasses of the specified
+     * {@code Class}.
      *
      * <p> The caller must have permission to access all of the
-     * requested Credentials, or a <code>SecurityException</code>
+     * requested Credentials, or a {@code SecurityException}
      * will be thrown.
      *
-     * <p> The returned <code>Set</code> is not backed by this Subject's
-     * internal private Credential <code>Set</code>.  A new
-     * <code>Set</code> is created and returned for each method invocation.
-     * Modifications to the returned <code>Set</code>
-     * will not affect the internal private Credential <code>Set</code>.
+     * <p> The returned {@code Set} is not backed by this Subject's
+     * internal private Credential {@code Set}.  A new
+     * {@code Set} is created and returned for each method invocation.
+     * Modifications to the returned {@code Set}
+     * will not affect the internal private Credential {@code Set}.
      *
      * <p>
      *
-     * @param c the returned <code>Set</code> of private credentials will all be
+     * @param <T> the type of the class modeled by {@code c}
+     *
+     * @param c the returned {@code Set} of private credentials will all be
      *          instances of this class.
      *
-     * @return a <code>Set</code> of private credentials that are instances
-     *          of the  specified <code>Class</code>.
+     * @return a {@code Set} of private credentials that are instances
+     *          of the  specified {@code Class}.
      *
-     * @exception NullPointerException if the specified <code>Class</code>
-     *          is <code>null</code>.
+     * @exception NullPointerException if the specified {@code Class}
+     *          is {@code null}.
      */
     public <T> Set<T> getPrivateCredentials(Class<T> c) {
 
@@ -750,25 +768,25 @@
     }
 
     /**
-     * Compares the specified Object with this <code>Subject</code>
+     * Compares the specified Object with this {@code Subject}
      * for equality.  Returns true if the given object is also a Subject
-     * and the two <code>Subject</code> instances are equivalent.
-     * More formally, two <code>Subject</code> instances are
-     * equal if their <code>Principal</code> and <code>Credential</code>
+     * and the two {@code Subject} instances are equivalent.
+     * More formally, two {@code Subject} instances are
+     * equal if their {@code Principal} and {@code Credential}
      * Sets are equal.
      *
      * <p>
      *
      * @param o Object to be compared for equality with this
-     *          <code>Subject</code>.
+     *          {@code Subject}.
      *
      * @return true if the specified Object is equal to this
-     *          <code>Subject</code>.
+     *          {@code Subject}.
      *
      * @exception SecurityException if the caller does not have permission
-     *          to access the private credentials for this <code>Subject</code>,
+     *          to access the private credentials for this {@code Subject},
      *          or if the caller does not have permission to access the
-     *          private credentials for the provided <code>Subject</code>.
+     *          private credentials for the provided {@code Subject}.
      */
     public boolean equals(Object o) {
 
@@ -815,11 +833,11 @@
     }
 
     /**
-     * Return the String representation of this <code>Subject</code>.
+     * Return the String representation of this {@code Subject}.
      *
      * <p>
      *
-     * @return the String representation of this <code>Subject</code>.
+     * @return the String representation of this {@code Subject}.
      */
     public String toString() {
         return toString(true);
@@ -876,11 +894,11 @@
     }
 
     /**
-     * Returns a hashcode for this <code>Subject</code>.
+     * Returns a hashcode for this {@code Subject}.
      *
      * <p>
      *
-     * @return a hashcode for this <code>Subject</code>.
+     * @return a hashcode for this {@code Subject}.
      *
      * @exception SecurityException if the caller does not have permission
      *          to access this Subject's private credentials.
@@ -892,10 +910,10 @@
          * hashcodes of this Subject's Principals and credentials.
          *
          * If a particular credential was destroyed
-         * (<code>credential.hashCode()</code> throws an
-         * <code>IllegalStateException</code>),
+         * ({@code credential.hashCode()} throws an
+         * {@code IllegalStateException}),
          * the hashcode for that credential is derived via:
-         * <code>credential.getClass().toString().hashCode()</code>.
+         * {@code credential.getClass().toString().hashCode()}.
          */
 
         int hashCode = 0;
@@ -946,7 +964,7 @@
 
         s.defaultReadObject();
 
-        // The Credential <code>Set</code> is not serialized, but we do not
+        // The Credential {@code Set} is not serialized, but we do not
         // want the default deserialization routine to set it to null.
         this.pubCredentials = Collections.synchronizedSet
                         (new SecureSet<Object>(this, PUB_CREDENTIAL_SET));
@@ -980,13 +998,13 @@
 
         /**
          * @serial An integer identifying the type of objects contained
-         *      in this set.  If <code>which == 1</code>,
+         *      in this set.  If {@code which == 1},
          *      this is a Principal set and all the elements are
-         *      of type <code>java.security.Principal</code>.
-         *      If <code>which == 2</code>, this is a public credential
-         *      set and all the elements are of type <code>Object</code>.
-         *      If <code>which == 3</code>, this is a private credential
-         *      set and all the elements are of type <code>Object</code>.
+         *      of type {@code java.security.Principal}.
+         *      If {@code which == 2}, this is a public credential
+         *      set and all the elements are of type {@code Object}.
+         *      If {@code which == 3}, this is a private credential
+         *      set and all the elements are of type {@code Object}.
          */
         private int which;
 
@@ -1303,7 +1321,7 @@
     }
 
     /**
-     * This class implements a <code>Set</code> which returns only
+     * This class implements a {@code Set} which returns only
      * members that are an instance of a specified Class.
      */
     private class ClassSet<T> extends AbstractSet<T> {
--- a/src/share/classes/javax/security/auth/SubjectDomainCombiner.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/SubjectDomainCombiner.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -39,9 +39,9 @@
 import java.lang.ref.WeakReference;
 
 /**
- * A <code>SubjectDomainCombiner</code> updates ProtectionDomains
- * with Principals from the <code>Subject</code> associated with this
- * <code>SubjectDomainCombiner</code>.
+ * A {@code SubjectDomainCombiner} updates ProtectionDomains
+ * with Principals from the {@code Subject} associated with this
+ * {@code SubjectDomainCombiner}.
  *
  */
 public class SubjectDomainCombiner implements java.security.DomainCombiner {
@@ -66,13 +66,13 @@
                                         (useJavaxPolicy && cachePolicy());
 
     /**
-     * Associate the provided <code>Subject</code> with this
-     * <code>SubjectDomainCombiner</code>.
+     * Associate the provided {@code Subject} with this
+     * {@code SubjectDomainCombiner}.
      *
      * <p>
      *
-     * @param subject the <code>Subject</code> to be associated with
-     *          with this <code>SubjectDomainCombiner</code>.
+     * @param subject the {@code Subject} to be associated with
+     *          with this {@code SubjectDomainCombiner}.
      */
     public SubjectDomainCombiner(Subject subject) {
         this.subject = subject;
@@ -85,19 +85,19 @@
     }
 
     /**
-     * Get the <code>Subject</code> associated with this
-     * <code>SubjectDomainCombiner</code>.
+     * Get the {@code Subject} associated with this
+     * {@code SubjectDomainCombiner}.
      *
      * <p>
      *
-     * @return the <code>Subject</code> associated with this
-     *          <code>SubjectDomainCombiner</code>, or <code>null</code>
-     *          if no <code>Subject</code> is associated with this
-     *          <code>SubjectDomainCombiner</code>.
+     * @return the {@code Subject} associated with this
+     *          {@code SubjectDomainCombiner}, or {@code null}
+     *          if no {@code Subject} is associated with this
+     *          {@code SubjectDomainCombiner}.
      *
      * @exception SecurityException if the caller does not have permission
-     *          to get the <code>Subject</code> associated with this
-     *          <code>SubjectDomainCombiner</code>.
+     *          to get the {@code Subject} associated with this
+     *          {@code SubjectDomainCombiner}.
      */
     public Subject getSubject() {
         java.lang.SecurityManager sm = System.getSecurityManager();
@@ -110,18 +110,18 @@
 
     /**
      * Update the relevant ProtectionDomains with the Principals
-     * from the <code>Subject</code> associated with this
-     * <code>SubjectDomainCombiner</code>.
+     * from the {@code Subject} associated with this
+     * {@code SubjectDomainCombiner}.
      *
-     * <p> A new <code>ProtectionDomain</code> instance is created
-     * for each <code>ProtectionDomain</code> in the
-     * <i>currentDomains</i> array.  Each new <code>ProtectionDomain</code>
-     * instance is created using the <code>CodeSource</code>,
-     * <code>Permission</code>s and <code>ClassLoader</code>
-     * from the corresponding <code>ProtectionDomain</code> in
+     * <p> A new {@code ProtectionDomain} instance is created
+     * for each {@code ProtectionDomain} in the
+     * <i>currentDomains</i> array.  Each new {@code ProtectionDomain}
+     * instance is created using the {@code CodeSource},
+     * {@code Permission}s and {@code ClassLoader}
+     * from the corresponding {@code ProtectionDomain} in
      * <i>currentDomains</i>, as well as with the Principals from
-     * the <code>Subject</code> associated with this
-     * <code>SubjectDomainCombiner</code>.
+     * the {@code Subject} associated with this
+     * {@code SubjectDomainCombiner}.
      *
      * <p> All of the newly instantiated ProtectionDomains are
      * combined into a new array.  The ProtectionDomains from the
@@ -136,23 +136,23 @@
      *
      * @param currentDomains the ProtectionDomains associated with the
      *          current execution Thread, up to the most recent
-     *          privileged <code>ProtectionDomain</code>.
+     *          privileged {@code ProtectionDomain}.
      *          The ProtectionDomains are are listed in order of execution,
-     *          with the most recently executing <code>ProtectionDomain</code>
+     *          with the most recently executing {@code ProtectionDomain}
      *          residing at the beginning of the array. This parameter may
-     *          be <code>null</code> if the current execution Thread
+     *          be {@code null} if the current execution Thread
      *          has no associated ProtectionDomains.<p>
      *
      * @param assignedDomains the ProtectionDomains inherited from the
      *          parent Thread, or the ProtectionDomains from the
      *          privileged <i>context</i>, if a call to
      *          AccessController.doPrivileged(..., <i>context</i>)
-     *          had occurred  This parameter may be <code>null</code>
+     *          had occurred  This parameter may be {@code null}
      *          if there were no ProtectionDomains inherited from the
      *          parent Thread, or from the privileged <i>context</i>.
      *
      * @return a new array consisting of the updated ProtectionDomains,
-     *          or <code>null</code>.
+     *          or {@code null}.
      */
     public ProtectionDomain[] combine(ProtectionDomain[] currentDomains,
                                 ProtectionDomain[] assignedDomains) {
--- a/src/share/classes/javax/security/auth/callback/Callback.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/callback/Callback.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,14 +28,14 @@
 
 /**
  * <p> Implementations of this interface are passed to a
- * <code>CallbackHandler</code>, allowing underlying security services
+ * {@code CallbackHandler}, allowing underlying security services
  * the ability to interact with a calling application to retrieve specific
  * authentication data such as usernames and passwords, or to display
  * certain information, such as error and warning messages.
  *
- * <p> <code>Callback</code> implementations do not retrieve or
+ * <p> {@code Callback} implementations do not retrieve or
  * display the information requested by underlying security services.
- * <code>Callback</code> implementations simply provide the means
+ * {@code Callback} implementations simply provide the means
  * to pass such requests to applications, and for applications,
  * if appropriate, to return requested information back to the
  * underlying security services.
--- a/src/share/classes/javax/security/auth/callback/CallbackHandler.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/callback/CallbackHandler.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,7 +26,7 @@
 package javax.security.auth.callback;
 
 /**
- * <p> An application implements a <code>CallbackHandler</code> and passes
+ * <p> An application implements a {@code CallbackHandler} and passes
  * it to underlying security services so that they may interact with
  * the application to retrieve specific authentication data,
  * such as usernames and passwords, or to display certain information,
@@ -40,12 +40,12 @@
  *
  * <p> Underlying security services make requests for different types
  * of information by passing individual Callbacks to the
- * <code>CallbackHandler</code>.  The <code>CallbackHandler</code>
+ * {@code CallbackHandler}.  The {@code CallbackHandler}
  * implementation decides how to retrieve and display information
  * depending on the Callbacks passed to it.  For example,
  * if the underlying service needs a username and password to
- * authenticate a user, it uses a <code>NameCallback</code> and
- * <code>PasswordCallback</code>.  The <code>CallbackHandler</code>
+ * authenticate a user, it uses a {@code NameCallback} and
+ * {@code PasswordCallback}.  The {@code CallbackHandler}
  * can then choose to prompt for a username and password serially,
  * or to prompt for both in a single window.
  *
@@ -54,10 +54,10 @@
  * {@code auth.login.defaultCallbackHandler} security property.
  *
  * <p> If the security property is set to the fully qualified name of a
- * <code>CallbackHandler</code> implementation class,
- * then a <code>LoginContext</code> will load the specified
- * <code>CallbackHandler</code> and pass it to the underlying LoginModules.
- * The <code>LoginContext</code> only loads the default handler
+ * {@code CallbackHandler} implementation class,
+ * then a {@code LoginContext} will load the specified
+ * {@code CallbackHandler} and pass it to the underlying LoginModules.
+ * The {@code LoginContext} only loads the default handler
  * if it was not provided one.
  *
  * <p> All default handler implementations must provide a public
@@ -71,11 +71,11 @@
      * <p> Retrieve or display the information requested in the
      * provided Callbacks.
      *
-     * <p> The <code>handle</code> method implementation checks the
-     * instance(s) of the <code>Callback</code> object(s) passed in
+     * <p> The {@code handle} method implementation checks the
+     * instance(s) of the {@code Callback} object(s) passed in
      * to retrieve or display the requested information.
      * The following example is provided to help demonstrate what an
-     * <code>handle</code> method implementation might look like.
+     * {@code handle} method implementation might look like.
      * This example code is for guidance only.  Many details,
      * including proper error handling, are left out for simplicity.
      *
@@ -135,7 +135,7 @@
      * }
      * }</pre>
      *
-     * @param callbacks an array of <code>Callback</code> objects provided
+     * @param callbacks an array of {@code Callback} objects provided
      *          by an underlying security service which contains
      *          the information requested to be retrieved or displayed.
      *
@@ -143,7 +143,7 @@
      *
      * @exception UnsupportedCallbackException if the implementation of this
      *          method does not support one or more of the Callbacks
-     *          specified in the <code>callbacks</code> parameter.
+     *          specified in the {@code callbacks} parameter.
      */
     void handle(Callback[] callbacks)
     throws java.io.IOException, UnsupportedCallbackException;
--- a/src/share/classes/javax/security/auth/callback/ChoiceCallback.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/callback/ChoiceCallback.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,8 +27,8 @@
 
 /**
  * <p> Underlying security services instantiate and pass a
- * <code>ChoiceCallback</code> to the <code>handle</code>
- * method of a <code>CallbackHandler</code> to display a list of choices
+ * {@code ChoiceCallback} to the {@code handle}
+ * method of a {@code CallbackHandler} to display a list of choices
  * and to retrieve the selected choice(s).
  *
  * @see javax.security.auth.callback.CallbackHandler
@@ -60,13 +60,13 @@
     private boolean multipleSelectionsAllowed;
     /**
      * @serial the selected choices, represented as indexes into the
-     *          <code>choices</code> list.
+     *          {@code choices} list.
      * @since 1.4
      */
     private int[] selections;
 
     /**
-     * Construct a <code>ChoiceCallback</code> with a prompt,
+     * Construct a {@code ChoiceCallback} with a prompt,
      * a list of choices, a default choice, and a boolean specifying
      * whether or not multiple selections from the list of choices are allowed.
      *
@@ -79,21 +79,21 @@
      * @param defaultChoice the choice to be used as the default choice
      *                  when the list of choices are displayed.  This value
      *                  is represented as an index into the
-     *                  <code>choices</code> array. <p>
+     *                  {@code choices} array. <p>
      *
      * @param multipleSelectionsAllowed boolean specifying whether or
      *                  not multiple selections can be made from the
      *                  list of choices.
      *
-     * @exception IllegalArgumentException if <code>prompt</code> is null,
-     *                  if <code>prompt</code> has a length of 0,
-     *                  if <code>choices</code> is null,
-     *                  if <code>choices</code> has a length of 0,
-     *                  if any element from <code>choices</code> is null,
-     *                  if any element from <code>choices</code>
-     *                  has a length of 0 or if <code>defaultChoice</code>
+     * @exception IllegalArgumentException if {@code prompt} is null,
+     *                  if {@code prompt} has a length of 0,
+     *                  if {@code choices} is null,
+     *                  if {@code choices} has a length of 0,
+     *                  if any element from {@code choices} is null,
+     *                  if any element from {@code choices}
+     *                  has a length of 0 or if {@code defaultChoice}
      *                  does not fall within the array boundaries of
-     *                  <code>choices</code>.
+     *                  {@code choices}.
      */
     public ChoiceCallback(String prompt, String[] choices,
                 int defaultChoice, boolean multipleSelectionsAllowed) {
@@ -142,7 +142,7 @@
      * <p>
      *
      * @return the defaultChoice, represented as an index into
-     *          the <code>choices</code> list.
+     *          the {@code choices} list.
      */
     public int getDefaultChoice() {
         return defaultChoice;
@@ -150,7 +150,7 @@
 
     /**
      * Get the boolean determining whether multiple selections from
-     * the <code>choices</code> list are allowed.
+     * the {@code choices} list are allowed.
      *
      * <p>
      *
@@ -166,7 +166,7 @@
      * <p>
      *
      * @param selection the selection represented as an index into the
-     *          <code>choices</code> list.
+     *          {@code choices} list.
      *
      * @see #getSelectedIndexes
      */
@@ -181,11 +181,11 @@
      * <p>
      *
      * @param selections the selections represented as indexes into the
-     *          <code>choices</code> list.
+     *          {@code choices} list.
      *
      * @exception UnsupportedOperationException if multiple selections are
      *          not allowed, as determined by
-     *          <code>allowMultipleSelections</code>.
+     *          {@code allowMultipleSelections}.
      *
      * @see #getSelectedIndexes
      */
@@ -201,7 +201,7 @@
      * <p>
      *
      * @return the selected choices, represented as indexes into the
-     *          <code>choices</code> list.
+     *          {@code choices} list.
      *
      * @see #setSelectedIndexes
      */
--- a/src/share/classes/javax/security/auth/callback/ConfirmationCallback.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/callback/ConfirmationCallback.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,8 +27,8 @@
 
 /**
  * <p> Underlying security services instantiate and pass a
- * <code>ConfirmationCallback</code> to the <code>handle</code>
- * method of a <code>CallbackHandler</code> to ask for YES/NO,
+ * {@code ConfirmationCallback} to the {@code handle}
+ * method of a {@code CallbackHandler} to ask for YES/NO,
  * OK/CANCEL, YES/NO/CANCEL or other similar confirmations.
  *
  * @see javax.security.auth.callback.CallbackHandler
@@ -40,9 +40,9 @@
     /**
      * Unspecified option type.
      *
-     * <p> The <code>getOptionType</code> method returns this
-     * value if this <code>ConfirmationCallback</code> was instantiated
-     * with <code>options</code> instead of an <code>optionType</code>.
+     * <p> The {@code getOptionType} method returns this
+     * value if this {@code ConfirmationCallback} was instantiated
+     * with {@code options} instead of an {@code optionType}.
      */
     public static final int UNSPECIFIED_OPTION          = -1;
 
@@ -50,9 +50,9 @@
      * YES/NO confirmation option.
      *
      * <p> An underlying security service specifies this as the
-     * <code>optionType</code> to a <code>ConfirmationCallback</code>
+     * {@code optionType} to a {@code ConfirmationCallback}
      * constructor if it requires a confirmation which can be answered
-     * with either <code>YES</code> or <code>NO</code>.
+     * with either {@code YES} or {@code NO}.
      */
     public static final int YES_NO_OPTION               = 0;
 
@@ -60,9 +60,9 @@
      * YES/NO/CANCEL confirmation confirmation option.
      *
      * <p> An underlying security service specifies this as the
-     * <code>optionType</code> to a <code>ConfirmationCallback</code>
+     * {@code optionType} to a {@code ConfirmationCallback}
      * constructor if it requires a confirmation which can be answered
-     * with either <code>YES</code>, <code>NO</code> or <code>CANCEL</code>.
+     * with either {@code YES}, {@code NO} or {@code CANCEL}.
      */
     public static final int YES_NO_CANCEL_OPTION        = 1;
 
@@ -70,45 +70,45 @@
      * OK/CANCEL confirmation confirmation option.
      *
      * <p> An underlying security service specifies this as the
-     * <code>optionType</code> to a <code>ConfirmationCallback</code>
+     * {@code optionType} to a {@code ConfirmationCallback}
      * constructor if it requires a confirmation which can be answered
-     * with either <code>OK</code> or <code>CANCEL</code>.
+     * with either {@code OK} or {@code CANCEL}.
      */
     public static final int OK_CANCEL_OPTION            = 2;
 
     /**
      * YES option.
      *
-     * <p> If an <code>optionType</code> was specified to this
-     * <code>ConfirmationCallback</code>, this option may be specified as a
-     * <code>defaultOption</code> or returned as the selected index.
+     * <p> If an {@code optionType} was specified to this
+     * {@code ConfirmationCallback}, this option may be specified as a
+     * {@code defaultOption} or returned as the selected index.
      */
     public static final int YES                         = 0;
 
     /**
      * NO option.
      *
-     * <p> If an <code>optionType</code> was specified to this
-     * <code>ConfirmationCallback</code>, this option may be specified as a
-     * <code>defaultOption</code> or returned as the selected index.
+     * <p> If an {@code optionType} was specified to this
+     * {@code ConfirmationCallback}, this option may be specified as a
+     * {@code defaultOption} or returned as the selected index.
      */
     public static final int NO                          = 1;
 
     /**
      * CANCEL option.
      *
-     * <p> If an <code>optionType</code> was specified to this
-     * <code>ConfirmationCallback</code>, this option may be specified as a
-     * <code>defaultOption</code> or returned as the selected index.
+     * <p> If an {@code optionType} was specified to this
+     * {@code ConfirmationCallback}, this option may be specified as a
+     * {@code defaultOption} or returned as the selected index.
      */
     public static final int CANCEL                      = 2;
 
     /**
      * OK option.
      *
-     * <p> If an <code>optionType</code> was specified to this
-     * <code>ConfirmationCallback</code>, this option may be specified as a
-     * <code>defaultOption</code> or returned as the selected index.
+     * <p> If an {@code optionType} was specified to this
+     * {@code ConfirmationCallback}, this option may be specified as a
+     * {@code defaultOption} or returned as the selected index.
      */
     public static final int OK                          = 3;
 
@@ -152,7 +152,7 @@
     private int selection;
 
     /**
-     * Construct a <code>ConfirmationCallback</code> with a
+     * Construct a {@code ConfirmationCallback} with a
      * message type, an option type and a default option.
      *
      * <p> Underlying security services use this constructor if
@@ -161,27 +161,27 @@
      *
      * <p>
      *
-     * @param messageType the message type (<code>INFORMATION</code>,
-     *                  <code>WARNING</code> or <code>ERROR</code>). <p>
+     * @param messageType the message type ({@code INFORMATION},
+     *                  {@code WARNING} or {@code ERROR}). <p>
      *
-     * @param optionType the option type (<code>YES_NO_OPTION</code>,
-     *                  <code>YES_NO_CANCEL_OPTION</code> or
-     *                  <code>OK_CANCEL_OPTION</code>). <p>
+     * @param optionType the option type ({@code YES_NO_OPTION},
+     *                  {@code YES_NO_CANCEL_OPTION} or
+     *                  {@code OK_CANCEL_OPTION}). <p>
      *
      * @param defaultOption the default option
-     *                  from the provided optionType (<code>YES</code>,
-     *                  <code>NO</code>, <code>CANCEL</code> or
-     *                  <code>OK</code>).
+     *                  from the provided optionType ({@code YES},
+     *                  {@code NO}, {@code CANCEL} or
+     *                  {@code OK}).
      *
      * @exception IllegalArgumentException if messageType is not either
-     *                  <code>INFORMATION</code>, <code>WARNING</code>,
-     *                  or <code>ERROR</code>, if optionType is not either
-     *                  <code>YES_NO_OPTION</code>,
-     *                  <code>YES_NO_CANCEL_OPTION</code>, or
-     *                  <code>OK_CANCEL_OPTION</code>,
-     *                  or if <code>defaultOption</code>
+     *                  {@code INFORMATION}, {@code WARNING},
+     *                  or {@code ERROR}, if optionType is not either
+     *                  {@code YES_NO_OPTION},
+     *                  {@code YES_NO_CANCEL_OPTION}, or
+     *                  {@code OK_CANCEL_OPTION},
+     *                  or if {@code defaultOption}
      *                  does not correspond to one of the options in
-     *                  <code>optionType</code>.
+     *                  {@code optionType}.
      */
     public ConfirmationCallback(int messageType,
                 int optionType, int defaultOption) {
@@ -212,35 +212,35 @@
     }
 
     /**
-     * Construct a <code>ConfirmationCallback</code> with a
+     * Construct a {@code ConfirmationCallback} with a
      * message type, a list of options and a default option.
      *
      * <p> Underlying security services use this constructor if
      * they require a confirmation different from the available preset
      * confirmations provided (for example, CONTINUE/ABORT or STOP/GO).
-     * The confirmation options are listed in the <code>options</code> array,
-     * and are displayed by the <code>CallbackHandler</code> implementation
+     * The confirmation options are listed in the {@code options} array,
+     * and are displayed by the {@code CallbackHandler} implementation
      * in a manner consistent with the way preset options are displayed.
      *
      * <p>
      *
-     * @param messageType the message type (<code>INFORMATION</code>,
-     *                  <code>WARNING</code> or <code>ERROR</code>). <p>
+     * @param messageType the message type ({@code INFORMATION},
+     *                  {@code WARNING} or {@code ERROR}). <p>
      *
      * @param options the list of confirmation options. <p>
      *
      * @param defaultOption the default option, represented as an index
-     *                  into the <code>options</code> array.
+     *                  into the {@code options} array.
      *
      * @exception IllegalArgumentException if messageType is not either
-     *                  <code>INFORMATION</code>, <code>WARNING</code>,
-     *                  or <code>ERROR</code>, if <code>options</code> is null,
-     *                  if <code>options</code> has a length of 0,
-     *                  if any element from <code>options</code> is null,
-     *                  if any element from <code>options</code>
-     *                  has a length of 0, or if <code>defaultOption</code>
+     *                  {@code INFORMATION}, {@code WARNING},
+     *                  or {@code ERROR}, if {@code options} is null,
+     *                  if {@code options} has a length of 0,
+     *                  if any element from {@code options} is null,
+     *                  if any element from {@code options}
+     *                  has a length of 0, or if {@code defaultOption}
      *                  does not lie within the array boundaries of
-     *                  <code>options</code>.
+     *                  {@code options}.
      */
     public ConfirmationCallback(int messageType,
                 String[] options, int defaultOption) {
@@ -261,7 +261,7 @@
     }
 
     /**
-     * Construct a <code>ConfirmationCallback</code> with a prompt,
+     * Construct a {@code ConfirmationCallback} with a prompt,
      * message type, an option type and a default option.
      *
      * <p> Underlying security services use this constructor if
@@ -272,29 +272,29 @@
      *
      * @param prompt the prompt used to describe the list of options. <p>
      *
-     * @param messageType the message type (<code>INFORMATION</code>,
-     *                  <code>WARNING</code> or <code>ERROR</code>). <p>
+     * @param messageType the message type ({@code INFORMATION},
+     *                  {@code WARNING} or {@code ERROR}). <p>
      *
-     * @param optionType the option type (<code>YES_NO_OPTION</code>,
-     *                  <code>YES_NO_CANCEL_OPTION</code> or
-     *                  <code>OK_CANCEL_OPTION</code>). <p>
+     * @param optionType the option type ({@code YES_NO_OPTION},
+     *                  {@code YES_NO_CANCEL_OPTION} or
+     *                  {@code OK_CANCEL_OPTION}). <p>
      *
      * @param defaultOption the default option
-     *                  from the provided optionType (<code>YES</code>,
-     *                  <code>NO</code>, <code>CANCEL</code> or
-     *                  <code>OK</code>).
+     *                  from the provided optionType ({@code YES},
+     *                  {@code NO}, {@code CANCEL} or
+     *                  {@code OK}).
      *
-     * @exception IllegalArgumentException if <code>prompt</code> is null,
-     *                  if <code>prompt</code> has a length of 0,
+     * @exception IllegalArgumentException if {@code prompt} is null,
+     *                  if {@code prompt} has a length of 0,
      *                  if messageType is not either
-     *                  <code>INFORMATION</code>, <code>WARNING</code>,
-     *                  or <code>ERROR</code>, if optionType is not either
-     *                  <code>YES_NO_OPTION</code>,
-     *                  <code>YES_NO_CANCEL_OPTION</code>, or
-     *                  <code>OK_CANCEL_OPTION</code>,
-     *                  or if <code>defaultOption</code>
+     *                  {@code INFORMATION}, {@code WARNING},
+     *                  or {@code ERROR}, if optionType is not either
+     *                  {@code YES_NO_OPTION},
+     *                  {@code YES_NO_CANCEL_OPTION}, or
+     *                  {@code OK_CANCEL_OPTION},
+     *                  or if {@code defaultOption}
      *                  does not correspond to one of the options in
-     *                  <code>optionType</code>.
+     *                  {@code optionType}.
      */
     public ConfirmationCallback(String prompt, int messageType,
                 int optionType, int defaultOption) {
@@ -327,39 +327,39 @@
     }
 
     /**
-     * Construct a <code>ConfirmationCallback</code> with a prompt,
+     * Construct a {@code ConfirmationCallback} with a prompt,
      * message type, a list of options and a default option.
      *
      * <p> Underlying security services use this constructor if
      * they require a confirmation different from the available preset
      * confirmations provided (for example, CONTINUE/ABORT or STOP/GO).
-     * The confirmation options are listed in the <code>options</code> array,
-     * and are displayed by the <code>CallbackHandler</code> implementation
+     * The confirmation options are listed in the {@code options} array,
+     * and are displayed by the {@code CallbackHandler} implementation
      * in a manner consistent with the way preset options are displayed.
      *
      * <p>
      *
      * @param prompt the prompt used to describe the list of options. <p>
      *
-     * @param messageType the message type (<code>INFORMATION</code>,
-     *                  <code>WARNING</code> or <code>ERROR</code>). <p>
+     * @param messageType the message type ({@code INFORMATION},
+     *                  {@code WARNING} or {@code ERROR}). <p>
      *
      * @param options the list of confirmation options. <p>
      *
      * @param defaultOption the default option, represented as an index
-     *                  into the <code>options</code> array.
+     *                  into the {@code options} array.
      *
-     * @exception IllegalArgumentException if <code>prompt</code> is null,
-     *                  if <code>prompt</code> has a length of 0,
+     * @exception IllegalArgumentException if {@code prompt} is null,
+     *                  if {@code prompt} has a length of 0,
      *                  if messageType is not either
-     *                  <code>INFORMATION</code>, <code>WARNING</code>,
-     *                  or <code>ERROR</code>, if <code>options</code> is null,
-     *                  if <code>options</code> has a length of 0,
-     *                  if any element from <code>options</code> is null,
-     *                  if any element from <code>options</code>
-     *                  has a length of 0, or if <code>defaultOption</code>
+     *                  {@code INFORMATION}, {@code WARNING},
+     *                  or {@code ERROR}, if {@code options} is null,
+     *                  if {@code options} has a length of 0,
+     *                  if any element from {@code options} is null,
+     *                  if any element from {@code options}
+     *                  has a length of 0, or if {@code defaultOption}
      *                  does not lie within the array boundaries of
-     *                  <code>options</code>.
+     *                  {@code options}.
      */
     public ConfirmationCallback(String prompt, int messageType,
                 String[] options, int defaultOption) {
@@ -386,8 +386,8 @@
      *
      * <p>
      *
-     * @return the prompt, or null if this <code>ConfirmationCallback</code>
-     *          was instantiated without a <code>prompt</code>.
+     * @return the prompt, or null if this {@code ConfirmationCallback}
+     *          was instantiated without a {@code prompt}.
      */
     public String getPrompt() {
         return prompt;
@@ -398,8 +398,8 @@
      *
      * <p>
      *
-     * @return the message type (<code>INFORMATION</code>,
-     *          <code>WARNING</code> or <code>ERROR</code>).
+     * @return the message type ({@code INFORMATION},
+     *          {@code WARNING} or {@code ERROR}).
      */
     public int getMessageType() {
         return messageType;
@@ -408,20 +408,20 @@
     /**
      * Get the option type.
      *
-     * <p> If this method returns <code>UNSPECIFIED_OPTION</code>, then this
-     * <code>ConfirmationCallback</code> was instantiated with
-     * <code>options</code> instead of an <code>optionType</code>.
-     * In this case, invoke the <code>getOptions</code> method
+     * <p> If this method returns {@code UNSPECIFIED_OPTION}, then this
+     * {@code ConfirmationCallback} was instantiated with
+     * {@code options} instead of an {@code optionType}.
+     * In this case, invoke the {@code getOptions} method
      * to determine which confirmation options to display.
      *
      * <p>
      *
-     * @return the option type (<code>YES_NO_OPTION</code>,
-     *          <code>YES_NO_CANCEL_OPTION</code> or
-     *          <code>OK_CANCEL_OPTION</code>), or
-     *          <code>UNSPECIFIED_OPTION</code> if this
-     *          <code>ConfirmationCallback</code> was instantiated with
-     *          <code>options</code> instead of an <code>optionType</code>.
+     * @return the option type ({@code YES_NO_OPTION},
+     *          {@code YES_NO_CANCEL_OPTION} or
+     *          {@code OK_CANCEL_OPTION}), or
+     *          {@code UNSPECIFIED_OPTION} if this
+     *          {@code ConfirmationCallback} was instantiated with
+     *          {@code options} instead of an {@code optionType}.
      */
     public int getOptionType() {
         return optionType;
@@ -433,8 +433,8 @@
      * <p>
      *
      * @return the list of confirmation options, or null if this
-     *          <code>ConfirmationCallback</code> was instantiated with
-     *          an <code>optionType</code> instead of <code>options</code>.
+     *          {@code ConfirmationCallback} was instantiated with
+     *          an {@code optionType} instead of {@code options}.
      */
     public String[] getOptions() {
         return options;
@@ -446,14 +446,14 @@
      * <p>
      *
      * @return the default option, represented as
-     *          <code>YES</code>, <code>NO</code>, <code>OK</code> or
-     *          <code>CANCEL</code> if an <code>optionType</code>
+     *          {@code YES}, {@code NO}, {@code OK} or
+     *          {@code CANCEL} if an {@code optionType}
      *          was specified to the constructor of this
-     *          <code>ConfirmationCallback</code>.
+     *          {@code ConfirmationCallback}.
      *          Otherwise, this method returns the default option as
      *          an index into the
-     *          <code>options</code> array specified to the constructor
-     *          of this <code>ConfirmationCallback</code>.
+     *          {@code options} array specified to the constructor
+     *          of this {@code ConfirmationCallback}.
      */
     public int getDefaultOption() {
         return defaultOption;
@@ -464,13 +464,13 @@
      *
      * <p>
      *
-     * @param selection the selection represented as <code>YES</code>,
-     *          <code>NO</code>, <code>OK</code> or <code>CANCEL</code>
-     *          if an <code>optionType</code> was specified to the constructor
-     *          of this <code>ConfirmationCallback</code>.
+     * @param selection the selection represented as {@code YES},
+     *          {@code NO}, {@code OK} or {@code CANCEL}
+     *          if an {@code optionType} was specified to the constructor
+     *          of this {@code ConfirmationCallback}.
      *          Otherwise, the selection represents the index into the
-     *          <code>options</code> array specified to the constructor
-     *          of this <code>ConfirmationCallback</code>.
+     *          {@code options} array specified to the constructor
+     *          of this {@code ConfirmationCallback}.
      *
      * @see #getSelectedIndex
      */
@@ -484,14 +484,14 @@
      * <p>
      *
      * @return the selected confirmation option represented as
-     *          <code>YES</code>, <code>NO</code>, <code>OK</code> or
-     *          <code>CANCEL</code> if an <code>optionType</code>
+     *          {@code YES}, {@code NO}, {@code OK} or
+     *          {@code CANCEL} if an {@code optionType}
      *          was specified to the constructor of this
-     *          <code>ConfirmationCallback</code>.
+     *          {@code ConfirmationCallback}.
      *          Otherwise, this method returns the selected confirmation
      *          option as an index into the
-     *          <code>options</code> array specified to the constructor
-     *          of this <code>ConfirmationCallback</code>.
+     *          {@code options} array specified to the constructor
+     *          of this {@code ConfirmationCallback}.
      *
      * @see #setSelectedIndex
      */
--- a/src/share/classes/javax/security/auth/callback/LanguageCallback.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/callback/LanguageCallback.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,8 +29,8 @@
 
 /**
  * <p> Underlying security services instantiate and pass a
- * <code>LanguageCallback</code> to the <code>handle</code>
- * method of a <code>CallbackHandler</code> to retrieve the <code>Locale</code>
+ * {@code LanguageCallback} to the {@code handle}
+ * method of a {@code CallbackHandler} to retrieve the {@code Locale}
  * used for localizing text.
  *
  * @see javax.security.auth.callback.CallbackHandler
@@ -46,16 +46,16 @@
     private Locale locale;
 
     /**
-     * Construct a <code>LanguageCallback</code>.
+     * Construct a {@code LanguageCallback}.
      */
     public LanguageCallback() { }
 
     /**
-     * Set the retrieved <code>Locale</code>.
+     * Set the retrieved {@code Locale}.
      *
      * <p>
      *
-     * @param locale the retrieved <code>Locale</code>.
+     * @param locale the retrieved {@code Locale}.
      *
      * @see #getLocale
      */
@@ -64,12 +64,12 @@
     }
 
     /**
-     * Get the retrieved <code>Locale</code>.
+     * Get the retrieved {@code Locale}.
      *
      * <p>
      *
-     * @return the retrieved <code>Locale</code>, or null
-     *          if no <code>Locale</code> could be retrieved.
+     * @return the retrieved {@code Locale}, or null
+     *          if no {@code Locale} could be retrieved.
      *
      * @see #setLocale
      */
--- a/src/share/classes/javax/security/auth/callback/NameCallback.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/callback/NameCallback.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,8 +27,8 @@
 
 /**
  * <p> Underlying security services instantiate and pass a
- * <code>NameCallback</code> to the <code>handle</code>
- * method of a <code>CallbackHandler</code> to retrieve name information.
+ * {@code NameCallback} to the {@code handle}
+ * method of a {@code CallbackHandler} to retrieve name information.
  *
  * @see javax.security.auth.callback.CallbackHandler
  */
@@ -53,14 +53,14 @@
     private String inputName;
 
     /**
-     * Construct a <code>NameCallback</code> with a prompt.
+     * Construct a {@code NameCallback} with a prompt.
      *
      * <p>
      *
      * @param prompt the prompt used to request the name.
      *
-     * @exception IllegalArgumentException if <code>prompt</code> is null
-     *                  or if <code>prompt</code> has a length of 0.
+     * @exception IllegalArgumentException if {@code prompt} is null
+     *                  or if {@code prompt} has a length of 0.
      */
     public NameCallback(String prompt) {
         if (prompt == null || prompt.length() == 0)
@@ -69,7 +69,7 @@
     }
 
     /**
-     * Construct a <code>NameCallback</code> with a prompt
+     * Construct a {@code NameCallback} with a prompt
      * and default name.
      *
      * <p>
@@ -79,10 +79,10 @@
      * @param defaultName the name to be used as the default name displayed
      *                  with the prompt.
      *
-     * @exception IllegalArgumentException if <code>prompt</code> is null,
-     *                  if <code>prompt</code> has a length of 0,
-     *                  if <code>defaultName</code> is null,
-     *                  or if <code>defaultName</code> has a length of 0.
+     * @exception IllegalArgumentException if {@code prompt} is null,
+     *                  if {@code prompt} has a length of 0,
+     *                  if {@code defaultName} is null,
+     *                  or if {@code defaultName} has a length of 0.
      */
     public NameCallback(String prompt, String defaultName) {
         if (prompt == null || prompt.length() == 0 ||
@@ -109,8 +109,8 @@
      *
      * <p>
      *
-     * @return the default name, or null if this <code>NameCallback</code>
-     *          was not instantiated with a <code>defaultName</code>.
+     * @return the default name, or null if this {@code NameCallback}
+     *          was not instantiated with a {@code defaultName}.
      */
     public String getDefaultName() {
         return defaultName;
--- a/src/share/classes/javax/security/auth/callback/PasswordCallback.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/callback/PasswordCallback.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,8 +27,8 @@
 
 /**
  * <p> Underlying security services instantiate and pass a
- * <code>PasswordCallback</code> to the <code>handle</code>
- * method of a <code>CallbackHandler</code> to retrieve password information.
+ * {@code PasswordCallback} to the {@code handle}
+ * method of a {@code CallbackHandler} to retrieve password information.
  *
  * @see javax.security.auth.callback.CallbackHandler
  */
@@ -53,7 +53,7 @@
     private char[] inputPassword;
 
     /**
-     * Construct a <code>PasswordCallback</code> with a prompt
+     * Construct a {@code PasswordCallback} with a prompt
      * and a boolean specifying whether the password should be displayed
      * as it is being typed.
      *
@@ -64,8 +64,8 @@
      * @param echoOn true if the password should be displayed
      *                  as it is being typed.
      *
-     * @exception IllegalArgumentException if <code>prompt</code> is null or
-     *                  if <code>prompt</code> has a length of 0.
+     * @exception IllegalArgumentException if {@code prompt} is null or
+     *                  if {@code prompt} has a length of 0.
      */
     public PasswordCallback(String prompt, boolean echoOn) {
         if (prompt == null || prompt.length() == 0)
--- a/src/share/classes/javax/security/auth/callback/TextInputCallback.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/callback/TextInputCallback.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,8 +27,8 @@
 
 /**
  * <p> Underlying security services instantiate and pass a
- * <code>TextInputCallback</code> to the <code>handle</code>
- * method of a <code>CallbackHandler</code> to retrieve generic text
+ * {@code TextInputCallback} to the {@code handle}
+ * method of a {@code CallbackHandler} to retrieve generic text
  * information.
  *
  * @see javax.security.auth.callback.CallbackHandler
@@ -54,14 +54,14 @@
     private String inputText;
 
     /**
-     * Construct a <code>TextInputCallback</code> with a prompt.
+     * Construct a {@code TextInputCallback} with a prompt.
      *
      * <p>
      *
      * @param prompt the prompt used to request the information.
      *
-     * @exception IllegalArgumentException if <code>prompt</code> is null
-     *                  or if <code>prompt</code> has a length of 0.
+     * @exception IllegalArgumentException if {@code prompt} is null
+     *                  or if {@code prompt} has a length of 0.
      */
     public TextInputCallback(String prompt) {
         if (prompt == null || prompt.length() == 0)
@@ -70,7 +70,7 @@
     }
 
     /**
-     * Construct a <code>TextInputCallback</code> with a prompt
+     * Construct a {@code TextInputCallback} with a prompt
      * and default input value.
      *
      * <p>
@@ -80,10 +80,10 @@
      * @param defaultText the text to be used as the default text displayed
      *                  with the prompt.
      *
-     * @exception IllegalArgumentException if <code>prompt</code> is null,
-     *                  if <code>prompt</code> has a length of 0,
-     *                  if <code>defaultText</code> is null
-     *                  or if <code>defaultText</code> has a length of 0.
+     * @exception IllegalArgumentException if {@code prompt} is null,
+     *                  if {@code prompt} has a length of 0,
+     *                  if {@code defaultText} is null
+     *                  or if {@code defaultText} has a length of 0.
      */
     public TextInputCallback(String prompt, String defaultText) {
         if (prompt == null || prompt.length() == 0 ||
@@ -110,8 +110,8 @@
      *
      * <p>
      *
-     * @return the default text, or null if this <code>TextInputCallback</code>
-     *          was not instantiated with <code>defaultText</code>.
+     * @return the default text, or null if this {@code TextInputCallback}
+     *          was not instantiated with {@code defaultText}.
      */
     public String getDefaultText() {
         return defaultText;
--- a/src/share/classes/javax/security/auth/callback/TextOutputCallback.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/callback/TextOutputCallback.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,8 +27,8 @@
 
 /**
  * <p> Underlying security services instantiate and pass a
- * <code>TextOutputCallback</code> to the <code>handle</code>
- * method of a <code>CallbackHandler</code> to display information messages,
+ * {@code TextOutputCallback} to the {@code handle}
+ * method of a {@code CallbackHandler} to display information messages,
  * warning messages and error messages.
  *
  * @see javax.security.auth.callback.CallbackHandler
@@ -61,16 +61,16 @@
      *
      * <p>
      *
-     * @param messageType the message type (<code>INFORMATION</code>,
-     *                  <code>WARNING</code> or <code>ERROR</code>). <p>
+     * @param messageType the message type ({@code INFORMATION},
+     *                  {@code WARNING} or {@code ERROR}). <p>
      *
      * @param message the message to be displayed. <p>
      *
-     * @exception IllegalArgumentException if <code>messageType</code>
-     *                  is not either <code>INFORMATION</code>,
-     *                  <code>WARNING</code> or <code>ERROR</code>,
-     *                  if <code>message</code> is null,
-     *                  or if <code>message</code> has a length of 0.
+     * @exception IllegalArgumentException if {@code messageType}
+     *                  is not either {@code INFORMATION},
+     *                  {@code WARNING} or {@code ERROR},
+     *                  if {@code message} is null,
+     *                  or if {@code message} has a length of 0.
      */
     public TextOutputCallback(int messageType, String message) {
         if ((messageType != INFORMATION &&
@@ -87,8 +87,8 @@
      *
      * <p>
      *
-     * @return the message type (<code>INFORMATION</code>,
-     *                  <code>WARNING</code> or <code>ERROR</code>).
+     * @return the message type ({@code INFORMATION},
+     *                  {@code WARNING} or {@code ERROR}).
      */
     public int getMessageType() {
         return messageType;
--- a/src/share/classes/javax/security/auth/callback/UnsupportedCallbackException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/callback/UnsupportedCallbackException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,8 +26,8 @@
 package javax.security.auth.callback;
 
 /**
- * Signals that a <code>CallbackHandler</code> does not
- * recognize a particular <code>Callback</code>.
+ * Signals that a {@code CallbackHandler} does not
+ * recognize a particular {@code Callback}.
  *
  */
 public class UnsupportedCallbackException extends Exception {
@@ -40,12 +40,12 @@
     private Callback callback;
 
     /**
-     * Constructs a <code>UnsupportedCallbackException</code>
+     * Constructs a {@code UnsupportedCallbackException}
      * with no detail message.
      *
      * <p>
      *
-     * @param callback the unrecognized <code>Callback</code>.
+     * @param callback the unrecognized {@code Callback}.
      */
     public UnsupportedCallbackException(Callback callback) {
         super();
@@ -59,7 +59,7 @@
      *
      * <p>
      *
-     * @param callback the unrecognized <code>Callback</code>. <p>
+     * @param callback the unrecognized {@code Callback}. <p>
      *
      * @param msg the detail message.
      */
@@ -69,11 +69,11 @@
     }
 
     /**
-     * Get the unrecognized <code>Callback</code>.
+     * Get the unrecognized {@code Callback}.
      *
      * <p>
      *
-     * @return the unrecognized <code>Callback</code>.
+     * @return the unrecognized {@code Callback}.
      */
     public Callback getCallback() {
         return callback;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/javax/security/auth/callback/package-info.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * This package provides the classes necessary for services
+ * to interact with applications in order to retrieve
+ * information (authentication data including usernames
+ * or passwords, for example) or to display information
+ * (error and warning messages, for example).
+ *
+ * @since JDK1.4
+ */
+package javax.security.auth.callback;
--- a/src/share/classes/javax/security/auth/callback/package.html	Thu Jul 18 03:38:49 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,57 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
-<html>
-<head>
-<!--
-Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
-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.
--->
-
-</head>
-<body bgcolor="white">
-
-	This package provides the classes necessary for services
- 	to interact with applications in order to retrieve 
- 	information (authentication data including usernames
- 	or passwords, for example) or to display information
- 	(error and warning messages, for example).
-
-<!--
-<h2>Package Specification</h2>
-
-##### FILL IN ANY SPECS NEEDED BY JAVA COMPATIBILITY KIT #####
-<ul>
-  <li><a href="">##### REFER TO ANY FRAMEMAKER SPECIFICATION HERE #####</a>
-</ul>
-
-<h2>Related Documentation</h2>
-
-For overviews, tutorials, examples, guides, and tool documentation, please see:
-<ul>
-  <li><a href="">##### REFER TO NON-SPEC DOCUMENTATION HERE #####</a>
-</ul>
-
--->
-
-@since JDK1.4
-</body>
-</html>
--- a/src/share/classes/javax/security/auth/kerberos/DelegationPermission.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/kerberos/DelegationPermission.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -38,7 +38,7 @@
  * This class is used to restrict the usage of the Kerberos
  * delegation model, ie: forwardable and proxiable tickets.
  * <p>
- * The target name of this <code>Permission</code> specifies a pair of
+ * The target name of this {@code Permission} specifies a pair of
  * kerberos service principals. The first is the subordinate service principal
  * being entrusted to use the TGT. The second service principal designates
  * the target service the subordinate service principal is to
@@ -71,15 +71,15 @@
     private transient String subordinate, service;
 
     /**
-     * Create a new <code>DelegationPermission</code>
+     * Create a new {@code DelegationPermission}
      * with the specified subordinate and target principals.
      *
      * <p>
      *
      * @param principals the name of the subordinate and target principals
      *
-     * @throws NullPointerException if <code>principals</code> is <code>null</code>.
-     * @throws IllegalArgumentException if <code>principals</code> is empty.
+     * @throws NullPointerException if {@code principals} is {@code null}.
+     * @throws IllegalArgumentException if {@code principals} is empty.
      */
     public DelegationPermission(String principals) {
         super(principals);
@@ -87,7 +87,7 @@
     }
 
     /**
-     * Create a new <code>DelegationPermission</code>
+     * Create a new {@code DelegationPermission}
      * with the specified subordinate and target principals.
      * <p>
      *
@@ -95,8 +95,8 @@
      * <p>
      * @param actions should be null.
      *
-     * @throws NullPointerException if <code>principals</code> is <code>null</code>.
-     * @throws IllegalArgumentException if <code>principals</code> is empty.
+     * @throws NullPointerException if {@code principals} is {@code null}.
+     * @throws IllegalArgumentException if {@code principals} is empty.
      */
     public DelegationPermission(String principals, String actions) {
         super(principals, actions);
@@ -134,7 +134,7 @@
      * Checks if this Kerberos delegation permission object "implies" the
      * specified permission.
      * <P>
-     * If none of the above are true, <code>implies</code> returns false.
+     * If none of the above are true, {@code implies} returns false.
      * @param p the permission to check against.
      *
      * @return true if the specified permission is implied by this object,
--- a/src/share/classes/javax/security/auth/kerberos/KerberosKey.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/kerberos/KerberosKey.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -76,7 +76,7 @@
     private int versionNum;
 
    /**
-    * <code>KeyImpl</code> is serialized by writing out the ASN1 Encoded bytes
+    * {@code KeyImpl} is serialized by writing out the ASN1 Encoded bytes
     * of the encryption key.
     * The ASN1 encoding is defined in RFC4120 and as  follows:
     * <pre>
@@ -241,7 +241,7 @@
     /**
      * Returns a hashcode for this KerberosKey.
      *
-     * @return a hashCode() for the <code>KerberosKey</code>
+     * @return a hashCode() for the {@code KerberosKey}
      * @since 1.6
      */
     public int hashCode() {
@@ -260,8 +260,8 @@
     /**
      * Compares the specified Object with this KerberosKey for equality.
      * Returns true if the given object is also a
-     * <code>KerberosKey</code> and the two
-     * <code>KerberosKey</code> instances are equivalent.
+     * {@code KerberosKey} and the two
+     * {@code KerberosKey} instances are equivalent.
      *
      * @param other the Object to compare to
      * @return true if the specified object is equal to this KerberosKey,
--- a/src/share/classes/javax/security/auth/kerberos/KerberosPrincipal.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/kerberos/KerberosPrincipal.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -181,11 +181,11 @@
     /**
      * Returns a hashcode for this principal. The hash code is defined to
      * be the result of the following  calculation:
-     * <pre><code>
+     * <pre>{@code
      *  hashCode = getName().hashCode();
-     * </code></pre>
+     * }</pre>
      *
-     * @return a hashCode() for the <code>KerberosPrincipal</code>
+     * @return a hashCode() for the {@code KerberosPrincipal}
      */
     public int hashCode() {
         return getName().hashCode();
@@ -194,11 +194,11 @@
     /**
      * Compares the specified Object with this Principal for equality.
      * Returns true if the given object is also a
-     * <code>KerberosPrincipal</code> and the two
-     * <code>KerberosPrincipal</code> instances are equivalent.
-     * More formally two <code>KerberosPrincipal</code> instances are equal
-     * if the values returned by <code>getName()</code> are equal and the
-     * values returned by <code>getNameType()</code> are equal.
+     * {@code KerberosPrincipal} and the two
+     * {@code KerberosPrincipal} instances are equivalent.
+     * More formally two {@code KerberosPrincipal} instances are equal
+     * if the values returned by {@code getName()} are equal and the
+     * values returned by {@code getNameType()} are equal.
      *
      * @param other the Object to compare to
      * @return true if the Object passed in represents the same principal
@@ -225,7 +225,7 @@
     /**
      * Save the KerberosPrincipal object to a stream
      *
-     * @serialData this <code>KerberosPrincipal</code> is serialized
+     * @serialData this {@code KerberosPrincipal} is serialized
      *          by writing out the PrincipalName and the
      *          realm in their DER-encoded form as specified in Section 5.2.2 of
      *          <a href=http://www.ietf.org/rfc/rfc4120.txt> RFC4120</a>.
--- a/src/share/classes/javax/security/auth/kerberos/KerberosTicket.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/kerberos/KerberosTicket.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -103,7 +103,7 @@
     private byte[] asn1Encoding;
 
     /**
-     *<code>KeyImpl</code> is serialized by writing out the ASN1 Encoded bytes
+     *{@code KeyImpl} is serialized by writing out the ASN1 Encoded bytes
      * of the encryption key. The ASN1 encoding is defined in RFC4120 and as
      * follows:
      * <pre>
@@ -667,7 +667,7 @@
     /**
      * Returns a hashcode for this KerberosTicket.
      *
-     * @return a hashCode() for the <code>KerberosTicket</code>
+     * @return a hashCode() for the {@code KerberosTicket}
      * @since 1.6
      */
     public int hashCode() {
@@ -704,8 +704,8 @@
     /**
      * Compares the specified Object with this KerberosTicket for equality.
      * Returns true if the given object is also a
-     * <code>KerberosTicket</code> and the two
-     * <code>KerberosTicket</code> instances are equivalent.
+     * {@code KerberosTicket} and the two
+     * {@code KerberosTicket} instances are equivalent.
      *
      * @param other the Object to compare to
      * @return true if the specified object is equal to this KerberosTicket,
--- a/src/share/classes/javax/security/auth/kerberos/KeyImpl.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/kerberos/KeyImpl.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -166,7 +166,7 @@
     }
 
     /**
-     * @serialData this <code>KeyImpl</code> is serialized by
+     * @serialData this {@code KeyImpl} is serialized by
      * writing out the ASN1 Encoded bytes of the encryption key.
      * The ASN1 encoding is defined in RFC4120 and as  follows:
      * EncryptionKey   ::= SEQUENCE {
--- a/src/share/classes/javax/security/auth/kerberos/KeyTab.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/kerberos/KeyTab.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -312,7 +312,7 @@
     /**
      * Returns a hashcode for this KeyTab.
      *
-     * @return a hashCode() for the <code>KeyTab</code>
+     * @return a hashCode() for the {@code KeyTab}
      */
     public int hashCode() {
         return Objects.hash(file, princ, bound);
@@ -321,8 +321,8 @@
     /**
      * Compares the specified Object with this KeyTab for equality.
      * Returns true if the given object is also a
-     * <code>KeyTab</code> and the two
-     * <code>KeyTab</code> instances are equivalent.
+     * {@code KeyTab} and the two
+     * {@code KeyTab} instances are equivalent.
      *
      * @param other the Object to compare to
      * @return true if the specified object is equal to this KeyTab
--- a/src/share/classes/javax/security/auth/kerberos/ServicePermission.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/kerberos/ServicePermission.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -50,7 +50,7 @@
  * used within.
  * <p>
  * The service principal name is the canonical name of the
- * <code>KereberosPrincipal</code> supplying the service, that is
+ * {@code KereberosPrincipal} supplying the service, that is
  * the KerberosPrincipal represents a Kerberos service
  * principal. This name is treated in a case sensitive manner.
  * An asterisk may appear by itself, to signify any service principal.
@@ -135,9 +135,9 @@
                             // created and re-used in the getAction function.
 
     /**
-     * Create a new <code>ServicePermission</code>
-     * with the specified <code>servicePrincipal</code>
-     * and <code>action</code>.
+     * Create a new {@code ServicePermission}
+     * with the specified {@code servicePrincipal}
+     * and {@code action}.
      *
      * @param servicePrincipal the name of the service principal.
      * An asterisk may appear by itself, to signify any service principal.
@@ -169,7 +169,7 @@
      * Checks if this Kerberos service permission object "implies" the
      * specified permission.
      * <P>
-     * If none of the above are true, <code>implies</code> returns false.
+     * If none of the above are true, {@code implies} returns false.
      * @param p the permission to check against.
      *
      * @return true if the specified permission is implied by this object,
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/javax/security/auth/kerberos/package-info.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * This package contains utility classes related to the Kerberos network
+ * authentication protocol. They do not provide much Kerberos support
+ * themselves.<p>
+ *
+ * The Kerberos network authentication protocol is defined in
+ * <a href=http://www.ietf.org/rfc/rfc4120.txt>RFC 4120</a>. The Java
+ * platform contains support for the client side of Kerberos via the
+ * {@link org.ietf.jgss} package. There might also be
+ * a login module that implements
+ * {@link javax.security.auth.spi.LoginModule LoginModule} to authenticate
+ * Kerberos principals.<p>
+ *
+ * You can provide the name of your default realm and Key Distribution
+ * Center (KDC) host for that realm using the system properties
+ * {@code java.security.krb5.realm} and {@code java.security.krb5.kdc}.
+ * Both properties must be set.
+ * Alternatively, the {@code java.security.krb5.conf} system property can
+ * be set to the location of an MIT style {@code krb5.conf} configuration
+ * file. If none of these system properties are set, the {@code krb5.conf}
+ * file is searched for in an implementation-specific manner. Typically,
+ * an implementation will first look for a {@code krb5.conf} file in
+ * {@code <java-home>/lib/security} and failing that, in an OS-specific
+ * location.<p>
+ *
+ * @since JDK1.4
+ */
+package javax.security.auth.kerberos;
--- a/src/share/classes/javax/security/auth/kerberos/package.html	Thu Jul 18 03:38:49 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,74 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
-<html>
-<head>
-<!--
-Copyright (c) 2001, 2006, Oracle and/or its affiliates. All rights reserved.
-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.
--->
-
-</head>
-<body bgcolor="white">
-
-    This package contains utility classes related to the Kerberos network
-    authentication protocol. They do not provide much Kerberos support
-    themselves.<p>
-
-    The Kerberos network authentication protocol is defined in 
-    <a href=http://www.ietf.org/rfc/rfc4120.txt>RFC 4120</a>. The Java
-    platform contains support for the client side of Kerberos via the 
-    {@link org.ietf.jgss} package. There might also be 
-    a login module that implements
-    {@link javax.security.auth.spi.LoginModule LoginModule} to authenticate 
-    Kerberos principals.<p>
-
-    You can provide the name of your default realm and Key Distribution
-    Center (KDC) host for that realm using the system properties
-    {@code java.security.krb5.realm} and {@code java.security.krb5.kdc}.
-    Both properties must be set.
-    Alternatively, the {@code java.security.krb5.conf} system property can
-    be set to the location of an MIT style {@code krb5.conf} configuration
-    file. If none of these system properties are set, the {@code krb5.conf}
-    file is searched for in an implementation-specific manner. Typically,
-    an implementation will first look for a {@code krb5.conf} file in
-    {@code <java-home>/lib/security} and failing that, in an OS-specific
-    location.<p>
-<!--
-<h2>Package Specification</h2>
-
-##### FILL IN ANY SPECS NEEDED BY JAVA COMPATIBILITY KIT #####
-<ul>
-  <li><a href="">##### REFER TO ANY FRAMEMAKER SPECIFICATION HERE #####</a>
-</ul>
-
-<h2>Related Documentation</h2>
-
-For overviews, tutorials, examples, guides, and tool documentation, please see:
-<ul>
-  <li><a href="">##### REFER TO NON-SPEC DOCUMENTATION HERE #####</a>
-</ul>
-
--->
-
-@since JDK1.4
-</body>
-</html>
--- a/src/share/classes/javax/security/auth/login/AccountExpiredException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/login/AccountExpiredException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,9 +29,9 @@
  * Signals that a user account has expired.
  *
  * <p> This exception is thrown by LoginModules when they determine
- * that an account has expired.  For example, a <code>LoginModule</code>,
+ * that an account has expired.  For example, a {@code LoginModule},
  * after successfully authenticating a user, may determine that the
- * user's account has expired.  In this case the <code>LoginModule</code>
+ * user's account has expired.  In this case the {@code LoginModule}
  * throws this exception to notify the application.  The application can
  * then take the appropriate steps to notify the user.
  *
--- a/src/share/classes/javax/security/auth/login/AppConfigurationEntry.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/login/AppConfigurationEntry.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,14 +29,14 @@
 import java.util.Collections;
 
 /**
- * This class represents a single <code>LoginModule</code> entry
+ * This class represents a single {@code LoginModule} entry
  * configured for the application specified in the
- * <code>getAppConfigurationEntry(String appName)</code>
- * method in the <code>Configuration</code> class.  Each respective
- * <code>AppConfigurationEntry</code> contains a <code>LoginModule</code> name,
- * a control flag (specifying whether this <code>LoginModule</code> is
+ * {@code getAppConfigurationEntry(String appName)}
+ * method in the {@code Configuration} class.  Each respective
+ * {@code AppConfigurationEntry} contains a {@code LoginModule} name,
+ * a control flag (specifying whether this {@code LoginModule} is
  * REQUIRED, REQUISITE, SUFFICIENT, or OPTIONAL), and LoginModule-specific
- * options.  Please refer to the <code>Configuration</code> class for
+ * options.  Please refer to the {@code Configuration} class for
  * more information on the different control flags and their semantics.
  *
  * @see javax.security.auth.login.Configuration
@@ -50,25 +50,25 @@
     /**
      * Default constructor for this class.
      *
-     * <p> This entry represents a single <code>LoginModule</code>
+     * <p> This entry represents a single {@code LoginModule}
      * entry configured for the application specified in the
-     * <code>getAppConfigurationEntry(String appName)</code>
-     * method from the <code>Configuration</code> class.
+     * {@code getAppConfigurationEntry(String appName)}
+     * method from the {@code Configuration} class.
      *
      * @param loginModuleName String representing the class name of the
-     *                  <code>LoginModule</code> configured for the
+     *                  {@code LoginModule} configured for the
      *                  specified application. <p>
      *
      * @param controlFlag either REQUIRED, REQUISITE, SUFFICIENT,
      *                  or OPTIONAL. <p>
      *
-     * @param options the options configured for this <code>LoginModule</code>.
+     * @param options the options configured for this {@code LoginModule}.
      *
-     * @exception IllegalArgumentException if <code>loginModuleName</code>
-     *                  is null, if <code>LoginModuleName</code>
-     *                  has a length of 0, if <code>controlFlag</code>
+     * @exception IllegalArgumentException if {@code loginModuleName}
+     *                  is null, if {@code LoginModuleName}
+     *                  has a length of 0, if {@code controlFlag}
      *                  is not either REQUIRED, REQUISITE, SUFFICIENT
-     *                  or OPTIONAL, or if <code>options</code> is null.
+     *                  or OPTIONAL, or if {@code options} is null.
      */
     public AppConfigurationEntry(String loginModuleName,
                                 LoginModuleControlFlag controlFlag,
@@ -88,9 +88,9 @@
     }
 
     /**
-     * Get the class name of the configured <code>LoginModule</code>.
+     * Get the class name of the configured {@code LoginModule}.
      *
-     * @return the class name of the configured <code>LoginModule</code> as
+     * @return the class name of the configured {@code LoginModule} as
      *          a String.
      */
     public String getLoginModuleName() {
@@ -100,28 +100,28 @@
     /**
      * Return the controlFlag
      * (either REQUIRED, REQUISITE, SUFFICIENT, or OPTIONAL)
-     * for this <code>LoginModule</code>.
+     * for this {@code LoginModule}.
      *
      * @return the controlFlag
      *          (either REQUIRED, REQUISITE, SUFFICIENT, or OPTIONAL)
-     *          for this <code>LoginModule</code>.
+     *          for this {@code LoginModule}.
      */
     public LoginModuleControlFlag getControlFlag() {
         return controlFlag;
     }
 
     /**
-     * Get the options configured for this <code>LoginModule</code>.
+     * Get the options configured for this {@code LoginModule}.
      *
-     * @return the options configured for this <code>LoginModule</code>
-     *          as an unmodifiable <code>Map</code>.
+     * @return the options configured for this {@code LoginModule}
+     *          as an unmodifiable {@code Map}.
      */
     public Map<String,?> getOptions() {
         return options;
     }
 
     /**
-     * This class represents whether or not a <code>LoginModule</code>
+     * This class represents whether or not a {@code LoginModule}
      * is REQUIRED, REQUISITE, SUFFICIENT or OPTIONAL.
      */
     public static class LoginModuleControlFlag {
@@ -129,25 +129,25 @@
         private String controlFlag;
 
         /**
-         * Required <code>LoginModule</code>.
+         * Required {@code LoginModule}.
          */
         public static final LoginModuleControlFlag REQUIRED =
                                 new LoginModuleControlFlag("required");
 
         /**
-         * Requisite <code>LoginModule</code>.
+         * Requisite {@code LoginModule}.
          */
         public static final LoginModuleControlFlag REQUISITE =
                                 new LoginModuleControlFlag("requisite");
 
         /**
-         * Sufficient <code>LoginModule</code>.
+         * Sufficient {@code LoginModule}.
          */
         public static final LoginModuleControlFlag SUFFICIENT =
                                 new LoginModuleControlFlag("sufficient");
 
         /**
-         * Optional <code>LoginModule</code>.
+         * Optional {@code LoginModule}.
          */
         public static final LoginModuleControlFlag OPTIONAL =
                                 new LoginModuleControlFlag("optional");
--- a/src/share/classes/javax/security/auth/login/Configuration.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/login/Configuration.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,9 +49,9 @@
  *
  * <p> A login configuration contains the following information.
  * Note that this example only represents the default syntax for the
- * <code>Configuration</code>.  Subclass implementations of this class
+ * {@code Configuration}.  Subclass implementations of this class
  * may implement alternative syntaxes and may retrieve the
- * <code>Configuration</code> from any source such as files, databases,
+ * {@code Configuration} from any source such as files, databases,
  * or servers.
  *
  * <pre>
@@ -70,9 +70,9 @@
  *      };
  * </pre>
  *
- * <p> Each entry in the <code>Configuration</code> is indexed via an
+ * <p> Each entry in the {@code Configuration} is indexed via an
  * application name, <i>Name</i>, and contains a list of
- * LoginModules configured for that application.  Each <code>LoginModule</code>
+ * LoginModules configured for that application.  Each {@code LoginModule}
  * is specified via its fully qualified class name.
  * Authentication proceeds down the module list in the exact order specified.
  * If an application does not have specific entry,
@@ -83,55 +83,55 @@
  * valid values for <i>Flag</i> and their respective semantics:
  *
  * <pre>
- *      1) Required     - The <code>LoginModule</code> is required to succeed.
+ *      1) Required     - The {@code LoginModule} is required to succeed.
  *                      If it succeeds or fails, authentication still continues
- *                      to proceed down the <code>LoginModule</code> list.
+ *                      to proceed down the {@code LoginModule} list.
  *
- *      2) Requisite    - The <code>LoginModule</code> is required to succeed.
+ *      2) Requisite    - The {@code LoginModule} is required to succeed.
  *                      If it succeeds, authentication continues down the
- *                      <code>LoginModule</code> list.  If it fails,
+ *                      {@code LoginModule} list.  If it fails,
  *                      control immediately returns to the application
  *                      (authentication does not proceed down the
- *                      <code>LoginModule</code> list).
+ *                      {@code LoginModule} list).
  *
- *      3) Sufficient   - The <code>LoginModule</code> is not required to
+ *      3) Sufficient   - The {@code LoginModule} is not required to
  *                      succeed.  If it does succeed, control immediately
  *                      returns to the application (authentication does not
- *                      proceed down the <code>LoginModule</code> list).
+ *                      proceed down the {@code LoginModule} list).
  *                      If it fails, authentication continues down the
- *                      <code>LoginModule</code> list.
+ *                      {@code LoginModule} list.
  *
- *      4) Optional     - The <code>LoginModule</code> is not required to
+ *      4) Optional     - The {@code LoginModule} is not required to
  *                      succeed.  If it succeeds or fails,
  *                      authentication still continues to proceed down the
- *                      <code>LoginModule</code> list.
+ *                      {@code LoginModule} list.
  * </pre>
  *
  * <p> The overall authentication succeeds only if all <i>Required</i> and
  * <i>Requisite</i> LoginModules succeed.  If a <i>Sufficient</i>
- * <code>LoginModule</code> is configured and succeeds,
+ * {@code LoginModule} is configured and succeeds,
  * then only the <i>Required</i> and <i>Requisite</i> LoginModules prior to
- * that <i>Sufficient</i> <code>LoginModule</code> need to have succeeded for
+ * that <i>Sufficient</i> {@code LoginModule} need to have succeeded for
  * the overall authentication to succeed. If no <i>Required</i> or
  * <i>Requisite</i> LoginModules are configured for an application,
  * then at least one <i>Sufficient</i> or <i>Optional</i>
- * <code>LoginModule</code> must succeed.
+ * {@code LoginModule} must succeed.
  *
  * <p> <i>ModuleOptions</i> is a space separated list of
- * <code>LoginModule</code>-specific values which are passed directly to
+ * {@code LoginModule}-specific values which are passed directly to
  * the underlying LoginModules.  Options are defined by the
- * <code>LoginModule</code> itself, and control the behavior within it.
- * For example, a <code>LoginModule</code> may define options to support
+ * {@code LoginModule} itself, and control the behavior within it.
+ * For example, a {@code LoginModule} may define options to support
  * debugging/testing capabilities.  The correct way to specify options in the
- * <code>Configuration</code> is by using the following key-value pairing:
+ * {@code Configuration} is by using the following key-value pairing:
  * <i>debug="true"</i>.  The key and value should be separated by an
  * 'equals' symbol, and the value should be surrounded by double quotes.
  * If a String in the form, ${system.property}, occurs in the value,
  * it will be expanded to the value of the system property.
  * Note that there is no limit to the number of
- * options a <code>LoginModule</code> may define.
+ * options a {@code LoginModule} may define.
  *
- * <p> The following represents an example <code>Configuration</code> entry
+ * <p> The following represents an example {@code Configuration} entry
  * based on the syntax above:
  *
  * <pre>
@@ -143,7 +143,7 @@
  * };
  * </pre>
  *
- * <p> This <code>Configuration</code> specifies that an application named,
+ * <p> This {@code Configuration} specifies that an application named,
  * "Login", requires users to first authenticate to the
  * <i>com.sun.security.auth.module.UnixLoginModule</i>, which is
  * required to succeed.  Even if the <i>UnixLoginModule</i>
@@ -165,11 +165,11 @@
  *
  * <p> There is only one Configuration object installed in the runtime at any
  * given time.  A Configuration object can be installed by calling the
- * <code>setConfiguration</code> method.  The installed Configuration object
- * can be obtained by calling the <code>getConfiguration</code> method.
+ * {@code setConfiguration} method.  The installed Configuration object
+ * can be obtained by calling the {@code getConfiguration} method.
  *
  * <p> If no Configuration object has been installed in the runtime, a call to
- * <code>getConfiguration</code> installs an instance of the default
+ * {@code getConfiguration} installs an instance of the default
  * Configuration implementation (a default subclass implementation of this
  * abstract class).
  * The default Configuration implementation can be changed by setting the value
@@ -178,7 +178,7 @@
  *
  * <p> Application code can directly subclass Configuration to provide a custom
  * implementation.  In addition, an instance of a Configuration object can be
- * constructed by invoking one of the <code>getInstance</code> factory methods
+ * constructed by invoking one of the {@code getInstance} factory methods
  * with a standard type.  The default policy type is "JavaLoginConfig".
  * See the Configuration section in the <a href=
  * "{@docRoot}/../technotes/guides/security/StandardNames.html#Configuration">
@@ -222,7 +222,7 @@
      * <p>
      *
      * @return the login Configuration.  If a Configuration object was set
-     *          via the <code>Configuration.setConfiguration</code> method,
+     *          via the {@code Configuration.setConfiguration} method,
      *          then that object is returned.  Otherwise, a default
      *          Configuration object is returned.
      *
@@ -286,14 +286,14 @@
     }
 
     /**
-     * Set the login <code>Configuration</code>.
+     * Set the login {@code Configuration}.
      *
      * <p>
      *
-     * @param configuration the new <code>Configuration</code>
+     * @param configuration the new {@code Configuration}
      *
      * @exception SecurityException if the current thread does not have
-     *                  Permission to set the <code>Configuration</code>.
+     *                  Permission to set the {@code Configuration}.
      *
      * @see #getConfiguration
      */
@@ -505,7 +505,7 @@
      * Return the Provider of this Configuration.
      *
      * <p> This Configuration instance will only have a Provider if it
-     * was obtained via a call to <code>Configuration.getInstance</code>.
+     * was obtained via a call to {@code Configuration.getInstance}.
      * Otherwise this method returns null.
      *
      * @return the Provider of this Configuration, or null.
@@ -520,7 +520,7 @@
      * Return the type of this Configuration.
      *
      * <p> This Configuration instance will only have a type if it
-     * was obtained via a call to <code>Configuration.getInstance</code>.
+     * was obtained via a call to {@code Configuration.getInstance}.
      * Otherwise this method returns null.
      *
      * @return the type of this Configuration, or null.
@@ -535,7 +535,7 @@
      * Return Configuration parameters.
      *
      * <p> This Configuration instance will only have parameters if it
-     * was obtained via a call to <code>Configuration.getInstance</code>.
+     * was obtained via a call to {@code Configuration.getInstance}.
      * Otherwise this method returns null.
      *
      * @return Configuration parameters, or null.
@@ -567,7 +567,7 @@
      * <p> This method causes this Configuration object to refresh/reload its
      * contents in an implementation-dependent manner.
      * For example, if this Configuration object stores its entries in a file,
-     * calling <code>refresh</code> may cause the file to be re-read.
+     * calling {@code refresh} may cause the file to be re-read.
      *
      * <p> The default implementation of this method does nothing.
      * This method should be overridden if a refresh operation is supported
--- a/src/share/classes/javax/security/auth/login/ConfigurationSpi.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/login/ConfigurationSpi.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,15 +28,15 @@
 
 /**
  * This class defines the <i>Service Provider Interface</i> (<b>SPI</b>)
- * for the <code>Configuration</code> class.
+ * for the {@code Configuration} class.
  * All the abstract methods in this class must be implemented by each
  * service provider who wishes to supply a Configuration implementation.
  *
  * <p> Subclass implementations of this abstract class must provide
- * a public constructor that takes a <code>Configuration.Parameters</code>
+ * a public constructor that takes a {@code Configuration.Parameters}
  * object as an input parameter.  This constructor also must throw
  * an IllegalArgumentException if it does not understand the
- * <code>Configuration.Parameters</code> input.
+ * {@code Configuration.Parameters} input.
  *
  *
  * @since 1.6
@@ -62,7 +62,7 @@
      * <p> This method causes this Configuration object to refresh/reload its
      * contents in an implementation-dependent manner.
      * For example, if this Configuration object stores its entries in a file,
-     * calling <code>refresh</code> may cause the file to be re-read.
+     * calling {@code refresh} may cause the file to be re-read.
      *
      * <p> The default implementation of this method does nothing.
      * This method should be overridden if a refresh operation is supported
--- a/src/share/classes/javax/security/auth/login/CredentialExpiredException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/login/CredentialExpiredException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,14 +26,14 @@
 package javax.security.auth.login;
 
 /**
- * Signals that a <code>Credential</code> has expired.
+ * Signals that a {@code Credential} has expired.
  *
  * <p> This exception is thrown by LoginModules when they determine
- * that a <code>Credential</code> has expired.
- * For example, a <code>LoginModule</code> authenticating a user
- * in its <code>login</code> method may determine that the user's
+ * that a {@code Credential} has expired.
+ * For example, a {@code LoginModule} authenticating a user
+ * in its {@code login} method may determine that the user's
  * password, although entered correctly, has expired.  In this case
- * the <code>LoginModule</code> throws this exception to notify
+ * the {@code LoginModule} throws this exception to notify
  * the application.  The application can then take the appropriate
  * steps to assist the user in updating the password.
  *
--- a/src/share/classes/javax/security/auth/login/FailedLoginException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/login/FailedLoginException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,7 +29,7 @@
  * Signals that user authentication failed.
  *
  * <p> This exception is thrown by LoginModules if authentication failed.
- * For example, a <code>LoginModule</code> throws this exception if
+ * For example, a {@code LoginModule} throws this exception if
  * the user entered an incorrect password.
  *
  */
--- a/src/share/classes/javax/security/auth/login/LoginContext.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/login/LoginContext.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -41,11 +41,11 @@
 import sun.security.util.ResourcesMgr;
 
 /**
- * <p> The <code>LoginContext</code> class describes the basic methods used
+ * <p> The {@code LoginContext} class describes the basic methods used
  * to authenticate Subjects and provides a way to develop an
  * application independent of the underlying authentication technology.
- * A <code>Configuration</code> specifies the authentication technology, or
- * <code>LoginModule</code>, to be used with a particular application.
+ * A {@code Configuration} specifies the authentication technology, or
+ * {@code LoginModule}, to be used with a particular application.
  * Different LoginModules can be plugged in under an application
  * without requiring any modifications to the application itself.
  *
@@ -57,36 +57,36 @@
  * LoginModule under an application.
  *
  * <p> A typical caller instantiates a LoginContext with
- * a <i>name</i> and a <code>CallbackHandler</code>.
+ * a <i>name</i> and a {@code CallbackHandler}.
  * LoginContext uses the <i>name</i> as the index into a
  * Configuration to determine which LoginModules should be used,
  * and which ones must succeed in order for the overall authentication to
- * succeed.  The <code>CallbackHandler</code> is passed to the underlying
+ * succeed.  The {@code CallbackHandler} is passed to the underlying
  * LoginModules so they may communicate and interact with users
  * (prompting for a username and password via a graphical user interface,
  * for example).
  *
  * <p> Once the caller has instantiated a LoginContext,
- * it invokes the <code>login</code> method to authenticate
- * a <code>Subject</code>.  The <code>login</code> method invokes
+ * it invokes the {@code login} method to authenticate
+ * a {@code Subject}.  The {@code login} method invokes
  * the configured modules to perform their respective types of authentication
  * (username/password, smart card pin verification, etc.).
  * Note that the LoginModules will not attempt authentication retries nor
  * introduce delays if the authentication fails.
  * Such tasks belong to the LoginContext caller.
  *
- * <p> If the <code>login</code> method returns without
+ * <p> If the {@code login} method returns without
  * throwing an exception, then the overall authentication succeeded.
  * The caller can then retrieve
  * the newly authenticated Subject by invoking the
- * <code>getSubject</code> method.  Principals and Credentials associated
+ * {@code getSubject} method.  Principals and Credentials associated
  * with the Subject may be retrieved by invoking the Subject's
- * respective <code>getPrincipals</code>, <code>getPublicCredentials</code>,
- * and <code>getPrivateCredentials</code> methods.
+ * respective {@code getPrincipals}, {@code getPublicCredentials},
+ * and {@code getPrivateCredentials} methods.
  *
  * <p> To logout the Subject, the caller calls
- * the <code>logout</code> method.  As with the <code>login</code>
- * method, this <code>logout</code> method invokes the <code>logout</code>
+ * the {@code logout} method.  As with the {@code login}
+ * method, this {@code logout} method invokes the {@code logout}
  * method for the configured modules.
  *
  * <p> A LoginContext should not be used to authenticate
@@ -96,14 +96,14 @@
  * <p> The following documentation applies to all LoginContext constructors:
  * <ol>
  *
- * <li> <code>Subject</code>
+ * <li> {@code Subject}
  * <ul>
  * <li> If the constructor has a Subject
  * input parameter, the LoginContext uses the caller-specified
  * Subject object.
  * <p>
- * <li> If the caller specifies a <code>null</code> Subject
- * and a <code>null</code> value is permitted,
+ * <li> If the caller specifies a {@code null} Subject
+ * and a {@code null} value is permitted,
  * the LoginContext instantiates a new Subject.
  * <p>
  * <li> If the constructor does <b>not</b> have a Subject
@@ -111,14 +111,14 @@
  * <p>
  * </ul>
  *
- * <li> <code>Configuration</code>
+ * <li> {@code Configuration}
  * <ul>
  * <li> If the constructor has a Configuration
  * input parameter and the caller specifies a non-null Configuration,
  * the LoginContext uses the caller-specified Configuration.
  * <p>
  * If the constructor does <b>not</b> have a Configuration
- * input parameter, or if the caller specifies a <code>null</code>
+ * input parameter, or if the caller specifies a {@code null}
  * Configuration object, the constructor uses the following call to
  * get the installed Configuration:
  * <pre>
@@ -126,42 +126,42 @@
  * </pre>
  * For both cases,
  * the <i>name</i> argument given to the constructor is passed to the
- * <code>Configuration.getAppConfigurationEntry</code> method.
+ * {@code Configuration.getAppConfigurationEntry} method.
  * If the Configuration has no entries for the specified <i>name</i>,
- * then the <code>LoginContext</code> calls
- * <code>getAppConfigurationEntry</code> with the name, "<i>other</i>"
+ * then the {@code LoginContext} calls
+ * {@code getAppConfigurationEntry} with the name, "<i>other</i>"
  * (the default entry name).  If there is no entry for "<i>other</i>",
- * then a <code>LoginException</code> is thrown.
+ * then a {@code LoginException} is thrown.
  * <p>
  * <li> When LoginContext uses the installed Configuration, the caller
  * requires the createLoginContext.<em>name</em> and possibly
  * createLoginContext.other AuthPermissions. Furthermore, the
  * LoginContext will invoke configured modules from within an
- * <code>AccessController.doPrivileged</code> call so that modules that
+ * {@code AccessController.doPrivileged} call so that modules that
  * perform security-sensitive tasks (such as connecting to remote hosts,
  * and updating the Subject) will require the respective permissions, but
  * the callers of the LoginContext will not require those permissions.
  * <p>
  * <li> When LoginContext uses a caller-specified Configuration, the caller
  * does not require any createLoginContext AuthPermission.  The LoginContext
- * saves the <code>AccessControlContext</code> for the caller,
+ * saves the {@code AccessControlContext} for the caller,
  * and invokes the configured modules from within an
- * <tt>AccessController.doPrivileged</tt> call constrained by that context.
+ * {@code AccessController.doPrivileged} call constrained by that context.
  * This means the caller context (stored when the LoginContext was created)
  * must have sufficient permissions to perform any security-sensitive tasks
  * that the modules may perform.
  * <p>
  * </ul>
  *
- * <li> <code>CallbackHandler</code>
+ * <li> {@code CallbackHandler}
  * <ul>
  * <li> If the constructor has a CallbackHandler
  * input parameter, the LoginContext uses the caller-specified
  * CallbackHandler object.
  * <p>
  * <li> If the constructor does <b>not</b> have a CallbackHandler
- * input parameter, or if the caller specifies a <code>null</code>
- * CallbackHandler object (and a <code>null</code> value is permitted),
+ * input parameter, or if the caller specifies a {@code null}
+ * CallbackHandler object (and a {@code null} value is permitted),
  * the LoginContext queries the
  * {@code auth.login.defaultCallbackHandler} security property for the
  * fully qualified class name of a default handler
@@ -177,10 +177,10 @@
  * then this LoginContext must wrap any
  * caller-specified or default CallbackHandler implementation
  * in a new CallbackHandler implementation
- * whose <code>handle</code> method implementation invokes the
- * specified CallbackHandler's <code>handle</code> method in a
- * <code>java.security.AccessController.doPrivileged</code> call
- * constrained by the caller's current <code>AccessControlContext</code>.
+ * whose {@code handle} method implementation invokes the
+ * specified CallbackHandler's {@code handle} method in a
+ * {@code java.security.AccessController.doPrivileged} call
+ * constrained by the caller's current {@code AccessControlContext}.
  * </ul>
  * </ol>
  *
@@ -317,14 +317,14 @@
     }
 
     /**
-     * Instantiate a new <code>LoginContext</code> object with a name.
+     * Instantiate a new {@code LoginContext} object with a name.
      *
      * @param name the name used as the index into the
-     *          <code>Configuration</code>.
+     *          {@code Configuration}.
      *
-     * @exception LoginException if the caller-specified <code>name</code>
-     *          does not appear in the <code>Configuration</code>
-     *          and there is no <code>Configuration</code> entry
+     * @exception LoginException if the caller-specified {@code name}
+     *          does not appear in the {@code Configuration}
+     *          and there is no {@code Configuration} entry
      *          for "<i>other</i>", or if the
      *          <i>auth.login.defaultCallbackHandler</i>
      *          security property was set, but the implementation
@@ -343,21 +343,21 @@
     }
 
     /**
-     * Instantiate a new <code>LoginContext</code> object with a name
-     * and a <code>Subject</code> object.
+     * Instantiate a new {@code LoginContext} object with a name
+     * and a {@code Subject} object.
      *
      * <p>
      *
      * @param name the name used as the index into the
-     *          <code>Configuration</code>. <p>
+     *          {@code Configuration}. <p>
      *
-     * @param subject the <code>Subject</code> to authenticate.
+     * @param subject the {@code Subject} to authenticate.
      *
-     * @exception LoginException if the caller-specified <code>name</code>
-     *          does not appear in the <code>Configuration</code>
-     *          and there is no <code>Configuration</code> entry
-     *          for "<i>other</i>", if the caller-specified <code>subject</code>
-     *          is <code>null</code>, or if the
+     * @exception LoginException if the caller-specified {@code name}
+     *          does not appear in the {@code Configuration}
+     *          and there is no {@code Configuration} entry
+     *          for "<i>other</i>", if the caller-specified {@code subject}
+     *          is {@code null}, or if the
      *          <i>auth.login.defaultCallbackHandler</i>
      *          security property was set, but the implementation
      *          class could not be loaded.
@@ -381,22 +381,22 @@
     }
 
     /**
-     * Instantiate a new <code>LoginContext</code> object with a name
-     * and a <code>CallbackHandler</code> object.
+     * Instantiate a new {@code LoginContext} object with a name
+     * and a {@code CallbackHandler} object.
      *
      * <p>
      *
      * @param name the name used as the index into the
-     *          <code>Configuration</code>. <p>
+     *          {@code Configuration}. <p>
      *
-     * @param callbackHandler the <code>CallbackHandler</code> object used by
+     * @param callbackHandler the {@code CallbackHandler} object used by
      *          LoginModules to communicate with the user.
      *
-     * @exception LoginException if the caller-specified <code>name</code>
-     *          does not appear in the <code>Configuration</code>
-     *          and there is no <code>Configuration</code> entry
+     * @exception LoginException if the caller-specified {@code name}
+     *          does not appear in the {@code Configuration}
+     *          and there is no {@code Configuration} entry
      *          for "<i>other</i>", or if the caller-specified
-     *          <code>callbackHandler</code> is <code>null</code>.
+     *          {@code callbackHandler} is {@code null}.
      *          <p>
      * @exception SecurityException if a SecurityManager is set and
      *          the caller does not have
@@ -417,27 +417,27 @@
     }
 
     /**
-     * Instantiate a new <code>LoginContext</code> object with a name,
-     * a <code>Subject</code> to be authenticated, and a
-     * <code>CallbackHandler</code> object.
+     * Instantiate a new {@code LoginContext} object with a name,
+     * a {@code Subject} to be authenticated, and a
+     * {@code CallbackHandler} object.
      *
      * <p>
      *
      * @param name the name used as the index into the
-     *          <code>Configuration</code>. <p>
+     *          {@code Configuration}. <p>
      *
-     * @param subject the <code>Subject</code> to authenticate. <p>
+     * @param subject the {@code Subject} to authenticate. <p>
      *
-     * @param callbackHandler the <code>CallbackHandler</code> object used by
+     * @param callbackHandler the {@code CallbackHandler} object used by
      *          LoginModules to communicate with the user.
      *
-     * @exception LoginException if the caller-specified <code>name</code>
-     *          does not appear in the <code>Configuration</code>
-     *          and there is no <code>Configuration</code> entry
+     * @exception LoginException if the caller-specified {@code name}
+     *          does not appear in the {@code Configuration}
+     *          and there is no {@code Configuration} entry
      *          for "<i>other</i>", or if the caller-specified
-     *          <code>subject</code> is <code>null</code>,
+     *          {@code subject} is {@code null},
      *          or if the caller-specified
-     *          <code>callbackHandler</code> is <code>null</code>.
+     *          {@code callbackHandler} is {@code null}.
      *          <p>
      * @exception SecurityException if a SecurityManager is set and
      *          the caller does not have
@@ -458,34 +458,34 @@
     }
 
     /**
-     * Instantiate a new <code>LoginContext</code> object with a name,
-     * a <code>Subject</code> to be authenticated,
-     * a <code>CallbackHandler</code> object, and a login
-     * <code>Configuration</code>.
+     * Instantiate a new {@code LoginContext} object with a name,
+     * a {@code Subject} to be authenticated,
+     * a {@code CallbackHandler} object, and a login
+     * {@code Configuration}.
      *
      * <p>
      *
      * @param name the name used as the index into the caller-specified
-     *          <code>Configuration</code>. <p>
+     *          {@code Configuration}. <p>
      *
-     * @param subject the <code>Subject</code> to authenticate,
-     *          or <code>null</code>. <p>
+     * @param subject the {@code Subject} to authenticate,
+     *          or {@code null}. <p>
      *
-     * @param callbackHandler the <code>CallbackHandler</code> object used by
-     *          LoginModules to communicate with the user, or <code>null</code>.
+     * @param callbackHandler the {@code CallbackHandler} object used by
+     *          LoginModules to communicate with the user, or {@code null}.
      *          <p>
      *
-     * @param config the <code>Configuration</code> that lists the
+     * @param config the {@code Configuration} that lists the
      *          login modules to be called to perform the authentication,
-     *          or <code>null</code>.
+     *          or {@code null}.
      *
-     * @exception LoginException if the caller-specified <code>name</code>
-     *          does not appear in the <code>Configuration</code>
-     *          and there is no <code>Configuration</code> entry
+     * @exception LoginException if the caller-specified {@code name}
+     *          does not appear in the {@code Configuration}
+     *          and there is no {@code Configuration} entry
      *          for "<i>other</i>".
      *          <p>
      * @exception SecurityException if a SecurityManager is set,
-     *          <i>config</i> is <code>null</code>,
+     *          <i>config</i> is {@code null},
      *          and either the caller does not have
      *          AuthPermission("createLoginContext.<i>name</i>"),
      *          or if a configuration entry for <i>name</i> does not exist and
@@ -522,46 +522,46 @@
     /**
      * Perform the authentication.
      *
-     * <p> This method invokes the <code>login</code> method for each
+     * <p> This method invokes the {@code login} method for each
      * LoginModule configured for the <i>name</i> specified to the
-     * <code>LoginContext</code> constructor, as determined by the login
-     * <code>Configuration</code>.  Each <code>LoginModule</code>
+     * {@code LoginContext} constructor, as determined by the login
+     * {@code Configuration}.  Each {@code LoginModule}
      * then performs its respective type of authentication
      * (username/password, smart card pin verification, etc.).
      *
      * <p> This method completes a 2-phase authentication process by
-     * calling each configured LoginModule's <code>commit</code> method
+     * calling each configured LoginModule's {@code commit} method
      * if the overall authentication succeeded (the relevant REQUIRED,
      * REQUISITE, SUFFICIENT, and OPTIONAL LoginModules succeeded),
-     * or by calling each configured LoginModule's <code>abort</code> method
+     * or by calling each configured LoginModule's {@code abort} method
      * if the overall authentication failed.  If authentication succeeded,
-     * each successful LoginModule's <code>commit</code> method associates
-     * the relevant Principals and Credentials with the <code>Subject</code>.
-     * If authentication failed, each LoginModule's <code>abort</code> method
+     * each successful LoginModule's {@code commit} method associates
+     * the relevant Principals and Credentials with the {@code Subject}.
+     * If authentication failed, each LoginModule's {@code abort} method
      * removes/destroys any previously stored state.
      *
-     * <p> If the <code>commit</code> phase of the authentication process
+     * <p> If the {@code commit} phase of the authentication process
      * fails, then the overall authentication fails and this method
-     * invokes the <code>abort</code> method for each configured
-     * <code>LoginModule</code>.
+     * invokes the {@code abort} method for each configured
+     * {@code LoginModule}.
      *
-     * <p> If the <code>abort</code> phase
+     * <p> If the {@code abort} phase
      * fails for any reason, then this method propagates the
-     * original exception thrown either during the <code>login</code> phase
-     * or the <code>commit</code> phase.  In either case, the overall
+     * original exception thrown either during the {@code login} phase
+     * or the {@code commit} phase.  In either case, the overall
      * authentication fails.
      *
      * <p> In the case where multiple LoginModules fail,
      * this method propagates the exception raised by the first
-     * <code>LoginModule</code> which failed.
+     * {@code LoginModule} which failed.
      *
-     * <p> Note that if this method enters the <code>abort</code> phase
-     * (either the <code>login</code> or <code>commit</code> phase failed),
+     * <p> Note that if this method enters the {@code abort} phase
+     * (either the {@code login} or {@code commit} phase failed),
      * this method invokes all LoginModules configured for the
-     * application regardless of their respective <code>Configuration</code>
-     * flag parameters.  Essentially this means that <code>Requisite</code>
-     * and <code>Sufficient</code> semantics are ignored during the
-     * <code>abort</code> phase.  This guarantees that proper cleanup
+     * application regardless of their respective {@code Configuration}
+     * flag parameters.  Essentially this means that {@code Requisite}
+     * and {@code Sufficient} semantics are ignored during the
+     * {@code abort} phase.  This guarantees that proper cleanup
      * and state restoration can take place.
      *
      * <p>
@@ -602,19 +602,19 @@
     }
 
     /**
-     * Logout the <code>Subject</code>.
+     * Logout the {@code Subject}.
      *
-     * <p> This method invokes the <code>logout</code> method for each
-     * <code>LoginModule</code> configured for this <code>LoginContext</code>.
-     * Each <code>LoginModule</code> performs its respective logout procedure
+     * <p> This method invokes the {@code logout} method for each
+     * {@code LoginModule} configured for this {@code LoginContext}.
+     * Each {@code LoginModule} performs its respective logout procedure
      * which may include removing/destroying
-     * <code>Principal</code> and <code>Credential</code> information
-     * from the <code>Subject</code> and state cleanup.
+     * {@code Principal} and {@code Credential} information
+     * from the {@code Subject} and state cleanup.
      *
      * <p> Note that this method invokes all LoginModules configured for the
      * application regardless of their respective
-     * <code>Configuration</code> flag parameters.  Essentially this means
-     * that <code>Requisite</code> and <code>Sufficient</code> semantics are
+     * {@code Configuration} flag parameters.  Essentially this means
+     * that {@code Requisite} and {@code Sufficient} semantics are
      * ignored for this method.  This guarantees that proper cleanup
      * and state restoration can take place.
      *
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/javax/security/auth/login/package-info.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * This package provides a pluggable authentication framework.
+ * <h2>Package Specification</h2>
+ *
+ * <ul>
+ *   <li><a href="{@docRoot}/../technotes/guides/security/StandardNames.html">
+ *     <b>Java&trade;
+ *     Cryptography Architecture Standard Algorithm Name
+ *     Documentation</b></a></li>
+ * </ul>
+ *
+ * @since 1.4
+ */
+package javax.security.auth.login;
--- a/src/share/classes/javax/security/auth/login/package.html	Thu Jul 18 03:38:49 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,54 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
-<html>
-<head>
-<!--
-Copyright (c) 2000, 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.
--->
-
-</head>
-<body bgcolor="white">
-
-	This package provides a pluggable authentication framework.
-<h2>Package Specification</h2>
-
-<ul>
-  <li><a href="{@docRoot}/../technotes/guides/security/StandardNames.html">
-    <b>Java<FONT SIZE=-2><SUP>TM</SUP></FONT>
-    Cryptography Architecture Standard Algorithm Name
-    Documentation</b></a></li>
-</ul>
-
-<!--
-<h2>Related Documentation</h2>
-
-For overviews, tutorials, examples, guides, and tool documentation, please see:
-<ul>
-  <li><a href="">##### REFER TO NON-SPEC DOCUMENTATION HERE #####</a>
-</ul>
-
--->
-
-@since 1.4
-</body>
-</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/javax/security/auth/package-info.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * This package provides a framework for authentication and
+ * authorization. The framework allows
+ * authentication to be performed in pluggable fashion. Different
+ * authentication modules can be plugged under an application without
+ * requiring modifications to the application itself. The
+ * authorization component allows specification of access controls
+ * based on code location, code signers and code executors
+ * (Subjects).
+ *
+ * @since JDK1.4
+ */
+package javax.security.auth;
--- a/src/share/classes/javax/security/auth/package.html	Thu Jul 18 03:38:49 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,61 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
-<html>
-<head>
-<!--
-Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
-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.
--->
-
-</head>
-<body bgcolor="white">
-
-    This package provides a framework for authentication and
-    authorization. The framework allows
-    authentication to be performed in pluggable fashion. Different
-    authentication modules can be plugged under an application without
-    requiring modifications to the application itself. The
-    authorization component allows specification of access controls
-    based on code location, code signers and code executors
-    (Subjects).
-
-
-<!--
-<h2>Package Specification</h2>
-
-##### FILL IN ANY SPECS NEEDED BY JAVA COMPATIBILITY KIT #####
-<ul>
-  <li><a href="">##### REFER TO ANY FRAMEMAKER SPECIFICATION HERE #####</a>
-</ul>
-
-<h2>Related Documentation</h2>
-
-For overviews, tutorials, examples, guides, and tool documentation, please see:
-<ul>
-  <li><a href="">##### REFER TO NON-SPEC DOCUMENTATION HERE #####</a>
-</ul>
-
--->
-
-@since JDK1.4
-</body>
-</html>
--- a/src/share/classes/javax/security/auth/spi/LoginModule.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/spi/LoginModule.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,95 +32,95 @@
 import java.util.Map;
 
 /**
- * <p> <code>LoginModule</code> describes the interface
+ * <p> {@code LoginModule} describes the interface
  * implemented by authentication technology providers.  LoginModules
  * are plugged in under applications to provide a particular type of
  * authentication.
  *
- * <p> While applications write to the <code>LoginContext</code> API,
+ * <p> While applications write to the {@code LoginContext} API,
  * authentication technology providers implement the
- * <code>LoginModule</code> interface.
- * A <code>Configuration</code> specifies the LoginModule(s)
+ * {@code LoginModule} interface.
+ * A {@code Configuration} specifies the LoginModule(s)
  * to be used with a particular login application.  Therefore different
  * LoginModules can be plugged in under the application without
  * requiring any modifications to the application itself.
  *
- * <p> The <code>LoginContext</code> is responsible for reading the
- * <code>Configuration</code> and instantiating the appropriate
- * LoginModules.  Each <code>LoginModule</code> is initialized with
- * a <code>Subject</code>, a <code>CallbackHandler</code>, shared
- * <code>LoginModule</code> state, and LoginModule-specific options.
+ * <p> The {@code LoginContext} is responsible for reading the
+ * {@code Configuration} and instantiating the appropriate
+ * LoginModules.  Each {@code LoginModule} is initialized with
+ * a {@code Subject}, a {@code CallbackHandler}, shared
+ * {@code LoginModule} state, and LoginModule-specific options.
  *
- * The <code>Subject</code> represents the
- * <code>Subject</code> currently being authenticated and is updated
+ * The {@code Subject} represents the
+ * {@code Subject} currently being authenticated and is updated
  * with relevant Credentials if authentication succeeds.
- * LoginModules use the <code>CallbackHandler</code> to
- * communicate with users.  The <code>CallbackHandler</code> may be
+ * LoginModules use the {@code CallbackHandler} to
+ * communicate with users.  The {@code CallbackHandler} may be
  * used to prompt for usernames and passwords, for example.
- * Note that the <code>CallbackHandler</code> may be null.  LoginModules
- * which absolutely require a <code>CallbackHandler</code> to authenticate
- * the <code>Subject</code> may throw a <code>LoginException</code>.
+ * Note that the {@code CallbackHandler} may be null.  LoginModules
+ * which absolutely require a {@code CallbackHandler} to authenticate
+ * the {@code Subject} may throw a {@code LoginException}.
  * LoginModules optionally use the shared state to share information
  * or data among themselves.
  *
  * <p> The LoginModule-specific options represent the options
- * configured for this <code>LoginModule</code> by an administrator or user
- * in the login <code>Configuration</code>.
- * The options are defined by the <code>LoginModule</code> itself
+ * configured for this {@code LoginModule} by an administrator or user
+ * in the login {@code Configuration}.
+ * The options are defined by the {@code LoginModule} itself
  * and control the behavior within it.  For example, a
- * <code>LoginModule</code> may define options to support debugging/testing
+ * {@code LoginModule} may define options to support debugging/testing
  * capabilities.  Options are defined using a key-value syntax,
- * such as <i>debug=true</i>.  The <code>LoginModule</code>
- * stores the options as a <code>Map</code> so that the values may
+ * such as <i>debug=true</i>.  The {@code LoginModule}
+ * stores the options as a {@code Map} so that the values may
  * be retrieved using the key.  Note that there is no limit to the number
- * of options a <code>LoginModule</code> chooses to define.
+ * of options a {@code LoginModule} chooses to define.
  *
  * <p> The calling application sees the authentication process as a single
  * operation.  However, the authentication process within the
- * <code>LoginModule</code> proceeds in two distinct phases.
+ * {@code LoginModule} proceeds in two distinct phases.
  * In the first phase, the LoginModule's
- * <code>login</code> method gets invoked by the LoginContext's
- * <code>login</code> method.  The <code>login</code>
- * method for the <code>LoginModule</code> then performs
+ * {@code login} method gets invoked by the LoginContext's
+ * {@code login} method.  The {@code login}
+ * method for the {@code LoginModule} then performs
  * the actual authentication (prompt for and verify a password for example)
  * and saves its authentication status as private state
- * information.  Once finished, the LoginModule's <code>login</code>
- * method either returns <code>true</code> (if it succeeded) or
- * <code>false</code> (if it should be ignored), or throws a
- * <code>LoginException</code> to specify a failure.
- * In the failure case, the <code>LoginModule</code> must not retry the
+ * information.  Once finished, the LoginModule's {@code login}
+ * method either returns {@code true} (if it succeeded) or
+ * {@code false} (if it should be ignored), or throws a
+ * {@code LoginException} to specify a failure.
+ * In the failure case, the {@code LoginModule} must not retry the
  * authentication or introduce delays.  The responsibility of such tasks
  * belongs to the application.  If the application attempts to retry
- * the authentication, the LoginModule's <code>login</code> method will be
+ * the authentication, the LoginModule's {@code login} method will be
  * called again.
  *
  * <p> In the second phase, if the LoginContext's overall authentication
  * succeeded (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL
- * LoginModules succeeded), then the <code>commit</code>
- * method for the <code>LoginModule</code> gets invoked.
- * The <code>commit</code> method for a <code>LoginModule</code> checks its
+ * LoginModules succeeded), then the {@code commit}
+ * method for the {@code LoginModule} gets invoked.
+ * The {@code commit} method for a {@code LoginModule} checks its
  * privately saved state to see if its own authentication succeeded.
- * If the overall <code>LoginContext</code> authentication succeeded
+ * If the overall {@code LoginContext} authentication succeeded
  * and the LoginModule's own authentication succeeded, then the
- * <code>commit</code> method associates the relevant
+ * {@code commit} method associates the relevant
  * Principals (authenticated identities) and Credentials (authentication data
- * such as cryptographic keys) with the <code>Subject</code>
- * located within the <code>LoginModule</code>.
+ * such as cryptographic keys) with the {@code Subject}
+ * located within the {@code LoginModule}.
  *
  * <p> If the LoginContext's overall authentication failed (the relevant
  * REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules did not succeed),
- * then the <code>abort</code> method for each <code>LoginModule</code>
- * gets invoked.  In this case, the <code>LoginModule</code> removes/destroys
+ * then the {@code abort} method for each {@code LoginModule}
+ * gets invoked.  In this case, the {@code LoginModule} removes/destroys
  * any authentication state originally saved.
  *
- * <p> Logging out a <code>Subject</code> involves only one phase.
- * The <code>LoginContext</code> invokes the LoginModule's <code>logout</code>
- * method.  The <code>logout</code> method for the <code>LoginModule</code>
+ * <p> Logging out a {@code Subject} involves only one phase.
+ * The {@code LoginContext} invokes the LoginModule's {@code logout}
+ * method.  The {@code logout} method for the {@code LoginModule}
  * then performs the logout procedures, such as removing Principals or
- * Credentials from the <code>Subject</code> or logging session information.
+ * Credentials from the {@code Subject} or logging session information.
  *
- * <p> A <code>LoginModule</code> implementation must have a constructor with
- * no arguments.  This allows classes which load the <code>LoginModule</code>
+ * <p> A {@code LoginModule} implementation must have a constructor with
+ * no arguments.  This allows classes which load the {@code LoginModule}
  * to instantiate it.
  *
  * @see javax.security.auth.login.LoginContext
@@ -131,38 +131,38 @@
     /**
      * Initialize this LoginModule.
      *
-     * <p> This method is called by the <code>LoginContext</code>
-     * after this <code>LoginModule</code> has been instantiated.
+     * <p> This method is called by the {@code LoginContext}
+     * after this {@code LoginModule} has been instantiated.
      * The purpose of this method is to initialize this
-     * <code>LoginModule</code> with the relevant information.
-     * If this <code>LoginModule</code> does not understand
-     * any of the data stored in <code>sharedState</code> or
-     * <code>options</code> parameters, they can be ignored.
+     * {@code LoginModule} with the relevant information.
+     * If this {@code LoginModule} does not understand
+     * any of the data stored in {@code sharedState} or
+     * {@code options} parameters, they can be ignored.
      *
      * <p>
      *
-     * @param subject the <code>Subject</code> to be authenticated. <p>
+     * @param subject the {@code Subject} to be authenticated. <p>
      *
-     * @param callbackHandler a <code>CallbackHandler</code> for communicating
+     * @param callbackHandler a {@code CallbackHandler} for communicating
      *                  with the end user (prompting for usernames and
      *                  passwords, for example). <p>
      *
      * @param sharedState state shared with other configured LoginModules. <p>
      *
      * @param options options specified in the login
-     *                  <code>Configuration</code> for this particular
-     *                  <code>LoginModule</code>.
+     *                  {@code Configuration} for this particular
+     *                  {@code LoginModule}.
      */
     void initialize(Subject subject, CallbackHandler callbackHandler,
                     Map<String,?> sharedState,
                     Map<String,?> options);
 
     /**
-     * Method to authenticate a <code>Subject</code> (phase 1).
+     * Method to authenticate a {@code Subject} (phase 1).
      *
      * <p> The implementation of this method authenticates
-     * a <code>Subject</code>.  For example, it may prompt for
-     * <code>Subject</code> information such
+     * a {@code Subject}.  For example, it may prompt for
+     * {@code Subject} information such
      * as a username and password and then attempt to verify the password.
      * This method saves the result of the authentication attempt
      * as private state within the LoginModule.
@@ -172,7 +172,7 @@
      * @exception LoginException if the authentication fails
      *
      * @return true if the authentication succeeded, or false if this
-     *                  <code>LoginModule</code> should be ignored.
+     *                  {@code LoginModule} should be ignored.
      */
     boolean login() throws LoginException;
 
@@ -186,9 +186,9 @@
      *
      * <p> If this LoginModule's own authentication attempt
      * succeeded (checked by retrieving the private state saved by the
-     * <code>login</code> method), then this method associates relevant
-     * Principals and Credentials with the <code>Subject</code> located in the
-     * <code>LoginModule</code>.  If this LoginModule's own
+     * {@code login} method), then this method associates relevant
+     * Principals and Credentials with the {@code Subject} located in the
+     * {@code LoginModule}.  If this LoginModule's own
      * authentication attempted failed, then this method removes/destroys
      * any state that was originally saved.
      *
@@ -197,7 +197,7 @@
      * @exception LoginException if the commit fails
      *
      * @return true if this method succeeded, or false if this
-     *                  <code>LoginModule</code> should be ignored.
+     *                  {@code LoginModule} should be ignored.
      */
     boolean commit() throws LoginException;
 
@@ -211,7 +211,7 @@
      *
      * <p> If this LoginModule's own authentication attempt
      * succeeded (checked by retrieving the private state saved by the
-     * <code>login</code> method), then this method cleans up any state
+     * {@code login} method), then this method cleans up any state
      * that was originally saved.
      *
      * <p>
@@ -219,12 +219,12 @@
      * @exception LoginException if the abort fails
      *
      * @return true if this method succeeded, or false if this
-     *                  <code>LoginModule</code> should be ignored.
+     *                  {@code LoginModule} should be ignored.
      */
     boolean abort() throws LoginException;
 
     /**
-     * Method which logs out a <code>Subject</code>.
+     * Method which logs out a {@code Subject}.
      *
      * <p>An implementation of this method might remove/destroy a Subject's
      * Principals and Credentials.
@@ -234,7 +234,7 @@
      * @exception LoginException if the logout fails
      *
      * @return true if this method succeeded, or false if this
-     *                  <code>LoginModule</code> should be ignored.
+     *                  {@code LoginModule} should be ignored.
      */
     boolean logout() throws LoginException;
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/javax/security/auth/spi/package-info.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * This package provides the interface to be used for
+ * implementing pluggable authentication modules.
+ *
+ * @since JDK1.4
+ */
+package javax.security.auth.spi;
--- a/src/share/classes/javax/security/auth/spi/package.html	Thu Jul 18 03:38:49 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,53 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
-<html>
-<head>
-<!--
-Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
-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.
--->
-
-</head>
-<body bgcolor="white">
-	
-	This package provides the interface to be used for
- 	implementing pluggable authentication modules.
-<!--
-<h2>Package Specification</h2>
-
-##### FILL IN ANY SPECS NEEDED BY JAVA COMPATIBILITY KIT #####
-<ul>
-  <li><a href="">##### REFER TO ANY FRAMEMAKER SPECIFICATION HERE #####</a>
-</ul>
-
-<h2>Related Documentation</h2>
-
-For overviews, tutorials, examples, guides, and tool documentation, please see:
-<ul>
-  <li><a href="">##### REFER TO NON-SPEC DOCUMENTATION HERE #####</a>
-</ul>
-
--->
-
-@since JDK1.4
-</body>
-</html>
--- a/src/share/classes/javax/security/auth/x500/X500Principal.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/x500/X500Principal.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,8 +33,8 @@
 import sun.security.util.*;
 
 /**
- * <p> This class represents an X.500 <code>Principal</code>.
- * <code>X500Principal</code>s are represented by distinguished names such as
+ * <p> This class represents an X.500 {@code Principal}.
+ * {@code X500Principal}s are represented by distinguished names such as
  * "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US".
  *
  * <p> This class can be instantiated by using a string representation
@@ -50,12 +50,12 @@
  * <a href="http://www.ietf.org/rfc/rfc3280.txt">RFC 3280: Internet X.509
  * Public Key Infrastructure Certificate and CRL Profile</a>.
  *
- * <p> The string representation for this <code>X500Principal</code>
- * can be obtained by calling the <code>getName</code> methods.
+ * <p> The string representation for this {@code X500Principal}
+ * can be obtained by calling the {@code getName} methods.
  *
- * <p> Note that the <code>getSubjectX500Principal</code> and
- * <code>getIssuerX500Principal</code> methods of
- * <code>X509Certificate</code> return X500Principals representing the
+ * <p> Note that the {@code getSubjectX500Principal} and
+ * {@code getIssuerX500Principal} methods of
+ * {@code X509Certificate} return X500Principals representing the
  * issuer and subject fields of the certificate.
  *
  * @see java.security.cert.X509Certificate
@@ -97,7 +97,7 @@
     }
 
     /**
-     * Creates an <code>X500Principal</code> from a string representation of
+     * Creates an {@code X500Principal} from a string representation of
      * an X.500 distinguished name (ex:
      * "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US").
      * The distinguished name must be specified using the grammar defined in
@@ -119,9 +119,9 @@
      * <p>{@code numericoid = number 1*( DOT number ) }
      *
      * @param name an X.500 distinguished name in RFC 1779 or RFC 2253 format
-     * @exception NullPointerException if the <code>name</code>
-     *                  is <code>null</code>
-     * @exception IllegalArgumentException if the <code>name</code>
+     * @exception NullPointerException if the {@code name}
+     *                  is {@code null}
+     * @exception IllegalArgumentException if the {@code name}
      *                  is improperly specified
      */
     public X500Principal(String name) {
@@ -129,7 +129,7 @@
     }
 
     /**
-     * Creates an <code>X500Principal</code> from a string representation of
+     * Creates an {@code X500Principal} from a string representation of
      * an X.500 distinguished name (ex:
      * "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US").
      * The distinguished name must be specified using the grammar defined in
@@ -137,13 +137,13 @@
      *
      * <p> This constructor recognizes the attribute type keywords specified
      * in {@link #X500Principal(String)} and also recognizes additional
-     * keywords that have entries in the <code>keywordMap</code> parameter.
+     * keywords that have entries in the {@code keywordMap} parameter.
      * Keyword entries in the keywordMap take precedence over the default
-     * keywords recognized by <code>X500Principal(String)</code>. Keywords
+     * keywords recognized by {@code X500Principal(String)}. Keywords
      * MUST be specified in all upper-case, otherwise they will be ignored.
      * Improperly specified keywords are ignored; however if a keyword in the
      * name maps to an improperly specified Object Identifier (OID), an
-     * <code>IllegalArgumentException</code> is thrown. It is permissible to
+     * {@code IllegalArgumentException} is thrown. It is permissible to
      * have 2 different keywords that map to the same OID.
      *
      * <p>This implementation enforces a more restrictive OID syntax than
@@ -157,11 +157,11 @@
      * @param keywordMap an attribute type keyword map, where each key is a
      *   keyword String that maps to a corresponding object identifier in String
      *   form (a sequence of nonnegative integers separated by periods). The map
-     *   may be empty but never <code>null</code>.
-     * @exception NullPointerException if <code>name</code> or
-     *   <code>keywordMap</code> is <code>null</code>
-     * @exception IllegalArgumentException if the <code>name</code> is
-     *   improperly specified or a keyword in the <code>name</code> maps to an
+     *   may be empty but never {@code null}.
+     * @exception NullPointerException if {@code name} or
+     *   {@code keywordMap} is {@code null}
+     * @exception IllegalArgumentException if the {@code name} is
+     *   improperly specified or a keyword in the {@code name} maps to an
      *   OID that is not in the correct form
      * @since 1.6
      */
@@ -188,10 +188,10 @@
     }
 
     /**
-     * Creates an <code>X500Principal</code> from a distinguished name in
+     * Creates an {@code X500Principal} from a distinguished name in
      * ASN.1 DER encoded form. The ASN.1 notation for this structure is as
      * follows.
-     * <pre><code>
+     * <pre>{@code
      * Name ::= CHOICE {
      *   RDNSequence }
      *
@@ -214,7 +214,7 @@
      *       universalString         UniversalString (SIZE (1..MAX)),
      *       utf8String              UTF8String (SIZE (1.. MAX)),
      *       bmpString               BMPString (SIZE (1..MAX)) }
-     * </code></pre>
+     * }</pre>
      *
      * @param name a byte array containing the distinguished name in ASN.1
      * DER encoded form
@@ -233,7 +233,7 @@
     }
 
     /**
-     * Creates an <code>X500Principal</code> from an <code>InputStream</code>
+     * Creates an {@code X500Principal} from an {@code InputStream}
      * containing the distinguished name in ASN.1 DER encoded form.
      * The ASN.1 notation for this structure is supplied in the
      * documentation for
@@ -242,11 +242,11 @@
      * <p> The read position of the input stream is positioned
      * to the next available byte after the encoded distinguished name.
      *
-     * @param is an <code>InputStream</code> containing the distinguished
+     * @param is an {@code InputStream} containing the distinguished
      *          name in ASN.1 DER encoded form
      *
-     * @exception NullPointerException if the <code>InputStream</code>
-     *          is <code>null</code>
+     * @exception NullPointerException if the {@code InputStream}
+     *          is {@code null}
      * @exception IllegalArgumentException if an encoding error occurs
      *          (incorrect form for DN)
      */
@@ -284,9 +284,9 @@
      * the format defined in RFC 2253.
      *
      * <p>This method is equivalent to calling
-     * <code>getName(X500Principal.RFC2253)</code>.
+     * {@code getName(X500Principal.RFC2253)}.
      *
-     * @return the distinguished name of this <code>X500Principal</code>
+     * @return the distinguished name of this {@code X500Principal}
      */
     public String getName() {
         return getName(X500Principal.RFC2253);
@@ -338,9 +338,9 @@
      *          those which section 2.4 of RFC 2253 states must be escaped
      *          (they are escaped using a preceding backslash character)
      * <li> The entire name is converted to upper case
-     *          using <code>String.toUpperCase(Locale.US)</code>
+     *          using {@code String.toUpperCase(Locale.US)}
      * <li> The entire name is converted to lower case
-     *          using <code>String.toLowerCase(Locale.US)</code>
+     *          using {@code String.toLowerCase(Locale.US)}
      * <li> The name is finally normalized using normalization form KD,
      *          as described in the Unicode Standard and UAX #15
      * </ol>
@@ -349,7 +349,7 @@
      *
      * @param format the format to use
      *
-     * @return a string representation of this <code>X500Principal</code>
+     * @return a string representation of this {@code X500Principal}
      *          using the specified format
      * @throws IllegalArgumentException if the specified format is invalid
      *          or null
@@ -371,16 +371,16 @@
      * Returns a string representation of the X.500 distinguished name
      * using the specified format. Valid values for the format are
      * "RFC1779" and "RFC2253" (case insensitive). "CANONICAL" is not
-     * permitted and an <code>IllegalArgumentException</code> will be thrown.
+     * permitted and an {@code IllegalArgumentException} will be thrown.
      *
      * <p>This method returns Strings in the format as specified in
      * {@link #getName(String)} and also emits additional attribute type
-     * keywords for OIDs that have entries in the <code>oidMap</code>
+     * keywords for OIDs that have entries in the {@code oidMap}
      * parameter. OID entries in the oidMap take precedence over the default
-     * OIDs recognized by <code>getName(String)</code>.
+     * OIDs recognized by {@code getName(String)}.
      * Improperly specified OIDs are ignored; however if an OID
      * in the name maps to an improperly specified keyword, an
-     * <code>IllegalArgumentException</code> is thrown.
+     * {@code IllegalArgumentException} is thrown.
      *
      * <p> Additional standard formats may be introduced in the future.
      *
@@ -393,12 +393,12 @@
      * @param oidMap an OID map, where each key is an object identifier in
      *  String form (a sequence of nonnegative integers separated by periods)
      *  that maps to a corresponding attribute type keyword String.
-     *  The map may be empty but never <code>null</code>.
-     * @return a string representation of this <code>X500Principal</code>
+     *  The map may be empty but never {@code null}.
+     * @return a string representation of this {@code X500Principal}
      *          using the specified format
      * @throws IllegalArgumentException if the specified format is invalid,
      *  null, or an OID in the name maps to an improperly specified keyword
-     * @throws NullPointerException if <code>oidMap</code> is <code>null</code>
+     * @throws NullPointerException if {@code oidMap} is {@code null}
      * @since 1.6
      */
     public String getName(String format, Map<String, String> oidMap) {
@@ -438,31 +438,31 @@
 
     /**
      * Return a user-friendly string representation of this
-     * <code>X500Principal</code>.
+     * {@code X500Principal}.
      *
-     * @return a string representation of this <code>X500Principal</code>
+     * @return a string representation of this {@code X500Principal}
      */
     public String toString() {
         return thisX500Name.toString();
     }
 
     /**
-     * Compares the specified <code>Object</code> with this
-     * <code>X500Principal</code> for equality.
+     * Compares the specified {@code Object} with this
+     * {@code X500Principal} for equality.
      *
-     * <p> Specifically, this method returns <code>true</code> if
-     * the <code>Object</code> <i>o</i> is an <code>X500Principal</code>
+     * <p> Specifically, this method returns {@code true} if
+     * the {@code Object} <i>o</i> is an {@code X500Principal}
      * and if the respective canonical string representations
-     * (obtained via the <code>getName(X500Principal.CANONICAL)</code> method)
+     * (obtained via the {@code getName(X500Principal.CANONICAL)} method)
      * of this object and <i>o</i> are equal.
      *
      * <p> This implementation is compliant with the requirements of RFC 3280.
      *
      * @param o Object to be compared for equality with this
-     *          <code>X500Principal</code>
+     *          {@code X500Principal}
      *
-     * @return <code>true</code> if the specified <code>Object</code> is equal
-     *          to this <code>X500Principal</code>, <code>false</code> otherwise
+     * @return {@code true} if the specified {@code Object} is equal
+     *          to this {@code X500Principal}, {@code false} otherwise
      */
     public boolean equals(Object o) {
         if (this == o) {
@@ -476,12 +476,12 @@
     }
 
     /**
-     * Return a hash code for this <code>X500Principal</code>.
+     * Return a hash code for this {@code X500Principal}.
      *
      * <p> The hash code is calculated via:
-     * <code>getName(X500Principal.CANONICAL).hashCode()</code>
+     * {@code getName(X500Principal.CANONICAL).hashCode()}
      *
-     * @return a hash code for this <code>X500Principal</code>
+     * @return a hash code for this {@code X500Principal}
      */
     public int hashCode() {
         return thisX500Name.hashCode();
@@ -490,9 +490,9 @@
     /**
      * Save the X500Principal object to a stream.
      *
-     * @serialData this <code>X500Principal</code> is serialized
+     * @serialData this {@code X500Principal} is serialized
      *          by writing out its DER-encoded form
-     *          (the value of <code>getEncoded</code> is serialized).
+     *          (the value of {@code getEncoded} is serialized).
      */
     private void writeObject(java.io.ObjectOutputStream s)
         throws IOException {
--- a/src/share/classes/javax/security/auth/x500/X500PrivateCredential.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/auth/x500/X500PrivateCredential.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,7 +30,7 @@
 import javax.security.auth.Destroyable;
 
 /**
- * <p> This class represents an <code>X500PrivateCredential</code>.
+ * <p> This class represents an {@code X500PrivateCredential}.
  * It associates an X.509 certificate, corresponding private key and the
  * KeyStore alias used to reference that exact key pair in the KeyStore.
  * This enables looking up the private credentials for an X.500 principal
@@ -48,8 +48,8 @@
      * <p>
      * @param cert X509Certificate
      * @param key  PrivateKey for the certificate
-     * @exception IllegalArgumentException if either <code>cert</code> or
-     * <code>key</code> is null
+     * @exception IllegalArgumentException if either {@code cert} or
+     * {@code key} is null
      *
      */
 
@@ -68,8 +68,8 @@
      * @param cert X509Certificate
      * @param key  PrivateKey for the certificate
      * @param alias KeyStore alias
-     * @exception IllegalArgumentException if either <code>cert</code>,
-     * <code>key</code> or <code>alias</code> is null
+     * @exception IllegalArgumentException if either {@code cert},
+     * {@code key} or {@code alias} is null
      *
      */
     public X500PrivateCredential(X509Certificate cert, PrivateKey key,
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/javax/security/auth/x500/package-info.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * This package contains the classes that should be used to store
+ * X500 Principal and X500 Private Credentials in a
+ * <i>Subject</i>.
+ *
+ * <h2>Package Specification</h2>
+ *
+ * <ul>
+ *   <li><a href="http://www.ietf.org/rfc/rfc1779.txt">
+ *     RFC 1779: A String Representation of Distinguished Names</a></li>
+ *   <li><a href="http://www.ietf.org/rfc/rfc2253.txt">
+ *     RFC 2253: Lightweight Directory Access Protocol (v3):
+ *     UTF-8 String Representation of Distinguished Names</a></li>
+ *   <li><a href="http://www.ietf.org/rfc/rfc3280.txt">
+ *     RFC 3280: Internet X.509 Public Key Infrastructure
+ *     Certificate and Certificate Revocation List (CRL) Profile</a></li>
+ *   <li><a href="http://www.ietf.org/rfc/rfc4512.txt">
+ *     RFC 4512: Lightweight Directory Access Protocol (LDAP):
+ *     Directory Information Models</a></li>
+ * </ul>
+ *
+ * @since JDK1.4
+ */
+package javax.security.auth.x500;
--- a/src/share/classes/javax/security/auth/x500/package.html	Thu Jul 18 03:38:49 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,64 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
-<html>
-<head>
-<!--
-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
-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.
--->
-
-</head>
-<body bgcolor="white">
-
-    This package contains the classes that should be used to store 
-    X500 Principal and X500 Private Credentials in a
-    <i>Subject</i>.
-
-<h2>Package Specification</h2>
-
-<ul>
-  <li><a href="http://www.ietf.org/rfc/rfc1779.txt">
-    RFC 1779: A String Representation of Distinguished Names</a></li>
-  <li><a href="http://www.ietf.org/rfc/rfc2253.txt">
-    RFC 2253: Lightweight Directory Access Protocol (v3):
-    UTF-8 String Representation of Distinguished Names</a></li>
-  <li><a href="http://www.ietf.org/rfc/rfc3280.txt">
-    RFC 3280: Internet X.509 Public Key Infrastructure
-    Certificate and Certificate Revocation List (CRL) Profile</a></li>
-  <li><a href="http://www.ietf.org/rfc/rfc4512.txt">
-    RFC 4512: Lightweight Directory Access Protocol (LDAP):
-    Directory Information Models</a></li>
-</ul>
-
-<!--
-<h2>Related Documentation</h2>
-
-For overviews, tutorials, examples, guides, and tool documentation, please see:
-<ul>
-  <li><a href="">##### REFER TO NON-SPEC DOCUMENTATION HERE #####</a>
-</ul>
-
--->
-
-@since JDK1.4
-</body>
-</html>
--- a/src/share/classes/javax/security/cert/Certificate.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/cert/Certificate.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,11 +49,11 @@
  * sets of information, and they store and retrieve the information in
  * different ways.
  *
- * <p><em>Note: The classes in the package <code>javax.security.cert</code>
+ * <p><em>Note: The classes in the package {@code javax.security.cert}
  * exist for compatibility with earlier versions of the
  * Java Secure Sockets Extension (JSSE). New applications should instead
  * use the standard Java SE certificate classes located in
- * <code>java.security.cert</code>.</em></p>
+ * {@code java.security.cert}.</em></p>
  *
  * @since 1.4
  * @see X509Certificate
@@ -64,8 +64,8 @@
 
     /**
      * Compares this certificate for equality with the specified
-     * object. If the <code>other</code> object is an
-     * <code>instanceof</code> <code>Certificate</code>, then
+     * object. If the {@code other} object is an
+     * {@code instanceof} {@code Certificate}, then
      * its encoded form is retrieved and compared with the
      * encoded form of this certificate.
      *
--- a/src/share/classes/javax/security/cert/CertificateEncodingException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/cert/CertificateEncodingException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,11 +30,11 @@
  * Certificate Encoding Exception. This is thrown whenever an error
  * occurs whilst attempting to encode a certificate.
  *
- * <p><em>Note: The classes in the package <code>javax.security.cert</code>
+ * <p><em>Note: The classes in the package {@code javax.security.cert}
  * exist for compatibility with earlier versions of the
  * Java Secure Sockets Extension (JSSE). New applications should instead
  * use the standard Java SE certificate classes located in
- * <code>java.security.cert</code>.</em></p>
+ * {@code java.security.cert}.</em></p>
  *
  * @since 1.4
  * @author Hemma Prafullchandra
--- a/src/share/classes/javax/security/cert/CertificateException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/cert/CertificateException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,11 +29,11 @@
 /**
  * This exception indicates one of a variety of certificate problems.
  *
- * <p><em>Note: The classes in the package <code>javax.security.cert</code>
+ * <p><em>Note: The classes in the package {@code javax.security.cert}
  * exist for compatibility with earlier versions of the
  * Java Secure Sockets Extension (JSSE). New applications should instead
  * use the standard Java SE certificate classes located in
- * <code>java.security.cert</code>.</em></p>
+ * {@code java.security.cert}.</em></p>
  *
  * @author Hemma Prafullchandra
  * @since 1.4
--- a/src/share/classes/javax/security/cert/CertificateExpiredException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/cert/CertificateExpiredException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,15 +28,15 @@
 
 /**
  * Certificate Expired Exception. This is thrown whenever the current
- * <code>Date</code> or the specified <code>Date</code> is after the
- * <code>notAfter</code> date/time specified in the validity period
+ * {@code Date} or the specified {@code Date} is after the
+ * {@code notAfter} date/time specified in the validity period
  * of the certificate.
  *
- * <p><em>Note: The classes in the package <code>javax.security.cert</code>
+ * <p><em>Note: The classes in the package {@code javax.security.cert}
  * exist for compatibility with earlier versions of the
  * Java Secure Sockets Extension (JSSE). New applications should instead
  * use the standard Java SE certificate classes located in
- * <code>java.security.cert</code>.</em></p>
+ * {@code java.security.cert}.</em></p>
  *
  * @since 1.4
  * @author Hemma Prafullchandra
--- a/src/share/classes/javax/security/cert/CertificateNotYetValidException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/cert/CertificateNotYetValidException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,15 +28,15 @@
 
 /**
  * Certificate is not yet valid exception. This is thrown whenever
- * the current <code>Date</code> or the specified <code>Date</code>
- * is before the <code>notBefore</code> date/time in the Certificate
+ * the current {@code Date} or the specified {@code Date}
+ * is before the {@code notBefore} date/time in the Certificate
  * validity period.
  *
- * <p><em>Note: The classes in the package <code>javax.security.cert</code>
+ * <p><em>Note: The classes in the package {@code javax.security.cert}
  * exist for compatibility with earlier versions of the
  * Java Secure Sockets Extension (JSSE). New applications should instead
  * use the standard Java SE certificate classes located in
- * <code>java.security.cert</code>.</em></p>
+ * {@code java.security.cert}.</em></p>
  *
  * @since 1.4
  * @author Hemma Prafullchandra
--- a/src/share/classes/javax/security/cert/CertificateParsingException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/cert/CertificateParsingException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,11 +31,11 @@
  * invalid DER encoded certificate is parsed or unsupported DER features
  * are found in the Certificate.
  *
- * <p><em>Note: The classes in the package <code>javax.security.cert</code>
+ * <p><em>Note: The classes in the package {@code javax.security.cert}
  * exist for compatibility with earlier versions of the
  * Java Secure Sockets Extension (JSSE). New applications should instead
  * use the standard Java SE certificate classes located in
- * <code>java.security.cert</code>.</em></p>
+ * {@code java.security.cert}.</em></p>
  *
  * @since 1.4
  * @author Hemma Prafullchandra
--- a/src/share/classes/javax/security/cert/X509Certificate.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/cert/X509Certificate.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -70,7 +70,7 @@
  * CA certificates are either signed by themselves, or by some other
  * CA such as a "root" CA.
  * <p>
- * The ASN.1 definition of <code>tbsCertificate</code> is:
+ * The ASN.1 definition of {@code tbsCertificate} is:
  * <pre>
  * TBSCertificate  ::=  SEQUENCE  {
  *     version         [0]  EXPLICIT Version DEFAULT v1,
@@ -113,11 +113,11 @@
  * initialization time and will fallback on a default implementation if
  * the Security property is not accessible.
  *
- * <p><em>Note: The classes in the package <code>javax.security.cert</code>
+ * <p><em>Note: The classes in the package {@code javax.security.cert}
  * exist for compatibility with earlier versions of the
  * Java Secure Sockets Extension (JSSE). New applications should instead
  * use the standard Java SE certificate classes located in
- * <code>java.security.cert</code>.</em></p>
+ * {@code java.security.cert}.</em></p>
  *
  * @author Hemma Prafullchandra
  * @since 1.4
@@ -150,7 +150,7 @@
 
     /**
      * Instantiates an X509Certificate object, and initializes it with
-     * the data read from the input stream <code>inStream</code>.
+     * the data read from the input stream {@code inStream}.
      * The implementation (X509Certificate is an abstract class) is
      * provided by the class specified as the value of the
      * {@code cert.provider.x509v1} security property.
@@ -159,9 +159,9 @@
      * certificate is expected to be in the input stream.
      * Also, all X509Certificate
      * subclasses must provide a constructor of the form:
-     * <code><pre>
-     * public &lt;subClass&gt;(InputStream inStream) ...
-     * </pre></code>
+     * <pre>{@code
+     * public <subClass>(InputStream inStream) ...
+     * }</pre>
      *
      * @param inStream an input stream with the data to be read to
      *        initialize the certificate.
@@ -184,14 +184,14 @@
      *
      * <p>Note: All X509Certificate
      * subclasses must provide a constructor of the form:
-     * <code><pre>
-     * public &lt;subClass&gt;(InputStream inStream) ...
-     * </pre></code>
+     * <pre>{@code
+     * public <subClass>(InputStream inStream) ...
+     * }</pre>
      *
      * @param certData a byte array containing the DER-encoded
      *        certificate.
      * @return an X509Certificate object initialized with the data
-     *         from <code>certData</code>.
+     *         from {@code certData}.
      * @exception CertificateException if a class initialization
      *            or certificate parsing error occurs.
      */
@@ -255,10 +255,12 @@
      * is valid. It is defined in
      * ASN.1 as:
      * <pre>
-     * validity             Validity<p>
+     * validity             Validity
+     *
      * Validity ::= SEQUENCE {
      *     notBefore      CertificateValidityDate,
-     *     notAfter       CertificateValidityDate }<p>
+     *     notAfter       CertificateValidityDate }
+     *
      * CertificateValidityDate ::= CHOICE {
      *     utcTime        UTCTime,
      *     generalTime    GeneralizedTime }
@@ -279,19 +281,20 @@
      * @param date the Date to check against to see if this certificate
      *        is valid at that date/time.
      * @exception CertificateExpiredException if the certificate has expired
-     *            with respect to the <code>date</code> supplied.
+     *            with respect to the {@code date} supplied.
      * @exception CertificateNotYetValidException if the certificate is not
-     *            yet valid with respect to the <code>date</code> supplied.
+     *            yet valid with respect to the {@code date} supplied.
      * @see #checkValidity()
      */
     public abstract void checkValidity(Date date)
         throws CertificateExpiredException, CertificateNotYetValidException;
 
     /**
-     * Gets the <code>version</code> (version number) value from the
+     * Gets the {@code version} (version number) value from the
      * certificate. The ASN.1 definition for this is:
      * <pre>
-     * version         [0]  EXPLICIT Version DEFAULT v1<p>
+     * version         [0]  EXPLICIT Version DEFAULT v1
+     *
      * Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }
      * </pre>
      *
@@ -300,14 +303,14 @@
     public abstract int getVersion();
 
     /**
-     * Gets the <code>serialNumber</code> value from the certificate.
+     * Gets the {@code serialNumber} value from the certificate.
      * The serial number is an integer assigned by the certification
      * authority to each certificate. It must be unique for each
      * certificate issued by a given CA (i.e., the issuer name and
      * serial number identify a unique certificate).
      * The ASN.1 definition for this is:
      * <pre>
-     * serialNumber     CertificateSerialNumber<p>
+     * serialNumber     CertificateSerialNumber
      *
      * CertificateSerialNumber  ::=  INTEGER
      * </pre>
@@ -317,7 +320,7 @@
     public abstract BigInteger getSerialNumber();
 
     /**
-     * Gets the <code>issuer</code> (issuer distinguished name) value from
+     * Gets the {@code issuer} (issuer distinguished name) value from
      * the certificate. The issuer name identifies the entity that signed (and
      * issued) the certificate.
      *
@@ -325,7 +328,7 @@
      * X.500 distinguished name (DN).
      * The ASN.1 definition for this is:
      * <pre>
-     * issuer    Name<p>
+     * issuer    Name
      *
      * Name ::= CHOICE { RDNSequence }
      * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
@@ -338,27 +341,27 @@
      * AttributeType ::= OBJECT IDENTIFIER
      * AttributeValue ::= ANY
      * </pre>
-     * The <code>Name</code> describes a hierarchical name composed of
+     * The {@code Name} describes a hierarchical name composed of
      * attributes, such as country name, and corresponding values, such as US.
-     * The type of the <code>AttributeValue</code> component is determined by
-     * the <code>AttributeType</code>; in general it will be a
-     * <code>directoryString</code>. A <code>directoryString</code> is usually
-     * one of <code>PrintableString</code>,
-     * <code>TeletexString</code> or <code>UniversalString</code>.
+     * The type of the {@code AttributeValue} component is determined by
+     * the {@code AttributeType}; in general it will be a
+     * {@code directoryString}. A {@code directoryString} is usually
+     * one of {@code PrintableString},
+     * {@code TeletexString} or {@code UniversalString}.
      *
      * @return a Principal whose name is the issuer distinguished name.
      */
     public abstract Principal getIssuerDN();
 
     /**
-     * Gets the <code>subject</code> (subject distinguished name) value
+     * Gets the {@code subject} (subject distinguished name) value
      * from the certificate.
      * The ASN.1 definition for this is:
      * <pre>
      * subject    Name
      * </pre>
      *
-     * <p>See {@link #getIssuerDN() getIssuerDN} for <code>Name</code>
+     * <p>See {@link #getIssuerDN() getIssuerDN} for {@code Name}
      * and other relevant definitions.
      *
      * @return a Principal whose name is the subject name.
@@ -367,15 +370,16 @@
     public abstract Principal getSubjectDN();
 
     /**
-     * Gets the <code>notBefore</code> date from the validity period of
+     * Gets the {@code notBefore} date from the validity period of
      * the certificate.
      * The relevant ASN.1 definitions are:
      * <pre>
-     * validity             Validity<p>
+     * validity             Validity
      *
      * Validity ::= SEQUENCE {
      *     notBefore      CertificateValidityDate,
-     *     notAfter       CertificateValidityDate }<p>
+     *     notAfter       CertificateValidityDate }
+     *
      * CertificateValidityDate ::= CHOICE {
      *     utcTime        UTCTime,
      *     generalTime    GeneralizedTime }
@@ -387,7 +391,7 @@
     public abstract Date getNotBefore();
 
     /**
-     * Gets the <code>notAfter</code> date from the validity period of
+     * Gets the {@code notAfter} date from the validity period of
      * the certificate. See {@link #getNotBefore() getNotBefore}
      * for relevant ASN.1 definitions.
      *
@@ -401,7 +405,8 @@
      * signature algorithm. An example is the string "SHA-1/DSA".
      * The ASN.1 definition for this is:
      * <pre>
-     * signatureAlgorithm   AlgorithmIdentifier<p>
+     * signatureAlgorithm   AlgorithmIdentifier
+     *
      * AlgorithmIdentifier  ::=  SEQUENCE  {
      *     algorithm               OBJECT IDENTIFIER,
      *     parameters              ANY DEFINED BY algorithm OPTIONAL  }
@@ -410,7 +415,7 @@
      *                             -- algorithm object identifier value
      * </pre>
      *
-     * <p>The algorithm name is determined from the <code>algorithm</code>
+     * <p>The algorithm name is determined from the {@code algorithm}
      * OID string.
      *
      * @return the signature algorithm name.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/javax/security/cert/package-info.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * Provides classes for public key certificates.
+ *
+ * These classes include a simplified version of the
+ * java.security.cert package.  These classes were developed
+ * as part of the Java Secure Socket
+ * Extension (JSSE).  When JSSE was added to the J2SE version 1.4, this
+ * package was added for backward-compatibility reasons only.
+ *
+ * New applications should not use this package, but rather
+ * java.security.cert.
+ *
+ * @since 1.4
+ */
+package javax.security.cert;
--- a/src/share/classes/javax/security/cert/package.html	Thu Jul 18 03:38:49 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
-<html>
-<head>
-<!--
-Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
-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.
--->
-
-</head>
-<body bgcolor="white">
-
-Provides classes for public key certificates.
-
-<P>
-
-These classes include a simplified version of the
-java.security.cert package.  These classes were developed
-as part of the Java Secure Socket
-Extension (JSSE).  When JSSE was added to the J2SE version 1.4, this
-package was added for backward-compatibility reasons only.
-
-<P>
-
-New applications should not use this package, but rather
-java.security.cert.
-<!--
-<h2>Package Specification</h2>
-
-##### FILL IN ANY SPECS NEEDED BY JAVA COMPATIBILITY KIT #####
-<ul>
-  <li><a href="">##### REFER TO ANY FRAMEMAKER SPECIFICATION HERE #####</a>
-</ul>
-
-<h2>Related Documentation</h2>
-
-For overviews, tutorials, examples, guides, and tool documentation, please see:
-<ul>
-  <li><a href="">##### REFER TO NON-SPEC DOCUMENTATION HERE #####</a>
-</ul>
-
--->
-
-@since 1.4
-</body>
-</html>
--- a/src/share/classes/javax/security/sasl/AuthenticationException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/sasl/AuthenticationException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -45,7 +45,7 @@
  */
 public class AuthenticationException extends SaslException {
     /**
-     * Constructs a new instance of <tt>AuthenticationException</tt>.
+     * Constructs a new instance of {@code AuthenticationException}.
      * The root exception and the detailed message are null.
      */
     public AuthenticationException () {
@@ -53,7 +53,7 @@
     }
 
     /**
-     * Constructs a new instance of <tt>AuthenticationException</tt>
+     * Constructs a new instance of {@code AuthenticationException}
      * with a detailed message.
      * The root exception is null.
      * @param detail A possibly null string containing details of the exception.
@@ -65,7 +65,7 @@
     }
 
     /**
-     * Constructs a new instance of <tt>AuthenticationException</tt> with a detailed message
+     * Constructs a new instance of {@code AuthenticationException} with a detailed message
      * and a root exception.
      *
      * @param detail A possibly null string containing details of the exception.
--- a/src/share/classes/javax/security/sasl/AuthorizeCallback.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/sasl/AuthorizeCallback.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,7 +28,7 @@
 import javax.security.auth.callback.Callback;
 
 /**
-  * This callback is used by <tt>SaslServer</tt> to determine whether
+  * This callback is used by {@code SaslServer} to determine whether
   * one entity (identified by an authenticated authentication id)
   * can act on
   * behalf of another entity (identified by an authorization id).
@@ -66,7 +66,7 @@
     private boolean authorized;
 
     /**
-     * Constructs an instance of <tt>AuthorizeCallback</tt>.
+     * Constructs an instance of {@code AuthorizeCallback}.
      *
      * @param authnID   The (authenticated) authentication id.
      * @param authzID   The authorization id.
@@ -96,7 +96,7 @@
      * Determines whether the authentication id is allowed to
      * act on behalf of the authorization id.
      *
-     * @return <tt>true</tt> if authorization is allowed; <tt>false</tt> otherwise
+     * @return {@code true} if authorization is allowed; {@code false} otherwise
      * @see #setAuthorized(boolean)
      * @see #getAuthorizedID()
      */
@@ -106,7 +106,7 @@
 
     /**
      * Sets whether the authorization is allowed.
-     * @param ok <tt>true</tt> if authorization is allowed; <tt>false</tt> otherwise
+     * @param ok {@code true} if authorization is allowed; {@code false} otherwise
      * @see #isAuthorized
      * @see #setAuthorizedID(java.lang.String)
      */
@@ -116,7 +116,7 @@
 
     /**
      * Returns the id of the authorized user.
-     * @return The id of the authorized user. <tt>null</tt> means the
+     * @return The id of the authorized user. {@code null} means the
      * authorization failed.
      * @see #setAuthorized(boolean)
      * @see #setAuthorizedID(java.lang.String)
--- a/src/share/classes/javax/security/sasl/RealmCallback.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/sasl/RealmCallback.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,7 +28,7 @@
 import javax.security.auth.callback.TextInputCallback;
 
 /**
-  * This callback is used by <tt>SaslClient</tt> and <tt>SaslServer</tt>
+  * This callback is used by {@code SaslClient} and {@code SaslServer}
   * to retrieve realm information.
   *
   * @since 1.5
@@ -39,10 +39,10 @@
 public class RealmCallback extends TextInputCallback {
 
     /**
-     * Constructs a <tt>RealmCallback</tt> with a prompt.
+     * Constructs a {@code RealmCallback} with a prompt.
      *
      * @param prompt The non-null prompt to use to request the realm information.
-     * @throws IllegalArgumentException If <tt>prompt</tt> is null or
+     * @throws IllegalArgumentException If {@code prompt} is null or
      * the empty string.
      */
     public RealmCallback(String prompt) {
@@ -50,14 +50,14 @@
     }
 
     /**
-     * Constructs a <tt>RealmCallback</tt> with a prompt and default
+     * Constructs a {@code RealmCallback} with a prompt and default
      * realm information.
      *
      * @param prompt The non-null prompt to use to request the realm information.
      * @param defaultRealmInfo The non-null default realm information to use.
-     * @throws IllegalArgumentException If <tt>prompt</tt> is null or
+     * @throws IllegalArgumentException If {@code prompt} is null or
      * the empty string,
-     * or if <tt>defaultRealm</tt> is empty or null.
+     * or if {@code defaultRealm} is empty or null.
      */
     public RealmCallback(String prompt, String defaultRealmInfo) {
         super(prompt, defaultRealmInfo);
--- a/src/share/classes/javax/security/sasl/RealmChoiceCallback.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/sasl/RealmChoiceCallback.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,7 +28,7 @@
 import javax.security.auth.callback.ChoiceCallback;
 
 /**
-  * This callback is used by <tt>SaslClient</tt> and <tt>SaslServer</tt>
+  * This callback is used by {@code SaslClient} and {@code SaslServer}
   * to obtain a realm given a list of realm choices.
   *
   * @since 1.5
@@ -39,19 +39,19 @@
 public class RealmChoiceCallback extends ChoiceCallback {
 
     /**
-     * Constructs a <tt>RealmChoiceCallback</tt> with a prompt, a list of
+     * Constructs a {@code RealmChoiceCallback} with a prompt, a list of
      * choices and a default choice.
      *
      * @param prompt the non-null prompt to use to request the realm.
      * @param choices the non-null list of realms to choose from.
      * @param defaultChoice the choice to be used as the default choice
      * when the list of choices is displayed. It is an index into
-     * the <tt>choices</tt> arary.
+     * the {@code choices} arary.
      * @param multiple true if multiple choices allowed; false otherwise
-     * @throws IllegalArgumentException If <tt>prompt</tt> is null or the empty string,
-     * if <tt>choices</tt> has a length of 0, if any element from
-     * <tt>choices</tt> is null or empty, or if <tt>defaultChoice</tt>
-     * does not fall within the array boundary of <tt>choices</tt>
+     * @throws IllegalArgumentException If {@code prompt} is null or the empty string,
+     * if {@code choices} has a length of 0, if any element from
+     * {@code choices} is null or empty, or if {@code defaultChoice}
+     * does not fall within the array boundary of {@code choices}
      */
     public RealmChoiceCallback(String prompt, String[]choices,
         int defaultChoice, boolean multiple) {
--- a/src/share/classes/javax/security/sasl/Sasl.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/sasl/Sasl.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -72,15 +72,15 @@
      * of quality-of-protection values that the
      * client or server is willing to support.  A qop value is one of
      * <ul>
-     * <li><tt>"auth"</tt> - authentication only</li>
-     * <li><tt>"auth-int"</tt> - authentication plus integrity protection</li>
-     * <li><tt>"auth-conf"</tt> - authentication plus integrity and confidentiality
+     * <li>{@code "auth"} - authentication only</li>
+     * <li>{@code "auth-int"} - authentication plus integrity protection</li>
+     * <li>{@code "auth-conf"} - authentication plus integrity and confidentiality
      * protection</li>
      * </ul>
      *
      * The order of the list specifies the preference order of the client or
-     * server. If this property is absent, the default qop is <tt>"auth"</tt>.
-     * The value of this constant is <tt>"javax.security.sasl.qop"</tt>.
+     * server. If this property is absent, the default qop is {@code "auth"}.
+     * The value of this constant is {@code "javax.security.sasl.qop"}.
      */
     public static final String QOP = "javax.security.sasl.qop";
 
@@ -90,9 +90,9 @@
      * of cipher strength values that
      * the client or server is willing to support. A strength value is one of
      * <ul>
-     * <li><tt>"low"</tt></li>
-     * <li><tt>"medium"</tt></li>
-     * <li><tt>"high"</tt></li>
+     * <li>{@code "low"}</li>
+     * <li>{@code "medium"}</li>
+     * <li>{@code "high"}</li>
      * </ul>
      * The order of the list specifies the preference order of the client or
      * server.  An implementation should allow configuration of the meaning
@@ -101,19 +101,19 @@
      * cipher suites that match the strength values.
      * <BR>
      * If this property is absent, the default strength is
-     * <tt>"high,medium,low"</tt>.
-     * The value of this constant is <tt>"javax.security.sasl.strength"</tt>.
+     * {@code "high,medium,low"}.
+     * The value of this constant is {@code "javax.security.sasl.strength"}.
      */
     public static final String STRENGTH = "javax.security.sasl.strength";
 
     /**
      * The name of a property that specifies whether the
      * server must authenticate to the client. The property contains
-     * <tt>"true"</tt> if the server must
-     * authenticate the to client; <tt>"false"</tt> otherwise.
-     * The default is <tt>"false"</tt>.
+     * {@code "true"} if the server must
+     * authenticate the to client; {@code "false"} otherwise.
+     * The default is {@code "false"}.
      * <br>The value of this constant is
-     * <tt>"javax.security.sasl.server.authentication"</tt>.
+     * {@code "javax.security.sasl.server.authentication"}.
      */
     public static final String SERVER_AUTH =
     "javax.security.sasl.server.authentication";
@@ -125,28 +125,28 @@
      * The property contains the bound host name after the authentication
      * exchange has completed. It is only available on the server side.
      * <br>The value of this constant is
-     * <tt>"javax.security.sasl.bound.server.name"</tt>.
+     * {@code "javax.security.sasl.bound.server.name"}.
      */
     public static final String BOUND_SERVER_NAME =
     "javax.security.sasl.bound.server.name";
 
     /**
      * The name of a property that specifies the maximum size of the receive
-     * buffer in bytes of <tt>SaslClient</tt>/<tt>SaslServer</tt>.
+     * buffer in bytes of {@code SaslClient}/{@code SaslServer}.
      * The property contains the string representation of an integer.
      * <br>If this property is absent, the default size
      * is defined by the mechanism.
-     * <br>The value of this constant is <tt>"javax.security.sasl.maxbuffer"</tt>.
+     * <br>The value of this constant is {@code "javax.security.sasl.maxbuffer"}.
      */
     public static final String MAX_BUFFER = "javax.security.sasl.maxbuffer";
 
     /**
      * The name of a property that specifies the maximum size of the raw send
-     * buffer in bytes of <tt>SaslClient</tt>/<tt>SaslServer</tt>.
+     * buffer in bytes of {@code SaslClient}/{@code SaslServer}.
      * The property contains the string representation of an integer.
      * The value of this property is negotiated between the client and server
      * during the authentication exchange.
-     * <br>The value of this constant is <tt>"javax.security.sasl.rawsendsize"</tt>.
+     * <br>The value of this constant is {@code "javax.security.sasl.rawsendsize"}.
      */
     public static final String RAW_SEND_SIZE = "javax.security.sasl.rawsendsize";
 
@@ -181,11 +181,11 @@
      * The name of a property that specifies
      * whether mechanisms susceptible to simple plain passive attacks (e.g.,
      * "PLAIN") are not permitted. The property
-     * contains <tt>"true"</tt> if such mechanisms are not permitted;
-     * <tt>"false"</tt> if such mechanisms are permitted.
-     * The default is <tt>"false"</tt>.
+     * contains {@code "true"} if such mechanisms are not permitted;
+     * {@code "false"} if such mechanisms are permitted.
+     * The default is {@code "false"}.
      * <br>The value of this constant is
-     * <tt>"javax.security.sasl.policy.noplaintext"</tt>.
+     * {@code "javax.security.sasl.policy.noplaintext"}.
      */
     public static final String POLICY_NOPLAINTEXT =
     "javax.security.sasl.policy.noplaintext";
@@ -194,12 +194,12 @@
      * The name of a property that specifies whether
      * mechanisms susceptible to active (non-dictionary) attacks
      * are not permitted.
-     * The property contains <tt>"true"</tt>
+     * The property contains {@code "true"}
      * if mechanisms susceptible to active attacks
-     * are not permitted; <tt>"false"</tt> if such mechanisms are permitted.
-     * The default is <tt>"false"</tt>.
+     * are not permitted; {@code "false"} if such mechanisms are permitted.
+     * The default is {@code "false"}.
      * <br>The value of this constant is
-     * <tt>"javax.security.sasl.policy.noactive"</tt>.
+     * {@code "javax.security.sasl.policy.noactive"}.
      */
     public static final String POLICY_NOACTIVE =
     "javax.security.sasl.policy.noactive";
@@ -207,26 +207,26 @@
     /**
      * The name of a property that specifies whether
      * mechanisms susceptible to passive dictionary attacks are not permitted.
-     * The property contains <tt>"true"</tt>
+     * The property contains {@code "true"}
      * if mechanisms susceptible to dictionary attacks are not permitted;
-     * <tt>"false"</tt> if such mechanisms are permitted.
-     * The default is <tt>"false"</tt>.
+     * {@code "false"} if such mechanisms are permitted.
+     * The default is {@code "false"}.
      *<br>
      * The value of this constant is
-     * <tt>"javax.security.sasl.policy.nodictionary"</tt>.
+     * {@code "javax.security.sasl.policy.nodictionary"}.
      */
     public static final String POLICY_NODICTIONARY =
     "javax.security.sasl.policy.nodictionary";
 
     /**
      * The name of a property that specifies whether mechanisms that accept
-     * anonymous login are not permitted. The property contains <tt>"true"</tt>
+     * anonymous login are not permitted. The property contains {@code "true"}
      * if mechanisms that accept anonymous login are not permitted;
-     * <tt>"false"</tt>
-     * if such mechanisms are permitted. The default is <tt>"false"</tt>.
+     * {@code "false"}
+     * if such mechanisms are permitted. The default is {@code "false"}.
      *<br>
      * The value of this constant is
-     * <tt>"javax.security.sasl.policy.noanonymous"</tt>.
+     * {@code "javax.security.sasl.policy.noanonymous"}.
      */
     public static final String POLICY_NOANONYMOUS =
     "javax.security.sasl.policy.noanonymous";
@@ -237,12 +237,12 @@
       * means that breaking into one session will not automatically
       * provide information for breaking into future sessions.
       * The property
-      * contains <tt>"true"</tt> if mechanisms that implement forward secrecy
-      * between sessions are required; <tt>"false"</tt> if such mechanisms
-      * are not required. The default is <tt>"false"</tt>.
+      * contains {@code "true"} if mechanisms that implement forward secrecy
+      * between sessions are required; {@code "false"} if such mechanisms
+      * are not required. The default is {@code "false"}.
       *<br>
       * The value of this constant is
-      * <tt>"javax.security.sasl.policy.forward"</tt>.
+      * {@code "javax.security.sasl.policy.forward"}.
       */
     public static final String POLICY_FORWARD_SECRECY =
     "javax.security.sasl.policy.forward";
@@ -250,12 +250,12 @@
     /**
      * The name of a property that specifies whether
      * mechanisms that pass client credentials are required. The property
-     * contains <tt>"true"</tt> if mechanisms that pass
-     * client credentials are required; <tt>"false"</tt>
-     * if such mechanisms are not required. The default is <tt>"false"</tt>.
+     * contains {@code "true"} if mechanisms that pass
+     * client credentials are required; {@code "false"}
+     * if such mechanisms are not required. The default is {@code "false"}.
      *<br>
      * The value of this constant is
-     * <tt>"javax.security.sasl.policy.credentials"</tt>.
+     * {@code "javax.security.sasl.policy.credentials"}.
      */
     public static final String POLICY_PASS_CREDENTIALS =
     "javax.security.sasl.policy.credentials";
@@ -269,38 +269,38 @@
      * supports delegated authentication.
      *<br>
      * The value of this constant is
-     * <tt>"javax.security.sasl.credentials"</tt>.
+     * {@code "javax.security.sasl.credentials"}.
      */
     public static final String CREDENTIALS = "javax.security.sasl.credentials";
 
     /**
-     * Creates a <tt>SaslClient</tt> using the parameters supplied.
+     * Creates a {@code SaslClient} using the parameters supplied.
      *
      * This method uses the
 <a href="{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#Provider">JCA Security Provider Framework</a>, described in the
      * "Java Cryptography Architecture API Specification &amp; Reference", for
-     * locating and selecting a <tt>SaslClient</tt> implementation.
+     * locating and selecting a {@code SaslClient} implementation.
      *
      * First, it
-     * obtains an ordered list of <tt>SaslClientFactory</tt> instances from
+     * obtains an ordered list of {@code SaslClientFactory} instances from
      * the registered security providers for the "SaslClientFactory" service
      * and the specified SASL mechanism(s). It then invokes
-     * <tt>createSaslClient()</tt> on each factory instance on the list
-     * until one produces a non-null <tt>SaslClient</tt> instance. It returns
-     * the non-null <tt>SaslClient</tt> instance, or null if the search fails
-     * to produce a non-null <tt>SaslClient</tt> instance.
+     * {@code createSaslClient()} on each factory instance on the list
+     * until one produces a non-null {@code SaslClient} instance. It returns
+     * the non-null {@code SaslClient} instance, or null if the search fails
+     * to produce a non-null {@code SaslClient} instance.
      *<p>
      * A security provider for SaslClientFactory registers with the
      * JCA Security Provider Framework keys of the form <br>
-     * <tt>SaslClientFactory.<em>mechanism_name</em></tt>
+     * {@code SaslClientFactory.}<em>{@code mechanism_name}</em>
      * <br>
      * and values that are class names of implementations of
-     * <tt>javax.security.sasl.SaslClientFactory</tt>.
+     * {@code javax.security.sasl.SaslClientFactory}.
      *
      * For example, a provider that contains a factory class,
-     * <tt>com.wiz.sasl.digest.ClientFactory</tt>, that supports the
+     * {@code com.wiz.sasl.digest.ClientFactory}, that supports the
      * "DIGEST-MD5" mechanism would register the following entry with the JCA:
-     * <tt>SaslClientFactory.DIGEST-MD5 com.wiz.sasl.digest.ClientFactory</tt>
+     * {@code SaslClientFactory.DIGEST-MD5 com.wiz.sasl.digest.ClientFactory}
      *<p>
      * See the
      * "Java Cryptography Architecture API Specification &amp; Reference"
@@ -325,9 +325,9 @@
      * @param props The possibly null set of properties used to
      * select the SASL mechanism and to configure the authentication
      * exchange of the selected mechanism.
-     * For example, if <tt>props</tt> contains the
-     * <code>Sasl.POLICY_NOPLAINTEXT</code> property with the value
-     * <tt>"true"</tt>, then the selected
+     * For example, if {@code props} contains the
+     * {@code Sasl.POLICY_NOPLAINTEXT} property with the value
+     * {@code "true"}, then the selected
      * SASL mechanism must not be susceptible to simple plain passive attacks.
      * In addition to the standard properties declared in this class,
      * other, possibly mechanism-specific, properties can be included.
@@ -338,16 +338,16 @@
      * mechanisms to get further information from the application/library
      * to complete the authentication. For example, a SASL mechanism might
      * require the authentication ID, password and realm from the caller.
-     * The authentication ID is requested by using a <tt>NameCallback</tt>.
-     * The password is requested by using a <tt>PasswordCallback</tt>.
-     * The realm is requested by using a <tt>RealmChoiceCallback</tt> if there is a list
-     * of realms to choose from, and by using a <tt>RealmCallback</tt> if
+     * The authentication ID is requested by using a {@code NameCallback}.
+     * The password is requested by using a {@code PasswordCallback}.
+     * The realm is requested by using a {@code RealmChoiceCallback} if there is a list
+     * of realms to choose from, and by using a {@code RealmCallback} if
      * the realm must be entered.
      *
-     *@return A possibly null <tt>SaslClient</tt> created using the parameters
-     * supplied. If null, cannot find a <tt>SaslClientFactory</tt>
+     *@return A possibly null {@code SaslClient} created using the parameters
+     * supplied. If null, cannot find a {@code SaslClientFactory}
      * that will produce one.
-     *@exception SaslException If cannot create a <tt>SaslClient</tt> because
+     *@exception SaslException If cannot create a {@code SaslClient} because
      * of an error.
      */
     public static SaslClient createSaslClient(
@@ -423,34 +423,34 @@
 
 
     /**
-     * Creates a <tt>SaslServer</tt> for the specified mechanism.
+     * Creates a {@code SaslServer} for the specified mechanism.
      *
      * This method uses the
 <a href="{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#Provider">JCA Security Provider Framework</a>,
      * described in the
      * "Java Cryptography Architecture API Specification &amp; Reference", for
-     * locating and selecting a <tt>SaslServer</tt> implementation.
+     * locating and selecting a {@code SaslServer} implementation.
      *
      * First, it
-     * obtains an ordered list of <tt>SaslServerFactory</tt> instances from
+     * obtains an ordered list of {@code SaslServerFactory} instances from
      * the registered security providers for the "SaslServerFactory" service
      * and the specified mechanism. It then invokes
-     * <tt>createSaslServer()</tt> on each factory instance on the list
-     * until one produces a non-null <tt>SaslServer</tt> instance. It returns
-     * the non-null <tt>SaslServer</tt> instance, or null if the search fails
-     * to produce a non-null <tt>SaslServer</tt> instance.
+     * {@code createSaslServer()} on each factory instance on the list
+     * until one produces a non-null {@code SaslServer} instance. It returns
+     * the non-null {@code SaslServer} instance, or null if the search fails
+     * to produce a non-null {@code SaslServer} instance.
      *<p>
      * A security provider for SaslServerFactory registers with the
      * JCA Security Provider Framework keys of the form <br>
-     * <tt>SaslServerFactory.<em>mechanism_name</em></tt>
+     * {@code SaslServerFactory.}<em>{@code mechanism_name}</em>
      * <br>
      * and values that are class names of implementations of
-     * <tt>javax.security.sasl.SaslServerFactory</tt>.
+     * {@code javax.security.sasl.SaslServerFactory}.
      *
      * For example, a provider that contains a factory class,
-     * <tt>com.wiz.sasl.digest.ServerFactory</tt>, that supports the
+     * {@code com.wiz.sasl.digest.ServerFactory}, that supports the
      * "DIGEST-MD5" mechanism would register the following entry with the JCA:
-     * <tt>SaslServerFactory.DIGEST-MD5  com.wiz.sasl.digest.ServerFactory</tt>
+     * {@code SaslServerFactory.DIGEST-MD5  com.wiz.sasl.digest.ServerFactory}
      *<p>
      * See the
      * "Java Cryptography Architecture API Specification &amp; Reference"
@@ -463,14 +463,14 @@
      * the authentication is being performed (e.g., "ldap").
      * @param serverName The fully qualified host name of the server, or null
      * if the server is not bound to any specific host name. If the mechanism
-     * does not allow an unbound server, a <code>SaslException</code> will
+     * does not allow an unbound server, a {@code SaslException} will
      * be thrown.
      * @param props The possibly null set of properties used to
      * select the SASL mechanism and to configure the authentication
      * exchange of the selected mechanism.
-     * For example, if <tt>props</tt> contains the
-     * <code>Sasl.POLICY_NOPLAINTEXT</code> property with the value
-     * <tt>"true"</tt>, then the selected
+     * For example, if {@code props} contains the
+     * {@code Sasl.POLICY_NOPLAINTEXT} property with the value
+     * {@code "true"}, then the selected
      * SASL mechanism must not be susceptible to simple plain passive attacks.
      * In addition to the standard properties declared in this class,
      * other, possibly mechanism-specific, properties can be included.
@@ -481,16 +481,16 @@
      * mechanisms to get further information from the application/library
      * to complete the authentication. For example, a SASL mechanism might
      * require the authentication ID, password and realm from the caller.
-     * The authentication ID is requested by using a <tt>NameCallback</tt>.
-     * The password is requested by using a <tt>PasswordCallback</tt>.
-     * The realm is requested by using a <tt>RealmChoiceCallback</tt> if there is a list
-     * of realms to choose from, and by using a <tt>RealmCallback</tt> if
+     * The authentication ID is requested by using a {@code NameCallback}.
+     * The password is requested by using a {@code PasswordCallback}.
+     * The realm is requested by using a {@code RealmChoiceCallback} if there is a list
+     * of realms to choose from, and by using a {@code RealmCallback} if
      * the realm must be entered.
      *
-     *@return A possibly null <tt>SaslServer</tt> created using the parameters
-     * supplied. If null, cannot find a <tt>SaslServerFactory</tt>
+     *@return A possibly null {@code SaslServer} created using the parameters
+     * supplied. If null, cannot find a {@code SaslServerFactory}
      * that will produce one.
-     *@exception SaslException If cannot create a <tt>SaslServer</tt> because
+     *@exception SaslException If cannot create a {@code SaslServer} because
      * of an error.
      **/
     public static SaslServer
@@ -533,11 +533,11 @@
     }
 
     /**
-     * Gets an enumeration of known factories for producing <tt>SaslClient</tt>.
+     * Gets an enumeration of known factories for producing {@code SaslClient}.
      * This method uses the same algorithm for locating factories as
-     * <tt>createSaslClient()</tt>.
+     * {@code createSaslClient()}.
      * @return A non-null enumeration of known factories for producing
-     * <tt>SaslClient</tt>.
+     * {@code SaslClient}.
      * @see #createSaslClient
      */
     public static Enumeration<SaslClientFactory> getSaslClientFactories() {
@@ -554,11 +554,11 @@
     }
 
     /**
-     * Gets an enumeration of known factories for producing <tt>SaslServer</tt>.
+     * Gets an enumeration of known factories for producing {@code SaslServer}.
      * This method uses the same algorithm for locating factories as
-     * <tt>createSaslServer()</tt>.
+     * {@code createSaslServer()}.
      * @return A non-null enumeration of known factories for producing
-     * <tt>SaslServer</tt>.
+     * {@code SaslServer}.
      * @see #createSaslServer
      */
     public static Enumeration<SaslServerFactory> getSaslServerFactories() {
--- a/src/share/classes/javax/security/sasl/SaslClient.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/sasl/SaslClient.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,14 +30,14 @@
  *<p>
  * A protocol library such as one for LDAP gets an instance of this
  * class in order to perform authentication defined by a specific SASL
- * mechanism. Invoking methods on the <tt>SaslClient</tt> instance
+ * mechanism. Invoking methods on the {@code SaslClient} instance
  * process challenges and create responses according to the SASL
- * mechanism implemented by the <tt>SaslClient</tt>.
+ * mechanism implemented by the {@code SaslClient}.
  * As the authentication proceeds, the instance
  * encapsulates the state of a SASL client's authentication exchange.
  *<p>
- * Here's an example of how an LDAP library might use a <tt>SaslClient</tt>.
- * It first gets an instance of a <tt>SaslClient</tt>:
+ * Here's an example of how an LDAP library might use a {@code SaslClient}.
+ * It first gets an instance of a {@code SaslClient}:
  *<blockquote><pre>{@code
  * SaslClient sc = Sasl.createSaslClient(mechanisms,
  *     authorizationId, protocol, serverName, props, callbackHandler);
@@ -77,16 +77,16 @@
  *}</pre></blockquote>
  *
  * If the mechanism has an initial response, the library invokes
- * <tt>evaluateChallenge()</tt> with an empty
+ * {@code evaluateChallenge()} with an empty
  * challenge and to get initial response.
  * Protocols such as IMAP4, which do not include an initial response with
  * their first authentication command to the server, initiates the
- * authentication without first calling <tt>hasInitialResponse()</tt>
- * or <tt>evaluateChallenge()</tt>.
+ * authentication without first calling {@code hasInitialResponse()}
+ * or {@code evaluateChallenge()}.
  * When the server responds to the command, it sends an initial challenge.
  * For a SASL mechanism in which the client sends data first, the server should
  * have issued a challenge with no data. This will then result in a call
- * (on the client) to <tt>evaluateChallenge()</tt> with an empty challenge.
+ * (on the client) to {@code evaluateChallenge()} with an empty challenge.
  *
  * @since 1.5
  *
@@ -107,7 +107,7 @@
 
     /**
      * Determines whether this mechanism has an optional initial response.
-     * If true, caller should call <tt>evaluateChallenge()</tt> with an
+     * If true, caller should call {@code evaluateChallenge()} with an
      * empty array to get the initial response.
      *
      * @return true if this mechanism has an initial response.
@@ -148,22 +148,22 @@
     /**
      * Unwraps a byte array received from the server.
      * This method can be called only after the authentication exchange has
-     * completed (i.e., when <tt>isComplete()</tt> returns true) and only if
+     * completed (i.e., when {@code isComplete()} returns true) and only if
      * the authentication exchange has negotiated integrity and/or privacy
      * as the quality of protection; otherwise, an
-     * <tt>IllegalStateException</tt> is thrown.
+     * {@code IllegalStateException} is thrown.
      *<p>
-     * <tt>incoming</tt> is the contents of the SASL buffer as defined in RFC 2222
+     * {@code incoming} is the contents of the SASL buffer as defined in RFC 2222
      * without the leading four octet field that represents the length.
-     * <tt>offset</tt> and <tt>len</tt> specify the portion of <tt>incoming</tt>
+     * {@code offset} and {@code len} specify the portion of {@code incoming}
      * to use.
      *
      * @param incoming A non-null byte array containing the encoded bytes
      *                from the server.
-     * @param offset The starting position at <tt>incoming</tt> of the bytes to use.
-     * @param len The number of bytes from <tt>incoming</tt> to use.
+     * @param offset The starting position at {@code incoming} of the bytes to use.
+     * @param len The number of bytes from {@code incoming} to use.
      * @return A non-null byte array containing the decoded bytes.
-     * @exception SaslException if <tt>incoming</tt> cannot be successfully
+     * @exception SaslException if {@code incoming} cannot be successfully
      * unwrapped.
      * @exception IllegalStateException if the authentication exchange has
      * not completed, or  if the negotiated quality of protection
@@ -175,22 +175,22 @@
     /**
      * Wraps a byte array to be sent to the server.
      * This method can be called only after the authentication exchange has
-     * completed (i.e., when <tt>isComplete()</tt> returns true) and only if
+     * completed (i.e., when {@code isComplete()} returns true) and only if
      * the authentication exchange has negotiated integrity and/or privacy
      * as the quality of protection; otherwise, an
-     * <tt>IllegalStateException</tt> is thrown.
+     * {@code IllegalStateException} is thrown.
      *<p>
      * The result of this method will make up the contents of the SASL buffer
      * as defined in RFC 2222 without the leading four octet field that
      * represents the length.
-     * <tt>offset</tt> and <tt>len</tt> specify the portion of <tt>outgoing</tt>
+     * {@code offset} and {@code len} specify the portion of {@code outgoing}
      * to use.
      *
      * @param outgoing A non-null byte array containing the bytes to encode.
-     * @param offset The starting position at <tt>outgoing</tt> of the bytes to use.
-     * @param len The number of bytes from <tt>outgoing</tt> to use.
+     * @param offset The starting position at {@code outgoing} of the bytes to use.
+     * @param len The number of bytes from {@code outgoing} to use.
      * @return A non-null byte array containing the encoded bytes.
-     * @exception SaslException if <tt>outgoing</tt> cannot be successfully
+     * @exception SaslException if {@code outgoing} cannot be successfully
      * wrapped.
      * @exception IllegalStateException if the authentication exchange has
      * not completed, or if the negotiated quality of protection
@@ -202,8 +202,8 @@
     /**
      * Retrieves the negotiated property.
      * This method can be called only after the authentication exchange has
-     * completed (i.e., when <tt>isComplete()</tt> returns true); otherwise, an
-     * <tt>IllegalStateException</tt> is thrown.
+     * completed (i.e., when {@code isComplete()} returns true); otherwise, an
+     * {@code IllegalStateException} is thrown.
      *
      * @param propName The non-null property name.
      * @return The value of the negotiated property. If null, the property was
--- a/src/share/classes/javax/security/sasl/SaslClientFactory.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/sasl/SaslClientFactory.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,16 +29,16 @@
 import javax.security.auth.callback.CallbackHandler;
 
 /**
- * An interface for creating instances of <tt>SaslClient</tt>.
+ * An interface for creating instances of {@code SaslClient}.
  * A class that implements this interface
  * must be thread-safe and handle multiple simultaneous
  * requests. It must also have a public constructor that accepts no
  * argument.
  *<p>
  * This interface is not normally accessed directly by a client, which will use the
- * <tt>Sasl</tt> static methods
+ * {@code Sasl} static methods
  * instead. However, a particular environment may provide and install a
- * new or different <tt>SaslClientFactory</tt>.
+ * new or different {@code SaslClientFactory}.
  *
  * @since 1.5
  *
@@ -66,7 +66,7 @@
      * of the server to authenticate to.
      * @param props The possibly null set of properties used to select the SASL
      * mechanism and to configure the authentication exchange of the selected
-     * mechanism. See the <tt>Sasl</tt> class for a list of standard properties.
+     * mechanism. See the {@code Sasl} class for a list of standard properties.
      * Other, possibly mechanism-specific, properties can be included.
      * Properties not relevant to the selected mechanism are ignored,
      * including any map entries with non-String keys.
@@ -75,16 +75,16 @@
      * mechanisms to get further information from the application/library
      * to complete the authentication. For example, a SASL mechanism might
      * require the authentication ID, password and realm from the caller.
-     * The authentication ID is requested by using a <tt>NameCallback</tt>.
-     * The password is requested by using a <tt>PasswordCallback</tt>.
-     * The realm is requested by using a <tt>RealmChoiceCallback</tt> if there is a list
-     * of realms to choose from, and by using a <tt>RealmCallback</tt> if
+     * The authentication ID is requested by using a {@code NameCallback}.
+     * The password is requested by using a {@code PasswordCallback}.
+     * The realm is requested by using a {@code RealmChoiceCallback} if there is a list
+     * of realms to choose from, and by using a {@code RealmCallback} if
      * the realm must be entered.
      *
-     *@return A possibly null <tt>SaslClient</tt> created using the parameters
-     * supplied. If null, this factory cannot produce a <tt>SaslClient</tt>
+     *@return A possibly null {@code SaslClient} created using the parameters
+     * supplied. If null, this factory cannot produce a {@code SaslClient}
      * using the parameters supplied.
-     *@exception SaslException If cannot create a <tt>SaslClient</tt> because
+     *@exception SaslException If cannot create a {@code SaslClient} because
      * of an error.
      */
     public abstract SaslClient createSaslClient(
@@ -99,12 +99,12 @@
      * Returns an array of names of mechanisms that match the specified
      * mechanism selection policies.
      * @param props The possibly null set of properties used to specify the
-     * security policy of the SASL mechanisms. For example, if <tt>props</tt>
-     * contains the <tt>Sasl.POLICY_NOPLAINTEXT</tt> property with the value
-     * <tt>"true"</tt>, then the factory must not return any SASL mechanisms
+     * security policy of the SASL mechanisms. For example, if {@code props}
+     * contains the {@code Sasl.POLICY_NOPLAINTEXT} property with the value
+     * {@code "true"}, then the factory must not return any SASL mechanisms
      * that are susceptible to simple plain passive attacks.
-     * See the <tt>Sasl</tt> class for a complete list of policy properties.
-     * Non-policy related properties, if present in <tt>props</tt>, are ignored,
+     * See the {@code Sasl} class for a complete list of policy properties.
+     * Non-policy related properties, if present in {@code props}, are ignored,
      * including any map entries with non-String keys.
      * @return A non-null array containing a IANA-registered SASL mechanism names.
      */
--- a/src/share/classes/javax/security/sasl/SaslException.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/sasl/SaslException.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -45,7 +45,7 @@
     private Throwable _exception;
 
     /**
-     * Constructs a new instance of <tt>SaslException</tt>.
+     * Constructs a new instance of {@code SaslException}.
      * The root exception and the detailed message are null.
      */
     public SaslException () {
@@ -53,7 +53,7 @@
     }
 
     /**
-     * Constructs a new instance of <tt>SaslException</tt> with a detailed message.
+     * Constructs a new instance of {@code SaslException} with a detailed message.
      * The root exception is null.
      * @param detail A possibly null string containing details of the exception.
      *
@@ -64,7 +64,7 @@
     }
 
     /**
-     * Constructs a new instance of <tt>SaslException</tt> with a detailed message
+     * Constructs a new instance of {@code SaslException} with a detailed message
      * and a root exception.
      * For example, a SaslException might result from a problem with
      * the callback handler, which might throw a NoSuchCallbackException if
--- a/src/share/classes/javax/security/sasl/SaslServer.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/sasl/SaslServer.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,14 +30,14 @@
  *<p>
  * A server such an LDAP server gets an instance of this
  * class in order to perform authentication defined by a specific SASL
- * mechanism. Invoking methods on the <tt>SaslServer</tt> instance
+ * mechanism. Invoking methods on the {@code SaslServer} instance
  * generates challenges according to the SASL
- * mechanism implemented by the <tt>SaslServer</tt>.
+ * mechanism implemented by the {@code SaslServer}.
  * As the authentication proceeds, the instance
  * encapsulates the state of a SASL server's authentication exchange.
  *<p>
- * Here's an example of how an LDAP server might use a <tt>SaslServer</tt>.
- * It first gets an instance of a <tt>SaslServer</tt> for the SASL mechanism
+ * Here's an example of how an LDAP server might use a {@code SaslServer}.
+ * It first gets an instance of a {@code SaslServer} for the SASL mechanism
  * requested by the client:
  *<blockquote><pre>
  * SaslServer ss = Sasl.createSaslServer(mechanism,
@@ -104,8 +104,8 @@
      * to the client. It is non-null if the authentication must be continued
      * by sending a challenge to the client, or if the authentication has
      * succeeded but challenge data needs to be processed by the client.
-     * <tt>isComplete()</tt> should be called
-     * after each call to <tt>evaluateResponse()</tt>,to determine if any further
+     * {@code isComplete()} should be called
+     * after each call to {@code evaluateResponse()},to determine if any further
      * response is needed from the client.
      *
      * @param response The non-null (but possibly empty) response sent
@@ -123,7 +123,7 @@
     /**
       * Determines whether the authentication exchange has completed.
       * This method is typically called after each invocation of
-      * <tt>evaluateResponse()</tt> to determine whether the
+      * {@code evaluateResponse()} to determine whether the
       * authentication has completed successfully or should be continued.
       * @return true if the authentication exchange has completed; false otherwise.
       */
@@ -141,22 +141,22 @@
     /**
      * Unwraps a byte array received from the client.
      * This method can be called only after the authentication exchange has
-     * completed (i.e., when <tt>isComplete()</tt> returns true) and only if
+     * completed (i.e., when {@code isComplete()} returns true) and only if
      * the authentication exchange has negotiated integrity and/or privacy
      * as the quality of protection; otherwise,
-     * an <tt>IllegalStateException</tt> is thrown.
+     * an {@code IllegalStateException} is thrown.
      *<p>
-     * <tt>incoming</tt> is the contents of the SASL buffer as defined in RFC 2222
+     * {@code incoming} is the contents of the SASL buffer as defined in RFC 2222
      * without the leading four octet field that represents the length.
-     * <tt>offset</tt> and <tt>len</tt> specify the portion of <tt>incoming</tt>
+     * {@code offset} and {@code len} specify the portion of {@code incoming}
      * to use.
      *
      * @param incoming A non-null byte array containing the encoded bytes
      *                from the client.
-     * @param offset The starting position at <tt>incoming</tt> of the bytes to use.
-     * @param len The number of bytes from <tt>incoming</tt> to use.
+     * @param offset The starting position at {@code incoming} of the bytes to use.
+     * @param len The number of bytes from {@code incoming} to use.
      * @return A non-null byte array containing the decoded bytes.
-     * @exception SaslException if <tt>incoming</tt> cannot be successfully
+     * @exception SaslException if {@code incoming} cannot be successfully
      * unwrapped.
      * @exception IllegalStateException if the authentication exchange has
      * not completed, or if the negotiated quality of protection
@@ -168,21 +168,21 @@
     /**
      * Wraps a byte array to be sent to the client.
      * This method can be called only after the authentication exchange has
-     * completed (i.e., when <tt>isComplete()</tt> returns true) and only if
+     * completed (i.e., when {@code isComplete()} returns true) and only if
      * the authentication exchange has negotiated integrity and/or privacy
-     * as the quality of protection; otherwise, a <tt>SaslException</tt> is thrown.
+     * as the quality of protection; otherwise, a {@code SaslException} is thrown.
      *<p>
      * The result of this method
      * will make up the contents of the SASL buffer as defined in RFC 2222
      * without the leading four octet field that represents the length.
-     * <tt>offset</tt> and <tt>len</tt> specify the portion of <tt>outgoing</tt>
+     * {@code offset} and {@code len} specify the portion of {@code outgoing}
      * to use.
      *
      * @param outgoing A non-null byte array containing the bytes to encode.
-     * @param offset The starting position at <tt>outgoing</tt> of the bytes to use.
-     * @param len The number of bytes from <tt>outgoing</tt> to use.
+     * @param offset The starting position at {@code outgoing} of the bytes to use.
+     * @param len The number of bytes from {@code outgoing} to use.
      * @return A non-null byte array containing the encoded bytes.
-     * @exception SaslException if <tt>outgoing</tt> cannot be successfully
+     * @exception SaslException if {@code outgoing} cannot be successfully
      * wrapped.
      * @exception IllegalStateException if the authentication exchange has
      * not completed, or if the negotiated quality of protection has
@@ -194,8 +194,8 @@
     /**
      * Retrieves the negotiated property.
      * This method can be called only after the authentication exchange has
-     * completed (i.e., when <tt>isComplete()</tt> returns true); otherwise, an
-     * <tt>IllegalStateException</tt> is thrown.
+     * completed (i.e., when {@code isComplete()} returns true); otherwise, an
+     * {@code IllegalStateException} is thrown.
      *
      * @param propName the property
      * @return The value of the negotiated property. If null, the property was
--- a/src/share/classes/javax/security/sasl/SaslServerFactory.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/security/sasl/SaslServerFactory.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,16 +29,16 @@
 import javax.security.auth.callback.CallbackHandler;
 
 /**
- * An interface for creating instances of <tt>SaslServer</tt>.
+ * An interface for creating instances of {@code SaslServer}.
  * A class that implements this interface
  * must be thread-safe and handle multiple simultaneous
  * requests. It must also have a public constructor that accepts no
  * argument.
  *<p>
  * This interface is not normally accessed directly by a server, which will use the
- * <tt>Sasl</tt> static methods
+ * {@code Sasl} static methods
  * instead. However, a particular environment may provide and install a
- * new or different <tt>SaslServerFactory</tt>.
+ * new or different {@code SaslServerFactory}.
  *
  * @since 1.5
  *
@@ -50,10 +50,10 @@
  */
 public abstract interface SaslServerFactory {
     /**
-     * Creates a <tt>SaslServer</tt> using the parameters supplied.
+     * Creates a {@code SaslServer} using the parameters supplied.
      * It returns null
-     * if no <tt>SaslServer</tt> can be created using the parameters supplied.
-     * Throws <tt>SaslException</tt> if it cannot create a <tt>SaslServer</tt>
+     * if no {@code SaslServer} can be created using the parameters supplied.
+     * Throws {@code SaslException} if it cannot create a {@code SaslServer}
      * because of an error.
      *
      * @param mechanism The non-null
@@ -63,10 +63,10 @@
      * @param serverName The fully qualified host name of the server to
      * authenticate to, or null if the server is not bound to any specific host
      * name. If the mechanism does not allow an unbound server, a
-     * <code>SaslException</code> will be thrown.
+     * {@code SaslException} will be thrown.
      * @param props The possibly null set of properties used to select the SASL
      * mechanism and to configure the authentication exchange of the selected
-     * mechanism. See the <tt>Sasl</tt> class for a list of standard properties.
+     * mechanism. See the {@code Sasl} class for a list of standard properties.
      * Other, possibly mechanism-specific, properties can be included.
      * Properties not relevant to the selected mechanism are ignored,
      * including any map entries with non-String keys.
@@ -75,16 +75,16 @@
      * mechanisms to get further information from the application/library
      * to complete the authentication. For example, a SASL mechanism might
      * require the authentication ID, password and realm from the caller.
-     * The authentication ID is requested by using a <tt>NameCallback</tt>.
-     * The password is requested by using a <tt>PasswordCallback</tt>.
-     * The realm is requested by using a <tt>RealmChoiceCallback</tt> if there is a list
-     * of realms to choose from, and by using a <tt>RealmCallback</tt> if
+     * The authentication ID is requested by using a {@code NameCallback}.
+     * The password is requested by using a {@code PasswordCallback}.
+     * The realm is requested by using a {@code RealmChoiceCallback} if there is a list
+     * of realms to choose from, and by using a {@code RealmCallback} if
      * the realm must be entered.
      *
-     *@return A possibly null <tt>SaslServer</tt> created using the parameters
-     * supplied. If null, this factory cannot produce a <tt>SaslServer</tt>
+     *@return A possibly null {@code SaslServer} created using the parameters
+     * supplied. If null, this factory cannot produce a {@code SaslServer}
      * using the parameters supplied.
-     *@exception SaslException If cannot create a <tt>SaslServer</tt> because
+     *@exception SaslException If cannot create a {@code SaslServer} because
      * of an error.
      */
     public abstract SaslServer createSaslServer(
@@ -98,12 +98,12 @@
      * Returns an array of names of mechanisms that match the specified
      * mechanism selection policies.
      * @param props The possibly null set of properties used to specify the
-     * security policy of the SASL mechanisms. For example, if <tt>props</tt>
-     * contains the <tt>Sasl.POLICY_NOPLAINTEXT</tt> property with the value
-     * <tt>"true"</tt>, then the factory must not return any SASL mechanisms
+     * security policy of the SASL mechanisms. For example, if {@code props}
+     * contains the {@code Sasl.POLICY_NOPLAINTEXT} property with the value
+     * {@code "true"}, then the factory must not return any SASL mechanisms
      * that are susceptible to simple plain passive attacks.
-     * See the <tt>Sasl</tt> class for a complete list of policy properties.
-     * Non-policy related properties, if present in <tt>props</tt>, are ignored,
+     * See the {@code Sasl} class for a complete list of policy properties.
+     * Non-policy related properties, if present in {@code props}, are ignored,
      * including any map entries with non-String keys.
      * @return A non-null array containing a IANA-registered SASL mechanism names.
      */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/javax/security/sasl/package-info.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * Contains class and interfaces for supporting SASL.
+ *
+ * This package defines classes and interfaces for SASL mechanisms.
+ * It is used by developers to add authentication support for
+ * connection-based protocols that use SASL.
+ *
+ * <h3>SASL Overview</h3>
+ *
+ * Simple Authentication and Security Layer (SASL) specifies a
+ * challenge-response protocol in which data is exchanged between the
+ * client and the server for the purposes of
+ * authentication and (optional) establishment of a security layer on
+ * which to carry on subsequent communications.  It is used with
+ * connection-based protocols such as LDAPv3 or IMAPv4.  SASL is
+ * described in
+ * <A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>.
+ *
+ *
+ * There are various <em>mechanisms</em> defined for SASL.
+ * Each mechanism defines the data that must be exchanged between the
+ * client and server in order for the authentication to succeed.
+ * This data exchange required for a particular mechanism is referred to
+ * to as its <em>protocol profile</em>.
+ * The following are some examples of mechanisms that have been defined by
+ * the Internet standards community.
+ * <ul>
+ * <li>DIGEST-MD5 (<A HREF="http://www.ietf.org/rfc/rfc2831.txt">RFC 2831</a>).
+ * This mechanism defines how HTTP Digest Authentication can be used as a SASL
+ * mechanism.
+ * <li>Anonymous (<A HREF="http://www.ietf.org/rfc/rfc2245.txt">RFC 2245</a>).
+ * This mechanism is anonymous authentication in which no credentials are
+ * necessary.
+ * <li>External (<A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>).
+ * This mechanism obtains authentication information
+ * from an external source (such as TLS or IPsec).
+ * <li>S/Key (<A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>).
+ * This mechanism uses the MD4 digest algorithm to exchange data based on
+ * a shared secret.
+ * <li>GSSAPI (<A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>).
+ * This mechanism uses the
+ * <A HREF="http://www.ietf.org/rfc/rfc2078.txt">GSSAPI</A>
+ * for obtaining authentication information.
+ * </ul>
+ *
+ * Some of these mechanisms provide both authentication and establishment
+ * of a security layer, others only authentication.  Anonymous and
+ * S/Key do not provide for any security layers.  GSSAPI and DIGEST-MD5
+ * allow negotiation of the security layer.  For External, the
+ * security layer is determined by the external protocol.
+ *
+ * <h3>Usage</h3>
+ *
+ * Users of this API are typically developers who produce
+ * client library implementations for connection-based protocols,
+ * such as LDAPv3 and IMAPv4,
+ * and developers who write servers (such as LDAP servers and IMAP servers).
+ * Developers who write client libraries use the
+ * {@code SaslClient} and {@code SaslClientFactory} interfaces.
+ * Developers who write servers use the
+ * {@code SaslServer} and {@code SaslServerFactory} interfaces.
+ *
+ * Among these two groups of users, each can be further divided into two groups:
+ * those who <em>produce</em> the SASL mechanisms and those
+ * who <em>use</em> the SASL mechanisms.
+ * The producers of SASL mechanisms need to provide implementations
+ * for these interfaces, while users of the SASL mechanisms use
+ * the APIs in this package to access those implementations.
+ *
+ * <h2>Related Documentation</h2>
+ *
+ * Please refer to the
+ * <a href="../../../../technotes/guides/security/sasl/sasl-refguide.html">Java
+ * SASL Programming Guide</a> for information on how to use this API.
+ *
+ * @since 1.5
+ */
+package javax.security.sasl;
--- a/src/share/classes/javax/security/sasl/package.html	Thu Jul 18 03:38:49 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,114 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
-<html>
-<head>
-<!--
-Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
-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.
--->
-</head>
-<body bgcolor="white">
-
-Contains class and interfaces for supporting SASL.
-
-This package defines classes and interfaces for SASL mechanisms.
-It is used by developers to add authentication support for 
-connection-based protocols that use SASL. 
-
-<h4>SASL Overview</h4>
-<p>
-
-Simple Authentication and Security Layer (SASL) specifies a
-challenge-response protocol in which data is exchanged between the
-client and the server for the purposes of
-authentication and (optional) establishment of a security layer on
-which to carry on subsequent communications.  It is used with
-connection-based protocols such as LDAPv3 or IMAPv4.  SASL is
-described in
-<A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>.
-
-<p>
-There are various <em>mechanisms</em> defined for SASL.
-Each mechanism defines the data that must be exchanged between the
-client and server in order for the authentication to succeed.
-This data exchange required for a particular mechanism is referred to
-to as its <em>protocol profile</em>.
-The following are some examples of mechanims that have been defined by 
-the Internet standards community.
-<ul>
-<li>DIGEST-MD5 (<A HREF="http://www.ietf.org/rfc/rfc2831.txt">RFC 2831</a>).
-This mechanism defines how HTTP Digest Authentication can be used as a SASL
-mechanism.
-<li>Anonymous (<A HREF="http://www.ietf.org/rfc/rfc2245.txt">RFC 2245</a>).
-This mechamism is anonymous authentication in which no credentials are
-necessary.
-<li>External (<A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>).
-This mechanism obtains authentication information 
-from an external source (such as TLS or IPsec).
-<li>S/Key (<A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>).
-This mechanism uses the MD4 digest algorithm to exchange data based on
-a shared secret.
-<li>GSSAPI (<A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>).
-This mechanism uses the 
-<A HREF="http://www.ietf.org/rfc/rfc2078.txt">GSSAPI</A>
-for obtaining authentication information.
-</ul>
-
-<p>
-Some of these mechanisms provide both authentication and establishment
-of a security layer, others only authentication.  Anonymous and
-S/Key do not provide for any security layers.  GSSAPI and DIGEST-MD5
-allow negotiation of the security layer.  For External, the
-security layer is determined by the external protocol.
-
-<h4>Usage</h4>
-
-<p>
-Users of this API are typically developers who produce
-client library implementations for connection-based protocols,
-such as LDAPv3 and IMAPv4,
-and developers who write servers (such as LDAP servers and IMAP servers).
-Developers who write client libraries use the
-<tt>SaslClient</tt> and <tt>SaslClientFactory</tt> interfaces.
-Developers who write servers use the
-<tt>SaslServer</tt> and <tt>SaslServerFactory</tt> interfaces.
-<p>
-Among these two groups of users, each can be further divided into two groups:
-those who <em>produce</em> the SASL mechanisms and those 
-who <em>use</em> the SASL mechanisms.
-The producers of SASL mechanisms need to provide implementations
-for these interfaces, while users of the SASL mechanisms use 
-the APIs in this package to access those implementations.
-
-<h2>Related Documentation</h2>
-
-Please refer to the 
-<a href="../../../../technotes/guides/security/sasl/sasl-refguide.html">Java 
-SASL Programming Guide</a> for information on how to use this API.
-
-
-@since 1.5
-
-
-</body>
-</html>
-
--- a/src/share/classes/javax/swing/text/html/parser/ContentModel.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/swing/text/html/parser/ContentModel.java	Mon Jul 22 17:37:15 2013 -0700
@@ -170,8 +170,8 @@
           case '&': {
             Element e = (Element) token;
             if (valSet == null) {
-                valSet = new boolean[Element.maxIndex + 1];
-                val = new boolean[Element.maxIndex + 1];
+                valSet = new boolean[Element.getMaxIndex() + 1];
+                val = new boolean[valSet.length];
                 // All Element instances are created before this ever executes
             }
             if (valSet[e.index]) {
--- a/src/share/classes/javax/swing/text/html/parser/Element.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/javax/swing/text/html/parser/Element.java	Mon Jul 22 17:37:15 2013 -0700
@@ -28,6 +28,7 @@
 import java.util.Hashtable;
 import java.util.BitSet;
 import java.io.*;
+import sun.awt.AppContext;
 
 /**
  * An element as described in a DTD using the ELEMENT construct.
@@ -51,8 +52,6 @@
     public ContentModel content;
     public AttributeList atts;
 
-    static int maxIndex = 0;
-
     /**
      * A field to store user data. Mostly used to store
      * style sheets.
@@ -68,7 +67,18 @@
     Element(String name, int index) {
         this.name = name;
         this.index = index;
-        maxIndex = Math.max(maxIndex, index);
+        if (index > getMaxIndex()) {
+            AppContext.getAppContext().put(MAX_INDEX_KEY, index);
+        }
+    }
+
+    private static final Object MAX_INDEX_KEY = new Object();
+
+    static int getMaxIndex() {
+        Integer value = (Integer) AppContext.getAppContext().get(MAX_INDEX_KEY);
+        return (value != null)
+                ? value.intValue()
+                : 0;
     }
 
     /**
--- a/src/share/classes/org/jcp/xml/dsig/internal/DigesterOutputStream.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/DigesterOutputStream.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,36 +2,37 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 1999-2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DigesterOutputStream.java,v 1.2 2008/07/24 15:20:31 mullan Exp $
+ * $Id: DigesterOutputStream.java,v 1.5 2005/12/20 20:02:39 mullan Exp $
  */
 package org.jcp.xml.dsig.internal;
 
 import java.io.ByteArrayInputStream;
+import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.security.MessageDigest;
-import java.util.logging.Logger;
-import java.util.logging.Level;
 
 import com.sun.org.apache.xml.internal.security.utils.UnsyncByteArrayOutputStream;
 
@@ -45,10 +46,12 @@
  * @author Sean Mullan
  */
 public class DigesterOutputStream extends OutputStream {
-    private boolean buffer = false;
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal");
+
+    private final boolean buffer;
     private UnsyncByteArrayOutputStream bos;
     private final MessageDigest md;
-    private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal");
 
     /**
      * Creates a DigesterOutputStream.
@@ -73,12 +76,6 @@
         }
     }
 
-    /** @inheritDoc */
-    public void write(byte[] input) {
-        write(input, 0, input.length);
-    }
-
-    /** @inheritDoc */
     public void write(int input) {
         if (buffer) {
             bos.write(input);
@@ -86,18 +83,18 @@
         md.update((byte)input);
     }
 
-    /** @inheritDoc */
+    @Override
     public void write(byte[] input, int offset, int len) {
         if (buffer) {
             bos.write(input, offset, len);
         }
-        if (log.isLoggable(Level.FINER)) {
-            log.log(Level.FINER, "Pre-digested input:");
-            StringBuffer sb = new StringBuffer(len);
-            for (int i=offset; i<(offset+len); i++) {
-                sb.append((char) input[i]);
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Pre-digested input:");
+            StringBuilder sb = new StringBuilder(len);
+            for (int i = offset; i < (offset + len); i++) {
+                sb.append((char)input[i]);
             }
-            log.log(Level.FINER, sb.toString());
+            log.log(java.util.logging.Level.FINE, sb.toString());
         }
         md.update(input, offset, len);
     }
@@ -120,4 +117,11 @@
             return null;
         }
     }
+
+    @Override
+    public void close() throws IOException {
+        if (buffer) {
+            bos.close();
+        }
+    }
 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/MacOutputStream.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/MacOutputStream.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 1999-2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.jcp.xml.dsig.internal;
 
@@ -38,19 +40,13 @@
         this.mac = mac;
     }
 
-    /** @inheritDoc */
-    public void write(byte[] arg0)  {
-        super.write(arg0, 0, arg0.length);
-        mac.update(arg0);
-    }
-
-    /** @inheritDoc */
+    @Override
     public void write(int arg0) {
         super.write(arg0);
         mac.update((byte) arg0);
     }
 
-    /** @inheritDoc */
+    @Override
     public void write(byte[] arg0, int arg1, int arg2) {
         super.write(arg0, arg1, arg2);
         mac.update(arg0, arg1, arg2);
--- a/src/share/classes/org/jcp/xml/dsig/internal/SignerOutputStream.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/SignerOutputStream.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 1999-2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: SignerOutputStream.java,v 1.2 2008/07/24 15:20:31 mullan Exp $
+ * $Id: SignerOutputStream.java,v 1.2 2005/09/15 14:29:02 mullan Exp $
  */
 package org.jcp.xml.dsig.internal;
 
@@ -32,8 +34,8 @@
 
 /**
  * Derived from Apache sources and changed to use java.security.Signature
- * objects as input instead of com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm
- * objects.
+ * objects as input instead of
+ * com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm objects.
  *
  * @author raul
  * @author Sean Mullan
@@ -42,36 +44,26 @@
     private final Signature sig;
 
     public SignerOutputStream(Signature sig) {
-        this.sig=sig;
+        this.sig = sig;
     }
 
-    /** @inheritDoc */
-    public void write(byte[] arg0)  {
-        super.write(arg0, 0, arg0.length);
-        try {
-            sig.update(arg0);
-        } catch (SignatureException e) {
-            throw new RuntimeException(""+e);
-        }
-    }
-
-    /** @inheritDoc */
+    @Override
     public void write(int arg0) {
         super.write(arg0);
         try {
             sig.update((byte)arg0);
         } catch (SignatureException e) {
-            throw new RuntimeException(""+e);
+            throw new RuntimeException(e);
         }
     }
 
-    /** @inheritDoc */
+    @Override
     public void write(byte[] arg0, int arg1, int arg2) {
         super.write(arg0, arg1, arg2);
         try {
-            sig.update(arg0,arg1,arg2);
+            sig.update(arg0, arg1, arg2);
         } catch (SignatureException e) {
-            throw new RuntimeException(""+e);
+            throw new RuntimeException(e);
         }
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/AbstractDOMSignatureMethod.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,218 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.jcp.xml.dsig.internal.dom;
+
+import java.security.Key;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.SignatureException;
+import java.security.spec.AlgorithmParameterSpec;
+import javax.xml.crypto.MarshalException;
+import javax.xml.crypto.dom.DOMCryptoContext;
+import javax.xml.crypto.dsig.SignatureMethod;
+import javax.xml.crypto.dsig.SignedInfo;
+import javax.xml.crypto.dsig.XMLSignature;
+import javax.xml.crypto.dsig.XMLSignatureException;
+import javax.xml.crypto.dsig.XMLSignContext;
+import javax.xml.crypto.dsig.XMLValidateContext;
+import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+/**
+ * An abstract class representing a SignatureMethod. Subclasses implement
+ * a specific XML DSig signature algorithm.
+ */
+abstract class AbstractDOMSignatureMethod extends DOMStructure
+    implements SignatureMethod {
+
+    // denotes the type of signature algorithm
+    enum Type { DSA, RSA, ECDSA, HMAC }
+
+    /**
+     * Verifies the passed-in signature with the specified key, using the
+     * underlying Signature or Mac algorithm.
+     *
+     * @param key the verification key
+     * @param si the SignedInfo
+     * @param sig the signature bytes to be verified
+     * @param context the XMLValidateContext
+     * @return <code>true</code> if the signature verified successfully,
+     *    <code>false</code> if not
+     * @throws NullPointerException if <code>key</code>, <code>si</code> or
+     *    <code>sig</code> are <code>null</code>
+     * @throws InvalidKeyException if the key is improperly encoded, of
+     *    the wrong type, or parameters are missing, etc
+     * @throws SignatureException if an unexpected error occurs, such
+     *    as the passed in signature is improperly encoded
+     * @throws XMLSignatureException if an unexpected error occurs
+     */
+    abstract boolean verify(Key key, SignedInfo si, byte[] sig,
+                            XMLValidateContext context)
+        throws InvalidKeyException, SignatureException, XMLSignatureException;
+
+    /**
+     * Signs the bytes with the specified key, using the underlying
+     * Signature or Mac algorithm.
+     *
+     * @param key the signing key
+     * @param si the SignedInfo
+     * @param context the XMLSignContext
+     * @return the signature
+     * @throws NullPointerException if <code>key</code> or
+     *    <code>si</code> are <code>null</code>
+     * @throws InvalidKeyException if the key is improperly encoded, of
+     *    the wrong type, or parameters are missing, etc
+     * @throws XMLSignatureException if an unexpected error occurs
+     */
+    abstract byte[] sign(Key key, SignedInfo si, XMLSignContext context)
+        throws InvalidKeyException, XMLSignatureException;
+
+    /**
+     * Returns the java.security.Signature or javax.crypto.Mac standard
+     * algorithm name.
+     */
+    abstract String getJCAAlgorithm();
+
+    /**
+     * Returns the type of signature algorithm.
+     */
+    abstract Type getAlgorithmType();
+
+    /**
+     * This method invokes the {@link #marshalParams marshalParams}
+     * method to marshal any algorithm-specific parameters.
+     */
+    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
+        throws MarshalException
+    {
+        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
+
+        Element smElem = DOMUtils.createElement(ownerDoc, "SignatureMethod",
+                                                XMLSignature.XMLNS, dsPrefix);
+        DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm());
+
+        if (getParameterSpec() != null) {
+            marshalParams(smElem, dsPrefix);
+        }
+
+        parent.appendChild(smElem);
+    }
+
+    /**
+     * Marshals the algorithm-specific parameters to an Element and
+     * appends it to the specified parent element. By default, this method
+     * throws an exception since most SignatureMethod algorithms do not have
+     * parameters. Subclasses should override it if they have parameters.
+     *
+     * @param parent the parent element to append the parameters to
+     * @param paramsPrefix the algorithm parameters prefix to use
+     * @throws MarshalException if the parameters cannot be marshalled
+     */
+    void marshalParams(Element parent, String paramsPrefix)
+        throws MarshalException
+    {
+        throw new MarshalException("no parameters should " +
+                                   "be specified for the " + getAlgorithm() +
+                                   " SignatureMethod algorithm");
+    }
+
+    /**
+     * Unmarshals <code>SignatureMethodParameterSpec</code> from the specified
+     * <code>Element</code>. By default, this method throws an exception since
+     * most SignatureMethod algorithms do not have parameters. Subclasses should
+     * override it if they have parameters.
+     *
+     * @param paramsElem the <code>Element</code> holding the input params
+     * @return the algorithm-specific <code>SignatureMethodParameterSpec</code>
+     * @throws MarshalException if the parameters cannot be unmarshalled
+     */
+    SignatureMethodParameterSpec unmarshalParams(Element paramsElem)
+        throws MarshalException
+    {
+        throw new MarshalException("no parameters should " +
+                                   "be specified for the " + getAlgorithm() +
+                                   " SignatureMethod algorithm");
+    }
+
+    /**
+     * Checks if the specified parameters are valid for this algorithm. By
+     * default, this method throws an exception if parameters are specified
+     * since most SignatureMethod algorithms do not have parameters. Subclasses
+     * should override it if they have parameters.
+     *
+     * @param params the algorithm-specific params (may be <code>null</code>)
+     * @throws InvalidAlgorithmParameterException if the parameters are not
+     *    appropriate for this signature method
+     */
+    void checkParams(SignatureMethodParameterSpec params)
+        throws InvalidAlgorithmParameterException
+    {
+        if (params != null) {
+            throw new InvalidAlgorithmParameterException("no parameters " +
+                "should be specified for the " + getAlgorithm() +
+                " SignatureMethod algorithm");
+        }
+    }
+
+    @Override
+    public boolean equals(Object o)
+    {
+        if (this == o) {
+            return true;
+        }
+
+        if (!(o instanceof SignatureMethod)) {
+            return false;
+        }
+        SignatureMethod osm = (SignatureMethod)o;
+
+        return (getAlgorithm().equals(osm.getAlgorithm()) &&
+            paramsEqual(osm.getParameterSpec()));
+    }
+
+    @Override
+    public int hashCode() {
+        int result = 17;
+        result = 31 * result + getAlgorithm().hashCode();
+        AlgorithmParameterSpec spec = getParameterSpec();
+        if (spec != null) {
+            result = 31 * result + spec.hashCode();
+        }
+
+        return result;
+    }
+
+    /**
+     * Returns true if parameters are equal; false otherwise.
+     *
+     * Subclasses should override this method to compare algorithm-specific
+     * parameters.
+     */
+    boolean paramsEqual(AlgorithmParameterSpec spec)
+    {
+        return (getParameterSpec() == spec);
+    }
+}
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,44 +2,42 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: ApacheCanonicalizer.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: ApacheCanonicalizer.java 1333869 2012-05-04 10:42:44Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
-import java.io.IOException;
 import java.io.OutputStream;
 import java.security.spec.AlgorithmParameterSpec;
 import java.security.InvalidAlgorithmParameterException;
 import java.util.Set;
-import java.util.logging.Logger;
-import java.util.logging.Level;
 import javax.xml.crypto.*;
 import javax.xml.crypto.dom.DOMCryptoContext;
 import javax.xml.crypto.dsig.TransformException;
 import javax.xml.crypto.dsig.TransformService;
-import javax.xml.crypto.dsig.XMLSignatureException;
 import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
 
 import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
@@ -48,7 +46,7 @@
 import com.sun.org.apache.xml.internal.security.transforms.Transform;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
+import org.w3c.dom.Node;
 
 public abstract class ApacheCanonicalizer extends TransformService {
 
@@ -56,7 +54,8 @@
         com.sun.org.apache.xml.internal.security.Init.init();
     }
 
-    private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom");
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
     protected Canonicalizer apacheCanonicalizer;
     private Transform apacheTransform;
     protected String inclusiveNamespaces;
@@ -64,51 +63,60 @@
     protected Document ownerDoc;
     protected Element transformElem;
 
-    public final AlgorithmParameterSpec getParameterSpec() {
+    public final AlgorithmParameterSpec getParameterSpec()
+    {
         return params;
     }
 
     public void init(XMLStructure parent, XMLCryptoContext context)
-        throws InvalidAlgorithmParameterException {
+        throws InvalidAlgorithmParameterException
+    {
         if (context != null && !(context instanceof DOMCryptoContext)) {
             throw new ClassCastException
                 ("context must be of type DOMCryptoContext");
         }
+        if (parent == null || !(parent instanceof javax.xml.crypto.dom.DOMStructure)) {
+            throw new ClassCastException("parent must be of type DOMStructure");
+        }
         transformElem = (Element)
-            ((javax.xml.crypto.dom.DOMStructure) parent).getNode();
+            ((javax.xml.crypto.dom.DOMStructure)parent).getNode();
         ownerDoc = DOMUtils.getOwnerDocument(transformElem);
     }
 
     public void marshalParams(XMLStructure parent, XMLCryptoContext context)
-        throws MarshalException {
+        throws MarshalException
+    {
         if (context != null && !(context instanceof DOMCryptoContext)) {
             throw new ClassCastException
                 ("context must be of type DOMCryptoContext");
         }
+        if (parent == null || !(parent instanceof javax.xml.crypto.dom.DOMStructure)) {
+            throw new ClassCastException("parent must be of type DOMStructure");
+        }
         transformElem = (Element)
-            ((javax.xml.crypto.dom.DOMStructure) parent).getNode();
+            ((javax.xml.crypto.dom.DOMStructure)parent).getNode();
         ownerDoc = DOMUtils.getOwnerDocument(transformElem);
     }
 
     public Data canonicalize(Data data, XMLCryptoContext xc)
-        throws TransformException {
+        throws TransformException
+    {
         return canonicalize(data, xc, null);
     }
 
     public Data canonicalize(Data data, XMLCryptoContext xc, OutputStream os)
-        throws TransformException {
-
+        throws TransformException
+    {
         if (apacheCanonicalizer == null) {
             try {
                 apacheCanonicalizer = Canonicalizer.getInstance(getAlgorithm());
-                if (log.isLoggable(Level.FINE)) {
-                    log.log(Level.FINE, "Created canonicalizer for algorithm: "
-                        + getAlgorithm());
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "Created canonicalizer for algorithm: " + getAlgorithm());
                 }
             } catch (InvalidCanonicalizerException ice) {
                 throw new TransformException
                     ("Couldn't find Canonicalizer for: " + getAlgorithm() +
-                        ": " + ice.getMessage(), ice);
+                     ": " + ice.getMessage(), ice);
             }
         }
 
@@ -119,10 +127,10 @@
         }
 
         try {
-            Set nodeSet = null;
+            Set<Node> nodeSet = null;
             if (data instanceof ApacheData) {
                 XMLSignatureInput in =
-                    ((ApacheData) data).getXMLSignatureInput();
+                    ((ApacheData)data).getXMLSignatureInput();
                 if (in.isElement()) {
                     if (inclusiveNamespaces != null) {
                         return new OctetStreamData(new ByteArrayInputStream
@@ -141,7 +149,7 @@
                             Utils.readBytesFromStream(in.getOctetStream()))));
                 }
             } else if (data instanceof DOMSubTreeData) {
-                DOMSubTreeData subTree = (DOMSubTreeData) data;
+                DOMSubTreeData subTree = (DOMSubTreeData)data;
                 if (inclusiveNamespaces != null) {
                     return new OctetStreamData(new ByteArrayInputStream
                         (apacheCanonicalizer.canonicalizeSubtree
@@ -152,12 +160,13 @@
                          (subTree.getRoot())));
                 }
             } else if (data instanceof NodeSetData) {
-                NodeSetData nsd = (NodeSetData) data;
+                NodeSetData nsd = (NodeSetData)data;
                 // convert Iterator to Set
-                nodeSet = Utils.toNodeSet(nsd.iterator());
-                if (log.isLoggable(Level.FINE)) {
-                    log.log(Level.FINE, "Canonicalizing " + nodeSet.size()
-                        + " nodes");
+                @SuppressWarnings("unchecked")
+                Set<Node> ns = Utils.toNodeSet(nsd.iterator());
+                nodeSet = ns;
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "Canonicalizing " + nodeSet.size() + " nodes");
                 }
             } else {
                 return new OctetStreamData(new ByteArrayInputStream(
@@ -179,7 +188,8 @@
     }
 
     public Data transform(Data data, XMLCryptoContext xc, OutputStream os)
-        throws TransformException {
+        throws TransformException
+    {
         if (data == null) {
             throw new NullPointerException("data must not be null");
         }
@@ -193,12 +203,11 @@
 
         if (apacheTransform == null) {
             try {
-                apacheTransform = new Transform
-                    (ownerDoc, getAlgorithm(), transformElem.getChildNodes());
+                apacheTransform =
+                    new Transform(ownerDoc, getAlgorithm(), transformElem.getChildNodes());
                 apacheTransform.setElement(transformElem, xc.getBaseURI());
-                if (log.isLoggable(Level.FINE)) {
-                    log.log(Level.FINE, "Created transform for algorithm: "
-                        + getAlgorithm());
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "Created transform for algorithm: " + getAlgorithm());
                 }
             } catch (Exception ex) {
                 throw new TransformException
@@ -208,26 +217,27 @@
 
         XMLSignatureInput in;
         if (data instanceof ApacheData) {
-            if (log.isLoggable(Level.FINE)) {
-                log.log(Level.FINE, "ApacheData = true");
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "ApacheData = true");
             }
-            in = ((ApacheData) data).getXMLSignatureInput();
+            in = ((ApacheData)data).getXMLSignatureInput();
         } else if (data instanceof NodeSetData) {
-            if (log.isLoggable(Level.FINE)) {
-                log.log(Level.FINE, "isNodeSet() = true");
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "isNodeSet() = true");
             }
             if (data instanceof DOMSubTreeData) {
-                DOMSubTreeData subTree = (DOMSubTreeData) data;
+                DOMSubTreeData subTree = (DOMSubTreeData)data;
                 in = new XMLSignatureInput(subTree.getRoot());
                 in.setExcludeComments(subTree.excludeComments());
             } else {
-                Set nodeSet =
-                    Utils.toNodeSet(((NodeSetData) data).iterator());
+                @SuppressWarnings("unchecked")
+                Set<Node> nodeSet =
+                    Utils.toNodeSet(((NodeSetData)data).iterator());
                 in = new XMLSignatureInput(nodeSet);
             }
         } else {
-            if (log.isLoggable(Level.FINE)) {
-                log.log(Level.FINE, "isNodeSet() = false");
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "isNodeSet() = false");
             }
             try {
                 in = new XMLSignatureInput
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheData.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheData.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: ApacheData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: ApacheData.java 1333869 2012-05-04 10:42:44Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -39,5 +41,5 @@
     /**
      * Returns the XMLSignatureInput.
      */
-    public XMLSignatureInput getXMLSignatureInput();
+    XMLSignatureInput getXMLSignatureInput();
 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,32 +2,33 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: ApacheNodeSetData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: ApacheNodeSetData.java 1203890 2011-11-18 22:47:56Z mullan $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import java.util.Collections;
-import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedHashSet;
 import java.util.List;
@@ -65,24 +66,22 @@
         return xi;
     }
 
-    private Set getNodeSet(List nodeFilters) {
+    private Set<Node> getNodeSet(List<NodeFilter> nodeFilters) {
         if (xi.isNeedsToBeExpanded()) {
             XMLUtils.circumventBug2650
                 (XMLUtils.getOwnerDocument(xi.getSubNode()));
         }
 
-        Set inputSet = new LinkedHashSet();
-        XMLUtils.getSet
-          (xi.getSubNode(), inputSet, null, !xi.isExcludeComments());
-        Set nodeSet = new LinkedHashSet();
-        Iterator i = inputSet.iterator();
-        while (i.hasNext()) {
-            Node currentNode = (Node) i.next();
-            Iterator it = nodeFilters.iterator();
+        Set<Node> inputSet = new LinkedHashSet<Node>();
+        XMLUtils.getSet(xi.getSubNode(), inputSet,
+                        null, !xi.isExcludeComments());
+        Set<Node> nodeSet = new LinkedHashSet<Node>();
+        for (Node currentNode : inputSet) {
+            Iterator<NodeFilter> it = nodeFilters.iterator();
             boolean skipNode = false;
             while (it.hasNext() && !skipNode) {
-                NodeFilter nf = (NodeFilter) it.next();
-                if (nf.isNodeInclude(currentNode)!=1) {
+                NodeFilter nf = it.next();
+                if (nf.isNodeInclude(currentNode) != 1) {
                     skipNode = true;
                 }
             }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheOctetStreamData.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheOctetStreamData.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: ApacheOctetStreamData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: ApacheOctetStreamData.java 1197150 2011-11-03 14:34:57Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -37,7 +39,8 @@
     private XMLSignatureInput xi;
 
     public ApacheOctetStreamData(XMLSignatureInput xi)
-        throws CanonicalizationException, IOException {
+        throws CanonicalizationException, IOException
+    {
         super(xi.getOctetStream(), xi.getSourceURI(), xi.getMIMEType());
         this.xi = xi;
     }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: ApacheTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: ApacheTransform.java 1333869 2012-05-04 10:42:44Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -30,11 +32,9 @@
 import java.security.InvalidAlgorithmParameterException;
 import java.security.spec.AlgorithmParameterSpec;
 import java.util.Set;
-import java.util.logging.Level;
-import java.util.logging.Logger;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
+import org.w3c.dom.Node;
 
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import com.sun.org.apache.xml.internal.security.transforms.Transform;
@@ -58,7 +58,8 @@
         com.sun.org.apache.xml.internal.security.Init.init();
     }
 
-    private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom");
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
     private Transform apacheTransform;
     protected Document ownerDoc;
     protected Element transformElem;
@@ -69,37 +70,47 @@
     }
 
     public void init(XMLStructure parent, XMLCryptoContext context)
-        throws InvalidAlgorithmParameterException {
+        throws InvalidAlgorithmParameterException
+    {
         if (context != null && !(context instanceof DOMCryptoContext)) {
             throw new ClassCastException
                 ("context must be of type DOMCryptoContext");
         }
+        if (parent == null || !(parent instanceof javax.xml.crypto.dom.DOMStructure)) {
+            throw new ClassCastException("parent must be of type DOMStructure");
+        }
         transformElem = (Element)
             ((javax.xml.crypto.dom.DOMStructure) parent).getNode();
         ownerDoc = DOMUtils.getOwnerDocument(transformElem);
     }
 
     public void marshalParams(XMLStructure parent, XMLCryptoContext context)
-        throws MarshalException {
+        throws MarshalException
+    {
         if (context != null && !(context instanceof DOMCryptoContext)) {
             throw new ClassCastException
                 ("context must be of type DOMCryptoContext");
         }
+        if (parent == null || !(parent instanceof javax.xml.crypto.dom.DOMStructure)) {
+            throw new ClassCastException("parent must be of type DOMStructure");
+        }
         transformElem = (Element)
             ((javax.xml.crypto.dom.DOMStructure) parent).getNode();
         ownerDoc = DOMUtils.getOwnerDocument(transformElem);
     }
 
     public Data transform(Data data, XMLCryptoContext xc)
-        throws TransformException {
+        throws TransformException
+    {
         if (data == null) {
             throw new NullPointerException("data must not be null");
         }
-        return transformIt(data, xc, (OutputStream) null);
+        return transformIt(data, xc, (OutputStream)null);
     }
 
     public Data transform(Data data, XMLCryptoContext xc, OutputStream os)
-        throws TransformException {
+        throws TransformException
+    {
         if (data == null) {
             throw new NullPointerException("data must not be null");
         }
@@ -110,24 +121,24 @@
     }
 
     private Data transformIt(Data data, XMLCryptoContext xc, OutputStream os)
-        throws TransformException {
-
+        throws TransformException
+    {
         if (ownerDoc == null) {
             throw new TransformException("transform must be marshalled");
         }
 
         if (apacheTransform == null) {
             try {
-                apacheTransform = new Transform
-                    (ownerDoc, getAlgorithm(), transformElem.getChildNodes());
+                apacheTransform =
+                    new Transform(ownerDoc, getAlgorithm(), transformElem.getChildNodes());
                 apacheTransform.setElement(transformElem, xc.getBaseURI());
-                if (log.isLoggable(Level.FINE)) {
-                    log.log(Level.FINE, "Created transform for algorithm: "
-                        + getAlgorithm());
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "Created transform for algorithm: " +
+                            getAlgorithm());
                 }
             } catch (Exception ex) {
-                throw new TransformException
-                    ("Couldn't find Transform for: " + getAlgorithm(), ex);
+                throw new TransformException("Couldn't find Transform for: " +
+                                             getAlgorithm(), ex);
             }
         }
 
@@ -135,36 +146,37 @@
             String algorithm = getAlgorithm();
             if (Transforms.TRANSFORM_XSLT.equals(algorithm)) {
                 throw new TransformException(
-                    "Transform " + algorithm +
-                    " is forbidden when secure validation is enabled");
+                    "Transform " + algorithm + " is forbidden when secure validation is enabled"
+                );
             }
         }
 
         XMLSignatureInput in;
         if (data instanceof ApacheData) {
-            if (log.isLoggable(Level.FINE)) {
-                log.log(Level.FINE, "ApacheData = true");
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "ApacheData = true");
             }
-            in = ((ApacheData) data).getXMLSignatureInput();
+            in = ((ApacheData)data).getXMLSignatureInput();
         } else if (data instanceof NodeSetData) {
-            if (log.isLoggable(Level.FINE)) {
-                log.log(Level.FINE, "isNodeSet() = true");
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "isNodeSet() = true");
             }
             if (data instanceof DOMSubTreeData) {
-                if (log.isLoggable(Level.FINE)) {
-                    log.log(Level.FINE, "DOMSubTreeData = true");
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, "DOMSubTreeData = true");
                 }
-                DOMSubTreeData subTree = (DOMSubTreeData) data;
+                DOMSubTreeData subTree = (DOMSubTreeData)data;
                 in = new XMLSignatureInput(subTree.getRoot());
                 in.setExcludeComments(subTree.excludeComments());
             } else {
-                Set nodeSet =
-                    Utils.toNodeSet(((NodeSetData) data).iterator());
+                @SuppressWarnings("unchecked")
+                Set<Node> nodeSet =
+                    Utils.toNodeSet(((NodeSetData)data).iterator());
                 in = new XMLSignatureInput(nodeSet);
             }
         } else {
-            if (log.isLoggable(Level.FINE)) {
-                log.log(Level.FINE, "isNodeSet() = false");
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "isNodeSet() = false");
             }
             try {
                 in = new XMLSignatureInput
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMBase64Transform.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMBase64Transform.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,33 +2,34 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMBase64Transform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMBase64Transform.java 1197150 2011-11-03 14:34:57Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import java.security.InvalidAlgorithmParameterException;
 
-import javax.xml.crypto.XMLStructure;
 import javax.xml.crypto.dsig.spec.TransformParameterSpec;
 
 /**
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14N11Method.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14N11Method.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2008 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMCanonicalXMLC14N11Method.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id$
  */
 package org.jcp.xml.dsig.internal.dom;
 
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14NMethod.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14NMethod.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMCanonicalXMLC14NMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMCanonicalXMLC14NMethod.java 1197150 2011-11-03 14:34:57Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,33 +2,36 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMCanonicalizationMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMCanonicalizationMethod.java 1333415 2012-05-03 12:03:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import java.io.OutputStream;
 import java.security.InvalidAlgorithmParameterException;
 import java.security.Provider;
+import java.security.spec.AlgorithmParameterSpec;
 
 import org.w3c.dom.Element;
 
@@ -49,7 +52,8 @@
      * @param spi TransformService
      */
     public DOMCanonicalizationMethod(TransformService spi)
-        throws InvalidAlgorithmParameterException {
+        throws InvalidAlgorithmParameterException
+    {
         super(spi);
         if (!(spi instanceof ApacheCanonicalizer) &&
                 !isC14Nalg(spi.getAlgorithm())) {
@@ -66,7 +70,9 @@
      * @param cmElem a CanonicalizationMethod element
      */
     public DOMCanonicalizationMethod(Element cmElem, XMLCryptoContext context,
-        Provider provider) throws MarshalException {
+                                     Provider provider)
+        throws MarshalException
+    {
         super(cmElem, context, provider);
         if (!(spi instanceof ApacheCanonicalizer) &&
                 !isC14Nalg(spi.getAlgorithm())) {
@@ -88,15 +94,18 @@
      *    canonicalizing the data
      */
     public Data canonicalize(Data data, XMLCryptoContext xc)
-        throws TransformException {
+        throws TransformException
+    {
         return transform(data, xc);
     }
 
     public Data canonicalize(Data data, XMLCryptoContext xc, OutputStream os)
-        throws TransformException {
+        throws TransformException
+    {
         return transform(data, xc, os);
     }
 
+    @Override
     public boolean equals(Object o) {
         if (this == o) {
             return true;
@@ -105,12 +114,24 @@
         if (!(o instanceof CanonicalizationMethod)) {
             return false;
         }
-        CanonicalizationMethod ocm = (CanonicalizationMethod) o;
+        CanonicalizationMethod ocm = (CanonicalizationMethod)o;
 
         return (getAlgorithm().equals(ocm.getAlgorithm()) &&
             DOMUtils.paramsEqual(getParameterSpec(), ocm.getParameterSpec()));
     }
 
+    @Override
+    public int hashCode() {
+        int result = 17;
+        result = 31 * result + getAlgorithm().hashCode();
+        AlgorithmParameterSpec spec = getParameterSpec();
+        if (spec != null) {
+            result = 31 * result + spec.hashCode();
+        }
+
+        return result;
+    }
+
     private static boolean isC14Nalg(String alg) {
         return (alg.equals(CanonicalizationMethod.INCLUSIVE) ||
                 alg.equals(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS) ||
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCryptoBinary.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCryptoBinary.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,34 +2,35 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMCryptoBinary.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMCryptoBinary.java 1197150 2011-11-03 14:34:57Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import java.math.BigInteger;
 import javax.xml.crypto.*;
 import javax.xml.crypto.dom.DOMCryptoContext;
-import javax.xml.crypto.dsig.*;
 import org.w3c.dom.Node;
 import org.w3c.dom.Text;
 
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMDigestMethod.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMDigestMethod.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMDigestMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMDigestMethod.java 1333415 2012-05-03 12:03:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -45,7 +47,7 @@
 public abstract class DOMDigestMethod extends DOMStructure
     implements DigestMethod {
 
-    final static String SHA384 =
+    static final String SHA384 =
         "http://www.w3.org/2001/04/xmldsig-more#sha384"; // see RFC 4051
     private DigestMethodParameterSpec params;
 
@@ -57,13 +59,14 @@
      *    appropriate for this digest method
      */
     DOMDigestMethod(AlgorithmParameterSpec params)
-        throws InvalidAlgorithmParameterException {
+        throws InvalidAlgorithmParameterException
+    {
         if (params != null && !(params instanceof DigestMethodParameterSpec)) {
             throw new InvalidAlgorithmParameterException
                 ("params must be of type DigestMethodParameterSpec");
         }
-        checkParams((DigestMethodParameterSpec) params);
-        this.params = (DigestMethodParameterSpec) params;
+        checkParams((DigestMethodParameterSpec)params);
+        this.params = (DigestMethodParameterSpec)params;
     }
 
     /**
@@ -96,8 +99,8 @@
         } else if (alg.equals(DigestMethod.SHA512)) {
             return new SHA512(dmElem);
         } else {
-            throw new MarshalException
-                ("unsupported DigestMethod algorithm: " + alg);
+            throw new MarshalException("unsupported DigestMethod algorithm: " +
+                                       alg);
         }
     }
 
@@ -112,11 +115,12 @@
      *    appropriate for this digest method
      */
     void checkParams(DigestMethodParameterSpec params)
-        throws InvalidAlgorithmParameterException {
+        throws InvalidAlgorithmParameterException
+    {
         if (params != null) {
             throw new InvalidAlgorithmParameterException("no parameters " +
-                "should be specified for the " + getMessageDigestAlgorithm()
-                 + " DigestMethod algorithm");
+                "should be specified for the " + getMessageDigestAlgorithm() +
+                " DigestMethod algorithm");
         }
     }
 
@@ -134,11 +138,13 @@
      * @return the algorithm-specific <code>DigestMethodParameterSpec</code>
      * @throws MarshalException if the parameters cannot be unmarshalled
      */
-    DigestMethodParameterSpec
-        unmarshalParams(Element paramsElem) throws MarshalException {
+    DigestMethodParameterSpec unmarshalParams(Element paramsElem)
+        throws MarshalException
+    {
         throw new MarshalException("no parameters should " +
-            "be specified for the " + getMessageDigestAlgorithm() +
-            " DigestMethod algorithm");
+                                   "be specified for the " +
+                                   getMessageDigestAlgorithm() +
+                                   " DigestMethod algorithm");
     }
 
     /**
@@ -146,11 +152,12 @@
      * method to marshal any algorithm-specific parameters.
      */
     public void marshal(Node parent, String prefix, DOMCryptoContext context)
-        throws MarshalException {
+        throws MarshalException
+    {
         Document ownerDoc = DOMUtils.getOwnerDocument(parent);
 
-        Element dmElem = DOMUtils.createElement
-            (ownerDoc, "DigestMethod", XMLSignature.XMLNS, prefix);
+        Element dmElem = DOMUtils.createElement(ownerDoc, "DigestMethod",
+                                                XMLSignature.XMLNS, prefix);
         DOMUtils.setAttribute(dmElem, "Algorithm", getAlgorithm());
 
         if (params != null) {
@@ -160,6 +167,7 @@
         parent.appendChild(dmElem);
     }
 
+    @Override
     public boolean equals(Object o) {
         if (this == o) {
             return true;
@@ -168,7 +176,7 @@
         if (!(o instanceof DigestMethod)) {
             return false;
         }
-        DigestMethod odm = (DigestMethod) o;
+        DigestMethod odm = (DigestMethod)o;
 
         boolean paramsEqual = (params == null ? odm.getParameterSpec() == null :
             params.equals(odm.getParameterSpec()));
@@ -176,6 +184,17 @@
         return (getAlgorithm().equals(odm.getAlgorithm()) && paramsEqual);
     }
 
+    @Override
+    public int hashCode() {
+        int result = 17;
+        if (params != null) {
+            result = 31 * result + params.hashCode();
+        }
+        result = 31 * result + getAlgorithm().hashCode();
+
+        return result;
+    }
+
     /**
      * Marshals the algorithm-specific parameters to an Element and
      * appends it to the specified parent element. By default, this method
@@ -187,10 +206,12 @@
      * @throws MarshalException if the parameters cannot be marshalled
      */
     void marshalParams(Element parent, String prefix)
-        throws MarshalException {
+        throws MarshalException
+    {
         throw new MarshalException("no parameters should " +
-            "be specified for the " + getMessageDigestAlgorithm() +
-            " DigestMethod algorithm");
+                                   "be specified for the " +
+                                   getMessageDigestAlgorithm() +
+                                   " DigestMethod algorithm");
     }
 
     /**
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMEnvelopedTransform.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMEnvelopedTransform.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMEnvelopedTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMEnvelopedTransform.java 1197150 2011-11-03 14:34:57Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMExcC14NMethod.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMExcC14NMethod.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMExcC14NMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMExcC14NMethod.java 1197150 2011-11-03 14:34:57Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -50,18 +52,20 @@
 public final class DOMExcC14NMethod extends ApacheCanonicalizer {
 
     public void init(TransformParameterSpec params)
-        throws InvalidAlgorithmParameterException {
+        throws InvalidAlgorithmParameterException
+    {
         if (params != null) {
             if (!(params instanceof ExcC14NParameterSpec)) {
                 throw new InvalidAlgorithmParameterException
                     ("params must be of type ExcC14NParameterSpec");
             }
-            this.params = (C14NMethodParameterSpec) params;
+            this.params = (C14NMethodParameterSpec)params;
         }
     }
 
     public void init(XMLStructure parent, XMLCryptoContext context)
-        throws InvalidAlgorithmParameterException {
+        throws InvalidAlgorithmParameterException
+    {
         super.init(parent, context);
         Element paramsElem = DOMUtils.getFirstChildElement(transformElem);
         if (paramsElem == null) {
@@ -77,7 +81,7 @@
         this.inclusiveNamespaces = prefixListAttr;
         int begin = 0;
         int end = prefixListAttr.indexOf(' ');
-        List prefixList = new ArrayList();
+        List<String> prefixList = new ArrayList<String>();
         while (end != -1) {
             prefixList.add(prefixListAttr.substring(begin, end));
             begin = end + 1;
@@ -90,39 +94,42 @@
     }
 
     public void marshalParams(XMLStructure parent, XMLCryptoContext context)
-        throws MarshalException {
-
+        throws MarshalException
+    {
         super.marshalParams(parent, context);
         AlgorithmParameterSpec spec = getParameterSpec();
         if (spec == null) {
             return;
         }
 
-        String prefix =
-            DOMUtils.getNSPrefix(context, CanonicalizationMethod.EXCLUSIVE);
-        Element excElem = DOMUtils.createElement
-            (ownerDoc, "InclusiveNamespaces",
-             CanonicalizationMethod.EXCLUSIVE, prefix);
+        String prefix = DOMUtils.getNSPrefix(context,
+                                             CanonicalizationMethod.EXCLUSIVE);
+        Element eElem = DOMUtils.createElement(ownerDoc,
+                                               "InclusiveNamespaces",
+                                               CanonicalizationMethod.EXCLUSIVE,
+                                               prefix);
         if (prefix == null || prefix.length() == 0) {
-            excElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns",
-                CanonicalizationMethod.EXCLUSIVE);
+            eElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns",
+                                 CanonicalizationMethod.EXCLUSIVE);
         } else {
-            excElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
-                "xmlns:" + prefix, CanonicalizationMethod.EXCLUSIVE);
+            eElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
+                                   "xmlns:" + prefix,
+                                   CanonicalizationMethod.EXCLUSIVE);
         }
 
-        ExcC14NParameterSpec params = (ExcC14NParameterSpec) spec;
+        ExcC14NParameterSpec params = (ExcC14NParameterSpec)spec;
         StringBuffer prefixListAttr = new StringBuffer("");
-        List prefixList = params.getPrefixList();
+        @SuppressWarnings("unchecked")
+        List<String> prefixList = params.getPrefixList();
         for (int i = 0, size = prefixList.size(); i < size; i++) {
-            prefixListAttr.append((String) prefixList.get(i));
+            prefixListAttr.append(prefixList.get(i));
             if (i < size - 1) {
                 prefixListAttr.append(" ");
             }
         }
-        DOMUtils.setAttribute(excElem, "PrefixList", prefixListAttr.toString());
+        DOMUtils.setAttribute(eElem, "PrefixList", prefixListAttr.toString());
         this.inclusiveNamespaces = prefixListAttr.toString();
-        transformElem.appendChild(excElem);
+        transformElem.appendChild(eElem);
     }
 
     public String getParamsNSURI() {
@@ -130,13 +137,13 @@
     }
 
     public Data transform(Data data, XMLCryptoContext xc)
-        throws TransformException {
-
+        throws TransformException
+    {
         // ignore comments if dereferencing same-document URI that require
         // you to omit comments, even if the Transform says otherwise -
         // this is to be compliant with section 4.3.3.3 of W3C Rec.
         if (data instanceof DOMSubTreeData) {
-            DOMSubTreeData subTree = (DOMSubTreeData) data;
+            DOMSubTreeData subTree = (DOMSubTreeData)data;
             if (subTree.excludeComments()) {
                 try {
                     apacheCanonicalizer = Canonicalizer.getInstance
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2009, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMHMACSignatureMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMHMACSignatureMethod.java 1333415 2012-05-03 12:03:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -38,8 +40,6 @@
 import java.security.NoSuchAlgorithmException;
 import java.security.SignatureException;
 import java.security.spec.AlgorithmParameterSpec;
-import java.util.logging.Level;
-import java.util.logging.Logger;
 import javax.crypto.Mac;
 import javax.crypto.SecretKey;
 import org.w3c.dom.Document;
@@ -52,13 +52,23 @@
  *
  * @author Sean Mullan
  */
-public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod {
+public abstract class DOMHMACSignatureMethod extends AbstractDOMSignatureMethod {
+
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
 
-    private static Logger log =
-        Logger.getLogger("org.jcp.xml.dsig.internal.dom");
+    // see RFC 4051 for these algorithm definitions
+    static final String HMAC_SHA256 =
+        "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
+    static final String HMAC_SHA384 =
+        "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384";
+    static final String HMAC_SHA512 =
+        "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512";
+
     private Mac hmac;
     private int outputLength;
     private boolean outputLengthSet;
+    private SignatureMethodParameterSpec params;
 
     /**
      * Creates a <code>DOMHMACSignatureMethod</code> with the specified params
@@ -67,8 +77,10 @@
      * @throws InvalidAlgorithmParameterException if params are inappropriate
      */
     DOMHMACSignatureMethod(AlgorithmParameterSpec params)
-        throws InvalidAlgorithmParameterException {
-        super(params);
+        throws InvalidAlgorithmParameterException
+    {
+        checkParams((SignatureMethodParameterSpec)params);
+        this.params = (SignatureMethodParameterSpec)params;
     }
 
     /**
@@ -77,54 +89,64 @@
      * @param smElem a SignatureMethod element
      */
     DOMHMACSignatureMethod(Element smElem) throws MarshalException {
-        super(smElem);
+        Element paramsElem = DOMUtils.getFirstChildElement(smElem);
+        if (paramsElem != null) {
+            params = unmarshalParams(paramsElem);
+        }
+        try {
+            checkParams(params);
+        } catch (InvalidAlgorithmParameterException iape) {
+            throw new MarshalException(iape);
+        }
     }
 
     void checkParams(SignatureMethodParameterSpec params)
-        throws InvalidAlgorithmParameterException {
+        throws InvalidAlgorithmParameterException
+    {
         if (params != null) {
             if (!(params instanceof HMACParameterSpec)) {
                 throw new InvalidAlgorithmParameterException
                     ("params must be of type HMACParameterSpec");
             }
-            outputLength = ((HMACParameterSpec) params).getOutputLength();
+            outputLength = ((HMACParameterSpec)params).getOutputLength();
             outputLengthSet = true;
-            if (log.isLoggable(Level.FINE)) {
-                log.log(Level.FINE,
-                    "Setting outputLength from HMACParameterSpec to: "
-                    + outputLength);
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "Setting outputLength from HMACParameterSpec to: " + outputLength);
             }
-        } else {
-            outputLength = -1;
         }
     }
 
+    public final AlgorithmParameterSpec getParameterSpec() {
+        return params;
+    }
+
     SignatureMethodParameterSpec unmarshalParams(Element paramsElem)
-        throws MarshalException {
-        outputLength = new Integer
-            (paramsElem.getFirstChild().getNodeValue()).intValue();
+        throws MarshalException
+    {
+        outputLength = Integer.valueOf(paramsElem.getFirstChild().getNodeValue()).intValue();
         outputLengthSet = true;
-        if (log.isLoggable(Level.FINE)) {
-            log.log(Level.FINE, "unmarshalled outputLength: " + outputLength);
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "unmarshalled outputLength: " + outputLength);
         }
         return new HMACParameterSpec(outputLength);
     }
 
     void marshalParams(Element parent, String prefix)
-        throws MarshalException {
-
+        throws MarshalException
+    {
         Document ownerDoc = DOMUtils.getOwnerDocument(parent);
         Element hmacElem = DOMUtils.createElement(ownerDoc, "HMACOutputLength",
-            XMLSignature.XMLNS, prefix);
+                                                  XMLSignature.XMLNS, prefix);
         hmacElem.appendChild(ownerDoc.createTextNode
            (String.valueOf(outputLength)));
 
         parent.appendChild(hmacElem);
     }
 
-    boolean verify(Key key, DOMSignedInfo si, byte[] sig,
-        XMLValidateContext context)
-        throws InvalidKeyException, SignatureException, XMLSignatureException {
+    boolean verify(Key key, SignedInfo si, byte[] sig,
+                   XMLValidateContext context)
+        throws InvalidKeyException, SignatureException, XMLSignatureException
+    {
         if (key == null || si == null || sig == null) {
             throw new NullPointerException();
         }
@@ -133,7 +155,7 @@
         }
         if (hmac == null) {
             try {
-                hmac = Mac.getInstance(getSignatureAlgorithm());
+                hmac = Mac.getInstance(getJCAAlgorithm());
             } catch (NoSuchAlgorithmException nsae) {
                 throw new XMLSignatureException(nsae);
             }
@@ -142,15 +164,16 @@
             throw new XMLSignatureException
                 ("HMACOutputLength must not be less than " + getDigestLength());
         }
-        hmac.init((SecretKey) key);
-        si.canonicalize(context, new MacOutputStream(hmac));
+        hmac.init((SecretKey)key);
+        ((DOMSignedInfo)si).canonicalize(context, new MacOutputStream(hmac));
         byte[] result = hmac.doFinal();
 
         return MessageDigest.isEqual(sig, result);
     }
 
-    byte[] sign(Key key, DOMSignedInfo si, XMLSignContext context)
-        throws InvalidKeyException, XMLSignatureException {
+    byte[] sign(Key key, SignedInfo si, XMLSignContext context)
+        throws InvalidKeyException, XMLSignatureException
+    {
         if (key == null || si == null) {
             throw new NullPointerException();
         }
@@ -159,7 +182,7 @@
         }
         if (hmac == null) {
             try {
-                hmac = Mac.getInstance(getSignatureAlgorithm());
+                hmac = Mac.getInstance(getJCAAlgorithm());
             } catch (NoSuchAlgorithmException nsae) {
                 throw new XMLSignatureException(nsae);
             }
@@ -168,8 +191,8 @@
             throw new XMLSignatureException
                 ("HMACOutputLength must not be less than " + getDigestLength());
         }
-        hmac.init((SecretKey) key);
-        si.canonicalize(context, new MacOutputStream(hmac));
+        hmac.init((SecretKey)key);
+        ((DOMSignedInfo)si).canonicalize(context, new MacOutputStream(hmac));
         return hmac.doFinal();
     }
 
@@ -180,11 +203,15 @@
         if (!(spec instanceof HMACParameterSpec)) {
             return false;
         }
-        HMACParameterSpec ospec = (HMACParameterSpec) spec;
+        HMACParameterSpec ospec = (HMACParameterSpec)spec;
 
         return (outputLength == ospec.getOutputLength());
     }
 
+    Type getAlgorithmType() {
+        return Type.HMAC;
+    }
+
     /**
      * Returns the output length of the hash/digest.
      */
@@ -201,7 +228,7 @@
         public String getAlgorithm() {
             return SignatureMethod.HMAC_SHA1;
         }
-        String getSignatureAlgorithm() {
+        String getJCAAlgorithm() {
             return "HmacSHA1";
         }
         int getDigestLength() {
@@ -220,7 +247,7 @@
         public String getAlgorithm() {
             return HMAC_SHA256;
         }
-        String getSignatureAlgorithm() {
+        String getJCAAlgorithm() {
             return "HmacSHA256";
         }
         int getDigestLength() {
@@ -239,7 +266,7 @@
         public String getAlgorithm() {
             return HMAC_SHA384;
         }
-        String getSignatureAlgorithm() {
+        String getJCAAlgorithm() {
             return "HmacSHA384";
         }
         int getDigestLength() {
@@ -258,7 +285,7 @@
         public String getAlgorithm() {
             return HMAC_SHA512;
         }
-        String getSignatureAlgorithm() {
+        String getJCAAlgorithm() {
             return "HmacSHA512";
         }
         int getDigestLength() {
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,38 +2,40 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMKeyInfo.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMKeyInfo.java 1333869 2012-05-04 10:42:44Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import javax.xml.crypto.*;
 import javax.xml.crypto.dsig.*;
-import javax.xml.crypto.dsig.dom.DOMSignContext;
 import javax.xml.crypto.dsig.keyinfo.KeyInfo;
 import javax.xml.crypto.dom.*;
 
 import java.security.Provider;
 import java.util.*;
+
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -48,7 +50,7 @@
 public final class DOMKeyInfo extends DOMStructure implements KeyInfo {
 
     private final String id;
-    private final List keyInfoTypes;
+    private final List<XMLStructure> keyInfoTypes;
 
     /**
      * Creates a <code>DOMKeyInfo</code>.
@@ -62,21 +64,21 @@
      * @throws ClassCastException if <code>content</code> contains any entries
      *    that are not of type {@link XMLStructure}
      */
-    public DOMKeyInfo(List content, String id) {
+    public DOMKeyInfo(List<? extends XMLStructure> content, String id) {
         if (content == null) {
             throw new NullPointerException("content cannot be null");
         }
-        List typesCopy = new ArrayList(content);
-        if (typesCopy.isEmpty()) {
+        this.keyInfoTypes =
+            Collections.unmodifiableList(new ArrayList<XMLStructure>(content));
+        if (this.keyInfoTypes.isEmpty()) {
             throw new IllegalArgumentException("content cannot be empty");
         }
-        for (int i = 0, size = typesCopy.size(); i < size; i++) {
-            if (!(typesCopy.get(i) instanceof XMLStructure)) {
+        for (int i = 0, size = this.keyInfoTypes.size(); i < size; i++) {
+            if (!(this.keyInfoTypes.get(i) instanceof XMLStructure)) {
                 throw new ClassCastException
                     ("content["+i+"] is not a valid KeyInfo type");
             }
         }
-        this.keyInfoTypes = Collections.unmodifiableList(typesCopy);
         this.id = id;
     }
 
@@ -86,7 +88,9 @@
      * @param kiElem KeyInfo element
      */
     public DOMKeyInfo(Element kiElem, XMLCryptoContext context,
-        Provider provider) throws MarshalException {
+                      Provider provider)
+        throws MarshalException
+    {
         // get Id attribute, if specified
         Attr attr = kiElem.getAttributeNodeNS(null, "Id");
         if (attr != null) {
@@ -103,24 +107,24 @@
             throw new MarshalException
                 ("KeyInfo must contain at least one type");
         }
-        List content = new ArrayList(length);
+        List<XMLStructure> content = new ArrayList<XMLStructure>(length);
         for (int i = 0; i < length; i++) {
             Node child = nl.item(i);
             // ignore all non-Element nodes
             if (child.getNodeType() != Node.ELEMENT_NODE) {
                 continue;
             }
-            Element childElem = (Element) child;
+            Element childElem = (Element)child;
             String localName = childElem.getLocalName();
             if (localName.equals("X509Data")) {
                 content.add(new DOMX509Data(childElem));
             } else if (localName.equals("KeyName")) {
                 content.add(new DOMKeyName(childElem));
             } else if (localName.equals("KeyValue")) {
-                content.add(new DOMKeyValue(childElem));
+                content.add(DOMKeyValue.unmarshal(childElem));
             } else if (localName.equals("RetrievalMethod")) {
-                content.add
-                    (new DOMRetrievalMethod(childElem, context, provider));
+                content.add(new DOMRetrievalMethod(childElem,
+                                                   context, provider));
             } else if (localName.equals("PGPData")) {
                 content.add(new DOMPGPData(childElem));
             } else { //may be MgmtData, SPKIData or element from other namespace
@@ -139,51 +143,58 @@
     }
 
     public void marshal(XMLStructure parent, XMLCryptoContext context)
-        throws MarshalException {
+        throws MarshalException
+    {
         if (parent == null) {
             throw new NullPointerException("parent is null");
         }
+        if (!(parent instanceof javax.xml.crypto.dom.DOMStructure)) {
+            throw new ClassCastException("parent must be of type DOMStructure");
+        }
 
-        Node pNode = ((javax.xml.crypto.dom.DOMStructure) parent).getNode();
+        Node pNode = ((javax.xml.crypto.dom.DOMStructure)parent).getNode();
         String dsPrefix = DOMUtils.getSignaturePrefix(context);
         Element kiElem = DOMUtils.createElement
             (DOMUtils.getOwnerDocument(pNode), "KeyInfo",
              XMLSignature.XMLNS, dsPrefix);
         if (dsPrefix == null || dsPrefix.length() == 0) {
-            kiElem.setAttributeNS
-                ("http://www.w3.org/2000/xmlns/", "xmlns", XMLSignature.XMLNS);
+            kiElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
+                                  "xmlns", XMLSignature.XMLNS);
         } else {
-            kiElem.setAttributeNS
-                ("http://www.w3.org/2000/xmlns/", "xmlns:" + dsPrefix,
-                 XMLSignature.XMLNS);
+            kiElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
+                                  "xmlns:" + dsPrefix, XMLSignature.XMLNS);
         }
-        marshal(pNode, kiElem, null, dsPrefix, (DOMCryptoContext) context);
+        marshal(pNode, kiElem, null, dsPrefix, (DOMCryptoContext)context);
     }
 
     public void marshal(Node parent, String dsPrefix,
-        DOMCryptoContext context) throws MarshalException {
+                        DOMCryptoContext context)
+        throws MarshalException
+    {
         marshal(parent, null, dsPrefix, context);
     }
 
     public void marshal(Node parent, Node nextSibling, String dsPrefix,
-        DOMCryptoContext context) throws MarshalException {
+                        DOMCryptoContext context)
+        throws MarshalException
+    {
         Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
-        Element kiElem = DOMUtils.createElement
-            (ownerDoc, "KeyInfo", XMLSignature.XMLNS, dsPrefix);
+        Element kiElem = DOMUtils.createElement(ownerDoc, "KeyInfo",
+                                                XMLSignature.XMLNS, dsPrefix);
         marshal(parent, kiElem, nextSibling, dsPrefix, context);
     }
 
     private void marshal(Node parent, Element kiElem, Node nextSibling,
-        String dsPrefix, DOMCryptoContext context) throws MarshalException {
+                         String dsPrefix, DOMCryptoContext context)
+        throws MarshalException
+    {
         // create and append KeyInfoType elements
-        for (int i = 0, size = keyInfoTypes.size(); i < size; i++) {
-            XMLStructure kiType = (XMLStructure) keyInfoTypes.get(i);
+        for (XMLStructure kiType : keyInfoTypes) {
             if (kiType instanceof DOMStructure) {
-                ((DOMStructure) kiType).marshal(kiElem, dsPrefix, context);
+                ((DOMStructure)kiType).marshal(kiElem, dsPrefix, context);
             } else {
                 DOMUtils.appendChild(kiElem,
-                    ((javax.xml.crypto.dom.DOMStructure) kiType).getNode());
+                    ((javax.xml.crypto.dom.DOMStructure)kiType).getNode());
             }
         }
 
@@ -193,6 +204,7 @@
         parent.insertBefore(kiElem, nextSibling);
     }
 
+    @Override
     public boolean equals(Object o) {
         if (this == o) {
             return true;
@@ -201,11 +213,22 @@
         if (!(o instanceof KeyInfo)) {
             return false;
         }
-        KeyInfo oki = (KeyInfo) o;
+        KeyInfo oki = (KeyInfo)o;
 
-        boolean idsEqual = (id == null ? oki.getId() == null :
-            id.equals(oki.getId()));
+        boolean idsEqual = (id == null ? oki.getId() == null
+                                       : id.equals(oki.getId()));
 
         return (keyInfoTypes.equals(oki.getContent()) && idsEqual);
     }
+
+    @Override
+    public int hashCode() {
+        int result = 17;
+        if (id != null) {
+            result = 31 * result + id.hashCode();
+        }
+        result = 31 * result + keyInfoTypes.hashCode();
+
+        return result;
+    }
 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfoFactory.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfoFactory.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMKeyInfoFactory.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMKeyInfoFactory.java 1333869 2012-05-04 10:42:44Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -31,8 +33,7 @@
 import java.security.PublicKey;
 import java.util.List;
 import javax.xml.crypto.*;
-import javax.xml.crypto.dsig.*;
-import javax.xml.crypto.dom.*;
+import javax.xml.crypto.dom.DOMCryptoContext;
 import javax.xml.crypto.dsig.keyinfo.*;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -51,6 +52,7 @@
         return newKeyInfo(content, null);
     }
 
+    @SuppressWarnings("unchecked")
     public KeyInfo newKeyInfo(List content, String id) {
         return new DOMKeyInfo(content, id);
     }
@@ -60,17 +62,28 @@
     }
 
     public KeyValue newKeyValue(PublicKey key)  throws KeyException {
-        return new DOMKeyValue(key);
+        String algorithm = key.getAlgorithm();
+        if (algorithm.equals("DSA")) {
+            return new DOMKeyValue.DSA(key);
+        } else if (algorithm.equals("RSA")) {
+            return new DOMKeyValue.RSA(key);
+        } else if (algorithm.equals("EC")) {
+            return new DOMKeyValue.EC(key);
+        } else {
+            throw new KeyException("unsupported key algorithm: " + algorithm);
+        }
     }
 
     public PGPData newPGPData(byte[] keyId) {
         return newPGPData(keyId, null, null);
     }
 
+    @SuppressWarnings("unchecked")
     public PGPData newPGPData(byte[] keyId, byte[] keyPacket, List other) {
         return new DOMPGPData(keyId, keyPacket, other);
     }
 
+    @SuppressWarnings("unchecked")
     public PGPData newPGPData(byte[] keyPacket, List other) {
         return new DOMPGPData(keyPacket, other);
     }
@@ -79,6 +92,7 @@
         return newRetrievalMethod(uri, null, null);
     }
 
+    @SuppressWarnings("unchecked")
     public RetrievalMethod newRetrievalMethod(String uri, String type,
         List transforms) {
         if (uri == null) {
@@ -87,6 +101,7 @@
         return new DOMRetrievalMethod(uri, type, transforms);
     }
 
+    @SuppressWarnings("unchecked")
     public X509Data newX509Data(List content) {
         return new DOMX509Data(content);
     }
@@ -113,6 +128,9 @@
         if (xmlStructure == null) {
             throw new NullPointerException("xmlStructure cannot be null");
         }
+        if (!(xmlStructure instanceof javax.xml.crypto.dom.DOMStructure)) {
+            throw new ClassCastException("xmlStructure must be of type DOMStructure");
+        }
         Node node =
             ((javax.xml.crypto.dom.DOMStructure) xmlStructure).getNode();
         node.normalize();
@@ -134,9 +152,14 @@
                 "support DOM Level 2 and be namespace aware");
         }
         if (tag.equals("KeyInfo")) {
-            return new DOMKeyInfo(element, null, getProvider());
+            return new DOMKeyInfo(element, new UnmarshalContext(), getProvider());
         } else {
             throw new MarshalException("invalid KeyInfo tag: " + tag);
         }
     }
+
+    private static class UnmarshalContext extends DOMCryptoContext {
+        UnmarshalContext() {}
+    }
+
 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyName.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyName.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMKeyName.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMKeyName.java 1333415 2012-05-03 12:03:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -71,15 +73,17 @@
     }
 
     public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException {
+        throws MarshalException
+    {
         Document ownerDoc = DOMUtils.getOwnerDocument(parent);
         // prepend namespace prefix, if necessary
-        Element knElem = DOMUtils.createElement
-            (ownerDoc, "KeyName", XMLSignature.XMLNS, dsPrefix);
+        Element knElem = DOMUtils.createElement(ownerDoc, "KeyName",
+                                                XMLSignature.XMLNS, dsPrefix);
         knElem.appendChild(ownerDoc.createTextNode(name));
         parent.appendChild(knElem);
     }
 
+    @Override
     public boolean equals(Object obj) {
         if (this == obj) {
             return true;
@@ -87,7 +91,15 @@
         if (!(obj instanceof KeyName)) {
             return false;
         }
-        KeyName okn = (KeyName) obj;
+        KeyName okn = (KeyName)obj;
         return name.equals(okn.getName());
     }
+
+    @Override
+    public int hashCode() {
+        int result = 17;
+        result = 31 * result + name.hashCode();
+
+        return result;
+    }
 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMKeyValue.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMKeyValue.java 1333415 2012-05-03 12:03:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -31,14 +33,25 @@
 import javax.xml.crypto.dsig.*;
 import javax.xml.crypto.dsig.keyinfo.KeyValue;
 
+// import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.security.AccessController;
 import java.security.KeyException;
 import java.security.KeyFactory;
 import java.security.NoSuchAlgorithmException;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
 import java.security.PublicKey;
 import java.security.interfaces.DSAParams;
 import java.security.interfaces.DSAPublicKey;
+import java.security.interfaces.ECPublicKey;
 import java.security.interfaces.RSAPublicKey;
 import java.security.spec.DSAPublicKeySpec;
+import java.security.spec.ECParameterSpec;
+import java.security.spec.ECPoint;
+import java.security.spec.ECPublicKeySpec;
+import java.security.spec.EllipticCurve;
 import java.security.spec.InvalidKeySpecException;
 import java.security.spec.KeySpec;
 import java.security.spec.RSAPublicKeySpec;
@@ -46,59 +59,46 @@
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
+import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
+import com.sun.org.apache.xml.internal.security.utils.Base64;
+
 /**
  * DOM-based implementation of KeyValue.
  *
  * @author Sean Mullan
  */
-public final class DOMKeyValue extends DOMStructure implements KeyValue {
-
-    private KeyFactory rsakf, dsakf;
-    private PublicKey publicKey;
-    private javax.xml.crypto.dom.DOMStructure externalPublicKey;
+public abstract class DOMKeyValue extends DOMStructure implements KeyValue {
 
-    // DSAKeyValue CryptoBinaries
-    private DOMCryptoBinary p, q, g, y, j, seed, pgen;
+    private static final String XMLDSIG_11_XMLNS
+        = "http://www.w3.org/2009/xmldsig11#";
+    private final PublicKey publicKey;
 
-    // RSAKeyValue CryptoBinaries
-    private DOMCryptoBinary modulus, exponent;
-
-    public DOMKeyValue(PublicKey key)  throws KeyException {
+    public DOMKeyValue(PublicKey key) throws KeyException {
         if (key == null) {
             throw new NullPointerException("key cannot be null");
         }
         this.publicKey = key;
-        if (key instanceof DSAPublicKey) {
-            DSAPublicKey dkey = (DSAPublicKey) key;
-            DSAParams params = dkey.getParams();
-            p = new DOMCryptoBinary(params.getP());
-            q = new DOMCryptoBinary(params.getQ());
-            g = new DOMCryptoBinary(params.getG());
-            y = new DOMCryptoBinary(dkey.getY());
-        } else if (key instanceof RSAPublicKey) {
-            RSAPublicKey rkey = (RSAPublicKey) key;
-            exponent = new DOMCryptoBinary(rkey.getPublicExponent());
-            modulus = new DOMCryptoBinary(rkey.getModulus());
-        } else {
-            throw new KeyException("unsupported key algorithm: " +
-                key.getAlgorithm());
-        }
     }
 
     /**
      * Creates a <code>DOMKeyValue</code> from an element.
      *
-     * @param kvElem a KeyValue element
+     * @param kvtElem a KeyValue child element
      */
-    public DOMKeyValue(Element kvElem) throws MarshalException {
+    public DOMKeyValue(Element kvtElem) throws MarshalException {
+        this.publicKey = unmarshalKeyValue(kvtElem);
+    }
+
+    static KeyValue unmarshal(Element kvElem) throws MarshalException {
         Element kvtElem = DOMUtils.getFirstChildElement(kvElem);
         if (kvtElem.getLocalName().equals("DSAKeyValue")) {
-            publicKey = unmarshalDSAKeyValue(kvtElem);
+            return new DSA(kvtElem);
         } else if (kvtElem.getLocalName().equals("RSAKeyValue")) {
-            publicKey = unmarshalRSAKeyValue(kvtElem);
+            return new RSA(kvtElem);
+        } else if (kvtElem.getLocalName().equals("ECKeyValue")) {
+            return new EC(kvtElem);
         } else {
-            publicKey = null;
-            externalPublicKey = new javax.xml.crypto.dom.DOMStructure(kvtElem);
+            return new Unknown(kvtElem);
         }
     }
 
@@ -111,133 +111,25 @@
     }
 
     public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException {
+        throws MarshalException
+    {
         Document ownerDoc = DOMUtils.getOwnerDocument(parent);
 
         // create KeyValue element
-        Element kvElem = DOMUtils.createElement
-            (ownerDoc, "KeyValue", XMLSignature.XMLNS, dsPrefix);
+        Element kvElem = DOMUtils.createElement(ownerDoc, "KeyValue",
+                                                XMLSignature.XMLNS, dsPrefix);
         marshalPublicKey(kvElem, ownerDoc, dsPrefix, context);
 
         parent.appendChild(kvElem);
     }
 
-    private void marshalPublicKey(Node parent, Document doc, String dsPrefix,
-        DOMCryptoContext context) throws MarshalException {
-        if (publicKey != null) {
-            if (publicKey instanceof DSAPublicKey) {
-                // create and append DSAKeyValue element
-                marshalDSAPublicKey(parent, doc, dsPrefix, context);
-            } else if (publicKey instanceof RSAPublicKey) {
-                // create and append RSAKeyValue element
-                marshalRSAPublicKey(parent, doc, dsPrefix, context);
-            } else {
-                throw new MarshalException(publicKey.getAlgorithm() +
-                    " public key algorithm not supported");
-            }
-        } else {
-            parent.appendChild(externalPublicKey.getNode());
-        }
-    }
-
-    private void marshalDSAPublicKey(Node parent, Document doc,
-        String dsPrefix, DOMCryptoContext context) throws MarshalException {
-        Element dsaElem = DOMUtils.createElement
-            (doc, "DSAKeyValue", XMLSignature.XMLNS, dsPrefix);
-        // parameters J, Seed & PgenCounter are not included
-        Element pElem = DOMUtils.createElement
-            (doc, "P", XMLSignature.XMLNS, dsPrefix);
-        Element qElem = DOMUtils.createElement
-            (doc, "Q", XMLSignature.XMLNS, dsPrefix);
-        Element gElem = DOMUtils.createElement
-            (doc, "G", XMLSignature.XMLNS, dsPrefix);
-        Element yElem = DOMUtils.createElement
-            (doc, "Y", XMLSignature.XMLNS, dsPrefix);
-        p.marshal(pElem, dsPrefix, context);
-        q.marshal(qElem, dsPrefix, context);
-        g.marshal(gElem, dsPrefix, context);
-        y.marshal(yElem, dsPrefix, context);
-        dsaElem.appendChild(pElem);
-        dsaElem.appendChild(qElem);
-        dsaElem.appendChild(gElem);
-        dsaElem.appendChild(yElem);
-        parent.appendChild(dsaElem);
-    }
-
-    private void marshalRSAPublicKey(Node parent, Document doc,
-        String dsPrefix, DOMCryptoContext context) throws MarshalException {
-        Element rsaElem = DOMUtils.createElement
-            (doc, "RSAKeyValue", XMLSignature.XMLNS, dsPrefix);
-        Element modulusElem = DOMUtils.createElement
-            (doc, "Modulus", XMLSignature.XMLNS, dsPrefix);
-        Element exponentElem = DOMUtils.createElement
-            (doc, "Exponent", XMLSignature.XMLNS, dsPrefix);
-        modulus.marshal(modulusElem, dsPrefix, context);
-        exponent.marshal(exponentElem, dsPrefix, context);
-        rsaElem.appendChild(modulusElem);
-        rsaElem.appendChild(exponentElem);
-        parent.appendChild(rsaElem);
-    }
+    abstract void marshalPublicKey(Node parent, Document doc, String dsPrefix,
+        DOMCryptoContext context) throws MarshalException;
 
-    private DSAPublicKey unmarshalDSAKeyValue(Element kvtElem)
-        throws MarshalException {
-        if (dsakf == null) {
-            try {
-                dsakf = KeyFactory.getInstance("DSA");
-            } catch (NoSuchAlgorithmException e) {
-                throw new RuntimeException("unable to create DSA KeyFactory: " +
-                    e.getMessage());
-            }
-        }
-        Element curElem = DOMUtils.getFirstChildElement(kvtElem);
-        // check for P and Q
-        if (curElem.getLocalName().equals("P")) {
-            p = new DOMCryptoBinary(curElem.getFirstChild());
-            curElem = DOMUtils.getNextSiblingElement(curElem);
-            q = new DOMCryptoBinary(curElem.getFirstChild());
-            curElem = DOMUtils.getNextSiblingElement(curElem);
-        }
-        if (curElem.getLocalName().equals("G")) {
-            g = new DOMCryptoBinary(curElem.getFirstChild());
-            curElem = DOMUtils.getNextSiblingElement(curElem);
-        }
-        y = new DOMCryptoBinary(curElem.getFirstChild());
-        curElem = DOMUtils.getNextSiblingElement(curElem);
-        if (curElem != null && curElem.getLocalName().equals("J")) {
-            j = new DOMCryptoBinary(curElem.getFirstChild());
-            curElem = DOMUtils.getNextSiblingElement(curElem);
-        }
-        if (curElem != null) {
-            seed = new DOMCryptoBinary(curElem.getFirstChild());
-            curElem = DOMUtils.getNextSiblingElement(curElem);
-            pgen = new DOMCryptoBinary(curElem.getFirstChild());
-        }
-        //@@@ do we care about j, pgenCounter or seed?
-        DSAPublicKeySpec spec = new DSAPublicKeySpec
-            (y.getBigNum(), p.getBigNum(), q.getBigNum(), g.getBigNum());
-        return (DSAPublicKey) generatePublicKey(dsakf, spec);
-    }
+    abstract PublicKey unmarshalKeyValue(Element kvtElem)
+        throws MarshalException;
 
-    private RSAPublicKey unmarshalRSAKeyValue(Element kvtElem)
-        throws MarshalException {
-        if (rsakf == null) {
-            try {
-                rsakf = KeyFactory.getInstance("RSA");
-            } catch (NoSuchAlgorithmException e) {
-                throw new RuntimeException("unable to create RSA KeyFactory: " +
-                    e.getMessage());
-            }
-        }
-        Element modulusElem = DOMUtils.getFirstChildElement(kvtElem);
-        modulus = new DOMCryptoBinary(modulusElem.getFirstChild());
-        Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem);
-        exponent = new DOMCryptoBinary(exponentElem.getFirstChild());
-        RSAPublicKeySpec spec = new RSAPublicKeySpec
-            (modulus.getBigNum(), exponent.getBigNum());
-        return (RSAPublicKey) generatePublicKey(rsakf, spec);
-    }
-
-    private PublicKey generatePublicKey(KeyFactory kf, KeySpec keyspec) {
+    private static PublicKey generatePublicKey(KeyFactory kf, KeySpec keyspec) {
         try {
             return kf.generatePublic(keyspec);
         } catch (InvalidKeySpecException e) {
@@ -246,6 +138,7 @@
         }
     }
 
+    @Override
     public boolean equals(Object obj) {
         if (this == obj) {
             return true;
@@ -254,7 +147,7 @@
             return false;
         }
         try {
-            KeyValue kv = (KeyValue) obj;
+            KeyValue kv = (KeyValue)obj;
             if (publicKey == null ) {
                 if (kv.getPublicKey() != null) {
                     return false;
@@ -269,4 +162,340 @@
 
         return true;
     }
+
+    @Override
+    public int hashCode() {
+        int result = 17;
+        if (publicKey != null) {
+            result = 31 * result + publicKey.hashCode();
+        }
+
+        return result;
+    }
+
+    static final class RSA extends DOMKeyValue {
+        // RSAKeyValue CryptoBinaries
+        private DOMCryptoBinary modulus, exponent;
+        private KeyFactory rsakf;
+
+        RSA(PublicKey key) throws KeyException {
+            super(key);
+            RSAPublicKey rkey = (RSAPublicKey)key;
+            exponent = new DOMCryptoBinary(rkey.getPublicExponent());
+            modulus = new DOMCryptoBinary(rkey.getModulus());
+        }
+
+        RSA(Element elem) throws MarshalException {
+            super(elem);
+        }
+
+        void marshalPublicKey(Node parent, Document doc, String dsPrefix,
+            DOMCryptoContext context) throws MarshalException {
+            Element rsaElem = DOMUtils.createElement(doc, "RSAKeyValue",
+                                                     XMLSignature.XMLNS,
+                                                     dsPrefix);
+            Element modulusElem = DOMUtils.createElement(doc, "Modulus",
+                                                         XMLSignature.XMLNS,
+                                                         dsPrefix);
+            Element exponentElem = DOMUtils.createElement(doc, "Exponent",
+                                                          XMLSignature.XMLNS,
+                                                          dsPrefix);
+            modulus.marshal(modulusElem, dsPrefix, context);
+            exponent.marshal(exponentElem, dsPrefix, context);
+            rsaElem.appendChild(modulusElem);
+            rsaElem.appendChild(exponentElem);
+            parent.appendChild(rsaElem);
+        }
+
+        PublicKey unmarshalKeyValue(Element kvtElem)
+            throws MarshalException
+        {
+            if (rsakf == null) {
+                try {
+                    rsakf = KeyFactory.getInstance("RSA");
+                } catch (NoSuchAlgorithmException e) {
+                    throw new RuntimeException
+                        ("unable to create RSA KeyFactory: " + e.getMessage());
+                }
+            }
+            Element modulusElem = DOMUtils.getFirstChildElement(kvtElem);
+            modulus = new DOMCryptoBinary(modulusElem.getFirstChild());
+            Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem);
+            exponent = new DOMCryptoBinary(exponentElem.getFirstChild());
+            RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus.getBigNum(),
+                                                         exponent.getBigNum());
+            return generatePublicKey(rsakf, spec);
+        }
+    }
+
+    static final class DSA extends DOMKeyValue {
+        // DSAKeyValue CryptoBinaries
+        private DOMCryptoBinary p, q, g, y, j; //, seed, pgen;
+        private KeyFactory dsakf;
+
+        DSA(PublicKey key) throws KeyException {
+            super(key);
+            DSAPublicKey dkey = (DSAPublicKey) key;
+            DSAParams params = dkey.getParams();
+            p = new DOMCryptoBinary(params.getP());
+            q = new DOMCryptoBinary(params.getQ());
+            g = new DOMCryptoBinary(params.getG());
+            y = new DOMCryptoBinary(dkey.getY());
+        }
+
+        DSA(Element elem) throws MarshalException {
+            super(elem);
+        }
+
+        void marshalPublicKey(Node parent, Document doc, String dsPrefix,
+                              DOMCryptoContext context)
+            throws MarshalException
+        {
+            Element dsaElem = DOMUtils.createElement(doc, "DSAKeyValue",
+                                                     XMLSignature.XMLNS,
+                                                     dsPrefix);
+            // parameters J, Seed & PgenCounter are not included
+            Element pElem = DOMUtils.createElement(doc, "P", XMLSignature.XMLNS,
+                                                   dsPrefix);
+            Element qElem = DOMUtils.createElement(doc, "Q", XMLSignature.XMLNS,
+                                                   dsPrefix);
+            Element gElem = DOMUtils.createElement(doc, "G", XMLSignature.XMLNS,
+                                                   dsPrefix);
+            Element yElem = DOMUtils.createElement(doc, "Y", XMLSignature.XMLNS,
+                                                   dsPrefix);
+            p.marshal(pElem, dsPrefix, context);
+            q.marshal(qElem, dsPrefix, context);
+            g.marshal(gElem, dsPrefix, context);
+            y.marshal(yElem, dsPrefix, context);
+            dsaElem.appendChild(pElem);
+            dsaElem.appendChild(qElem);
+            dsaElem.appendChild(gElem);
+            dsaElem.appendChild(yElem);
+            parent.appendChild(dsaElem);
+        }
+
+        PublicKey unmarshalKeyValue(Element kvtElem)
+            throws MarshalException
+        {
+            if (dsakf == null) {
+                try {
+                    dsakf = KeyFactory.getInstance("DSA");
+                } catch (NoSuchAlgorithmException e) {
+                    throw new RuntimeException
+                        ("unable to create DSA KeyFactory: " + e.getMessage());
+                }
+            }
+            Element curElem = DOMUtils.getFirstChildElement(kvtElem);
+            // check for P and Q
+            if (curElem.getLocalName().equals("P")) {
+                p = new DOMCryptoBinary(curElem.getFirstChild());
+                curElem = DOMUtils.getNextSiblingElement(curElem);
+                q = new DOMCryptoBinary(curElem.getFirstChild());
+                curElem = DOMUtils.getNextSiblingElement(curElem);
+            }
+            if (curElem.getLocalName().equals("G")) {
+                g = new DOMCryptoBinary(curElem.getFirstChild());
+                curElem = DOMUtils.getNextSiblingElement(curElem);
+            }
+            y = new DOMCryptoBinary(curElem.getFirstChild());
+            curElem = DOMUtils.getNextSiblingElement(curElem);
+            if (curElem != null && curElem.getLocalName().equals("J")) {
+                j = new DOMCryptoBinary(curElem.getFirstChild());
+                // curElem = DOMUtils.getNextSiblingElement(curElem);
+            }
+            /*
+            if (curElem != null) {
+                seed = new DOMCryptoBinary(curElem.getFirstChild());
+                curElem = DOMUtils.getNextSiblingElement(curElem);
+                pgen = new DOMCryptoBinary(curElem.getFirstChild());
+            }
+            */
+            //@@@ do we care about j, pgenCounter or seed?
+            DSAPublicKeySpec spec = new DSAPublicKeySpec(y.getBigNum(),
+                                                         p.getBigNum(),
+                                                         q.getBigNum(),
+                                                         g.getBigNum());
+            return generatePublicKey(dsakf, spec);
+        }
+    }
+
+    static final class EC extends DOMKeyValue {
+        // ECKeyValue CryptoBinaries
+        private byte[] ecPublicKey;
+        private KeyFactory eckf;
+        private ECParameterSpec ecParams;
+        private Method encodePoint, decodePoint, getCurveName,
+                       getECParameterSpec;
+
+        EC(PublicKey key) throws KeyException {
+            super(key);
+            ECPublicKey ecKey = (ECPublicKey)key;
+            ECPoint ecPoint = ecKey.getW();
+            ecParams = ecKey.getParams();
+            try {
+                AccessController.doPrivileged(
+                    new PrivilegedExceptionAction<Void>() {
+                        public Void run() throws
+                            ClassNotFoundException, NoSuchMethodException
+                        {
+                            getMethods();
+                            return null;
+                        }
+                    }
+                );
+            } catch (PrivilegedActionException pae) {
+                throw new KeyException("ECKeyValue not supported",
+                                        pae.getException());
+            }
+            Object[] args = new Object[] { ecPoint, ecParams.getCurve() };
+            try {
+                ecPublicKey = (byte[])encodePoint.invoke(null, args);
+            } catch (IllegalAccessException iae) {
+                throw new KeyException(iae);
+            } catch (InvocationTargetException ite) {
+                throw new KeyException(ite);
+            }
+        }
+
+        EC(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+
+        void getMethods() throws ClassNotFoundException, NoSuchMethodException {
+            Class c  = Class.forName("sun.security.ec.ECParameters");
+            Class[] params = new Class[] { ECPoint.class, EllipticCurve.class };
+            encodePoint = c.getMethod("encodePoint", params);
+            params = new Class[] { ECParameterSpec.class };
+            getCurveName = c.getMethod("getCurveName", params);
+            params = new Class[] { byte[].class, EllipticCurve.class };
+            decodePoint = c.getMethod("decodePoint", params);
+            c  = Class.forName("sun.security.ec.NamedCurve");
+            params = new Class[] { String.class };
+            getECParameterSpec = c.getMethod("getECParameterSpec", params);
+        }
+
+        void marshalPublicKey(Node parent, Document doc, String dsPrefix,
+                              DOMCryptoContext context)
+            throws MarshalException
+        {
+            String prefix = DOMUtils.getNSPrefix(context, XMLDSIG_11_XMLNS);
+            Element ecKeyValueElem = DOMUtils.createElement(doc, "ECKeyValue",
+                                                            XMLDSIG_11_XMLNS,
+                                                            prefix);
+            Element namedCurveElem = DOMUtils.createElement(doc, "NamedCurve",
+                                                            XMLDSIG_11_XMLNS,
+                                                            prefix);
+            Element publicKeyElem = DOMUtils.createElement(doc, "PublicKey",
+                                                           XMLDSIG_11_XMLNS,
+                                                           prefix);
+            Object[] args = new Object[] { ecParams };
+            try {
+                String oid = (String) getCurveName.invoke(null, args);
+                DOMUtils.setAttribute(namedCurveElem, "URI", "urn:oid:" + oid);
+            } catch (IllegalAccessException iae) {
+                throw new MarshalException(iae);
+            } catch (InvocationTargetException ite) {
+                throw new MarshalException(ite);
+            }
+            String qname = (prefix == null || prefix.length() == 0)
+                       ? "xmlns" : "xmlns:" + prefix;
+            namedCurveElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
+                                          qname, XMLDSIG_11_XMLNS);
+            ecKeyValueElem.appendChild(namedCurveElem);
+            String encoded = Base64.encode(ecPublicKey);
+            publicKeyElem.appendChild
+                (DOMUtils.getOwnerDocument(publicKeyElem).createTextNode(encoded));
+            ecKeyValueElem.appendChild(publicKeyElem);
+            parent.appendChild(ecKeyValueElem);
+        }
+
+        PublicKey unmarshalKeyValue(Element kvtElem)
+            throws MarshalException
+        {
+            if (eckf == null) {
+                try {
+                    eckf = KeyFactory.getInstance("EC");
+                } catch (NoSuchAlgorithmException e) {
+                    throw new RuntimeException
+                        ("unable to create EC KeyFactory: " + e.getMessage());
+                }
+            }
+            try {
+                AccessController.doPrivileged(
+                    new PrivilegedExceptionAction<Void>() {
+                        public Void run() throws
+                            ClassNotFoundException, NoSuchMethodException
+                        {
+                            getMethods();
+                            return null;
+                        }
+                    }
+                );
+            } catch (PrivilegedActionException pae) {
+                throw new MarshalException("ECKeyValue not supported",
+                                           pae.getException());
+            }
+            ECParameterSpec ecParams = null;
+            Element curElem = DOMUtils.getFirstChildElement(kvtElem);
+            if (curElem.getLocalName().equals("ECParameters")) {
+                throw new UnsupportedOperationException
+                    ("ECParameters not supported");
+            } else if (curElem.getLocalName().equals("NamedCurve")) {
+                String uri = DOMUtils.getAttributeValue(curElem, "URI");
+                // strip off "urn:oid"
+                if (uri.startsWith("urn:oid:")) {
+                    String oid = uri.substring(8);
+                    try {
+                        Object[] args = new Object[] { oid };
+                        ecParams = (ECParameterSpec)
+                                    getECParameterSpec.invoke(null, args);
+                    } catch (IllegalAccessException iae) {
+                        throw new MarshalException(iae);
+                    } catch (InvocationTargetException ite) {
+                        throw new MarshalException(ite);
+                    }
+                } else {
+                    throw new MarshalException("Invalid NamedCurve URI");
+                }
+            } else {
+                throw new MarshalException("Invalid ECKeyValue");
+            }
+            curElem = DOMUtils.getNextSiblingElement(curElem);
+            ECPoint ecPoint = null;
+            try {
+                Object[] args = new Object[] { Base64.decode(curElem),
+                                               ecParams.getCurve() };
+                ecPoint = (ECPoint)decodePoint.invoke(null, args);
+            } catch (Base64DecodingException bde) {
+                throw new MarshalException("Invalid EC PublicKey", bde);
+            } catch (IllegalAccessException iae) {
+                throw new MarshalException(iae);
+            } catch (InvocationTargetException ite) {
+                throw new MarshalException(ite);
+            }
+/*
+                ecPoint = sun.security.ec.ECParameters.decodePoint(
+                    Base64.decode(curElem), ecParams.getCurve());
+*/
+            ECPublicKeySpec spec = new ECPublicKeySpec(ecPoint, ecParams);
+            return generatePublicKey(eckf, spec);
+        }
+    }
+
+    static final class Unknown extends DOMKeyValue {
+        private javax.xml.crypto.dom.DOMStructure externalPublicKey;
+        Unknown(Element elem) throws MarshalException {
+            super(elem);
+        }
+        PublicKey unmarshalKeyValue(Element kvElem) throws MarshalException {
+            externalPublicKey = new javax.xml.crypto.dom.DOMStructure(kvElem);
+            return null;
+        }
+        void marshalPublicKey(Node parent, Document doc, String dsPrefix,
+                              DOMCryptoContext context)
+            throws MarshalException
+        {
+            parent.appendChild(externalPublicKey.getNode());
+        }
+    }
 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMManifest.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMManifest.java 1333415 2012-05-03 12:03:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -32,6 +34,7 @@
 
 import java.security.Provider;
 import java.util.*;
+
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -44,7 +47,7 @@
  */
 public final class DOMManifest extends DOMStructure implements Manifest {
 
-    private final List references;
+    private final List<Reference> references;
     private final String id;
 
     /**
@@ -60,22 +63,22 @@
      * @throws ClassCastException if <code>references</code> contains any
      *    entries that are not of type {@link Reference}
      */
-    public DOMManifest(List references, String id) {
+    public DOMManifest(List<? extends Reference> references, String id) {
         if (references == null) {
             throw new NullPointerException("references cannot be null");
         }
-        List refCopy = new ArrayList(references);
-        if (refCopy.isEmpty()) {
+        this.references =
+            Collections.unmodifiableList(new ArrayList<Reference>(references));
+        if (this.references.isEmpty()) {
             throw new IllegalArgumentException("list of references must " +
                 "contain at least one entry");
         }
-        for (int i = 0, size = refCopy.size(); i < size; i++) {
-            if (!(refCopy.get(i) instanceof Reference)) {
+        for (int i = 0, size = this.references.size(); i < size; i++) {
+            if (!(this.references.get(i) instanceof Reference)) {
                 throw new ClassCastException
                     ("references["+i+"] is not a valid type");
             }
         }
-        this.references = Collections.unmodifiableList(refCopy);
         this.id = id;
     }
 
@@ -85,7 +88,9 @@
      * @param manElem a Manifest element
      */
     public DOMManifest(Element manElem, XMLCryptoContext context,
-        Provider provider) throws MarshalException {
+                       Provider provider)
+        throws MarshalException
+    {
         Attr attr = manElem.getAttributeNodeNS(null, "Id");
         if (attr != null) {
             this.id = attr.getValue();
@@ -95,8 +100,10 @@
         }
 
         boolean secVal = Utils.secureValidation(context);
+
         Element refElem = DOMUtils.getFirstChildElement(manElem);
-        List refs = new ArrayList();
+        List<Reference> refs = new ArrayList<Reference>();
+
         int refCount = 0;
         while (refElem != null) {
             refs.add(new DOMReference(refElem, context, provider));
@@ -104,10 +111,8 @@
 
             refCount++;
             if (secVal && (refCount > DOMSignedInfo.MAXIMUM_REFERENCE_COUNT)) {
-                String error = "A maxiumum of " +
-                               DOMSignedInfo.MAXIMUM_REFERENCE_COUNT +
-                               " references per Manifest are allowed with" +
-                               " secure validation";
+                String error = "A maxiumum of " + DOMSignedInfo.MAXIMUM_REFERENCE_COUNT + " "
+                    + "references per Manifest are allowed with secure validation";
                 throw new MarshalException(error);
             }
         }
@@ -123,22 +128,22 @@
     }
 
     public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException {
+        throws MarshalException
+    {
         Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
-        Element manElem = DOMUtils.createElement
-            (ownerDoc, "Manifest", XMLSignature.XMLNS, dsPrefix);
+        Element manElem = DOMUtils.createElement(ownerDoc, "Manifest",
+                                                 XMLSignature.XMLNS, dsPrefix);
 
         DOMUtils.setAttributeID(manElem, "Id", id);
 
         // add references
-        for (int i = 0, size = references.size(); i < size; i++) {
-            DOMReference ref = (DOMReference) references.get(i);
-            ref.marshal(manElem, dsPrefix, context);
+        for (Reference ref : references) {
+            ((DOMReference)ref).marshal(manElem, dsPrefix, context);
         }
         parent.appendChild(manElem);
     }
 
+    @Override
     public boolean equals(Object o) {
         if (this == o) {
             return true;
@@ -147,11 +152,22 @@
         if (!(o instanceof Manifest)) {
             return false;
         }
-        Manifest oman = (Manifest) o;
+        Manifest oman = (Manifest)o;
 
-        boolean idsEqual = (id == null ? oman.getId() == null :
-            id.equals(oman.getId()));
+        boolean idsEqual = (id == null ? oman.getId() == null
+                                       : id.equals(oman.getId()));
 
         return (idsEqual && references.equals(oman.getReferences()));
     }
+
+    @Override
+    public int hashCode() {
+        int result = 17;
+        if (id != null) {
+            result = 31 * result + id.hashCode();
+        }
+        result = 31 * result + references.hashCode();
+
+        return result;
+    }
 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMPGPData.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMPGPData.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMPGPData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMPGPData.java 1203846 2011-11-18 21:18:17Z mullan $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -48,7 +50,7 @@
 
     private final byte[] keyId;
     private final byte[] keyPacket;
-    private final List externalElements;
+    private final List<XMLStructure> externalElements;
 
     /**
      * Creates a <code>DOMPGPData</code> containing the specified key packet.
@@ -67,23 +69,23 @@
      * @throws ClassCastException if <code>other</code> contains any
      *    entries that are not of type {@link XMLStructure}
      */
-    public DOMPGPData(byte[] keyPacket, List other) {
+    public DOMPGPData(byte[] keyPacket, List<? extends XMLStructure> other) {
         if (keyPacket == null) {
             throw new NullPointerException("keyPacket cannot be null");
         }
         if (other == null || other.isEmpty()) {
-            this.externalElements = Collections.EMPTY_LIST;
+            this.externalElements = Collections.emptyList();
         } else {
-            List otherCopy = new ArrayList(other);
-            for (int i = 0, size = otherCopy.size(); i < size; i++) {
-                if (!(otherCopy.get(i) instanceof XMLStructure)) {
+            this.externalElements =
+                Collections.unmodifiableList(new ArrayList<XMLStructure>(other));
+            for (int i = 0, size = this.externalElements.size(); i < size; i++) {
+                if (!(this.externalElements.get(i) instanceof XMLStructure)) {
                     throw new ClassCastException
                         ("other["+i+"] is not a valid PGPData type");
                 }
             }
-            this.externalElements = Collections.unmodifiableList(otherCopy);
         }
-        this.keyPacket = (byte []) keyPacket.clone();
+        this.keyPacket = (byte[])keyPacket.clone();
         checkKeyPacket(keyPacket);
         this.keyId = null;
     }
@@ -108,7 +110,9 @@
      * @throws ClassCastException if <code>other</code> contains any
      *    entries that are not of type {@link XMLStructure}
      */
-    public DOMPGPData(byte[] keyId, byte[] keyPacket, List other) {
+    public DOMPGPData(byte[] keyId, byte[] keyPacket,
+                      List<? extends XMLStructure> other)
+    {
         if (keyId == null) {
             throw new NullPointerException("keyId cannot be null");
         }
@@ -117,19 +121,20 @@
             throw new IllegalArgumentException("keyId must be 8 bytes long");
         }
         if (other == null || other.isEmpty()) {
-            this.externalElements = Collections.EMPTY_LIST;
+            this.externalElements = Collections.emptyList();
         } else {
-            List otherCopy = new ArrayList(other);
-            for (int i = 0, size = otherCopy.size(); i < size; i++) {
-                if (!(otherCopy.get(i) instanceof XMLStructure)) {
+            this.externalElements =
+                Collections.unmodifiableList(new ArrayList<XMLStructure>(other));
+            for (int i = 0, size = this.externalElements.size(); i < size; i++) {
+                if (!(this.externalElements.get(i) instanceof XMLStructure)) {
                     throw new ClassCastException
                         ("other["+i+"] is not a valid PGPData type");
                 }
             }
-            this.externalElements = Collections.unmodifiableList(otherCopy);
         }
-        this.keyId = (byte []) keyId.clone();
-        this.keyPacket = keyPacket == null ? null : (byte []) keyPacket.clone();
+        this.keyId = (byte[])keyId.clone();
+        this.keyPacket = keyPacket == null ? null
+                                           : (byte[])keyPacket.clone();
         if (keyPacket != null) {
             checkKeyPacket(keyPacket);
         }
@@ -146,11 +151,11 @@
         byte[] keyPacket = null;
         NodeList nl = pdElem.getChildNodes();
         int length = nl.getLength();
-        List other = new ArrayList(length);
+        List<XMLStructure> other = new ArrayList<XMLStructure>(length);
         for (int x = 0; x < length; x++) {
             Node n = nl.item(x);
             if (n.getNodeType() == Node.ELEMENT_NODE) {
-                Element childElem = (Element) n;
+                Element childElem = (Element)n;
                 String localName = childElem.getLocalName();
                 try {
                     if (localName.equals("PGPKeyID")) {
@@ -172,11 +177,11 @@
     }
 
     public byte[] getKeyId() {
-        return (keyId == null ? null : (byte []) keyId.clone());
+        return (keyId == null ? null : (byte[])keyId.clone());
     }
 
     public byte[] getKeyPacket() {
-        return (keyPacket == null ? null : (byte []) keyPacket.clone());
+        return (keyPacket == null ? null : (byte[])keyPacket.clone());
     }
 
     public List getExternalElements() {
@@ -184,16 +189,17 @@
     }
 
     public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException {
+        throws MarshalException
+    {
         Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
-        Element pdElem = DOMUtils.createElement
-            (ownerDoc, "PGPData", XMLSignature.XMLNS, dsPrefix);
+        Element pdElem = DOMUtils.createElement(ownerDoc, "PGPData",
+                                                XMLSignature.XMLNS, dsPrefix);
 
         // create and append PGPKeyID element
         if (keyId != null) {
-            Element keyIdElem = DOMUtils.createElement
-                (ownerDoc, "PGPKeyID", XMLSignature.XMLNS, dsPrefix);
+            Element keyIdElem = DOMUtils.createElement(ownerDoc, "PGPKeyID",
+                                                       XMLSignature.XMLNS,
+                                                       dsPrefix);
             keyIdElem.appendChild
                 (ownerDoc.createTextNode(Base64.encode(keyId)));
             pdElem.appendChild(keyIdElem);
@@ -201,17 +207,19 @@
 
         // create and append PGPKeyPacket element
         if (keyPacket != null) {
-            Element keyPktElem = DOMUtils.createElement
-                (ownerDoc, "PGPKeyPacket", XMLSignature.XMLNS, dsPrefix);
+            Element keyPktElem = DOMUtils.createElement(ownerDoc,
+                                                        "PGPKeyPacket",
+                                                        XMLSignature.XMLNS,
+                                                        dsPrefix);
             keyPktElem.appendChild
                 (ownerDoc.createTextNode(Base64.encode(keyPacket)));
             pdElem.appendChild(keyPktElem);
         }
 
         // create and append any elements
-        for (int i = 0, size = externalElements.size(); i < size; i++) {
+        for (XMLStructure extElem : externalElements) {
             DOMUtils.appendChild(pdElem, ((javax.xml.crypto.dom.DOMStructure)
-                externalElements.get(i)).getNode());
+                extElem).getNode());
         }
 
         parent.appendChild(pdElem);
@@ -229,26 +237,26 @@
         // and minimally one byte of content
         if (keyPacket.length < 3) {
             throw new IllegalArgumentException("keypacket must be at least " +
-                "3 bytes long");
+                                               "3 bytes long");
         }
 
         int tag = keyPacket[0];
         // first bit must be set
         if ((tag & 128) != 128) {
             throw new IllegalArgumentException("keypacket tag is invalid: " +
-                "bit 7 is not set");
+                                               "bit 7 is not set");
         }
         // make sure using new format
         if ((tag & 64) != 64) {
             throw new IllegalArgumentException("old keypacket tag format is " +
-                "unsupported");
+                                               "unsupported");
         }
 
         // tag value must be 6, 14, 5 or 7
         if (((tag & 6) != 6) && ((tag & 14) != 14) &&
             ((tag & 5) != 5) && ((tag & 7) != 7)) {
             throw new IllegalArgumentException("keypacket tag is invalid: " +
-                "must be 6, 14, 5, or 7");
+                                               "must be 6, 14, 5, or 7");
         }
     }
 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
@@ -29,7 +31,7 @@
  * ===========================================================================
  */
 /*
- * $Id: DOMReference.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMReference.java 1334007 2012-05-04 14:59:46Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -43,8 +45,6 @@
 import java.net.URISyntaxException;
 import java.security.*;
 import java.util.*;
-import java.util.logging.Level;
-import java.util.logging.Logger;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -66,11 +66,10 @@
 public final class DOMReference extends DOMStructure
     implements Reference, DOMURIReference {
 
-    /**
-     * The maximum number of transforms per reference, if secure validation
-     * is enabled.
-     */
-    public static final int MAXIMUM_TRANSFORM_COUNT = 5;
+   /**
+    * The maximum number of transforms per reference, if secure validation is enabled.
+    */
+   public static final int MAXIMUM_TRANSFORM_COUNT = 5;
 
    /**
     * Look up useC14N11 system property. If true, an explicit C14N11 transform
@@ -82,17 +81,18 @@
     private static boolean useC14N11 =
         AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
             public Boolean run() {
-                return Boolean.getBoolean
-                    ("com.sun.org.apache.xml.internal.security.useC14N11");
+                return Boolean.valueOf(Boolean.getBoolean
+                    ("com.sun.org.apache.xml.internal.security.useC14N11"));
             }
         });
 
-    private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom");
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
 
     private final DigestMethod digestMethod;
     private final String id;
-    private final List transforms;
-    private List allTransforms;
+    private final List<Transform> transforms;
+    private List<Transform> allTransforms;
     private final Data appliedTransformData;
     private Attr here;
     private final String uri;
@@ -124,46 +124,51 @@
      *    not of type <code>Transform</code>
      */
     public DOMReference(String uri, String type, DigestMethod dm,
-        List transforms, String id, Provider provider) {
+                        List<? extends Transform> transforms, String id,
+                        Provider provider)
+    {
         this(uri, type, dm, null, null, transforms, id, null, provider);
     }
 
     public DOMReference(String uri, String type, DigestMethod dm,
-        List appliedTransforms, Data result, List transforms, String id,
-        Provider provider) {
+                        List<? extends Transform> appliedTransforms,
+                        Data result, List<? extends Transform> transforms,
+                        String id, Provider provider)
+    {
         this(uri, type, dm, appliedTransforms,
              result, transforms, id, null, provider);
     }
 
     public DOMReference(String uri, String type, DigestMethod dm,
-        List appliedTransforms, Data result, List transforms, String id,
-        byte[] digestValue, Provider provider) {
+                        List<? extends Transform> appliedTransforms,
+                        Data result, List<? extends Transform> transforms,
+                        String id, byte[] digestValue, Provider provider)
+    {
         if (dm == null) {
             throw new NullPointerException("DigestMethod must be non-null");
         }
-        this.allTransforms = new ArrayList();
-        if (appliedTransforms != null) {
-            List transformsCopy = new ArrayList(appliedTransforms);
-            for (int i = 0, size = transformsCopy.size(); i < size; i++) {
-                if (!(transformsCopy.get(i) instanceof Transform)) {
+        if (appliedTransforms == null) {
+            this.allTransforms = new ArrayList<Transform>();
+        } else {
+            this.allTransforms = new ArrayList<Transform>(appliedTransforms);
+            for (int i = 0, size = this.allTransforms.size(); i < size; i++) {
+                if (!(this.allTransforms.get(i) instanceof Transform)) {
                     throw new ClassCastException
                         ("appliedTransforms["+i+"] is not a valid type");
                 }
             }
-            this.allTransforms = transformsCopy;
         }
         if (transforms == null) {
-            this.transforms = Collections.EMPTY_LIST;
+            this.transforms = Collections.emptyList();
         } else {
-            List transformsCopy = new ArrayList(transforms);
-            for (int i = 0, size = transformsCopy.size(); i < size; i++) {
-                if (!(transformsCopy.get(i) instanceof Transform)) {
+            this.transforms = new ArrayList<Transform>(transforms);
+            for (int i = 0, size = this.transforms.size(); i < size; i++) {
+                if (!(this.transforms.get(i) instanceof Transform)) {
                     throw new ClassCastException
                         ("transforms["+i+"] is not a valid type");
                 }
             }
-            this.transforms = transformsCopy;
-            this.allTransforms.addAll(transformsCopy);
+            this.allTransforms.addAll(this.transforms);
         }
         this.digestMethod = dm;
         this.uri = uri;
@@ -177,7 +182,7 @@
         this.type = type;
         this.id = id;
         if (digestValue != null) {
-            this.digestValue = (byte[]) digestValue.clone();
+            this.digestValue = (byte[])digestValue.clone();
             this.digested = true;
         }
         this.appliedTransformData = result;
@@ -190,12 +195,14 @@
      * @param refElem a Reference element
      */
     public DOMReference(Element refElem, XMLCryptoContext context,
-        Provider provider) throws MarshalException {
+                        Provider provider)
+        throws MarshalException
+    {
         boolean secVal = Utils.secureValidation(context);
 
         // unmarshal Transforms, if specified
         Element nextSibling = DOMUtils.getFirstChildElement(refElem);
-        List transforms = new ArrayList(5);
+        List<Transform> transforms = new ArrayList<Transform>(5);
         if (nextSibling.getLocalName().equals("Transforms")) {
             Element transformElem = DOMUtils.getFirstChildElement(nextSibling);
 
@@ -207,9 +214,8 @@
 
                 transformCount++;
                 if (secVal && (transformCount > MAXIMUM_TRANSFORM_COUNT)) {
-                    String error = "A maxiumum of " + MAXIMUM_TRANSFORM_COUNT +
-                                   " transforms per Reference are allowed" +
-                                   " with secure validation";
+                    String error = "A maxiumum of " + MAXIMUM_TRANSFORM_COUNT + " "
+                        + "transforms per Reference are allowed with secure validation";
                     throw new MarshalException(error);
                 }
             }
@@ -221,11 +227,10 @@
         this.digestMethod = DOMDigestMethod.unmarshal(dmElem);
         String digestMethodAlgorithm = this.digestMethod.getAlgorithm();
         if (secVal
-            && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(digestMethodAlgorithm))
-        {
-             throw new MarshalException("It is forbidden to use algorithm " +
-                                        digestMethod +
-                                        " when secure validation is enabled");
+            && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(digestMethodAlgorithm)) {
+            throw new MarshalException(
+                "It is forbidden to use algorithm " + digestMethod + " when secure validation is enabled"
+            );
         }
 
         // unmarshal DigestValue
@@ -277,23 +282,24 @@
     }
 
     public byte[] getDigestValue() {
-        return (digestValue == null ? null : (byte[]) digestValue.clone());
+        return (digestValue == null ? null : (byte[])digestValue.clone());
     }
 
     public byte[] getCalculatedDigestValue() {
         return (calcDigestValue == null ? null
-                : (byte[]) calcDigestValue.clone());
+                                        : (byte[])calcDigestValue.clone());
     }
 
     public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException {
-        if (log.isLoggable(Level.FINE)) {
-            log.log(Level.FINE, "Marshalling Reference");
+        throws MarshalException
+    {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Marshalling Reference");
         }
         Document ownerDoc = DOMUtils.getOwnerDocument(parent);
 
-        refElem = DOMUtils.createElement
-            (ownerDoc, "Reference", XMLSignature.XMLNS, dsPrefix);
+        refElem = DOMUtils.createElement(ownerDoc, "Reference",
+                                         XMLSignature.XMLNS, dsPrefix);
 
         // set attributes
         DOMUtils.setAttributeID(refElem, "Id", id);
@@ -302,25 +308,28 @@
 
         // create and append Transforms element
         if (!allTransforms.isEmpty()) {
-            Element transformsElem = DOMUtils.createElement
-                (ownerDoc, "Transforms", XMLSignature.XMLNS, dsPrefix);
+            Element transformsElem = DOMUtils.createElement(ownerDoc,
+                                                            "Transforms",
+                                                            XMLSignature.XMLNS,
+                                                            dsPrefix);
             refElem.appendChild(transformsElem);
-            for (int i = 0, size = allTransforms.size(); i < size; i++) {
-                DOMStructure transform =
-                    (DOMStructure) allTransforms.get(i);
-                transform.marshal(transformsElem, dsPrefix, context);
+            for (Transform transform : allTransforms) {
+                ((DOMStructure)transform).marshal(transformsElem,
+                                                  dsPrefix, context);
             }
         }
 
         // create and append DigestMethod element
-        ((DOMDigestMethod) digestMethod).marshal(refElem, dsPrefix, context);
+        ((DOMDigestMethod)digestMethod).marshal(refElem, dsPrefix, context);
 
         // create and append DigestValue element
-        if (log.isLoggable(Level.FINE)) {
-            log.log(Level.FINE, "Adding digestValueElem");
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Adding digestValueElem");
         }
-        Element digestValueElem = DOMUtils.createElement
-            (ownerDoc, "DigestValue", XMLSignature.XMLNS, dsPrefix);
+        Element digestValueElem = DOMUtils.createElement(ownerDoc,
+                                                         "DigestValue",
+                                                         XMLSignature.XMLNS,
+                                                         dsPrefix);
         if (digestValue != null) {
             digestValueElem.appendChild
                 (ownerDoc.createTextNode(Base64.encode(digestValue)));
@@ -332,7 +341,8 @@
     }
 
     public void digest(XMLSignContext signContext)
-        throws XMLSignatureException {
+        throws XMLSignatureException
+    {
         Data data = null;
         if (appliedTransformData == null) {
             data = dereference(signContext);
@@ -343,8 +353,8 @@
 
         // insert digestValue into DigestValue element
         String encodedDV = Base64.encode(digestValue);
-        if (log.isLoggable(Level.FINE)) {
-            log.log(Level.FINE, "Reference object uri = " + uri);
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Reference object uri = " + uri);
         }
         Element digestElem = DOMUtils.getLastChildElement(refElem);
         if (digestElem == null) {
@@ -355,13 +365,14 @@
             (refElem.getOwnerDocument().createTextNode(encodedDV));
 
         digested = true;
-        if (log.isLoggable(Level.FINE)) {
-            log.log(Level.FINE, "Reference digesting completed");
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Reference digesting completed");
         }
     }
 
     public boolean validate(XMLValidateContext validateContext)
-        throws XMLSignatureException {
+        throws XMLSignatureException
+    {
         if (validateContext == null) {
             throw new NullPointerException("validateContext cannot be null");
         }
@@ -371,11 +382,9 @@
         Data data = dereference(validateContext);
         calcDigestValue = transform(data, validateContext);
 
-        if (log.isLoggable(Level.FINE)) {
-            log.log(Level.FINE, "Expected digest: "
-                + Base64.encode(digestValue));
-            log.log(Level.FINE, "Actual digest: "
-                + Base64.encode(calcDigestValue));
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Expected digest: " + Base64.encode(digestValue));
+            log.log(java.util.logging.Level.FINE, "Actual digest: " + Base64.encode(calcDigestValue));
         }
 
         validationStatus = Arrays.equals(digestValue, calcDigestValue);
@@ -392,7 +401,8 @@
     }
 
     private Data dereference(XMLCryptoContext context)
-        throws XMLSignatureException {
+        throws XMLSignatureException
+    {
         Data data = null;
 
         // use user-specified URIDereferencer if specified; otherwise use deflt
@@ -402,11 +412,9 @@
         }
         try {
             data = deref.dereference(this, context);
-            if (log.isLoggable(Level.FINE)) {
-                log.log(Level.FINE, "URIDereferencer class name: "
-                    + deref.getClass().getName());
-                log.log(Level.FINE, "Data class name: "
-                    + data.getClass().getName());
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "URIDereferencer class name: " + deref.getClass().getName());
+                log.log(java.util.logging.Level.FINE, "Data class name: " + data.getClass().getName());
             }
         } catch (URIReferenceException ure) {
             throw new XMLSignatureException(ure);
@@ -416,12 +424,13 @@
     }
 
     private byte[] transform(Data dereferencedData,
-        XMLCryptoContext context) throws XMLSignatureException {
-
+                             XMLCryptoContext context)
+        throws XMLSignatureException
+    {
         if (md == null) {
             try {
                 md = MessageDigest.getInstance
-                    (((DOMDigestMethod) digestMethod).getMessageDigestAlgorithm());
+                    (((DOMDigestMethod)digestMethod).getMessageDigestAlgorithm());
             } catch (NoSuchAlgorithmException nsae) {
                 throw new XMLSignatureException(nsae);
             }
@@ -430,28 +439,25 @@
         DigesterOutputStream dos;
         Boolean cache = (Boolean)
             context.getProperty("javax.xml.crypto.dsig.cacheReference");
-        if (cache != null && cache.booleanValue() == true) {
+        if (cache != null && cache.booleanValue()) {
             this.derefData = copyDerefData(dereferencedData);
             dos = new DigesterOutputStream(md, true);
         } else {
             dos = new DigesterOutputStream(md);
         }
-        OutputStream os = new UnsyncBufferedOutputStream(dos);
+        OutputStream os = null;
         Data data = dereferencedData;
-        for (int i = 0, size = transforms.size(); i < size; i++) {
-            DOMTransform transform = (DOMTransform) transforms.get(i);
-            try {
+        try {
+            os = new UnsyncBufferedOutputStream(dos);
+            for (int i = 0, size = transforms.size(); i < size; i++) {
+                DOMTransform transform = (DOMTransform)transforms.get(i);
                 if (i < size - 1) {
                     data = transform.transform(data, context);
                 } else {
                     data = transform.transform(data, context, os);
                 }
-            } catch (TransformException te) {
-                throw new XMLSignatureException(te);
             }
-        }
 
-        try {
             if (data != null) {
                 XMLSignatureInput xi;
                 // explicitly use C14N 1.1 when generating signature
@@ -460,9 +466,9 @@
                 String c14nalg = CanonicalizationMethod.INCLUSIVE;
                 if (context instanceof XMLSignContext) {
                     if (!c14n11) {
-                        Boolean prop = (Boolean) context.getProperty
+                        Boolean prop = (Boolean)context.getProperty
                             ("com.sun.org.apache.xml.internal.security.useC14N11");
-                        c14n11 = (prop != null && prop.booleanValue() == true);
+                        c14n11 = (prop != null && prop.booleanValue());
                         if (c14n11) {
                             c14nalg = "http://www.w3.org/2006/12/xml-c14n11";
                         }
@@ -471,17 +477,20 @@
                     }
                 }
                 if (data instanceof ApacheData) {
-                    xi = ((ApacheData) data).getXMLSignatureInput();
+                    xi = ((ApacheData)data).getXMLSignatureInput();
                 } else if (data instanceof OctetStreamData) {
                     xi = new XMLSignatureInput
                         (((OctetStreamData)data).getOctetStream());
                 } else if (data instanceof NodeSetData) {
                     TransformService spi = null;
-                    try {
+                    if (provider == null) {
                         spi = TransformService.getInstance(c14nalg, "DOM");
-                    } catch (NoSuchAlgorithmException nsae) {
-                        spi = TransformService.getInstance
-                            (c14nalg, "DOM", provider);
+                    } else {
+                        try {
+                            spi = TransformService.getInstance(c14nalg, "DOM", provider);
+                        } catch (NoSuchAlgorithmException nsae) {
+                            spi = TransformService.getInstance(c14nalg, "DOM");
+                        }
                     }
                     data = spi.transform(data, context);
                     xi = new XMLSignatureInput
@@ -491,8 +500,18 @@
                 }
                 if (context instanceof XMLSignContext && c14n11
                     && !xi.isOctetStream() && !xi.isOutputStreamSet()) {
-                    DOMTransform t = new DOMTransform
-                        (TransformService.getInstance(c14nalg, "DOM"));
+                    TransformService spi = null;
+                    if (provider == null) {
+                        spi = TransformService.getInstance(c14nalg, "DOM");
+                    } else {
+                        try {
+                            spi = TransformService.getInstance(c14nalg, "DOM", provider);
+                        } catch (NoSuchAlgorithmException nsae) {
+                            spi = TransformService.getInstance(c14nalg, "DOM");
+                        }
+                    }
+
+                    DOMTransform t = new DOMTransform(spi);
                     Element transformsElem = null;
                     String dsPrefix = DOMUtils.getSignaturePrefix(context);
                     if (allTransforms.isEmpty()) {
@@ -504,7 +523,8 @@
                     } else {
                         transformsElem = DOMUtils.getFirstChildElement(refElem);
                     }
-                    t.marshal(transformsElem, dsPrefix, (DOMCryptoContext) context);
+                    t.marshal(transformsElem, dsPrefix,
+                              (DOMCryptoContext)context);
                     allTransforms.add(t);
                     xi.updateOutputStream(os, true);
                 } else {
@@ -512,12 +532,35 @@
                 }
             }
             os.flush();
-            if (cache != null && cache.booleanValue() == true) {
+            if (cache != null && cache.booleanValue()) {
                 this.dis = dos.getInputStream();
             }
             return dos.getDigestValue();
-        } catch (Exception e) {
+        } catch (NoSuchAlgorithmException e) {
+            throw new XMLSignatureException(e);
+        } catch (TransformException e) {
+            throw new XMLSignatureException(e);
+        } catch (MarshalException e) {
+            throw new XMLSignatureException(e);
+        } catch (IOException e) {
+            throw new XMLSignatureException(e);
+        } catch (com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException e) {
             throw new XMLSignatureException(e);
+        } finally {
+            if (os != null) {
+                try {
+                    os.close();
+                } catch (IOException e) {
+                    throw new XMLSignatureException(e);
+                }
+            }
+            if (dos != null) {
+                try {
+                    dos.close();
+                } catch (IOException e) {
+                    throw new XMLSignatureException(e);
+                }
+            }
         }
     }
 
@@ -525,6 +568,7 @@
         return here;
     }
 
+    @Override
     public boolean equals(Object o) {
         if (this == o) {
             return true;
@@ -533,19 +577,41 @@
         if (!(o instanceof Reference)) {
             return false;
         }
-        Reference oref = (Reference) o;
+        Reference oref = (Reference)o;
 
-        boolean idsEqual = (id == null ? oref.getId() == null :
-            id.equals(oref.getId()));
-        boolean urisEqual = (uri == null ? oref.getURI() == null :
-            uri.equals(oref.getURI()));
-        boolean typesEqual = (type == null ? oref.getType() == null :
-            type.equals(oref.getType()));
+        boolean idsEqual = (id == null ? oref.getId() == null
+                                       : id.equals(oref.getId()));
+        boolean urisEqual = (uri == null ? oref.getURI() == null
+                                         : uri.equals(oref.getURI()));
+        boolean typesEqual = (type == null ? oref.getType() == null
+                                           : type.equals(oref.getType()));
         boolean digestValuesEqual =
             Arrays.equals(digestValue, oref.getDigestValue());
 
-        return (digestMethod.equals(oref.getDigestMethod()) && idsEqual &&
-            urisEqual && typesEqual && allTransforms.equals(oref.getTransforms()));
+        return digestMethod.equals(oref.getDigestMethod()) && idsEqual &&
+            urisEqual && typesEqual &&
+            allTransforms.equals(oref.getTransforms()) && digestValuesEqual;
+    }
+
+    @Override
+    public int hashCode() {
+        int result = 17;
+        if (id != null) {
+            result = 31 * result + id.hashCode();
+        }
+        if (uri != null) {
+            result = 31 * result + uri.hashCode();
+        }
+        if (type != null) {
+            result = 31 * result + type.hashCode();
+        }
+        if (digestValue != null) {
+            result = 31 * result + Arrays.hashCode(digestValue);
+        }
+        result = 31 * result + digestMethod.hashCode();
+        result = 31 * result + allTransforms.hashCode();
+
+        return result;
     }
 
     boolean isDigested() {
@@ -555,18 +621,17 @@
     private static Data copyDerefData(Data dereferencedData) {
         if (dereferencedData instanceof ApacheData) {
             // need to make a copy of the Data
-            ApacheData ad = (ApacheData) dereferencedData;
+            ApacheData ad = (ApacheData)dereferencedData;
             XMLSignatureInput xsi = ad.getXMLSignatureInput();
             if (xsi.isNodeSet()) {
                 try {
-                    final Set s = xsi.getNodeSet();
+                    final Set<Node> s = xsi.getNodeSet();
                     return new NodeSetData() {
                         public Iterator iterator() { return s.iterator(); }
                     };
                 } catch (Exception e) {
                     // log a warning
-                            log.log(Level.WARNING,
-                        "cannot cache dereferenced data: " + e);
+                    log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + e);
                     return null;
                 }
             } else if (xsi.isElement()) {
@@ -574,12 +639,12 @@
                     (xsi.getSubNode(), xsi.isExcludeComments());
             } else if (xsi.isOctetStream() || xsi.isByteArray()) {
                 try {
-                return new OctetStreamData
-                  (xsi.getOctetStream(), xsi.getSourceURI(), xsi.getMIMEType());
+                    return new OctetStreamData
+                        (xsi.getOctetStream(), xsi.getSourceURI(),
+                         xsi.getMIMEType());
                 } catch (IOException ioe) {
                     // log a warning
-                            log.log(Level.WARNING,
-                        "cannot cache dereferenced data: " + ioe);
+                    log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + ioe);
                     return null;
                 }
             }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
@@ -29,7 +31,7 @@
  * ===========================================================================
  */
 /*
- * $Id: DOMRetrievalMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMRetrievalMethod.java 1333415 2012-05-03 12:03:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -38,6 +40,7 @@
 import java.net.URISyntaxException;
 import java.security.Provider;
 import java.util.*;
+
 import javax.xml.XMLConstants;
 import javax.xml.crypto.*;
 import javax.xml.crypto.dsig.*;
@@ -50,8 +53,6 @@
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
-import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
-
 /**
  * DOM-based implementation of RetrievalMethod.
  *
@@ -61,7 +62,7 @@
 public final class DOMRetrievalMethod extends DOMStructure
     implements RetrievalMethod, DOMURIReference {
 
-    private final List transforms;
+    private final List<Transform> transforms;
     private String uri;
     private String type;
     private Attr here;
@@ -83,24 +84,26 @@
      * @throws ClassCastException if <code>transforms</code> contains any
      *    entries that are not of type {@link Transform}
      */
-    public DOMRetrievalMethod(String uri, String type, List transforms) {
+    public DOMRetrievalMethod(String uri, String type,
+                              List<? extends Transform> transforms)
+    {
         if (uri == null) {
             throw new NullPointerException("uri cannot be null");
         }
         if (transforms == null || transforms.isEmpty()) {
-            this.transforms = Collections.EMPTY_LIST;
+            this.transforms = Collections.emptyList();
         } else {
-            List transformsCopy = new ArrayList(transforms);
-            for (int i = 0, size = transformsCopy.size(); i < size; i++) {
-                if (!(transformsCopy.get(i) instanceof Transform)) {
+            this.transforms = Collections.unmodifiableList(
+                new ArrayList<Transform>(transforms));
+            for (int i = 0, size = this.transforms.size(); i < size; i++) {
+                if (!(this.transforms.get(i) instanceof Transform)) {
                     throw new ClassCastException
                         ("transforms["+i+"] is not a valid type");
                 }
             }
-            this.transforms = Collections.unmodifiableList(transformsCopy);
         }
         this.uri = uri;
-        if ((uri != null) && (!uri.equals(""))) {
+        if (!uri.equals("")) {
             try {
                 new URI(uri);
             } catch (URISyntaxException e) {
@@ -117,7 +120,9 @@
      * @param rmElem a RetrievalMethod element
      */
     public DOMRetrievalMethod(Element rmElem, XMLCryptoContext context,
-        Provider provider) throws MarshalException {
+                              Provider provider)
+        throws MarshalException
+    {
         // get URI and Type attributes
         uri = DOMUtils.getAttributeValue(rmElem, "URI");
         type = DOMUtils.getAttributeValue(rmElem, "Type");
@@ -128,7 +133,7 @@
         boolean secVal = Utils.secureValidation(context);
 
         // get Transforms, if specified
-        List transforms = new ArrayList();
+        List<Transform> transforms = new ArrayList<Transform>();
         Element transformsElem = DOMUtils.getFirstChildElement(rmElem);
 
         int transformCount = 0;
@@ -141,19 +146,15 @@
                 transformElem = DOMUtils.getNextSiblingElement(transformElem);
 
                 transformCount++;
-                if (secVal &&
-                    (transformCount > DOMReference.MAXIMUM_TRANSFORM_COUNT))
-                {
-                    String error = "A maxiumum of " +
-                                   DOMReference.MAXIMUM_TRANSFORM_COUNT +
-                                   " transforms per Reference are allowed" +
-                                   " with secure validation";
+                if (secVal && (transformCount > DOMReference.MAXIMUM_TRANSFORM_COUNT)) {
+                    String error = "A maxiumum of " + DOMReference.MAXIMUM_TRANSFORM_COUNT + " "
+                        + "transforms per Reference are allowed with secure validation";
                     throw new MarshalException(error);
                 }
             }
         }
         if (transforms.isEmpty()) {
-            this.transforms = Collections.EMPTY_LIST;
+            this.transforms = Collections.emptyList();
         } else {
             this.transforms = Collections.unmodifiableList(transforms);
         }
@@ -172,11 +173,11 @@
     }
 
     public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException {
+        throws MarshalException
+    {
         Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
-        Element rmElem = DOMUtils.createElement
-            (ownerDoc, "RetrievalMethod", XMLSignature.XMLNS, dsPrefix);
+        Element rmElem = DOMUtils.createElement(ownerDoc, "RetrievalMethod",
+                                                XMLSignature.XMLNS, dsPrefix);
 
         // add URI and Type attributes
         DOMUtils.setAttribute(rmElem, "URI", uri);
@@ -184,12 +185,14 @@
 
         // add Transforms elements
         if (!transforms.isEmpty()) {
-            Element transformsElem = DOMUtils.createElement
-                (ownerDoc, "Transforms", XMLSignature.XMLNS, dsPrefix);
+            Element transformsElem = DOMUtils.createElement(ownerDoc,
+                                                            "Transforms",
+                                                            XMLSignature.XMLNS,
+                                                            dsPrefix);
             rmElem.appendChild(transformsElem);
-            for (int i = 0, size = transforms.size(); i < size; i++) {
-                ((DOMTransform) transforms.get(i)).marshal
-                    (transformsElem, dsPrefix, context);
+            for (Transform transform : transforms) {
+                ((DOMTransform)transform).marshal(transformsElem,
+                                                   dsPrefix, context);
             }
         }
 
@@ -204,8 +207,8 @@
     }
 
     public Data dereference(XMLCryptoContext context)
-        throws URIReferenceException {
-
+        throws URIReferenceException
+    {
         if (context == null) {
             throw new NullPointerException("context cannot be null");
         }
@@ -223,9 +226,8 @@
 
         // pass dereferenced data through Transforms
         try {
-            for (int i = 0, size = transforms.size(); i < size; i++) {
-                Transform transform = (Transform) transforms.get(i);
-                data = ((DOMTransform) transform).transform(data, context);
+            for (Transform transform : transforms) {
+                data = ((DOMTransform)transform).transform(data, context);
             }
         } catch (Exception e) {
             throw new URIReferenceException(e);
@@ -249,14 +251,13 @@
     }
 
     public XMLStructure dereferenceAsXMLStructure(XMLCryptoContext context)
-        throws URIReferenceException {
-
+        throws URIReferenceException
+    {
         try {
-            ApacheData data = (ApacheData) dereference(context);
+            ApacheData data = (ApacheData)dereference(context);
             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
             dbf.setNamespaceAware(true);
-            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
-                           Boolean.TRUE);
+            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
             DocumentBuilder db = dbf.newDocumentBuilder();
             Document doc = db.parse(new ByteArrayInputStream
                 (data.getXMLSignatureInput().getBytes()));
@@ -271,6 +272,7 @@
         }
     }
 
+    @Override
     public boolean equals(Object obj) {
         if (this == obj) {
             return true;
@@ -278,12 +280,24 @@
         if (!(obj instanceof RetrievalMethod)) {
             return false;
         }
-        RetrievalMethod orm = (RetrievalMethod) obj;
+        RetrievalMethod orm = (RetrievalMethod)obj;
 
-        boolean typesEqual = (type == null ? orm.getType() == null :
-            type.equals(orm.getType()));
+        boolean typesEqual = (type == null ? orm.getType() == null
+                                           : type.equals(orm.getType()));
 
         return (uri.equals(orm.getURI()) &&
             transforms.equals(orm.getTransforms()) && typesEqual);
     }
+
+    @Override
+    public int hashCode() {
+        int result = 17;
+        if (type != null) {
+            result = 31 * result + type.hashCode();
+        }
+        result = 31 * result + uri.hashCode();
+        result = 31 * result + transforms.hashCode();
+
+        return result;
+    }
 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,44 +2,42 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMSignatureMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMSignatureMethod.java 1333415 2012-05-03 12:03:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import javax.xml.crypto.*;
-import javax.xml.crypto.dom.DOMCryptoContext;
 import javax.xml.crypto.dsig.*;
 import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec;
 
 import java.io.IOException;
 import java.security.*;
 import java.security.spec.AlgorithmParameterSpec;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
-import org.w3c.dom.Node;
 
+import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA;
 import org.jcp.xml.dsig.internal.SignerOutputStream;
 
 /**
@@ -47,29 +45,30 @@
  *
  * @author Sean Mullan
  */
-public abstract class DOMSignatureMethod extends DOMStructure
-    implements SignatureMethod {
-
-    private static Logger log =
-        Logger.getLogger("org.jcp.xml.dsig.internal.dom");
+public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod {
 
-    // see RFC 4051 for these algorithm definitions
-    final static String RSA_SHA256 =
-        "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
-    final static String RSA_SHA384 =
-        "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384";
-    final static String RSA_SHA512 =
-        "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512";
-    final static String HMAC_SHA256 =
-        "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
-    final static String HMAC_SHA384 =
-        "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384";
-    final static String HMAC_SHA512 =
-        "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512";
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
 
     private SignatureMethodParameterSpec params;
     private Signature signature;
 
+    // see RFC 4051 for these algorithm definitions
+    static final String RSA_SHA256 =
+        "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
+    static final String RSA_SHA384 =
+        "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384";
+    static final String RSA_SHA512 =
+        "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512";
+    static final String ECDSA_SHA1 =
+        "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1";
+    static final String ECDSA_SHA256 =
+        "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256";
+    static final String ECDSA_SHA384 =
+        "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384";
+    static final String ECDSA_SHA512 =
+        "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512";
+
     /**
      * Creates a <code>DOMSignatureMethod</code>.
      *
@@ -78,19 +77,20 @@
      *    appropriate for this signature method
      */
     DOMSignatureMethod(AlgorithmParameterSpec params)
-        throws InvalidAlgorithmParameterException {
+        throws InvalidAlgorithmParameterException
+    {
         if (params != null &&
             !(params instanceof SignatureMethodParameterSpec)) {
             throw new InvalidAlgorithmParameterException
                 ("params must be of type SignatureMethodParameterSpec");
         }
-        checkParams((SignatureMethodParameterSpec) params);
-        this.params = (SignatureMethodParameterSpec) params;
+        checkParams((SignatureMethodParameterSpec)params);
+        this.params = (SignatureMethodParameterSpec)params;
     }
 
     /**
      * Creates a <code>DOMSignatureMethod</code> from an element. This ctor
-     * invokes the abstract {@link #unmarshalParams unmarshalParams} method to
+     * invokes the {@link #unmarshalParams unmarshalParams} method to
      * unmarshal any algorithm-specific input parameters.
      *
      * @param smElem a SignatureMethod element
@@ -119,13 +119,21 @@
             return new SHA512withRSA(smElem);
         } else if (alg.equals(SignatureMethod.DSA_SHA1)) {
             return new SHA1withDSA(smElem);
+        } else if (alg.equals(ECDSA_SHA1)) {
+            return new SHA1withECDSA(smElem);
+        } else if (alg.equals(ECDSA_SHA256)) {
+            return new SHA256withECDSA(smElem);
+        } else if (alg.equals(ECDSA_SHA384)) {
+            return new SHA384withECDSA(smElem);
+        } else if (alg.equals(ECDSA_SHA512)) {
+            return new SHA512withECDSA(smElem);
         } else if (alg.equals(SignatureMethod.HMAC_SHA1)) {
             return new DOMHMACSignatureMethod.SHA1(smElem);
-        } else if (alg.equals(HMAC_SHA256)) {
+        } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA256)) {
             return new DOMHMACSignatureMethod.SHA256(smElem);
-        } else if (alg.equals(HMAC_SHA384)) {
+        } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA384)) {
             return new DOMHMACSignatureMethod.SHA384(smElem);
-        } else if (alg.equals(HMAC_SHA512)) {
+        } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA512)) {
             return new DOMHMACSignatureMethod.SHA512(smElem);
         } else {
             throw new MarshalException
@@ -133,86 +141,14 @@
         }
     }
 
-    /**
-     * Checks if the specified parameters are valid for this algorithm. By
-     * default, this method throws an exception if parameters are specified
-     * since most SignatureMethod algorithms do not have parameters. Subclasses
-     * should override it if they have parameters.
-     *
-     * @param params the algorithm-specific params (may be <code>null</code>)
-     * @throws InvalidAlgorithmParameterException if the parameters are not
-     *    appropriate for this signature method
-     */
-    void checkParams(SignatureMethodParameterSpec params)
-        throws InvalidAlgorithmParameterException {
-        if (params != null) {
-            throw new InvalidAlgorithmParameterException("no parameters " +
-                "should be specified for the " + getSignatureAlgorithm()
-                 + " SignatureMethod algorithm");
-        }
-    }
-
     public final AlgorithmParameterSpec getParameterSpec() {
         return params;
     }
 
-    /**
-     * Unmarshals <code>SignatureMethodParameterSpec</code> from the specified
-     * <code>Element</code>. By default, this method throws an exception since
-     * most SignatureMethod algorithms do not have parameters. Subclasses should
-     * override it if they have parameters.
-     *
-     * @param paramsElem the <code>Element</code> holding the input params
-     * @return the algorithm-specific <code>SignatureMethodParameterSpec</code>
-     * @throws MarshalException if the parameters cannot be unmarshalled
-     */
-    SignatureMethodParameterSpec
-        unmarshalParams(Element paramsElem) throws MarshalException {
-        throw new MarshalException("no parameters should " +
-            "be specified for the " + getSignatureAlgorithm() +
-            " SignatureMethod algorithm");
-    }
-
-    /**
-     * This method invokes the abstract {@link #marshalParams marshalParams}
-     * method to marshal any algorithm-specific parameters.
-     */
-    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException {
-        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
-        Element smElem = DOMUtils.createElement
-            (ownerDoc, "SignatureMethod", XMLSignature.XMLNS, dsPrefix);
-        DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm());
-
-        if (params != null) {
-            marshalParams(smElem, dsPrefix);
-        }
-
-        parent.appendChild(smElem);
-    }
-
-    /**
-     * Verifies the passed-in signature with the specified key, using the
-     * underlying signature or MAC algorithm.
-     *
-     * @param key the verification key
-     * @param si the DOMSignedInfo
-     * @param signature the signature bytes to be verified
-     * @param context the XMLValidateContext
-     * @return <code>true</code> if the signature verified successfully,
-     *    <code>false</code> if not
-     * @throws NullPointerException if <code>key</code>, <code>si</code> or
-     *    <code>signature</code> are <code>null</code>
-     * @throws InvalidKeyException if the key is improperly encoded, of
-     *    the wrong type, or parameters are missing, etc
-     * @throws SignatureException if an unexpected error occurs, such
-     *    as the passed in signature is improperly encoded
-     * @throws XMLSignatureException if an unexpected error occurs
-     */
-    boolean verify(Key key, DOMSignedInfo si, byte[] sig,
-        XMLValidateContext context) throws InvalidKeyException,
-        SignatureException, XMLSignatureException {
+    boolean verify(Key key, SignedInfo si, byte[] sig,
+                   XMLValidateContext context)
+        throws InvalidKeyException, SignatureException, XMLSignatureException
+    {
         if (key == null || si == null || sig == null) {
             throw new NullPointerException();
         }
@@ -222,49 +158,40 @@
         }
         if (signature == null) {
             try {
-                Provider p = (Provider) context.getProperty
+                Provider p = (Provider)context.getProperty
                     ("org.jcp.xml.dsig.internal.dom.SignatureProvider");
                 signature = (p == null)
-                    ? Signature.getInstance(getSignatureAlgorithm())
-                    : Signature.getInstance(getSignatureAlgorithm(), p);
+                    ? Signature.getInstance(getJCAAlgorithm())
+                    : Signature.getInstance(getJCAAlgorithm(), p);
             } catch (NoSuchAlgorithmException nsae) {
                 throw new XMLSignatureException(nsae);
             }
         }
-        signature.initVerify((PublicKey) key);
-        if (log.isLoggable(Level.FINE)) {
-            log.log(Level.FINE, "Signature provider:"+ signature.getProvider());
-            log.log(Level.FINE, "verifying with key: " + key);
+        signature.initVerify((PublicKey)key);
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Signature provider:" + signature.getProvider());
+            log.log(java.util.logging.Level.FINE, "verifying with key: " + key);
         }
-        si.canonicalize(context, new SignerOutputStream(signature));
+        ((DOMSignedInfo)si).canonicalize(context,
+                                         new SignerOutputStream(signature));
 
-        if (getAlgorithm().equals(SignatureMethod.DSA_SHA1)) {
-            try {
+        try {
+            Type type = getAlgorithmType();
+            if (type == Type.DSA) {
                 return signature.verify(convertXMLDSIGtoASN1(sig));
-            } catch (IOException ioe) {
-                throw new XMLSignatureException(ioe);
+            } else if (type == Type.ECDSA) {
+                return signature.verify(SignatureECDSA.convertXMLDSIGtoASN1(sig));
+            } else {
+                return signature.verify(sig);
             }
-        } else {
-            return signature.verify(sig);
+        } catch (IOException ioe) {
+            throw new XMLSignatureException(ioe);
         }
     }
 
-    /**
-     * Signs the bytes with the specified key, using the underlying
-     * signature or MAC algorithm.
-     *
-     * @param key the signing key
-     * @param si the DOMSignedInfo
-     * @param context the XMLSignContext
-     * @return the signature
-     * @throws NullPointerException if <code>key</code> or
-     *    <code>si</code> are <code>null</code>
-     * @throws InvalidKeyException if the key is improperly encoded, of
-     *    the wrong type, or parameters are missing, etc
-     * @throws XMLSignatureException if an unexpected error occurs
-     */
-    byte[] sign(Key key, DOMSignedInfo si, XMLSignContext context)
-        throws InvalidKeyException, XMLSignatureException {
+    byte[] sign(Key key, SignedInfo si, XMLSignContext context)
+        throws InvalidKeyException, XMLSignatureException
+    {
         if (key == null || si == null) {
             throw new NullPointerException();
         }
@@ -274,26 +201,30 @@
         }
         if (signature == null) {
             try {
-                Provider p = (Provider) context.getProperty
+                Provider p = (Provider)context.getProperty
                     ("org.jcp.xml.dsig.internal.dom.SignatureProvider");
                 signature = (p == null)
-                    ? Signature.getInstance(getSignatureAlgorithm())
-                    : Signature.getInstance(getSignatureAlgorithm(), p);
+                    ? Signature.getInstance(getJCAAlgorithm())
+                    : Signature.getInstance(getJCAAlgorithm(), p);
             } catch (NoSuchAlgorithmException nsae) {
                 throw new XMLSignatureException(nsae);
             }
         }
-        signature.initSign((PrivateKey) key);
-        if (log.isLoggable(Level.FINE)) {
-            log.log(Level.FINE, "Signature provider:" +signature.getProvider());
-            log.log(Level.FINE, "Signing with key: " + key);
+        signature.initSign((PrivateKey)key);
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Signature provider:" + signature.getProvider());
+            log.log(java.util.logging.Level.FINE, "Signing with key: " + key);
         }
 
-        si.canonicalize(context, new SignerOutputStream(signature));
+        ((DOMSignedInfo)si).canonicalize(context,
+                                         new SignerOutputStream(signature));
 
         try {
-            if (getAlgorithm().equals(SignatureMethod.DSA_SHA1)) {
+            Type type = getAlgorithmType();
+            if (type == Type.DSA) {
                 return convertASN1toXMLDSIG(signature.sign());
+            } else if (type == Type.ECDSA) {
+                return SignatureECDSA.convertASN1toXMLDSIG(signature.sign());
             } else {
                 return signature.sign();
             }
@@ -305,52 +236,6 @@
     }
 
     /**
-     * Marshals the algorithm-specific parameters to an Element and
-     * appends it to the specified parent element. By default, this method
-     * throws an exception since most SignatureMethod algorithms do not have
-     * parameters. Subclasses should override it if they have parameters.
-     *
-     * @param parent the parent element to append the parameters to
-     * @param paramsPrefix the algorithm parameters prefix to use
-     * @throws MarshalException if the parameters cannot be marshalled
-     */
-    void marshalParams(Element parent, String paramsPrefix)
-        throws MarshalException {
-        throw new MarshalException("no parameters should " +
-            "be specified for the " + getSignatureAlgorithm() +
-            " SignatureMethod algorithm");
-    }
-
-    /**
-     * Returns the java.security.Signature standard algorithm name.
-     */
-    abstract String getSignatureAlgorithm();
-
-    /**
-     * Returns true if parameters are equal; false otherwise.
-     *
-     * Subclasses should override this method to compare algorithm-specific
-     * parameters.
-     */
-    boolean paramsEqual(AlgorithmParameterSpec spec) {
-        return (getParameterSpec() == spec);
-    }
-
-    public boolean equals(Object o) {
-        if (this == o) {
-            return true;
-        }
-
-        if (!(o instanceof SignatureMethod)) {
-            return false;
-        }
-        SignatureMethod osm = (SignatureMethod) o;
-
-        return (getAlgorithm().equals(osm.getAlgorithm()) &&
-            paramsEqual(osm.getParameterSpec()));
-    }
-
-    /**
      * Converts an ASN.1 DSA value to a XML Signature DSA Value.
      *
      * The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
@@ -362,8 +247,8 @@
      * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
      */
     private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[])
-        throws IOException {
-
+        throws IOException
+    {
         byte rLength = asn1Bytes[3];
         int i;
 
@@ -384,7 +269,7 @@
 
             System.arraycopy(asn1Bytes, (4+rLength)-i, xmldsigBytes, 20-i, i);
             System.arraycopy(asn1Bytes, (6+rLength+sLength)-j, xmldsigBytes,
-                          40 - j, j);
+                             40 - j, j);
 
             return xmldsigBytes;
         }
@@ -402,8 +287,8 @@
      * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
      */
     private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[])
-        throws IOException {
-
+        throws IOException
+    {
         if (xmldsigBytes.length != 40) {
             throw new IOException("Invalid XMLDSIG format of DSA signature");
         }
@@ -431,9 +316,9 @@
         byte asn1Bytes[] = new byte[6 + j + l];
 
         asn1Bytes[0] = 48;
-        asn1Bytes[1] = (byte) (4 + j + l);
+        asn1Bytes[1] = (byte)(4 + j + l);
         asn1Bytes[2] = 2;
-        asn1Bytes[3] = (byte) j;
+        asn1Bytes[3] = (byte)j;
 
         System.arraycopy(xmldsigBytes, 20 - i, asn1Bytes, (4 + j) - i, i);
 
@@ -456,9 +341,12 @@
         public String getAlgorithm() {
             return SignatureMethod.RSA_SHA1;
         }
-        String getSignatureAlgorithm() {
+        String getJCAAlgorithm() {
             return "SHA1withRSA";
         }
+        Type getAlgorithmType() {
+            return Type.RSA;
+        }
     }
 
     static final class SHA256withRSA extends DOMSignatureMethod {
@@ -472,9 +360,12 @@
         public String getAlgorithm() {
             return RSA_SHA256;
         }
-        String getSignatureAlgorithm() {
+        String getJCAAlgorithm() {
             return "SHA256withRSA";
         }
+        Type getAlgorithmType() {
+            return Type.RSA;
+        }
     }
 
     static final class SHA384withRSA extends DOMSignatureMethod {
@@ -488,9 +379,12 @@
         public String getAlgorithm() {
             return RSA_SHA384;
         }
-        String getSignatureAlgorithm() {
+        String getJCAAlgorithm() {
             return "SHA384withRSA";
         }
+        Type getAlgorithmType() {
+            return Type.RSA;
+        }
     }
 
     static final class SHA512withRSA extends DOMSignatureMethod {
@@ -504,9 +398,12 @@
         public String getAlgorithm() {
             return RSA_SHA512;
         }
-        String getSignatureAlgorithm() {
+        String getJCAAlgorithm() {
             return "SHA512withRSA";
         }
+        Type getAlgorithmType() {
+            return Type.RSA;
+        }
     }
 
     static final class SHA1withDSA extends DOMSignatureMethod {
@@ -520,8 +417,87 @@
         public String getAlgorithm() {
             return SignatureMethod.DSA_SHA1;
         }
-        String getSignatureAlgorithm() {
+        String getJCAAlgorithm() {
             return "SHA1withDSA";
         }
+        Type getAlgorithmType() {
+            return Type.DSA;
+        }
+    }
+
+    static final class SHA1withECDSA extends DOMSignatureMethod {
+        SHA1withECDSA(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        SHA1withECDSA(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        public String getAlgorithm() {
+            return ECDSA_SHA1;
+        }
+        String getJCAAlgorithm() {
+            return "SHA1withECDSA";
+        }
+        Type getAlgorithmType() {
+            return Type.ECDSA;
+        }
+    }
+
+    static final class SHA256withECDSA extends DOMSignatureMethod {
+        SHA256withECDSA(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        SHA256withECDSA(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        public String getAlgorithm() {
+            return ECDSA_SHA256;
+        }
+        String getJCAAlgorithm() {
+            return "SHA256withECDSA";
+        }
+        Type getAlgorithmType() {
+            return Type.ECDSA;
+        }
+    }
+
+    static final class SHA384withECDSA extends DOMSignatureMethod {
+        SHA384withECDSA(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        SHA384withECDSA(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        public String getAlgorithm() {
+            return ECDSA_SHA384;
+        }
+        String getJCAAlgorithm() {
+            return "SHA384withECDSA";
+        }
+        Type getAlgorithmType() {
+            return Type.ECDSA;
+        }
+    }
+
+    static final class SHA512withECDSA extends DOMSignatureMethod {
+        SHA512withECDSA(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        SHA512withECDSA(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        public String getAlgorithm() {
+            return ECDSA_SHA512;
+        }
+        String getJCAAlgorithm() {
+            return "SHA512withECDSA";
+        }
+        Type getAlgorithmType() {
+            return Type.ECDSA;
+        }
     }
 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMSignatureProperties.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMSignatureProperties.java 1333415 2012-05-03 12:03:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -31,6 +33,7 @@
 import javax.xml.crypto.dsig.*;
 
 import java.util.*;
+
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -46,7 +49,7 @@
     implements SignatureProperties {
 
     private final String id;
-    private final List properties;
+    private final List<SignatureProperty> properties;
 
     /**
      * Creates a <code>DOMSignatureProperties</code> from the specified
@@ -61,20 +64,22 @@
      * @throws IllegalArgumentException if <code>properties</code> is empty
      * @throws NullPointerException if <code>properties</code>
      */
-    public DOMSignatureProperties(List properties, String id) {
+    public DOMSignatureProperties(List<? extends SignatureProperty> properties,
+                                  String id)
+    {
         if (properties == null) {
             throw new NullPointerException("properties cannot be null");
         } else if (properties.isEmpty()) {
             throw new IllegalArgumentException("properties cannot be empty");
         } else {
-            List propsCopy = new ArrayList(properties);
-            for (int i = 0, size = propsCopy.size(); i < size; i++) {
-                if (!(propsCopy.get(i) instanceof SignatureProperty)) {
+            this.properties = Collections.unmodifiableList(
+                new ArrayList<SignatureProperty>(properties));
+            for (int i = 0, size = this.properties.size(); i < size; i++) {
+                if (!(this.properties.get(i) instanceof SignatureProperty)) {
                     throw new ClassCastException
                         ("properties["+i+"] is not a valid type");
                 }
             }
-            this.properties = Collections.unmodifiableList(propsCopy);
         }
         this.id = id;
     }
@@ -85,7 +90,9 @@
      * @param propsElem a SignatureProperties element
      * @throws MarshalException if a marshalling error occurs
      */
-    public DOMSignatureProperties(Element propsElem) throws MarshalException{
+    public DOMSignatureProperties(Element propsElem, XMLCryptoContext context)
+        throws MarshalException
+    {
         // unmarshal attributes
         Attr attr = propsElem.getAttributeNodeNS(null, "Id");
         if (attr != null) {
@@ -97,11 +104,13 @@
 
         NodeList nodes = propsElem.getChildNodes();
         int length = nodes.getLength();
-        List properties = new ArrayList(length);
+        List<SignatureProperty> properties =
+            new ArrayList<SignatureProperty>(length);
         for (int i = 0; i < length; i++) {
             Node child = nodes.item(i);
             if (child.getNodeType() == Node.ELEMENT_NODE) {
-                properties.add(new DOMSignatureProperty((Element) child));
+                properties.add(new DOMSignatureProperty((Element)child,
+                                                        context));
             }
         }
         if (properties.isEmpty()) {
@@ -120,25 +129,27 @@
     }
 
     public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException {
+        throws MarshalException
+    {
         Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
-        Element propsElem = DOMUtils.createElement
-            (ownerDoc, "SignatureProperties", XMLSignature.XMLNS, dsPrefix);
+        Element propsElem = DOMUtils.createElement(ownerDoc,
+                                                   "SignatureProperties",
+                                                   XMLSignature.XMLNS,
+                                                   dsPrefix);
 
         // set attributes
         DOMUtils.setAttributeID(propsElem, "Id", id);
 
         // create and append any properties
-        for (int i = 0, size = properties.size(); i < size; i++) {
-            DOMSignatureProperty property =
-                (DOMSignatureProperty) properties.get(i);
-            property.marshal(propsElem, dsPrefix, context);
+        for (SignatureProperty property : properties) {
+            ((DOMSignatureProperty)property).marshal(propsElem, dsPrefix,
+                                                     context);
         }
 
         parent.appendChild(propsElem);
     }
 
+    @Override
     public boolean equals(Object o) {
         if (this == o) {
             return true;
@@ -147,11 +158,22 @@
         if (!(o instanceof SignatureProperties)) {
             return false;
         }
-        SignatureProperties osp = (SignatureProperties) o;
+        SignatureProperties osp = (SignatureProperties)o;
 
-        boolean idsEqual = (id == null ? osp.getId() == null :
-            id.equals(osp.getId()));
+        boolean idsEqual = (id == null ? osp.getId() == null
+                                       : id.equals(osp.getId()));
 
         return (properties.equals(osp.getProperties()) && idsEqual);
     }
+
+    @Override
+    public int hashCode() {
+        int result = 17;
+        if (id != null) {
+            result = 31 * result + id.hashCode();
+        }
+        result = 31 * result + properties.hashCode();
+
+        return result;
+    }
 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMSignatureProperty.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMSignatureProperty.java 1333415 2012-05-03 12:03:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -31,6 +33,7 @@
 import javax.xml.crypto.dsig.*;
 
 import java.util.*;
+
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -47,7 +50,7 @@
 
     private final String id;
     private final String target;
-    private final List content;
+    private final List<XMLStructure> content;
 
     /**
      * Creates a <code>SignatureProperty</code> from the specified parameters.
@@ -63,7 +66,9 @@
      * @throws NullPointerException if <code>content</code> or
      *    <code>target</code> is <code>null</code>
      */
-    public DOMSignatureProperty(List content, String target, String id) {
+    public DOMSignatureProperty(List<? extends XMLStructure> content,
+                                String target, String id)
+    {
         if (target == null) {
             throw new NullPointerException("target cannot be null");
         } else if (content == null) {
@@ -71,14 +76,14 @@
         } else if (content.isEmpty()) {
             throw new IllegalArgumentException("content cannot be empty");
         } else {
-            List contentCopy = new ArrayList(content);
-            for (int i = 0, size = contentCopy.size(); i < size; i++) {
-                if (!(contentCopy.get(i) instanceof XMLStructure)) {
+            this.content = Collections.unmodifiableList(
+                new ArrayList<XMLStructure>(content));
+            for (int i = 0, size = this.content.size(); i < size; i++) {
+                if (!(this.content.get(i) instanceof XMLStructure)) {
                     throw new ClassCastException
                         ("content["+i+"] is not a valid type");
                 }
             }
-            this.content = Collections.unmodifiableList(contentCopy);
         }
         this.target = target;
         this.id = id;
@@ -89,7 +94,9 @@
      *
      * @param propElem a SignatureProperty element
      */
-    public DOMSignatureProperty(Element propElem) throws MarshalException {
+    public DOMSignatureProperty(Element propElem, XMLCryptoContext context)
+        throws MarshalException
+    {
         // unmarshal attributes
         target = DOMUtils.getAttributeValue(propElem, "Target");
         if (target == null) {
@@ -105,7 +112,7 @@
 
         NodeList nodes = propElem.getChildNodes();
         int length = nodes.getLength();
-        List content = new ArrayList(length);
+        List<XMLStructure> content = new ArrayList<XMLStructure>(length);
         for (int i = 0; i < length; i++) {
             content.add(new javax.xml.crypto.dom.DOMStructure(nodes.item(i)));
         }
@@ -129,26 +136,26 @@
     }
 
     public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException {
+        throws MarshalException
+    {
         Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
-        Element propElem = DOMUtils.createElement
-            (ownerDoc, "SignatureProperty", XMLSignature.XMLNS, dsPrefix);
+        Element propElem = DOMUtils.createElement(ownerDoc, "SignatureProperty",
+                                                  XMLSignature.XMLNS, dsPrefix);
 
         // set attributes
         DOMUtils.setAttributeID(propElem, "Id", id);
         DOMUtils.setAttribute(propElem, "Target", target);
 
         // create and append any elements and mixed content
-        for (int i = 0, size = content.size(); i < size; i++) {
-            javax.xml.crypto.dom.DOMStructure property =
-                (javax.xml.crypto.dom.DOMStructure) content.get(i);
-            DOMUtils.appendChild(propElem, property.getNode());
+        for (XMLStructure property : content) {
+            DOMUtils.appendChild(propElem,
+                ((javax.xml.crypto.dom.DOMStructure)property).getNode());
         }
 
         parent.appendChild(propElem);
     }
 
+    @Override
     public boolean equals(Object o) {
         if (this == o) {
             return true;
@@ -157,31 +164,43 @@
         if (!(o instanceof SignatureProperty)) {
             return false;
         }
-        SignatureProperty osp = (SignatureProperty) o;
+        SignatureProperty osp = (SignatureProperty)o;
+
+        boolean idsEqual = (id == null ? osp.getId() == null
+                                       : id.equals(osp.getId()));
 
-        boolean idsEqual = (id == null ? osp.getId() == null :
-            id.equals(osp.getId()));
-
-        return (equalsContent(osp.getContent()) &&
-            target.equals(osp.getTarget()) && idsEqual);
+        @SuppressWarnings("unchecked")
+        List<XMLStructure> ospContent = osp.getContent();
+        return (equalsContent(ospContent) &&
+                target.equals(osp.getTarget()) && idsEqual);
     }
 
-    private boolean equalsContent(List otherContent) {
+    @Override
+    public int hashCode() {
+        int result = 17;
+        if (id != null) {
+            result = 31 * result + id.hashCode();
+        }
+        result = 31 * result + target.hashCode();
+        result = 31 * result + content.hashCode();
+
+        return result;
+    }
+
+    private boolean equalsContent(List<XMLStructure> otherContent) {
         int osize = otherContent.size();
         if (content.size() != osize) {
             return false;
         }
         for (int i = 0; i < osize; i++) {
-            XMLStructure oxs = (XMLStructure) otherContent.get(i);
-            XMLStructure xs = (XMLStructure) content.get(i);
+            XMLStructure oxs = otherContent.get(i);
+            XMLStructure xs = content.get(i);
             if (oxs instanceof javax.xml.crypto.dom.DOMStructure) {
                 if (!(xs instanceof javax.xml.crypto.dom.DOMStructure)) {
                     return false;
                 }
-                Node onode =
-                    ((javax.xml.crypto.dom.DOMStructure) oxs).getNode();
-                Node node =
-                    ((javax.xml.crypto.dom.DOMStructure) xs).getNode();
+                Node onode = ((javax.xml.crypto.dom.DOMStructure)oxs).getNode();
+                Node node = ((javax.xml.crypto.dom.DOMStructure)xs).getNode();
                 if (!DOMUtils.nodesEqual(node, onode)) {
                     return false;
                 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMSignedInfo.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMSignedInfo.java 1333415 2012-05-03 12:03:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -33,13 +35,11 @@
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.InputStream;
+import java.io.OutputStream;
 import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
 import java.security.Provider;
 import java.util.*;
-import java.util.logging.Level;
-import java.util.logging.Logger;
+
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
@@ -47,7 +47,6 @@
 import com.sun.org.apache.xml.internal.security.utils.Base64;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream;
-import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 
 /**
  * DOM-based implementation of SignedInfo.
@@ -57,12 +56,12 @@
 public final class DOMSignedInfo extends DOMStructure implements SignedInfo {
 
     /**
-     * The maximum number of references per Manifest, if secure validation is
-     * enabled.
+     * The maximum number of references per Manifest, if secure validation is enabled.
      */
     public static final int MAXIMUM_REFERENCE_COUNT = 30;
 
-    private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom");
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
 
     /** Signature - NOT Recommended RSAwithMD5 */
     private static final String ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5 =
@@ -72,7 +71,7 @@
     private static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 =
         Constants.MoreAlgorithmsSpecNS + "hmac-md5";
 
-    private List references;
+    private List<Reference> references;
     private CanonicalizationMethod canonicalizationMethod;
     private SignatureMethod signatureMethod;
     private String id;
@@ -95,14 +94,14 @@
      *    type <code>Reference</code>
      */
     public DOMSignedInfo(CanonicalizationMethod cm, SignatureMethod sm,
-        List references) {
+                         List<? extends Reference> references) {
         if (cm == null || sm == null || references == null) {
             throw new NullPointerException();
         }
         this.canonicalizationMethod = cm;
         this.signatureMethod = sm;
-        this.references = Collections.unmodifiableList
-            (new ArrayList(references));
+        this.references = Collections.unmodifiableList(
+            new ArrayList<Reference>(references));
         if (this.references.isEmpty()) {
             throw new IllegalArgumentException("list of references must " +
                 "contain at least one entry");
@@ -132,7 +131,7 @@
      *    type <code>Reference</code>
      */
     public DOMSignedInfo(CanonicalizationMethod cm, SignatureMethod sm,
-        List references, String id) {
+                         List<? extends Reference> references, String id) {
         this(cm, sm, references);
         this.id = id;
     }
@@ -142,8 +141,8 @@
      *
      * @param siElem a SignedInfo element
      */
-    public DOMSignedInfo(Element siElem, XMLCryptoContext context,
-        Provider provider) throws MarshalException {
+    public DOMSignedInfo(Element siElem, XMLCryptoContext context, Provider provider)
+        throws MarshalException {
         localSiElem = siElem;
         ownerDoc = siElem.getOwnerDocument();
 
@@ -152,26 +151,26 @@
 
         // unmarshal CanonicalizationMethod
         Element cmElem = DOMUtils.getFirstChildElement(siElem);
-        canonicalizationMethod = new DOMCanonicalizationMethod
-            (cmElem, context, provider);
+        canonicalizationMethod = new DOMCanonicalizationMethod(cmElem, context, provider);
 
         // unmarshal SignatureMethod
         Element smElem = DOMUtils.getNextSiblingElement(cmElem);
         signatureMethod = DOMSignatureMethod.unmarshal(smElem);
 
         boolean secVal = Utils.secureValidation(context);
-        String sigMethAlg = signatureMethod.getAlgorithm();
-        if (secVal && ((ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(sigMethAlg)
-            || ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(sigMethAlg))))
-        {
-            throw new MarshalException("It is forbidden to use algorithm " +
-                                       signatureMethod +
-                                       " when secure validation is enabled");
+
+        String signatureMethodAlgorithm = signatureMethod.getAlgorithm();
+        if (secVal && ((ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(signatureMethodAlgorithm)
+                || ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(signatureMethodAlgorithm)))) {
+            throw new MarshalException(
+                "It is forbidden to use algorithm " + signatureMethod + " when secure validation is enabled"
+            );
         }
 
         // unmarshal References
-        ArrayList refList = new ArrayList(5);
+        ArrayList<Reference> refList = new ArrayList<Reference>(5);
         Element refElem = DOMUtils.getNextSiblingElement(smElem);
+
         int refCount = 0;
         while (refElem != null) {
             refList.add(new DOMReference(refElem, context, provider));
@@ -179,9 +178,8 @@
 
             refCount++;
             if (secVal && (refCount > MAXIMUM_REFERENCE_COUNT)) {
-                String error = "A maxiumum of " + MAXIMUM_REFERENCE_COUNT +
-                               " references per SignedInfo are allowed with" +
-                               " secure validation";
+                String error = "A maxiumum of " + MAXIMUM_REFERENCE_COUNT + " "
+                    + "references per Manifest are allowed with secure validation";
                 throw new MarshalException(error);
             }
         }
@@ -208,9 +206,8 @@
         return canonData;
     }
 
-    public void canonicalize(XMLCryptoContext context,ByteArrayOutputStream bos)
+    public void canonicalize(XMLCryptoContext context, ByteArrayOutputStream bos)
         throws XMLSignatureException {
-
         if (context == null) {
             throw new NullPointerException("context cannot be null");
         }
@@ -219,14 +216,17 @@
         try {
             os.close();
         } catch (IOException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+            }
             // Impossible
         }
 
         DOMSubTreeData subTree = new DOMSubTreeData(localSiElem, true);
 
         try {
-            Data data = ((DOMCanonicalizationMethod)
-                canonicalizationMethod).canonicalize(subTree, context, os);
+            ((DOMCanonicalizationMethod)
+                canonicalizationMethod).canonicalize(subTree, context, bos);
         } catch (TransformException te) {
             throw new XMLSignatureException(te);
         }
@@ -234,44 +234,37 @@
         byte[] signedInfoBytes = bos.toByteArray();
 
         // this whole block should only be done if logging is enabled
-        if (log.isLoggable(Level.FINE)) {
-            InputStreamReader isr = new InputStreamReader
-                (new ByteArrayInputStream(signedInfoBytes));
-            char[] siBytes = new char[signedInfoBytes.length];
-            try {
-                isr.read(siBytes);
-                log.log(Level.FINE, "Canonicalized SignedInfo:\n"
-                    + new String(siBytes));
-            } catch (IOException ioex) {
-                log.log(Level.FINE, "IOException reading SignedInfo bytes");
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Canonicalized SignedInfo:");
+            StringBuilder sb = new StringBuilder(signedInfoBytes.length);
+            for (int i = 0; i < signedInfoBytes.length; i++) {
+                sb.append((char)signedInfoBytes[i]);
             }
-            log.log(Level.FINE, "Data to be signed/verified:"
-                + Base64.encode(signedInfoBytes));
+            log.log(java.util.logging.Level.FINE, sb.toString());
+            log.log(java.util.logging.Level.FINE, "Data to be signed/verified:" + Base64.encode(signedInfoBytes));
         }
 
         this.canonData = new ByteArrayInputStream(signedInfoBytes);
     }
 
     public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException {
+        throws MarshalException
+    {
         ownerDoc = DOMUtils.getOwnerDocument(parent);
-
-        Element siElem = DOMUtils.createElement
-            (ownerDoc, "SignedInfo", XMLSignature.XMLNS, dsPrefix);
+        Element siElem = DOMUtils.createElement(ownerDoc, "SignedInfo",
+                                                XMLSignature.XMLNS, dsPrefix);
 
         // create and append CanonicalizationMethod element
         DOMCanonicalizationMethod dcm =
-            (DOMCanonicalizationMethod) canonicalizationMethod;
+            (DOMCanonicalizationMethod)canonicalizationMethod;
         dcm.marshal(siElem, dsPrefix, context);
 
         // create and append SignatureMethod element
-        ((DOMSignatureMethod) signatureMethod).marshal
-            (siElem, dsPrefix, context);
+        ((DOMStructure)signatureMethod).marshal(siElem, dsPrefix, context);
 
         // create and append Reference elements
-        for (int i = 0, size = references.size(); i < size; i++) {
-            DOMReference reference = (DOMReference) references.get(i);
-            reference.marshal(siElem, dsPrefix, context);
+        for (Reference reference : references) {
+            ((DOMReference)reference).marshal(siElem, dsPrefix, context);
         }
 
         // append Id attribute
@@ -281,6 +274,7 @@
         localSiElem = siElem;
     }
 
+    @Override
     public boolean equals(Object o) {
         if (this == o) {
             return true;
@@ -289,13 +283,26 @@
         if (!(o instanceof SignedInfo)) {
             return false;
         }
-        SignedInfo osi = (SignedInfo) o;
+        SignedInfo osi = (SignedInfo)o;
 
-        boolean idEqual = (id == null ? osi.getId() == null :
-            id.equals(osi.getId()));
+        boolean idEqual = (id == null ? osi.getId() == null
+                                      : id.equals(osi.getId()));
 
         return (canonicalizationMethod.equals(osi.getCanonicalizationMethod())
-            && signatureMethod.equals(osi.getSignatureMethod()) &&
-            references.equals(osi.getReferences()) && idEqual);
+                && signatureMethod.equals(osi.getSignatureMethod()) &&
+                references.equals(osi.getReferences()) && idEqual);
+    }
+
+    @Override
+    public int hashCode() {
+        int result = 17;
+        if (id != null) {
+            result = 31 * result + id.hashCode();
+        }
+        result = 31 * result + canonicalizationMethod.hashCode();
+        result = 31 * result + signatureMethod.hashCode();
+        result = 31 * result + references.hashCode();
+
+        return result;
     }
 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMStructure.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMStructure.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMStructure.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMStructure.java 1197150 2011-11-03 14:34:57Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSubTreeData.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSubTreeData.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2006 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMSubTreeData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id$
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -45,17 +47,15 @@
 public class DOMSubTreeData implements NodeSetData {
 
     private boolean excludeComments;
-    private Iterator ni;
     private Node root;
 
     public DOMSubTreeData(Node root, boolean excludeComments) {
         this.root = root;
-        this.ni = new DelayedNodeIterator(root, excludeComments);
         this.excludeComments = excludeComments;
     }
 
     public Iterator iterator() {
-        return ni;
+        return new DelayedNodeIterator(root, excludeComments);
     }
 
     public Node getRoot() {
@@ -70,10 +70,10 @@
      * This is an Iterator that contains a backing node-set that is
      * not populated until the caller first attempts to advance the iterator.
      */
-    static class DelayedNodeIterator implements Iterator {
+    static class DelayedNodeIterator implements Iterator<Node> {
         private Node root;
-        private List nodeSet;
-        private ListIterator li;
+        private List<Node> nodeSet;
+        private ListIterator<Node> li;
         private boolean withComments;
 
         DelayedNodeIterator(Node root, boolean excludeComments) {
@@ -89,13 +89,13 @@
             return li.hasNext();
         }
 
-        public Object next() {
+        public Node next() {
             if (nodeSet == null) {
                 nodeSet = dereferenceSameDocumentURI(root);
                 li = nodeSet.listIterator();
             }
             if (li.hasNext()) {
-                return (Node) li.next();
+                return li.next();
             } else {
                 throw new NoSuchElementException();
             }
@@ -109,11 +109,11 @@
          * Dereferences a same-document URI fragment.
          *
          * @param node the node (document or element) referenced by the
-         *       URI fragment. If null, returns an empty set.
+         *        URI fragment. If null, returns an empty set.
          * @return a set of nodes (minus any comment nodes)
          */
-        private List dereferenceSameDocumentURI(Node node) {
-            List nodeSet = new ArrayList();
+        private List<Node> dereferenceSameDocumentURI(Node node) {
+            List<Node> nodeSet = new ArrayList<Node>();
             if (node != null) {
                 nodeSetMinusCommentNodes(node, nodeSet, null);
             }
@@ -129,8 +129,10 @@
          * @param nodeSet the set of nodes traversed so far
          * @param the previous sibling node
          */
-        private void nodeSetMinusCommentNodes(Node node, List nodeSet,
-            Node prevSibling) {
+        @SuppressWarnings("fallthrough")
+        private void nodeSetMinusCommentNodes(Node node, List<Node> nodeSet,
+                                              Node prevSibling)
+        {
             switch (node.getNodeType()) {
                 case Node.ELEMENT_NODE :
                     NamedNodeMap attrs = node.getAttributes();
@@ -140,8 +142,15 @@
                         }
                     }
                     nodeSet.add(node);
+                    Node pSibling = null;
+                    for (Node child = node.getFirstChild(); child != null;
+                        child = child.getNextSibling()) {
+                        nodeSetMinusCommentNodes(child, nodeSet, pSibling);
+                        pSibling = child;
+                    }
+                    break;
                 case Node.DOCUMENT_NODE :
-                    Node pSibling = null;
+                    pSibling = null;
                     for (Node child = node.getFirstChild(); child != null;
                         child = child.getNextSibling()) {
                         nodeSetMinusCommentNodes(child, nodeSet, pSibling);
@@ -154,8 +163,11 @@
                     // contiguous text/cdata nodes
                     if (prevSibling != null &&
                         (prevSibling.getNodeType() == Node.TEXT_NODE ||
-                         prevSibling.getNodeType() == Node.CDATA_SECTION_NODE)){                        return;
+                         prevSibling.getNodeType() == Node.CDATA_SECTION_NODE)) {
+                        return;
                     }
+                    nodeSet.add(node);
+                    break;
                 case Node.PROCESSING_INSTRUCTION_NODE :
                     nodeSet.add(node);
                     break;
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMTransform.java 1333415 2012-05-03 12:03:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -35,13 +37,11 @@
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
 
 import javax.xml.crypto.*;
 import javax.xml.crypto.dsig.*;
 import javax.xml.crypto.dom.DOMCryptoContext;
 import javax.xml.crypto.dsig.dom.DOMSignContext;
-import javax.xml.crypto.dsig.spec.TransformParameterSpec;
 
 /**
  * DOM-based abstract implementation of Transform.
@@ -69,15 +69,26 @@
      * @param transElem a Transform element
      */
     public DOMTransform(Element transElem, XMLCryptoContext context,
-        Provider provider) throws MarshalException {
+                        Provider provider)
+        throws MarshalException
+    {
         String algorithm = DOMUtils.getAttributeValue(transElem, "Algorithm");
-        try {
-            spi = TransformService.getInstance(algorithm, "DOM");
-        } catch (NoSuchAlgorithmException e1) {
+
+        if (provider == null) {
+            try {
+                spi = TransformService.getInstance(algorithm, "DOM");
+            } catch (NoSuchAlgorithmException e1) {
+                throw new MarshalException(e1);
+            }
+        } else {
             try {
                 spi = TransformService.getInstance(algorithm, "DOM", provider);
-            } catch (NoSuchAlgorithmException e2) {
-                throw new MarshalException(e2);
+            } catch (NoSuchAlgorithmException nsae) {
+                try {
+                    spi = TransformService.getInstance(algorithm, "DOM");
+                } catch (NoSuchAlgorithmException e2) {
+                    throw new MarshalException(e2);
+                }
             }
         }
         try {
@@ -100,21 +111,25 @@
      * method to marshal any algorithm-specific parameters.
      */
     public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException {
+        throws MarshalException
+    {
         Document ownerDoc = DOMUtils.getOwnerDocument(parent);
 
         Element transformElem = null;
         if (parent.getLocalName().equals("Transforms")) {
-            transformElem = DOMUtils.createElement
-                (ownerDoc, "Transform", XMLSignature.XMLNS, dsPrefix);
+            transformElem = DOMUtils.createElement(ownerDoc, "Transform",
+                                                   XMLSignature.XMLNS,
+                                                   dsPrefix);
         } else {
-            transformElem = DOMUtils.createElement
-            (ownerDoc, "CanonicalizationMethod", XMLSignature.XMLNS, dsPrefix);
+            transformElem = DOMUtils.createElement(ownerDoc,
+                                                   "CanonicalizationMethod",
+                                                   XMLSignature.XMLNS,
+                                                   dsPrefix);
         }
         DOMUtils.setAttribute(transformElem, "Algorithm", getAlgorithm());
 
-        spi.marshalParams
-            (new javax.xml.crypto.dom.DOMStructure(transformElem), context);
+        spi.marshalParams(new javax.xml.crypto.dom.DOMStructure(transformElem),
+                          context);
 
         parent.appendChild(transformElem);
     }
@@ -131,7 +146,8 @@
      *    executing the transform
      */
     public Data transform(Data data, XMLCryptoContext xc)
-        throws TransformException {
+        throws TransformException
+    {
         return spi.transform(data, xc);
     }
 
@@ -149,10 +165,12 @@
      *    executing the transform
      */
     public Data transform(Data data, XMLCryptoContext xc, OutputStream os)
-        throws TransformException {
+        throws TransformException
+    {
         return spi.transform(data, xc, os);
     }
 
+    @Override
     public boolean equals(Object o) {
         if (this == o) {
             return true;
@@ -161,11 +179,23 @@
         if (!(o instanceof Transform)) {
             return false;
         }
-        Transform otransform = (Transform) o;
+        Transform otransform = (Transform)o;
 
         return (getAlgorithm().equals(otransform.getAlgorithm()) &&
-            DOMUtils.paramsEqual
-                (getParameterSpec(), otransform.getParameterSpec()));
+                DOMUtils.paramsEqual(getParameterSpec(),
+                                     otransform.getParameterSpec()));
+    }
+
+    @Override
+    public int hashCode() {
+        int result = 17;
+        result = 31 * result + getAlgorithm().hashCode();
+        AlgorithmParameterSpec spec = getParameterSpec();
+        if (spec != null) {
+            result = 31 * result + spec.hashCode();
+        }
+
+        return result;
     }
 
     /**
@@ -185,9 +215,10 @@
      *    executing the transform
      */
     Data transform(Data data, XMLCryptoContext xc, DOMSignContext context)
-        throws MarshalException, TransformException {
+        throws MarshalException, TransformException
+    {
         marshal(context.getParent(),
-            DOMUtils.getSignaturePrefix(context), context);
+                DOMUtils.getSignaturePrefix(context), context);
         return transform(data, xc);
     }
 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMURIDereferencer.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMURIDereferencer.java 1231033 2012-01-13 12:12:12Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -37,7 +39,6 @@
 
 import javax.xml.crypto.*;
 import javax.xml.crypto.dom.*;
-import javax.xml.crypto.dsig.*;
 
 /**
  * DOM-based implementation of URIDereferencer.
@@ -82,21 +83,17 @@
                 id = id.substring(i1+1, i2);
             }
 
-            Node refElem = dcc.getElementById(id);
-            if (refElem != null) {
+            Node referencedElem = dcc.getElementById(id);
+            if (referencedElem != null) {
                 if (secVal) {
-                    Element start =
-                        refElem.getOwnerDocument().getDocumentElement();
-                    if (!XMLUtils.protectAgainstWrappingAttack(start,
-                                                               (Element)refElem,
-                                                               id)) {
-                        String error = "Multiple Elements with the same ID " +
-                                       id + " were detected";
+                    Element start = referencedElem.getOwnerDocument().getDocumentElement();
+                    if (!XMLUtils.protectAgainstWrappingAttack(start, (Element)referencedElem, id)) {
+                        String error = "Multiple Elements with the same ID " + id + " were detected";
                         throw new URIReferenceException(error);
                     }
                 }
 
-                XMLSignatureInput result = new XMLSignatureInput(refElem);
+                XMLSignatureInput result = new XMLSignatureInput(referencedElem);
                 if (!uri.substring(1).startsWith("xpointer(id(")) {
                     result.setExcludeComments(true);
                 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMUtils.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMUtils.java 1333415 2012-05-03 12:03:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -34,7 +36,6 @@
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 import javax.xml.crypto.*;
-import javax.xml.crypto.dsig.dom.DOMSignContext;
 import javax.xml.crypto.dsig.*;
 import javax.xml.crypto.dsig.spec.*;
 
@@ -56,7 +57,7 @@
      */
     public static Document getOwnerDocument(Node node) {
         if (node.getNodeType() == Node.DOCUMENT_NODE) {
-            return (Document) node;
+            return (Document)node;
         } else {
             return node.getOwnerDocument();
         }
@@ -72,8 +73,9 @@
      * @param prefix the namespace prefix
      * @return the newly created element
      */
-    public static Element createElement(Document doc, String tag, String nsURI,
-        String prefix) {
+    public static Element createElement(Document doc, String tag,
+                                        String nsURI, String prefix)
+    {
         String qName = (prefix == null || prefix.length() == 0)
                        ? tag : prefix + ":" + tag;
         return doc.createElementNS(nsURI, qName);
@@ -88,7 +90,9 @@
      * @param value the attribute value. If null, no attribute is set.
      */
     public static void setAttribute(Element elem, String name, String value) {
-        if (value == null) return;
+        if (value == null) {
+            return;
+        }
         elem.setAttributeNS(null, name, value);
     }
 
@@ -103,7 +107,9 @@
      * @param value the attribute value. If null, no attribute is set.
      */
     public static void setAttributeID(Element elem, String name, String value) {
-        if (value == null) return;
+        if (value == null) {
+            return;
+        }
         elem.setAttributeNS(null, name, value);
         elem.setIdAttributeNS(null, name, true);
     }
@@ -122,7 +128,7 @@
         while (child != null && child.getNodeType() != Node.ELEMENT_NODE) {
             child = child.getNextSibling();
         }
-        return (Element) child;
+        return (Element)child;
     }
 
     /**
@@ -139,7 +145,7 @@
         while (child != null && child.getNodeType() != Node.ELEMENT_NODE) {
             child = child.getPreviousSibling();
         }
-        return (Element) child;
+        return (Element)child;
     }
 
     /**
@@ -156,7 +162,7 @@
         while (sibling != null && sibling.getNodeType() != Node.ELEMENT_NODE) {
             sibling = sibling.getNextSibling();
         }
-        return (Element) sibling;
+        return (Element)sibling;
     }
 
     /**
@@ -185,25 +191,25 @@
      * @param nl the NodeList
      * @return a Set of Nodes
      */
-    public static Set nodeSet(NodeList nl) {
+    public static Set<Node> nodeSet(NodeList nl) {
         return new NodeSet(nl);
     }
 
-    static class NodeSet extends AbstractSet {
+    static class NodeSet extends AbstractSet<Node> {
         private NodeList nl;
         public NodeSet(NodeList nl) {
             this.nl = nl;
         }
 
         public int size() { return nl.getLength(); }
-        public Iterator iterator() {
-            return new Iterator() {
+        public Iterator<Node> iterator() {
+            return new Iterator<Node>() {
                 int index = 0;
 
                 public void remove() {
                     throw new UnsupportedOperationException();
                 }
-                public Object next() {
+                public Node next() {
                     if (!hasNext()) {
                         throw new NoSuchElementException();
                     }
@@ -291,39 +297,41 @@
         }
         if (spec1 instanceof XPathFilter2ParameterSpec &&
             spec2 instanceof XPathFilter2ParameterSpec) {
-            return paramsEqual((XPathFilter2ParameterSpec) spec1,
-                (XPathFilter2ParameterSpec) spec2);
+            return paramsEqual((XPathFilter2ParameterSpec)spec1,
+                               (XPathFilter2ParameterSpec)spec2);
         }
         if (spec1 instanceof ExcC14NParameterSpec &&
             spec2 instanceof ExcC14NParameterSpec) {
             return paramsEqual((ExcC14NParameterSpec) spec1,
-                (ExcC14NParameterSpec) spec2);
+                               (ExcC14NParameterSpec)spec2);
         }
         if (spec1 instanceof XPathFilterParameterSpec &&
             spec2 instanceof XPathFilterParameterSpec) {
-            return paramsEqual((XPathFilterParameterSpec) spec1,
-                (XPathFilterParameterSpec) spec2);
+            return paramsEqual((XPathFilterParameterSpec)spec1,
+                               (XPathFilterParameterSpec)spec2);
         }
         if (spec1 instanceof XSLTTransformParameterSpec &&
             spec2 instanceof XSLTTransformParameterSpec) {
-            return paramsEqual((XSLTTransformParameterSpec) spec1,
-                (XSLTTransformParameterSpec) spec2);
+            return paramsEqual((XSLTTransformParameterSpec)spec1,
+                               (XSLTTransformParameterSpec)spec2);
         }
         return false;
     }
 
     private static boolean paramsEqual(XPathFilter2ParameterSpec spec1,
-        XPathFilter2ParameterSpec spec2) {
-
-        List types = spec1.getXPathList();
-        List otypes = spec2.getXPathList();
+                                       XPathFilter2ParameterSpec spec2)
+    {
+        @SuppressWarnings("unchecked")
+        List<XPathType> types = spec1.getXPathList();
+        @SuppressWarnings("unchecked")
+        List<XPathType> otypes = spec2.getXPathList();
         int size = types.size();
         if (size != otypes.size()) {
             return false;
         }
         for (int i = 0; i < size; i++) {
-            XPathType type = (XPathType) types.get(i);
-            XPathType otype = (XPathType) otypes.get(i);
+            XPathType type = types.get(i);
+            XPathType otype = otypes.get(i);
             if (!type.getExpression().equals(otype.getExpression()) ||
                 !type.getNamespaceMap().equals(otype.getNamespaceMap()) ||
                 type.getFilter() != otype.getFilter()) {
@@ -334,18 +342,21 @@
     }
 
     private static boolean paramsEqual(ExcC14NParameterSpec spec1,
-        ExcC14NParameterSpec spec2) {
+                                       ExcC14NParameterSpec spec2)
+    {
         return spec1.getPrefixList().equals(spec2.getPrefixList());
     }
 
     private static boolean paramsEqual(XPathFilterParameterSpec spec1,
-        XPathFilterParameterSpec spec2) {
+                                       XPathFilterParameterSpec spec2)
+    {
         return (spec1.getXPath().equals(spec2.getXPath()) &&
-            spec1.getNamespaceMap().equals(spec2.getNamespaceMap()));
+                spec1.getNamespaceMap().equals(spec2.getNamespaceMap()));
     }
 
     private static boolean paramsEqual(XSLTTransformParameterSpec spec1,
-        XSLTTransformParameterSpec spec2) {
+                                       XSLTTransformParameterSpec spec2)
+    {
 
         XMLStructure ostylesheet = spec2.getStylesheet();
         if (!(ostylesheet instanceof javax.xml.crypto.dom.DOMStructure)) {
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509Data.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509Data.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMX509Data.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMX509Data.java 1333415 2012-05-03 12:03:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -51,7 +53,7 @@
 //@@@ check for illegal combinations of data violating MUSTs in W3c spec
 public final class DOMX509Data extends DOMStructure implements X509Data {
 
-    private final List content;
+    private final List<Object> content;
     private CertificateFactory cf;
 
     /**
@@ -69,18 +71,18 @@
      * @throws ClassCastException if <code>content</code> contains any entries
      *    that are not of one of the valid types mentioned above
      */
-    public DOMX509Data(List content) {
+    public DOMX509Data(List<?> content) {
         if (content == null) {
             throw new NullPointerException("content cannot be null");
         }
-        List contentCopy = new ArrayList(content);
+        List<Object> contentCopy = new ArrayList<Object>(content);
         if (contentCopy.isEmpty()) {
             throw new IllegalArgumentException("content cannot be empty");
         }
         for (int i = 0, size = contentCopy.size(); i < size; i++) {
             Object x509Type = contentCopy.get(i);
             if (x509Type instanceof String) {
-                new X500Principal((String) x509Type);
+                new X500Principal((String)x509Type);
             } else if (!(x509Type instanceof byte[]) &&
                 !(x509Type instanceof X509Certificate) &&
                 !(x509Type instanceof X509CRL) &&
@@ -102,7 +104,7 @@
         // get all children nodes
         NodeList nl = xdElem.getChildNodes();
         int length = nl.getLength();
-        List content = new ArrayList(length);
+        List<Object> content = new ArrayList<Object>(length);
         for (int i = 0; i < length; i++) {
             Node child = nl.item(i);
             // ignore all non-Element nodes
@@ -110,7 +112,7 @@
                 continue;
             }
 
-            Element childElem = (Element) child;
+            Element childElem = (Element)child;
             String localName = childElem.getLocalName();
             if (localName.equals("X509Certificate")) {
                 content.add(unmarshalX509Certificate(childElem));
@@ -138,32 +140,32 @@
     }
 
     public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException {
+        throws MarshalException
+    {
         Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
-        Element xdElem = DOMUtils.createElement
-            (ownerDoc, "X509Data", XMLSignature.XMLNS, dsPrefix);
+        Element xdElem = DOMUtils.createElement(ownerDoc, "X509Data",
+                                                XMLSignature.XMLNS, dsPrefix);
 
         // append children and preserve order
         for (int i = 0, size = content.size(); i < size; i++) {
             Object object = content.get(i);
             if (object instanceof X509Certificate) {
-                marshalCert((X509Certificate) object,xdElem,ownerDoc,dsPrefix);
+                marshalCert((X509Certificate)object,xdElem,ownerDoc,dsPrefix);
             } else if (object instanceof XMLStructure) {
                 if (object instanceof X509IssuerSerial) {
-                    ((DOMX509IssuerSerial) object).marshal
+                    ((DOMX509IssuerSerial)object).marshal
                         (xdElem, dsPrefix, context);
                 } else {
                     javax.xml.crypto.dom.DOMStructure domContent =
-                        (javax.xml.crypto.dom.DOMStructure) object;
+                        (javax.xml.crypto.dom.DOMStructure)object;
                     DOMUtils.appendChild(xdElem, domContent.getNode());
                 }
             } else if (object instanceof byte[]) {
-                marshalSKI((byte[]) object, xdElem, ownerDoc, dsPrefix);
+                marshalSKI((byte[])object, xdElem, ownerDoc, dsPrefix);
             } else if (object instanceof String) {
-                marshalSubjectName((String) object, xdElem, ownerDoc,dsPrefix);
+                marshalSubjectName((String)object, xdElem, ownerDoc,dsPrefix);
             } else if (object instanceof X509CRL) {
-                marshalCRL((X509CRL) object, xdElem, ownerDoc, dsPrefix);
+                marshalCRL((X509CRL)object, xdElem, ownerDoc, dsPrefix);
             }
         }
 
@@ -171,31 +173,32 @@
     }
 
     private void marshalSKI(byte[] skid, Node parent, Document doc,
-        String dsPrefix) {
-
-        Element skidElem = DOMUtils.createElement
-            (doc, "X509SKI", XMLSignature.XMLNS, dsPrefix);
+                            String dsPrefix)
+    {
+        Element skidElem = DOMUtils.createElement(doc, "X509SKI",
+                                                  XMLSignature.XMLNS, dsPrefix);
         skidElem.appendChild(doc.createTextNode(Base64.encode(skid)));
         parent.appendChild(skidElem);
     }
 
     private void marshalSubjectName(String name, Node parent, Document doc,
-        String dsPrefix) {
-
-        Element snElem = DOMUtils.createElement
-            (doc, "X509SubjectName", XMLSignature.XMLNS, dsPrefix);
+                                    String dsPrefix)
+    {
+        Element snElem = DOMUtils.createElement(doc, "X509SubjectName",
+                                                XMLSignature.XMLNS, dsPrefix);
         snElem.appendChild(doc.createTextNode(name));
         parent.appendChild(snElem);
     }
 
     private void marshalCert(X509Certificate cert, Node parent, Document doc,
-        String dsPrefix) throws MarshalException {
-
-        Element certElem = DOMUtils.createElement
-            (doc, "X509Certificate", XMLSignature.XMLNS, dsPrefix);
+                             String dsPrefix)
+        throws MarshalException
+    {
+        Element certElem = DOMUtils.createElement(doc, "X509Certificate",
+                                                  XMLSignature.XMLNS, dsPrefix);
         try {
             certElem.appendChild(doc.createTextNode
-                (Base64.encode(cert.getEncoded())));
+                                 (Base64.encode(cert.getEncoded())));
         } catch (CertificateEncodingException e) {
             throw new MarshalException("Error encoding X509Certificate", e);
         }
@@ -203,13 +206,14 @@
     }
 
     private void marshalCRL(X509CRL crl, Node parent, Document doc,
-        String dsPrefix) throws MarshalException {
-
-        Element crlElem = DOMUtils.createElement
-            (doc, "X509CRL", XMLSignature.XMLNS, dsPrefix);
+                            String dsPrefix)
+        throws MarshalException
+    {
+        Element crlElem = DOMUtils.createElement(doc, "X509CRL",
+                                                 XMLSignature.XMLNS, dsPrefix);
         try {
             crlElem.appendChild(doc.createTextNode
-                (Base64.encode(crl.getEncoded())));
+                                (Base64.encode(crl.getEncoded())));
         } catch (CRLException e) {
             throw new MarshalException("Error encoding X509CRL", e);
         }
@@ -217,10 +221,11 @@
     }
 
     private X509Certificate unmarshalX509Certificate(Element elem)
-        throws MarshalException {
+        throws MarshalException
+    {
         try {
             ByteArrayInputStream bs = unmarshalBase64Binary(elem);
-            return (X509Certificate) cf.generateCertificate(bs);
+            return (X509Certificate)cf.generateCertificate(bs);
         } catch (CertificateException e) {
             throw new MarshalException("Cannot create X509Certificate", e);
         }
@@ -229,7 +234,7 @@
     private X509CRL unmarshalX509CRL(Element elem) throws MarshalException {
         try {
             ByteArrayInputStream bs = unmarshalBase64Binary(elem);
-            return (X509CRL) cf.generateCRL(bs);
+            return (X509CRL)cf.generateCRL(bs);
         } catch (CRLException e) {
             throw new MarshalException("Cannot create X509CRL", e);
         }
@@ -249,6 +254,7 @@
         }
     }
 
+    @Override
     public boolean equals(Object o) {
         if (this == o) {
             return true;
@@ -257,9 +263,9 @@
         if (!(o instanceof X509Data)) {
             return false;
         }
-        X509Data oxd = (X509Data) o;
+        X509Data oxd = (X509Data)o;
 
-        List ocontent = oxd.getContent();
+        @SuppressWarnings("unchecked") List<Object> ocontent = oxd.getContent();
         int size = content.size();
         if (size != ocontent.size()) {
             return false;
@@ -270,7 +276,7 @@
             Object ox = ocontent.get(i);
             if (x instanceof byte[]) {
                 if (!(ox instanceof byte[]) ||
-                    !Arrays.equals((byte[]) x, (byte[]) ox)) {
+                    !Arrays.equals((byte[])x, (byte[])ox)) {
                     return false;
                 }
             } else {
@@ -282,4 +288,12 @@
 
         return true;
     }
+
+    @Override
+    public int hashCode() {
+        int result = 17;
+        result = 31 * result + content.hashCode();
+
+        return result;
+    }
 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509IssuerSerial.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509IssuerSerial.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMX509IssuerSerial.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMX509IssuerSerial.java 1333415 2012-05-03 12:03:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -94,15 +96,16 @@
     }
 
     public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException {
+        throws MarshalException
+    {
         Document ownerDoc = DOMUtils.getOwnerDocument(parent);
 
-        Element isElem = DOMUtils.createElement
-            (ownerDoc, "X509IssuerSerial", XMLSignature.XMLNS, dsPrefix);
-        Element inElem = DOMUtils.createElement
-            (ownerDoc, "X509IssuerName", XMLSignature.XMLNS, dsPrefix);
-        Element snElem = DOMUtils.createElement
-            (ownerDoc, "X509SerialNumber", XMLSignature.XMLNS, dsPrefix);
+        Element isElem = DOMUtils.createElement(ownerDoc, "X509IssuerSerial",
+                                                XMLSignature.XMLNS, dsPrefix);
+        Element inElem = DOMUtils.createElement(ownerDoc, "X509IssuerName",
+                                                XMLSignature.XMLNS, dsPrefix);
+        Element snElem = DOMUtils.createElement(ownerDoc, "X509SerialNumber",
+                                                XMLSignature.XMLNS, dsPrefix);
         inElem.appendChild(ownerDoc.createTextNode(issuerName));
         snElem.appendChild(ownerDoc.createTextNode(serialNumber.toString()));
         isElem.appendChild(inElem);
@@ -110,6 +113,7 @@
         parent.appendChild(isElem);
     }
 
+    @Override
     public boolean equals(Object obj) {
         if (this == obj) {
             return true;
@@ -117,8 +121,17 @@
         if (!(obj instanceof X509IssuerSerial)) {
             return false;
         }
-        X509IssuerSerial ois = (X509IssuerSerial) obj;
+        X509IssuerSerial ois = (X509IssuerSerial)obj;
         return (issuerName.equals(ois.getIssuerName()) &&
-            serialNumber.equals(ois.getSerialNumber()));
+                serialNumber.equals(ois.getSerialNumber()));
+    }
+
+    @Override
+    public int hashCode() {
+        int result = 17;
+        result = 31 * result + issuerName.hashCode();
+        result = 31 * result + serialNumber.hashCode();
+
+        return result;
     }
 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMXMLObject.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMXMLObject.java 1333415 2012-05-03 12:03:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -32,6 +34,7 @@
 
 import java.security.Provider;
 import java.util.*;
+
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -48,7 +51,8 @@
     private final String id;
     private final String mimeType;
     private final String encoding;
-    private final List content;
+    private final List<XMLStructure> content;
+    private Element objectElem;
 
     /**
      * Creates an <code>XMLObject</code> from the specified parameters.
@@ -63,19 +67,20 @@
      * @throws ClassCastException if <code>content</code> contains any
      *    entries that are not of type {@link XMLStructure}
      */
-    public DOMXMLObject(List content, String id, String mimeType,
-        String encoding) {
+    public DOMXMLObject(List<? extends XMLStructure> content, String id,
+                        String mimeType, String encoding)
+    {
         if (content == null || content.isEmpty()) {
-            this.content = Collections.EMPTY_LIST;
+            this.content = Collections.emptyList();
         } else {
-            List contentCopy = new ArrayList(content);
-            for (int i = 0, size = contentCopy.size(); i < size; i++) {
-                if (!(contentCopy.get(i) instanceof XMLStructure)) {
+            this.content = Collections.unmodifiableList(
+                new ArrayList<XMLStructure>(content));
+            for (int i = 0, size = this.content.size(); i < size; i++) {
+                if (!(this.content.get(i) instanceof XMLStructure)) {
                     throw new ClassCastException
                         ("content["+i+"] is not a valid type");
                 }
             }
-            this.content = Collections.unmodifiableList(contentCopy);
         }
         this.id = id;
         this.mimeType = mimeType;
@@ -89,7 +94,9 @@
      * @throws MarshalException if there is an error when unmarshalling
      */
     public DOMXMLObject(Element objElem, XMLCryptoContext context,
-        Provider provider) throws MarshalException {
+                        Provider provider)
+    throws MarshalException
+    {
         // unmarshal attributes
         this.encoding = DOMUtils.getAttributeValue(objElem, "Encoding");
 
@@ -104,17 +111,17 @@
 
         NodeList nodes = objElem.getChildNodes();
         int length = nodes.getLength();
-        List content = new ArrayList(length);
+        List<XMLStructure> content = new ArrayList<XMLStructure>(length);
         for (int i = 0; i < length; i++) {
             Node child = nodes.item(i);
             if (child.getNodeType() == Node.ELEMENT_NODE) {
-                Element childElem = (Element) child;
+                Element childElem = (Element)child;
                 String tag = childElem.getLocalName();
                 if (tag.equals("Manifest")) {
                     content.add(new DOMManifest(childElem, context, provider));
                     continue;
                 } else if (tag.equals("SignatureProperties")) {
-                    content.add(new DOMSignatureProperties(childElem));
+                    content.add(new DOMSignatureProperties(childElem, context));
                     continue;
                 } else if (tag.equals("X509Data")) {
                     content.add(new DOMX509Data(childElem));
@@ -125,10 +132,11 @@
             content.add(new javax.xml.crypto.dom.DOMStructure(child));
         }
         if (content.isEmpty()) {
-            this.content = Collections.EMPTY_LIST;
+            this.content = Collections.emptyList();
         } else {
             this.content = Collections.unmodifiableList(content);
         }
+        this.objectElem = objElem;
     }
 
     public List getContent() {
@@ -151,29 +159,32 @@
         throws MarshalException {
         Document ownerDoc = DOMUtils.getOwnerDocument(parent);
 
-        Element objElem = DOMUtils.createElement
-            (ownerDoc, "Object", XMLSignature.XMLNS, dsPrefix);
+        Element objElem = objectElem != null ? objectElem : null;
+        if (objElem == null) {
+            objElem = DOMUtils.createElement(ownerDoc, "Object",
+                                             XMLSignature.XMLNS, dsPrefix);
 
-        // set attributes
-        DOMUtils.setAttributeID(objElem, "Id", id);
-        DOMUtils.setAttribute(objElem, "MimeType", mimeType);
-        DOMUtils.setAttribute(objElem, "Encoding", encoding);
+            // set attributes
+            DOMUtils.setAttributeID(objElem, "Id", id);
+            DOMUtils.setAttribute(objElem, "MimeType", mimeType);
+            DOMUtils.setAttribute(objElem, "Encoding", encoding);
 
-        // create and append any elements and mixed content, if necessary
-        for (int i = 0, size = content.size(); i < size; i++) {
-            XMLStructure object = (XMLStructure) content.get(i);
-            if (object instanceof DOMStructure) {
-                ((DOMStructure) object).marshal(objElem, dsPrefix, context);
-            } else {
-                javax.xml.crypto.dom.DOMStructure domObject =
-                    (javax.xml.crypto.dom.DOMStructure) object;
-                DOMUtils.appendChild(objElem, domObject.getNode());
+            // create and append any elements and mixed content, if necessary
+            for (XMLStructure object : content) {
+                if (object instanceof DOMStructure) {
+                    ((DOMStructure)object).marshal(objElem, dsPrefix, context);
+                } else {
+                    javax.xml.crypto.dom.DOMStructure domObject =
+                        (javax.xml.crypto.dom.DOMStructure)object;
+                    DOMUtils.appendChild(objElem, domObject.getNode());
+                }
             }
         }
 
         parent.appendChild(objElem);
     }
 
+    @Override
     public boolean equals(Object o) {
         if (this == o) {
             return true;
@@ -182,34 +193,53 @@
         if (!(o instanceof XMLObject)) {
             return false;
         }
-        XMLObject oxo = (XMLObject) o;
+        XMLObject oxo = (XMLObject)o;
 
-        boolean idsEqual = (id == null ? oxo.getId() == null :
-            id.equals(oxo.getId()));
-        boolean encodingsEqual = (encoding == null ? oxo.getEncoding() == null :
-            encoding.equals(oxo.getEncoding()));
-        boolean mimeTypesEqual = (mimeType == null ? oxo.getMimeType() == null :
-            mimeType.equals(oxo.getMimeType()));
+        boolean idsEqual = (id == null ? oxo.getId() == null
+                                       : id.equals(oxo.getId()));
+        boolean encodingsEqual =
+            (encoding == null ? oxo.getEncoding() == null
+                              : encoding.equals(oxo.getEncoding()));
+        boolean mimeTypesEqual =
+            (mimeType == null ? oxo.getMimeType() == null
+                              : mimeType.equals(oxo.getMimeType()));
 
+        @SuppressWarnings("unchecked")
+        List<XMLStructure> oxoContent = oxo.getContent();
         return (idsEqual && encodingsEqual && mimeTypesEqual &&
-            equalsContent(oxo.getContent()));
+                equalsContent(oxoContent));
     }
 
-    private boolean equalsContent(List otherContent) {
+    @Override
+    public int hashCode() {
+        int result = 17;
+        if (id != null) {
+            result = 31 * result + id.hashCode();
+        }
+        if (encoding != null) {
+            result = 31 * result + encoding.hashCode();
+        }
+        if (mimeType != null) {
+            result = 31 * result + mimeType.hashCode();
+        }
+        result = 31 * result + content.hashCode();
+
+        return result;
+    }
+
+    private boolean equalsContent(List<XMLStructure> otherContent) {
         if (content.size() != otherContent.size()) {
             return false;
         }
         for (int i = 0, osize = otherContent.size(); i < osize; i++) {
-            XMLStructure oxs = (XMLStructure) otherContent.get(i);
-            XMLStructure xs = (XMLStructure) content.get(i);
+            XMLStructure oxs = otherContent.get(i);
+            XMLStructure xs = content.get(i);
             if (oxs instanceof javax.xml.crypto.dom.DOMStructure) {
                 if (!(xs instanceof javax.xml.crypto.dom.DOMStructure)) {
                     return false;
                 }
-                Node onode =
-                    ((javax.xml.crypto.dom.DOMStructure) oxs).getNode();
-                Node node =
-                    ((javax.xml.crypto.dom.DOMStructure) xs).getNode();
+                Node onode = ((javax.xml.crypto.dom.DOMStructure)oxs).getNode();
+                Node node = ((javax.xml.crypto.dom.DOMStructure)xs).getNode();
                 if (!DOMUtils.nodesEqual(node, onode)) {
                     return false;
                 }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
@@ -29,7 +31,7 @@
  * ===========================================================================
  */
 /*
- * $Id: DOMXMLSignature.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMXMLSignature.java 1333415 2012-05-03 12:03:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -40,7 +42,6 @@
 import javax.xml.crypto.dsig.dom.DOMValidateContext;
 import javax.xml.crypto.dsig.keyinfo.KeyInfo;
 
-import java.io.*;
 import java.security.InvalidKeyException;
 import java.security.Key;
 import java.security.Provider;
@@ -48,8 +49,7 @@
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
-import java.util.logging.Level;
-import java.util.logging.Logger;
+
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -67,11 +67,12 @@
 public final class DOMXMLSignature extends DOMStructure
     implements XMLSignature {
 
-    private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom");
+    private static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
     private String id;
     private SignatureValue sv;
     private KeyInfo ki;
-    private List objects;
+    private List<XMLObject> objects;
     private SignedInfo si;
     private Document ownerDoc = null;
     private Element localSigElem = null;
@@ -79,7 +80,7 @@
     private boolean validationStatus;
     private boolean validated = false;
     private KeySelectorResult ksr;
-    private HashMap signatureIdMap;
+    private HashMap<String, XMLStructure> signatureIdMap;
 
     static {
         com.sun.org.apache.xml.internal.security.Init.init();
@@ -98,8 +99,9 @@
      *  omit)
      * @throws NullPointerException if <code>si</code> is <code>null</code>
      */
-    public DOMXMLSignature(SignedInfo si, KeyInfo ki, List objs, String id,
-        String signatureValueId)
+    public DOMXMLSignature(SignedInfo si, KeyInfo ki,
+                           List<? extends XMLObject> objs,
+                           String id, String signatureValueId)
     {
         if (si == null) {
             throw new NullPointerException("signedInfo cannot be null");
@@ -108,16 +110,16 @@
         this.id = id;
         this.sv = new DOMSignatureValue(signatureValueId);
         if (objs == null) {
-            this.objects = Collections.EMPTY_LIST;
+            this.objects = Collections.emptyList();
         } else {
-            List objsCopy = new ArrayList(objs);
-            for (int i = 0, size = objsCopy.size(); i < size; i++) {
-                if (!(objsCopy.get(i) instanceof XMLObject)) {
+            this.objects =
+                Collections.unmodifiableList(new ArrayList<XMLObject>(objs));
+            for (int i = 0, size = this.objects.size(); i < size; i++) {
+                if (!(this.objects.get(i) instanceof XMLObject)) {
                     throw new ClassCastException
                         ("objs["+i+"] is not an XMLObject");
                 }
             }
-            this.objects = Collections.unmodifiableList(objsCopy);
         }
         this.ki = ki;
     }
@@ -129,7 +131,9 @@
      * @throws MarshalException if XMLSignature cannot be unmarshalled
      */
     public DOMXMLSignature(Element sigElem, XMLCryptoContext context,
-        Provider provider) throws MarshalException {
+                           Provider provider)
+        throws MarshalException
+    {
         localSigElem = sigElem;
         ownerDoc = localSigElem.getOwnerDocument();
 
@@ -142,7 +146,7 @@
 
         // unmarshal SignatureValue
         Element sigValElem = DOMUtils.getNextSiblingElement(siElem);
-        sv = new DOMSignatureValue(sigValElem);
+        sv = new DOMSignatureValue(sigValElem, context);
 
         // unmarshal KeyInfo, if specified
         Element nextSibling = DOMUtils.getNextSiblingElement(sigValElem);
@@ -153,12 +157,12 @@
 
         // unmarshal Objects, if specified
         if (nextSibling == null) {
-            objects = Collections.EMPTY_LIST;
+            objects = Collections.emptyList();
         } else {
-            List tempObjects = new ArrayList();
+            List<XMLObject> tempObjects = new ArrayList<XMLObject>();
             while (nextSibling != null) {
-                tempObjects.add
-                    (new DOMXMLObject(nextSibling, context, provider));
+                tempObjects.add(new DOMXMLObject(nextSibling,
+                                                 context, provider));
                 nextSibling = DOMUtils.getNextSiblingElement(nextSibling);
             }
             objects = Collections.unmodifiableList(tempObjects);
@@ -190,41 +194,42 @@
     }
 
     public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException {
+        throws MarshalException
+    {
         marshal(parent, null, dsPrefix, context);
     }
 
     public void marshal(Node parent, Node nextSibling, String dsPrefix,
-        DOMCryptoContext context) throws MarshalException {
+                        DOMCryptoContext context)
+        throws MarshalException
+    {
         ownerDoc = DOMUtils.getOwnerDocument(parent);
-
-        sigElem = DOMUtils.createElement
-            (ownerDoc, "Signature", XMLSignature.XMLNS, dsPrefix);
+        sigElem = DOMUtils.createElement(ownerDoc, "Signature",
+                                         XMLSignature.XMLNS, dsPrefix);
 
         // append xmlns attribute
         if (dsPrefix == null || dsPrefix.length() == 0) {
-            sigElem.setAttributeNS
-                ("http://www.w3.org/2000/xmlns/", "xmlns", XMLSignature.XMLNS);
+            sigElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns",
+                                   XMLSignature.XMLNS);
         } else {
-            sigElem.setAttributeNS
-                ("http://www.w3.org/2000/xmlns/", "xmlns:" + dsPrefix,
-                 XMLSignature.XMLNS);
+            sigElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" +
+                                   dsPrefix, XMLSignature.XMLNS);
         }
 
         // create and append SignedInfo element
-        ((DOMSignedInfo) si).marshal(sigElem, dsPrefix, context);
+        ((DOMSignedInfo)si).marshal(sigElem, dsPrefix, context);
 
         // create and append SignatureValue element
-        ((DOMSignatureValue) sv).marshal(sigElem, dsPrefix, context);
+        ((DOMSignatureValue)sv).marshal(sigElem, dsPrefix, context);
 
         // create and append KeyInfo element if necessary
         if (ki != null) {
-            ((DOMKeyInfo) ki).marshal(sigElem, null, dsPrefix, context);
+            ((DOMKeyInfo)ki).marshal(sigElem, null, dsPrefix, context);
         }
 
         // create and append Object elements if necessary
         for (int i = 0, size = objects.size(); i < size; i++) {
-            ((DOMXMLObject) objects.get(i)).marshal(sigElem, dsPrefix, context);
+            ((DOMXMLObject)objects.get(i)).marshal(sigElem, dsPrefix, context);
         }
 
         // append Id attribute
@@ -234,8 +239,8 @@
     }
 
     public boolean validate(XMLValidateContext vc)
-        throws XMLSignatureException {
-
+        throws XMLSignatureException
+    {
         if (vc == null) {
             throw new NullPointerException("validateContext is null");
         }
@@ -258,20 +263,20 @@
         }
 
         // validate all References
-        List refs = this.si.getReferences();
+        @SuppressWarnings("unchecked")
+        List<Reference> refs = this.si.getReferences();
         boolean validateRefs = true;
         for (int i = 0, size = refs.size(); validateRefs && i < size; i++) {
-            Reference ref = (Reference) refs.get(i);
+            Reference ref = refs.get(i);
             boolean refValid = ref.validate(vc);
-            if (log.isLoggable(Level.FINE)) {
-                log.log(Level.FINE, "Reference[" + ref.getURI() + "] is valid: "
-                    + refValid);
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "Reference[" + ref.getURI() + "] is valid: " + refValid);
             }
             validateRefs &= refValid;
         }
         if (!validateRefs) {
-            if (log.isLoggable(Level.FINE)) {
-                log.log(Level.FINE, "Couldn't validate the References");
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "Couldn't validate the References");
             }
             validationStatus = false;
             validated = true;
@@ -281,27 +286,30 @@
         // validate Manifests, if property set
         boolean validateMans = true;
         if (Boolean.TRUE.equals(vc.getProperty
-            ("org.jcp.xml.dsig.validateManifests"))) {
-
+                                ("org.jcp.xml.dsig.validateManifests")))
+        {
             for (int i=0, size=objects.size(); validateMans && i < size; i++) {
-                XMLObject xo = (XMLObject) objects.get(i);
-                List content = xo.getContent();
+                XMLObject xo = objects.get(i);
+                @SuppressWarnings("unchecked")
+                List<XMLStructure> content = xo.getContent();
                 int csize = content.size();
                 for (int j = 0; validateMans && j < csize; j++) {
-                    XMLStructure xs = (XMLStructure) content.get(j);
+                    XMLStructure xs = content.get(j);
                     if (xs instanceof Manifest) {
-                        if (log.isLoggable(Level.FINE)) {
-                            log.log(Level.FINE, "validating manifest");
+                        if (log.isLoggable(java.util.logging.Level.FINE)) {
+                            log.log(java.util.logging.Level.FINE, "validating manifest");
                         }
-                        Manifest man = (Manifest) xs;
-                        List manRefs = man.getReferences();
+                        Manifest man = (Manifest)xs;
+                        @SuppressWarnings("unchecked")
+                        List<Reference> manRefs = man.getReferences();
                         int rsize = manRefs.size();
                         for (int k = 0; validateMans && k < rsize; k++) {
-                            Reference ref = (Reference) manRefs.get(k);
+                            Reference ref = manRefs.get(k);
                             boolean refValid = ref.validate(vc);
-                            if (log.isLoggable(Level.FINE)) {
-                                log.log(Level.FINE, "Manifest ref["
-                                    + ref.getURI() + "] is valid: " + refValid);
+                            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                                log.log(java.util.logging.Level.FINE,
+                                    "Manifest ref[" + ref.getURI() + "] is valid: " + refValid
+                                );
                             }
                             validateMans &= refValid;
                         }
@@ -316,41 +324,39 @@
     }
 
     public void sign(XMLSignContext signContext)
-        throws MarshalException, XMLSignatureException {
+        throws MarshalException, XMLSignatureException
+    {
         if (signContext == null) {
             throw new NullPointerException("signContext cannot be null");
         }
-        DOMSignContext context = (DOMSignContext) signContext;
-        if (context != null) {
-            marshal(context.getParent(), context.getNextSibling(),
+        DOMSignContext context = (DOMSignContext)signContext;
+        marshal(context.getParent(), context.getNextSibling(),
                 DOMUtils.getSignaturePrefix(context), context);
-        }
 
         // generate references and signature value
-        List allReferences = new ArrayList();
+        List<Reference> allReferences = new ArrayList<Reference>();
 
         // traverse the Signature and register all objects with IDs that
         // may contain References
-        signatureIdMap = new HashMap();
+        signatureIdMap = new HashMap<String, XMLStructure>();
         signatureIdMap.put(id, this);
         signatureIdMap.put(si.getId(), si);
-        List refs = si.getReferences();
-        for (int i = 0, size = refs.size(); i < size; i++) {
-            Reference ref = (Reference) refs.get(i);
+        @SuppressWarnings("unchecked")
+        List<Reference> refs = si.getReferences();
+        for (Reference ref : refs) {
             signatureIdMap.put(ref.getId(), ref);
         }
-        for (int i = 0, size = objects.size(); i < size; i++) {
-            XMLObject obj = (XMLObject) objects.get(i);
+        for (XMLObject obj : objects) {
             signatureIdMap.put(obj.getId(), obj);
-            List content = obj.getContent();
-            for (int j = 0, csize = content.size(); j < csize; j++) {
-                XMLStructure xs = (XMLStructure) content.get(j);
+            @SuppressWarnings("unchecked")
+            List<XMLStructure> content = obj.getContent();
+            for (XMLStructure xs : content) {
                 if (xs instanceof Manifest) {
-                    Manifest man = (Manifest) xs;
+                    Manifest man = (Manifest)xs;
                     signatureIdMap.put(man.getId(), man);
-                    List manRefs = man.getReferences();
-                    for (int k = 0, msize = manRefs.size(); k < msize; k++) {
-                        Reference ref = (Reference) manRefs.get(k);
+                    @SuppressWarnings("unchecked")
+                    List<Reference> manRefs = man.getReferences();
+                    for (Reference ref : manRefs) {
                         allReferences.add(ref);
                         signatureIdMap.put(ref.getId(), ref);
                     }
@@ -359,56 +365,51 @@
         }
         // always add SignedInfo references after Manifest references so
         // that Manifest reference are digested first
-        allReferences.addAll(si.getReferences());
+        allReferences.addAll(refs);
 
         // generate/digest each reference
-        for (int i = 0, size = allReferences.size(); i < size; i++) {
-            DOMReference ref = (DOMReference) allReferences.get(i);
-            digestReference(ref, signContext);
+        for (Reference ref : allReferences) {
+            digestReference((DOMReference)ref, signContext);
         }
 
         // do final sweep to digest any references that were skipped or missed
-        for (int i = 0, size = allReferences.size(); i < size; i++) {
-            DOMReference ref = (DOMReference) allReferences.get(i);
-            if (ref.isDigested()) {
+        for (Reference ref : allReferences) {
+            if (((DOMReference)ref).isDigested()) {
                 continue;
             }
-            ref.digest(signContext);
+            ((DOMReference)ref).digest(signContext);
         }
 
         Key signingKey = null;
         KeySelectorResult ksr = null;
         try {
-            ksr = signContext.getKeySelector().select
-                (ki, KeySelector.Purpose.SIGN,
-                si.getSignatureMethod(), signContext);
+            ksr = signContext.getKeySelector().select(ki,
+                                                      KeySelector.Purpose.SIGN,
+                                                      si.getSignatureMethod(),
+                                                      signContext);
             signingKey = ksr.getKey();
             if (signingKey == null) {
                 throw new XMLSignatureException("the keySelector did not " +
-                "find a signing key");
+                                                "find a signing key");
             }
         } catch (KeySelectorException kse) {
             throw new XMLSignatureException("cannot find signing key", kse);
         }
 
         // calculate signature value
-        byte[] val = null;
         try {
-            val = ((DOMSignatureMethod) si.getSignatureMethod()).sign
-                (signingKey, (DOMSignedInfo) si, signContext);
+            byte[] val = ((AbstractDOMSignatureMethod)
+                si.getSignatureMethod()).sign(signingKey, si, signContext);
+            ((DOMSignatureValue)sv).setValue(val);
         } catch (InvalidKeyException ike) {
             throw new XMLSignatureException(ike);
         }
 
-        if (log.isLoggable(Level.FINE)) {
-            log.log(Level.FINE, "SignatureValue = " + val);
-        }
-        ((DOMSignatureValue) sv).setValue(val);
-
         this.localSigElem = sigElem;
         this.ksr = ksr;
     }
 
+    @Override
     public boolean equals(Object o) {
         if (this == o) {
             return true;
@@ -417,22 +418,39 @@
         if (!(o instanceof XMLSignature)) {
             return false;
         }
-        XMLSignature osig = (XMLSignature) o;
+        XMLSignature osig = (XMLSignature)o;
 
         boolean idEqual =
             (id == null ? osig.getId() == null : id.equals(osig.getId()));
         boolean keyInfoEqual =
-            (ki == null ? osig.getKeyInfo() == null :
-             ki.equals(osig.getKeyInfo()));
+            (ki == null ? osig.getKeyInfo() == null
+                        : ki.equals(osig.getKeyInfo()));
 
         return (idEqual && keyInfoEqual &&
-            sv.equals(osig.getSignatureValue()) &&
-            si.equals(osig.getSignedInfo()) &&
-            objects.equals(osig.getObjects()));
+                sv.equals(osig.getSignatureValue()) &&
+                si.equals(osig.getSignedInfo()) &&
+                objects.equals(osig.getObjects()));
+    }
+
+    @Override
+    public int hashCode() {
+        int result = 17;
+        if (id != null) {
+            result = 31 * result + id.hashCode();
+        }
+        if (ki != null) {
+            result = 31 * result + ki.hashCode();
+        }
+        result = 31 * result + sv.hashCode();
+        result = 31 * result + si.hashCode();
+        result = 31 * result + objects.hashCode();
+
+        return result;
     }
 
     private void digestReference(DOMReference ref, XMLSignContext signContext)
-        throws XMLSignatureException {
+        throws XMLSignatureException
+    {
         if (ref.isDigested()) {
             return;
         }
@@ -441,15 +459,15 @@
         if (Utils.sameDocumentURI(uri)) {
             String id = Utils.parseIdFromSameDocumentURI(uri);
             if (id != null && signatureIdMap.containsKey(id)) {
-                Object obj = signatureIdMap.get(id);
-                if (obj instanceof DOMReference) {
-                    digestReference((DOMReference) obj, signContext);
-                } else if (obj instanceof Manifest) {
-                    Manifest man = (Manifest) obj;
+                XMLStructure xs = signatureIdMap.get(id);
+                if (xs instanceof DOMReference) {
+                    digestReference((DOMReference)xs, signContext);
+                } else if (xs instanceof Manifest) {
+                    Manifest man = (Manifest)xs;
                     List manRefs = man.getReferences();
                     for (int i = 0, size = manRefs.size(); i < size; i++) {
-                        digestReference
-                            ((DOMReference) manRefs.get(i), signContext);
+                        digestReference((DOMReference)manRefs.get(i),
+                                        signContext);
                     }
                 }
             }
@@ -457,9 +475,9 @@
             // reference dependencies in the XPath Transform - so be on
             // the safe side, and skip and do at end in the final sweep
             if (uri.length() == 0) {
-                List transforms = ref.getTransforms();
-                for (int i = 0, size = transforms.size(); i < size; i++) {
-                    Transform transform = (Transform) transforms.get(i);
+                @SuppressWarnings("unchecked")
+                List<Transform> transforms = ref.getTransforms();
+                for (Transform transform : transforms) {
                     String transformAlg = transform.getAlgorithm();
                     if (transformAlg.equals(Transform.XPATH) ||
                         transformAlg.equals(Transform.XPATH2)) {
@@ -472,8 +490,8 @@
     }
 
     public class DOMSignatureValue extends DOMStructure
-        implements SignatureValue {
-
+        implements SignatureValue
+    {
         private String id;
         private byte[] value;
         private String valueBase64;
@@ -485,7 +503,9 @@
             this.id = id;
         }
 
-        DOMSignatureValue(Element sigValueElem) throws MarshalException {
+        DOMSignatureValue(Element sigValueElem, XMLCryptoContext context)
+            throws MarshalException
+        {
             try {
                 // base64 decode signatureValue
                 value = Base64.decode(sigValueElem);
@@ -508,12 +528,12 @@
         }
 
         public byte[] getValue() {
-            return (value == null) ? null : (byte[]) value.clone();
+            return (value == null) ? null : (byte[])value.clone();
         }
 
         public boolean validate(XMLValidateContext validateContext)
-            throws XMLSignatureException {
-
+            throws XMLSignatureException
+        {
             if (validateContext == null) {
                 throw new NullPointerException("context cannot be null");
             }
@@ -531,18 +551,18 @@
                     (ki, KeySelector.Purpose.VERIFY, sm, validateContext);
                 validationKey = ksResult.getKey();
                 if (validationKey == null) {
-                    throw new XMLSignatureException("the keyselector did " +
-                        "not find a validation key");
+                    throw new XMLSignatureException("the keyselector did not " +
+                                                    "find a validation key");
                 }
             } catch (KeySelectorException kse) {
                 throw new XMLSignatureException("cannot find validation " +
-                    "key", kse);
+                                                "key", kse);
             }
 
             // canonicalize SignedInfo and verify signature
             try {
-                validationStatus = ((DOMSignatureMethod) sm).verify
-                    (validationKey, (DOMSignedInfo) si, value, validateContext);
+                validationStatus = ((AbstractDOMSignatureMethod)sm).verify
+                    (validationKey, si, value, validateContext);
             } catch (Exception e) {
                 throw new XMLSignatureException(e);
             }
@@ -552,6 +572,7 @@
             return validationStatus;
         }
 
+        @Override
         public boolean equals(Object o) {
             if (this == o) {
                 return true;
@@ -560,7 +581,7 @@
             if (!(o instanceof SignatureValue)) {
                 return false;
             }
-            SignatureValue osv = (SignatureValue) o;
+            SignatureValue osv = (SignatureValue)o;
 
             boolean idEqual =
                 (id == null ? osv.getId() == null : id.equals(osv.getId()));
@@ -569,12 +590,23 @@
             return idEqual;
         }
 
-        public void marshal(Node parent, String dsPrefix,
-            DOMCryptoContext context) throws MarshalException {
+        @Override
+        public int hashCode() {
+            int result = 17;
+            if (id != null) {
+                result = 31 * result + id.hashCode();
+            }
 
+            return result;
+        }
+
+        public void marshal(Node parent, String dsPrefix,
+                            DOMCryptoContext context)
+            throws MarshalException
+        {
             // create SignatureValue element
-            sigValueElem = DOMUtils.createElement
-                (ownerDoc, "SignatureValue", XMLSignature.XMLNS, dsPrefix);
+            sigValueElem = DOMUtils.createElement(ownerDoc, "SignatureValue",
+                                                  XMLSignature.XMLNS, dsPrefix);
             if (valueBase64 != null) {
                 sigValueElem.appendChild(ownerDoc.createTextNode(valueBase64));
             }
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,31 +2,34 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMXMLSignatureFactory.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMXMLSignatureFactory.java 1333869 2012-05-04 10:42:44Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import javax.xml.crypto.*;
+import javax.xml.crypto.dom.DOMCryptoContext;
 import javax.xml.crypto.dsig.*;
 import javax.xml.crypto.dsig.dom.DOMValidateContext;
 import javax.xml.crypto.dsig.keyinfo.*;
@@ -34,7 +37,6 @@
 
 import java.security.InvalidAlgorithmParameterException;
 import java.security.NoSuchAlgorithmException;
-import java.security.spec.AlgorithmParameterSpec;
 import java.util.List;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -56,6 +58,7 @@
         return new DOMXMLSignature(si, ki, null, null, null);
     }
 
+    @SuppressWarnings("unchecked")
     public XMLSignature newXMLSignature(SignedInfo si, KeyInfo ki,
         List objects, String id, String signatureValueId) {
         return new DOMXMLSignature(si, ki, objects, id, signatureValueId);
@@ -65,11 +68,13 @@
         return newReference(uri, dm, null, null, null);
     }
 
+    @SuppressWarnings("unchecked")
     public Reference newReference(String uri, DigestMethod dm, List transforms,
         String type, String id) {
         return new DOMReference(uri, type, dm, transforms, id, getProvider());
     }
 
+    @SuppressWarnings("unchecked")
     public Reference newReference(String uri, DigestMethod dm,
         List appliedTransforms, Data result, List transforms, String type,
         String id) {
@@ -86,6 +91,7 @@
             (uri, type, dm, appliedTransforms, result, transforms, id, getProvider());
     }
 
+    @SuppressWarnings("unchecked")
     public Reference newReference(String uri, DigestMethod dm, List transforms,
         String type, String id, byte[] digestValue) {
         if (digestValue == null) {
@@ -95,34 +101,41 @@
             (uri, type, dm, null, null, transforms, id, digestValue, getProvider());
     }
 
+    @SuppressWarnings("unchecked")
     public SignedInfo newSignedInfo(CanonicalizationMethod cm,
         SignatureMethod sm, List references) {
         return newSignedInfo(cm, sm, references, null);
     }
 
+    @SuppressWarnings("unchecked")
     public SignedInfo newSignedInfo(CanonicalizationMethod cm,
         SignatureMethod sm, List references, String id) {
         return new DOMSignedInfo(cm, sm, references, id);
     }
 
     // Object factory methods
+    @SuppressWarnings("unchecked")
     public XMLObject newXMLObject(List content, String id, String mimeType,
         String encoding) {
         return new DOMXMLObject(content, id, mimeType, encoding);
     }
 
+    @SuppressWarnings("unchecked")
     public Manifest newManifest(List references) {
         return newManifest(references, null);
     }
 
+    @SuppressWarnings("unchecked")
     public Manifest newManifest(List references, String id) {
         return new DOMManifest(references, id);
     }
 
+    @SuppressWarnings("unchecked")
     public SignatureProperties newSignatureProperties(List props, String id) {
         return new DOMSignatureProperties(props, id);
     }
 
+    @SuppressWarnings("unchecked")
     public SignatureProperty newSignatureProperty
         (List info, String target, String id) {
         return new DOMSignatureProperty(info, target, id);
@@ -143,12 +156,19 @@
         if (xmlStructure == null) {
             throw new NullPointerException("xmlStructure cannot be null");
         }
+        if (!(xmlStructure instanceof javax.xml.crypto.dom.DOMStructure)) {
+            throw new ClassCastException("xmlStructure must be of type DOMStructure");
+        }
         return unmarshal
             (((javax.xml.crypto.dom.DOMStructure) xmlStructure).getNode(),
-             null);
+             new UnmarshalContext());
     }
 
-    private XMLSignature unmarshal(Node node, XMLValidateContext context)
+    private static class UnmarshalContext extends DOMCryptoContext {
+        UnmarshalContext() {}
+    }
+
+    private XMLSignature unmarshal(Node node, XMLCryptoContext context)
         throws MarshalException {
 
         node.normalize();
@@ -221,12 +241,20 @@
             return new DOMSignatureMethod.SHA1withDSA(params);
         } else if (algorithm.equals(SignatureMethod.HMAC_SHA1)) {
             return new DOMHMACSignatureMethod.SHA1(params);
-        } else if (algorithm.equals(DOMSignatureMethod.HMAC_SHA256)) {
+        } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA256)) {
             return new DOMHMACSignatureMethod.SHA256(params);
-        } else if (algorithm.equals(DOMSignatureMethod.HMAC_SHA384)) {
+        } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA384)) {
             return new DOMHMACSignatureMethod.SHA384(params);
-        } else if (algorithm.equals(DOMSignatureMethod.HMAC_SHA512)) {
+        } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA512)) {
             return new DOMHMACSignatureMethod.SHA512(params);
+        } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA1)) {
+            return new DOMSignatureMethod.SHA1withECDSA(params);
+        } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA256)) {
+            return new DOMSignatureMethod.SHA256withECDSA(params);
+        } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA384)) {
+            return new DOMSignatureMethod.SHA384withECDSA(params);
+        } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA512)) {
+            return new DOMSignatureMethod.SHA512withECDSA(params);
         } else {
             throw new NoSuchAlgorithmException("unsupported algorithm");
         }
@@ -235,12 +263,18 @@
     public Transform newTransform(String algorithm,
         TransformParameterSpec params) throws NoSuchAlgorithmException,
         InvalidAlgorithmParameterException {
+
         TransformService spi;
-        try {
+        if (getProvider() == null) {
             spi = TransformService.getInstance(algorithm, "DOM");
-        } catch (NoSuchAlgorithmException nsae) {
-            spi = TransformService.getInstance(algorithm, "DOM", getProvider());
+        } else {
+            try {
+                spi = TransformService.getInstance(algorithm, "DOM", getProvider());
+            } catch (NoSuchAlgorithmException nsae) {
+                spi = TransformService.getInstance(algorithm, "DOM");
+            }
         }
+
         spi.init(params);
         return new DOMTransform(spi);
     }
@@ -249,11 +283,16 @@
         XMLStructure params) throws NoSuchAlgorithmException,
         InvalidAlgorithmParameterException {
         TransformService spi;
-        try {
+        if (getProvider() == null) {
             spi = TransformService.getInstance(algorithm, "DOM");
-        } catch (NoSuchAlgorithmException nsae) {
-            spi = TransformService.getInstance(algorithm, "DOM", getProvider());
+        } else {
+            try {
+                spi = TransformService.getInstance(algorithm, "DOM", getProvider());
+            } catch (NoSuchAlgorithmException nsae) {
+                spi = TransformService.getInstance(algorithm, "DOM");
+            }
         }
+
         if (params == null) {
             spi.init(null);
         } else {
@@ -266,11 +305,16 @@
         C14NMethodParameterSpec params) throws NoSuchAlgorithmException,
         InvalidAlgorithmParameterException {
         TransformService spi;
-        try {
+        if (getProvider() == null) {
             spi = TransformService.getInstance(algorithm, "DOM");
-        } catch (NoSuchAlgorithmException nsae) {
-            spi = TransformService.getInstance(algorithm, "DOM", getProvider());
+        } else {
+            try {
+                spi = TransformService.getInstance(algorithm, "DOM", getProvider());
+            } catch (NoSuchAlgorithmException nsae) {
+                spi = TransformService.getInstance(algorithm, "DOM");
+            }
         }
+
         spi.init(params);
         return new DOMCanonicalizationMethod(spi);
     }
@@ -279,16 +323,21 @@
         XMLStructure params) throws NoSuchAlgorithmException,
         InvalidAlgorithmParameterException {
         TransformService spi;
-        try {
+        if (getProvider() == null) {
             spi = TransformService.getInstance(algorithm, "DOM");
-        } catch (NoSuchAlgorithmException nsae) {
-            spi = TransformService.getInstance(algorithm, "DOM", getProvider());
+        } else {
+            try {
+                spi = TransformService.getInstance(algorithm, "DOM", getProvider());
+            } catch (NoSuchAlgorithmException nsae) {
+                spi = TransformService.getInstance(algorithm, "DOM");
+            }
         }
         if (params == null) {
             spi.init(null);
         } else {
             spi.init(params, null);
         }
+
         return new DOMCanonicalizationMethod(spi);
     }
 
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * ===========================================================================
@@ -29,7 +31,7 @@
  * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMXPathFilter2Transform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMXPathFilter2Transform.java 1203789 2011-11-18 18:46:07Z mullan $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -40,10 +42,10 @@
 import javax.xml.crypto.dsig.spec.XPathFilter2ParameterSpec;
 import java.security.InvalidAlgorithmParameterException;
 import java.util.ArrayList;
-import java.util.Iterator;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.HashMap;
+import java.util.Set;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Element;
 import org.w3c.dom.NamedNodeMap;
@@ -57,7 +59,8 @@
 public final class DOMXPathFilter2Transform extends ApacheTransform {
 
     public void init(TransformParameterSpec params)
-        throws InvalidAlgorithmParameterException {
+        throws InvalidAlgorithmParameterException
+    {
         if (params == null) {
             throw new InvalidAlgorithmParameterException("params are required");
         } else if (!(params instanceof XPathFilter2ParameterSpec)) {
@@ -68,23 +71,23 @@
     }
 
     public void init(XMLStructure parent, XMLCryptoContext context)
-        throws InvalidAlgorithmParameterException {
-
+        throws InvalidAlgorithmParameterException
+    {
         super.init(parent, context);
         try {
             unmarshalParams(DOMUtils.getFirstChildElement(transformElem));
         } catch (MarshalException me) {
-            throw (InvalidAlgorithmParameterException)
-                new InvalidAlgorithmParameterException().initCause(me);
+            throw new InvalidAlgorithmParameterException(me);
         }
     }
 
-    private void unmarshalParams(Element curXPathElem) throws MarshalException {
-        List list = new ArrayList();
+    private void unmarshalParams(Element curXPathElem) throws MarshalException
+    {
+        List<XPathType> list = new ArrayList<XPathType>();
         while (curXPathElem != null) {
             String xPath = curXPathElem.getFirstChild().getNodeValue();
-            String filterVal =
-                DOMUtils.getAttributeValue(curXPathElem, "Filter");
+            String filterVal = DOMUtils.getAttributeValue(curXPathElem,
+                                                          "Filter");
             if (filterVal == null) {
                 throw new MarshalException("filter cannot be null");
             }
@@ -96,15 +99,16 @@
             } else if (filterVal.equals("union")) {
                 filter = XPathType.Filter.UNION;
             } else {
-                throw new MarshalException("Unknown XPathType filter type"
-                    + filterVal);
+                throw new MarshalException("Unknown XPathType filter type" +
+                                           filterVal);
             }
             NamedNodeMap attributes = curXPathElem.getAttributes();
             if (attributes != null) {
                 int length = attributes.getLength();
-                Map namespaceMap = new HashMap(length);
+                Map<String, String> namespaceMap =
+                    new HashMap<String, String>(length);
                 for (int i = 0; i < length; i++) {
-                    Attr attr = (Attr) attributes.item(i);
+                    Attr attr = (Attr)attributes.item(i);
                     String prefix = attr.getPrefix();
                     if (prefix != null && prefix.equals("xmlns")) {
                         namespaceMap.put(attr.getLocalName(), attr.getValue());
@@ -121,32 +125,34 @@
     }
 
     public void marshalParams(XMLStructure parent, XMLCryptoContext context)
-        throws MarshalException {
-
+        throws MarshalException
+    {
         super.marshalParams(parent, context);
         XPathFilter2ParameterSpec xp =
-            (XPathFilter2ParameterSpec) getParameterSpec();
+            (XPathFilter2ParameterSpec)getParameterSpec();
         String prefix = DOMUtils.getNSPrefix(context, Transform.XPATH2);
         String qname = (prefix == null || prefix.length() == 0)
                        ? "xmlns" : "xmlns:" + prefix;
-        List list = xp.getXPathList();
-        for (int i = 0, size = list.size(); i < size; i++) {
-            XPathType xpathType = (XPathType) list.get(i);
-            Element elem = DOMUtils.createElement
-                (ownerDoc, "XPath", Transform.XPATH2, prefix);
+        @SuppressWarnings("unchecked")
+        List<XPathType> xpathList = xp.getXPathList();
+        for (XPathType xpathType : xpathList) {
+            Element elem = DOMUtils.createElement(ownerDoc, "XPath",
+                                                  Transform.XPATH2, prefix);
             elem.appendChild
                 (ownerDoc.createTextNode(xpathType.getExpression()));
-            DOMUtils.setAttribute
-                (elem, "Filter", xpathType.getFilter().toString());
+            DOMUtils.setAttribute(elem, "Filter",
+                                  xpathType.getFilter().toString());
             elem.setAttributeNS("http://www.w3.org/2000/xmlns/", qname,
-                Transform.XPATH2);
+                                Transform.XPATH2);
 
             // add namespace attributes, if necessary
-            Iterator it = xpathType.getNamespaceMap().entrySet().iterator();
-            while (it.hasNext()) {
-                Map.Entry entry = (Map.Entry) it.next();
-                elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:"
-                    + (String) entry.getKey(), (String) entry.getValue());
+            @SuppressWarnings("unchecked")
+            Set<Map.Entry<String, String>> entries =
+                xpathType.getNamespaceMap().entrySet();
+            for (Map.Entry<String, String> entry : entries) {
+                elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" +
+                                    entry.getKey(),
+                                    entry.getValue());
             }
 
             transformElem.appendChild(elem);
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathTransform.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathTransform.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMXPathTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMXPathTransform.java 1203789 2011-11-18 18:46:07Z mullan $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -31,9 +33,9 @@
 import javax.xml.crypto.dsig.spec.TransformParameterSpec;
 import javax.xml.crypto.dsig.spec.XPathFilterParameterSpec;
 import java.security.InvalidAlgorithmParameterException;
-import java.util.Iterator;
+import java.util.HashMap;
 import java.util.Map;
-import java.util.HashMap;
+import java.util.Set;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Element;
 import org.w3c.dom.NamedNodeMap;
@@ -47,7 +49,8 @@
 public final class DOMXPathTransform extends ApacheTransform {
 
     public void init(TransformParameterSpec params)
-        throws InvalidAlgorithmParameterException {
+        throws InvalidAlgorithmParameterException
+    {
         if (params == null) {
             throw new InvalidAlgorithmParameterException("params are required");
         } else if (!(params instanceof XPathFilterParameterSpec)) {
@@ -58,8 +61,8 @@
     }
 
     public void init(XMLStructure parent, XMLCryptoContext context)
-        throws InvalidAlgorithmParameterException {
-
+        throws InvalidAlgorithmParameterException
+    {
         super.init(parent, context);
         unmarshalParams(DOMUtils.getFirstChildElement(transformElem));
     }
@@ -70,9 +73,10 @@
         NamedNodeMap attributes = paramsElem.getAttributes();
         if (attributes != null) {
             int length = attributes.getLength();
-            Map namespaceMap = new HashMap(length);
+            Map<String, String> namespaceMap =
+                new HashMap<String, String>(length);
             for (int i = 0; i < length; i++) {
-                Attr attr = (Attr) attributes.item(i);
+                Attr attr = (Attr)attributes.item(i);
                 String prefix = attr.getPrefix();
                 if (prefix != null && prefix.equals("xmlns")) {
                     namespaceMap.put(attr.getLocalName(), attr.getValue());
@@ -85,22 +89,23 @@
     }
 
     public void marshalParams(XMLStructure parent, XMLCryptoContext context)
-        throws MarshalException {
-
+        throws MarshalException
+    {
         super.marshalParams(parent, context);
         XPathFilterParameterSpec xp =
-            (XPathFilterParameterSpec) getParameterSpec();
-        Element xpathElem = DOMUtils.createElement
-            (ownerDoc, "XPath", XMLSignature.XMLNS,
-             DOMUtils.getSignaturePrefix(context));
+            (XPathFilterParameterSpec)getParameterSpec();
+        Element xpathElem = DOMUtils.createElement(ownerDoc, "XPath",
+             XMLSignature.XMLNS, DOMUtils.getSignaturePrefix(context));
         xpathElem.appendChild(ownerDoc.createTextNode(xp.getXPath()));
 
         // add namespace attributes, if necessary
-        Iterator i = xp.getNamespaceMap().entrySet().iterator();
-        while (i.hasNext()) {
-            Map.Entry entry = (Map.Entry) i.next();
-            xpathElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:"
-                + (String) entry.getKey(), (String) entry.getValue());
+        @SuppressWarnings("unchecked")
+        Set<Map.Entry<String, String>> entries =
+            xp.getNamespaceMap().entrySet();
+        for (Map.Entry<String, String> entry : entries) {
+            xpathElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" +
+                                     entry.getKey(),
+                                     entry.getValue());
         }
 
         transformElem.appendChild(xpathElem);
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXSLTTransform.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXSLTTransform.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMXSLTTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMXSLTTransform.java 1197150 2011-11-03 14:34:57Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -31,7 +33,6 @@
 import org.w3c.dom.Node;
 
 import javax.xml.crypto.*;
-import javax.xml.crypto.dsig.*;
 import javax.xml.crypto.dsig.spec.TransformParameterSpec;
 import javax.xml.crypto.dsig.spec.XSLTTransformParameterSpec;
 
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,27 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: Utils.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: Utils.java 1197150 2011-11-03 14:34:57Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -44,7 +46,8 @@
     private Utils() {}
 
     public static byte[] readBytesFromStream(InputStream is)
-        throws IOException {
+        throws IOException
+    {
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         byte[] buf = new byte[1024];
         while (true) {
@@ -67,10 +70,10 @@
      * @param i the Iterator
      * @return the Set of Nodes
      */
-    static Set toNodeSet(Iterator i) {
-        Set nodeSet = new HashSet();
+    static Set<Node> toNodeSet(Iterator<Node> i) {
+        Set<Node> nodeSet = new HashSet<Node>();
         while (i.hasNext()) {
-            Node n = (Node) i.next();
+            Node n = i.next();
             nodeSet.add(n);
             // insert attributes nodes to comply with XPath
             if (n.getNodeType() == Node.ELEMENT_NODE) {
--- a/src/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java	Mon Jul 22 17:37:15 2013 -0700
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 /*
  * ===========================================================================
@@ -29,7 +31,7 @@
  * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: XMLDSigRI.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: XMLDSigRI.java 1400021 2012-10-19 10:16:04Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -53,13 +55,15 @@
     static final long serialVersionUID = -5049765099299494554L;
 
     private static final String INFO = "XMLDSig " +
-    "(DOM XMLSignatureFactory; DOM KeyInfoFactory)";
+        "(DOM XMLSignatureFactory; DOM KeyInfoFactory; " +
+        "C14N 1.0, C14N 1.1, Exclusive C14N, Base64, Enveloped, XPath, " +
+        "XPath2, XSLT TransformServices)";
 
     public XMLDSigRI() {
         /* We are the XMLDSig provider */
-        super("XMLDSig", 1.0, INFO);
+        super("XMLDSig", 1.8, INFO);
 
-        final Map map = new HashMap();
+        final Map<Object, Object> map = new HashMap<Object, Object>();
         map.put("XMLSignatureFactory.DOM",
                 "org.jcp.xml.dsig.internal.dom.DOMXMLSignatureFactory");
         map.put("KeyInfoFactory.DOM",
@@ -67,94 +71,89 @@
 
 
         // Inclusive C14N
-        map.put((String)"TransformService." + CanonicalizationMethod.INCLUSIVE,
+        map.put("TransformService." + CanonicalizationMethod.INCLUSIVE,
                 "org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod");
         map.put("Alg.Alias.TransformService.INCLUSIVE",
                 CanonicalizationMethod.INCLUSIVE);
-        map.put((String)"TransformService." + CanonicalizationMethod.INCLUSIVE +
+        map.put("TransformService." + CanonicalizationMethod.INCLUSIVE +
                 " MechanismType", "DOM");
 
         // InclusiveWithComments C14N
-        map.put((String) "TransformService." +
+        map.put("TransformService." +
                 CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                 "org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod");
         map.put("Alg.Alias.TransformService.INCLUSIVE_WITH_COMMENTS",
                 CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS);
-        map.put((String) "TransformService." +
+        map.put("TransformService." +
                 CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS +
                 " MechanismType", "DOM");
 
         // Inclusive C14N 1.1
-        map.put((String)"TransformService." +
-                "http://www.w3.org/2006/12/xml-c14n11",
+        map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11",
                 "org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method");
-        map.put((String)"TransformService." +
-                "http://www.w3.org/2006/12/xml-c14n11" +
+        map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11" +
                 " MechanismType", "DOM");
 
         // InclusiveWithComments C14N 1.1
-        map.put((String)"TransformService." +
-                "http://www.w3.org/2006/12/xml-c14n11#WithComments",
+        map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11#WithComments",
                 "org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method");
-        map.put((String)"TransformService." +
-                "http://www.w3.org/2006/12/xml-c14n11#WithComments" +
+        map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11#WithComments" +
                 " MechanismType", "DOM");
 
         // Exclusive C14N
-        map.put((String) "TransformService." + CanonicalizationMethod.EXCLUSIVE,
+        map.put("TransformService." + CanonicalizationMethod.EXCLUSIVE,
                 "org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod");
         map.put("Alg.Alias.TransformService.EXCLUSIVE",
                 CanonicalizationMethod.EXCLUSIVE);
-        map.put((String)"TransformService." + CanonicalizationMethod.EXCLUSIVE +
+        map.put("TransformService." + CanonicalizationMethod.EXCLUSIVE +
                 " MechanismType", "DOM");
 
         // ExclusiveWithComments C14N
-        map.put((String) "TransformService." +
+        map.put("TransformService." +
                 CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
                 "org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod");
         map.put("Alg.Alias.TransformService.EXCLUSIVE_WITH_COMMENTS",
                 CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS);
-        map.put((String) "TransformService." +
+        map.put("TransformService." +
                 CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS +
                 " MechanismType", "DOM");
 
         // Base64 Transform
-        map.put((String) "TransformService." + Transform.BASE64,
+        map.put("TransformService." + Transform.BASE64,
                 "org.jcp.xml.dsig.internal.dom.DOMBase64Transform");
         map.put("Alg.Alias.TransformService.BASE64", Transform.BASE64);
-        map.put((String) "TransformService." + Transform.BASE64 +
+        map.put("TransformService." + Transform.BASE64 +
                 " MechanismType", "DOM");
 
         // Enveloped Transform
-        map.put((String) "TransformService." + Transform.ENVELOPED,
+        map.put("TransformService." + Transform.ENVELOPED,
                 "org.jcp.xml.dsig.internal.dom.DOMEnvelopedTransform");
         map.put("Alg.Alias.TransformService.ENVELOPED", Transform.ENVELOPED);
-        map.put((String) "TransformService." + Transform.ENVELOPED +
+        map.put("TransformService." + Transform.ENVELOPED +
                 " MechanismType", "DOM");
 
         // XPath2 Transform
-        map.put((String) "TransformService." + Transform.XPATH2,
+        map.put("TransformService." + Transform.XPATH2,
                 "org.jcp.xml.dsig.internal.dom.DOMXPathFilter2Transform");
         map.put("Alg.Alias.TransformService.XPATH2", Transform.XPATH2);
-        map.put((String) "TransformService." + Transform.XPATH2 +
+        map.put("TransformService." + Transform.XPATH2 +
                 " MechanismType", "DOM");
 
         // XPath Transform
-        map.put((String) "TransformService." + Transform.XPATH,
+        map.put("TransformService." + Transform.XPATH,
                 "org.jcp.xml.dsig.internal.dom.DOMXPathTransform");
         map.put("Alg.Alias.TransformService.XPATH", Transform.XPATH);
-        map.put((String) "TransformService." + Transform.XPATH +
+        map.put("TransformService." + Transform.XPATH +
                 " MechanismType", "DOM");
 
         // XSLT Transform
-        map.put((String) "TransformService." + Transform.XSLT,
+        map.put("TransformService." + Transform.XSLT,
                 "org.jcp.xml.dsig.internal.dom.DOMXSLTTransform");
         map.put("Alg.Alias.TransformService.XSLT", Transform.XSLT);
-        map.put((String) "TransformService." + Transform.XSLT +
-                " MechanismType", "DOM");
+        map.put("TransformService." + Transform.XSLT + " MechanismType", "DOM");
 
-        AccessController.doPrivileged(new java.security.PrivilegedAction() {
-            public Object run() {
+        AccessController.doPrivileged(new PrivilegedAction<Void>() {
+            public Void run() {
                 putAll(map);
                 return null;
             }
--- a/src/share/classes/sun/java2d/SunGraphics2D.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/sun/java2d/SunGraphics2D.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1795,20 +1795,10 @@
     }
 
     public Rectangle getClipBounds() {
-        Rectangle r;
         if (clipState == CLIP_DEVICE) {
-            r = null;
-        } else if (transformState <= TRANSFORM_INT_TRANSLATE) {
-            if (usrClip instanceof Rectangle) {
-                r = new Rectangle((Rectangle) usrClip);
-            } else {
-                r = usrClip.getBounds();
-            }
-            r.translate(-transX, -transY);
-        } else {
-            r = getClip().getBounds();
+            return null;
         }
-        return r;
+        return getClipBounds(new Rectangle());
     }
 
     public Rectangle getClipBounds(Rectangle r) {
@@ -1817,11 +1807,11 @@
                 if (usrClip instanceof Rectangle) {
                     r.setBounds((Rectangle) usrClip);
                 } else {
-                    r.setBounds(usrClip.getBounds());
+                    r.setFrame(usrClip.getBounds2D());
                 }
                 r.translate(-transX, -transY);
             } else {
-                r.setBounds(getClip().getBounds());
+                r.setFrame(getClip().getBounds2D());
             }
         } else if (r == null) {
             throw new NullPointerException("null rectangle parameter");
@@ -1996,10 +1986,10 @@
             matrix[2] = matrix[0] + rect.getWidth();
             matrix[3] = matrix[1] + rect.getHeight();
             tx.transform(matrix, 0, matrix, 0, 2);
-            rect = new Rectangle2D.Float();
-            rect.setFrameFromDiagonal(matrix[0], matrix[1],
-                                      matrix[2], matrix[3]);
-            return rect;
+            fixRectangleOrientation(matrix, rect);
+            return new Rectangle2D.Double(matrix[0], matrix[1],
+                                          matrix[2] - matrix[0],
+                                          matrix[3] - matrix[1]);
         }
 
         if (tx.isIdentity()) {
@@ -2009,6 +1999,22 @@
         return tx.createTransformedShape(clip);
     }
 
+    /**
+     * Sets orientation of the rectangle according to the clip.
+     */
+    private static void fixRectangleOrientation(double[] m, Rectangle2D clip) {
+        if (clip.getWidth() > 0 != (m[2] - m[0] > 0)) {
+            double t = m[0];
+            m[0] = m[2];
+            m[2] = t;
+        }
+        if (clip.getHeight() > 0 != (m[3] - m[1] > 0)) {
+            double t = m[1];
+            m[1] = m[3];
+            m[3] = t;
+        }
+    }
+
     public void clipRect(int x, int y, int w, int h) {
         clip(new Rectangle(x, y, w, h));
     }
--- a/src/share/classes/sun/management/ManagementFactoryHelper.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/sun/management/ManagementFactoryHelper.java	Mon Jul 22 17:37:15 2013 -0700
@@ -147,18 +147,20 @@
         }
     }
 
-    // The logging MXBean object is an instance of
-    // PlatformLoggingMXBean and java.util.logging.LoggingMXBean
-    // but it can't directly implement two MXBean interfaces
-    // as a compliant MXBean implements exactly one MXBean interface,
-    // or if it implements one interface that is a subinterface of
-    // all the others; otherwise, it is a non-compliant MXBean
-    // and MBeanServer will throw NotCompliantMBeanException.
-    // See the Definition of an MXBean section in javax.management.MXBean spec.
-    //
-    // To create a compliant logging MXBean, define a LoggingMXBean interface
-    // that extend PlatformLoggingMXBean and j.u.l.LoggingMXBean
-    interface LoggingMXBean
+    /**
+     * The logging MXBean object is an instance of
+     * PlatformLoggingMXBean and java.util.logging.LoggingMXBean
+     * but it can't directly implement two MXBean interfaces
+     * as a compliant MXBean implements exactly one MXBean interface,
+     * or if it implements one interface that is a subinterface of
+     * all the others; otherwise, it is a non-compliant MXBean
+     * and MBeanServer will throw NotCompliantMBeanException.
+     * See the Definition of an MXBean section in javax.management.MXBean spec.
+     *
+     * To create a compliant logging MXBean, define a LoggingMXBean interface
+     * that extend PlatformLoggingMXBean and j.u.l.LoggingMXBean
+    */
+    public interface LoggingMXBean
         extends PlatformLoggingMXBean, java.util.logging.LoggingMXBean {
     }
 
--- a/src/share/classes/sun/misc/JavaLangAccess.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/sun/misc/JavaLangAccess.java	Mon Jul 22 17:37:15 2013 -0700
@@ -36,10 +36,10 @@
     ConstantPool getConstantPool(Class<?> klass);
 
     /**
-     * Set the AnnotationType instance corresponding to this class.
+     * Compare-And-Swap the AnnotationType instance corresponding to this class.
      * (This method only applies to annotation types.)
      */
-    void setAnnotationType(Class<?> klass, AnnotationType annotationType);
+    boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType);
 
     /**
      * Get the AnnotationType instance corresponding to this class.
@@ -49,6 +49,12 @@
 
     /**
      * Get the array of bytes that is the class-file representation
+     * of this Class' annotations.
+     */
+    byte[] getRawClassAnnotations(Class<?> klass);
+
+    /**
+     * Get the array of bytes that is the class-file representation
      * of this Class' type annotations.
      */
     byte[] getRawClassTypeAnnotations(Class<?> klass);
--- a/src/share/classes/sun/reflect/annotation/AnnotationParser.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/sun/reflect/annotation/AnnotationParser.java	Mon Jul 22 17:37:15 2013 -0700
@@ -69,7 +69,35 @@
             return Collections.emptyMap();
 
         try {
-            return parseAnnotations2(rawAnnotations, constPool, container);
+            return parseAnnotations2(rawAnnotations, constPool, container, null);
+        } catch(BufferUnderflowException e) {
+            throw new AnnotationFormatError("Unexpected end of annotations.");
+        } catch(IllegalArgumentException e) {
+            // Type mismatch in constant pool
+            throw new AnnotationFormatError(e);
+        }
+    }
+
+    /**
+     * Like {@link #parseAnnotations(byte[], sun.reflect.ConstantPool, Class)}
+     * with an additional parameter {@code selectAnnotationClasses} which selects the
+     * annotation types to parse (other than selected are quickly skipped).<p>
+     * This method is only used to parse select meta annotations in the construction
+     * phase of {@link AnnotationType} instances to prevent infinite recursion.
+     *
+     * @param selectAnnotationClasses an array of annotation types to select when parsing
+     */
+    @SafeVarargs
+    static Map<Class<? extends Annotation>, Annotation> parseSelectAnnotations(
+                byte[] rawAnnotations,
+                ConstantPool constPool,
+                Class<?> container,
+                Class<? extends Annotation> ... selectAnnotationClasses) {
+        if (rawAnnotations == null)
+            return Collections.emptyMap();
+
+        try {
+            return parseAnnotations2(rawAnnotations, constPool, container, selectAnnotationClasses);
         } catch(BufferUnderflowException e) {
             throw new AnnotationFormatError("Unexpected end of annotations.");
         } catch(IllegalArgumentException e) {
@@ -81,22 +109,23 @@
     private static Map<Class<? extends Annotation>, Annotation> parseAnnotations2(
                 byte[] rawAnnotations,
                 ConstantPool constPool,
-                Class<?> container) {
+                Class<?> container,
+                Class<? extends Annotation>[] selectAnnotationClasses) {
         Map<Class<? extends Annotation>, Annotation> result =
             new LinkedHashMap<Class<? extends Annotation>, Annotation>();
         ByteBuffer buf = ByteBuffer.wrap(rawAnnotations);
         int numAnnotations = buf.getShort() & 0xFFFF;
         for (int i = 0; i < numAnnotations; i++) {
-            Annotation a = parseAnnotation(buf, constPool, container, false);
+            Annotation a = parseAnnotation2(buf, constPool, container, false, selectAnnotationClasses);
             if (a != null) {
                 Class<? extends Annotation> klass = a.annotationType();
-                AnnotationType type = AnnotationType.getInstance(klass);
-                if (type.retention() == RetentionPolicy.RUNTIME)
-                    if (result.put(klass, a) != null)
+                if (AnnotationType.getInstance(klass).retention() == RetentionPolicy.RUNTIME &&
+                    result.put(klass, a) != null) {
                         throw new AnnotationFormatError(
                             "Duplicate annotation for class: "+klass+": " + a);
             }
         }
+        }
         return result;
     }
 
@@ -189,11 +218,19 @@
      * TypeNotPresentException if a referenced annotation type is not
      * available at runtime
      */
-    @SuppressWarnings("unchecked")
     static Annotation parseAnnotation(ByteBuffer buf,
                                               ConstantPool constPool,
                                               Class<?> container,
                                               boolean exceptionOnMissingAnnotationClass) {
+       return parseAnnotation2(buf, constPool, container, exceptionOnMissingAnnotationClass, null);
+    }
+
+    @SuppressWarnings("unchecked")
+    private static Annotation parseAnnotation2(ByteBuffer buf,
+                                              ConstantPool constPool,
+                                              Class<?> container,
+                                              boolean exceptionOnMissingAnnotationClass,
+                                              Class<? extends Annotation>[] selectAnnotationClasses) {
         int typeIndex = buf.getShort() & 0xFFFF;
         Class<? extends Annotation> annotationClass = null;
         String sig = "[unknown]";
@@ -219,6 +256,10 @@
             skipAnnotation(buf, false);
             return null;
         }
+        if (selectAnnotationClasses != null && !contains(selectAnnotationClasses, annotationClass)) {
+            skipAnnotation(buf, false);
+            return null;
+        }
         AnnotationType type = null;
         try {
             type = AnnotationType.getInstance(annotationClass);
@@ -800,6 +841,17 @@
             skipMemberValue(buf);
     }
 
+    /**
+     * Searches for given {@code element} in given {@code array} by identity.
+     * Returns {@code true} if found {@code false} if not.
+     */
+    private static boolean contains(Object[] array, Object element) {
+        for (Object e : array)
+            if (e == element)
+                return true;
+        return false;
+    }
+
     /*
      * This method converts the annotation map returned by the parseAnnotations()
      * method to an array.  It is called by Field.getDeclaredAnnotations(),
--- a/src/share/classes/sun/reflect/annotation/AnnotationType.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/sun/reflect/annotation/AnnotationType.java	Mon Jul 22 17:37:15 2013 -0700
@@ -25,6 +25,8 @@
 
 package sun.reflect.annotation;
 
+import sun.misc.JavaLangAccess;
+
 import java.lang.annotation.*;
 import java.lang.reflect.*;
 import java.util.*;
@@ -61,12 +63,12 @@
     /**
      * The retention policy for this annotation type.
      */
-    private RetentionPolicy retention = RetentionPolicy.RUNTIME;;
+    private final RetentionPolicy retention;
 
     /**
      * Whether this annotation type is inherited.
      */
-    private boolean inherited = false;
+    private final boolean inherited;
 
     /**
      * Returns an AnnotationType instance for the specified annotation type.
@@ -74,13 +76,20 @@
      * @throw IllegalArgumentException if the specified class object for
      *     does not represent a valid annotation type
      */
-    public static synchronized AnnotationType getInstance(
+    public static AnnotationType getInstance(
         Class<? extends Annotation> annotationClass)
     {
-        AnnotationType result = sun.misc.SharedSecrets.getJavaLangAccess().
-            getAnnotationType(annotationClass);
-        if (result == null)
-            result = new AnnotationType((Class<? extends Annotation>) annotationClass);
+        JavaLangAccess jla = sun.misc.SharedSecrets.getJavaLangAccess();
+        AnnotationType result = jla.getAnnotationType(annotationClass); // volatile read
+        if (result == null) {
+            result = new AnnotationType(annotationClass);
+            // try to CAS the AnnotationType: null -> result
+            if (!jla.casAnnotationType(annotationClass, null, result)) {
+                // somebody was quicker -> read it's result
+                result = jla.getAnnotationType(annotationClass);
+                assert result != null;
+            }
+        }
 
         return result;
     }
@@ -121,16 +130,25 @@
                 memberDefaults.put(name, defaultValue);
         }
 
-        sun.misc.SharedSecrets.getJavaLangAccess().
-            setAnnotationType(annotationClass, this);
-
         // Initialize retention, & inherited fields.  Special treatment
         // of the corresponding annotation types breaks infinite recursion.
         if (annotationClass != Retention.class &&
             annotationClass != Inherited.class) {
-            Retention ret = annotationClass.getAnnotation(Retention.class);
+            JavaLangAccess jla = sun.misc.SharedSecrets.getJavaLangAccess();
+            Map<Class<? extends Annotation>, Annotation> metaAnnotations =
+                AnnotationParser.parseSelectAnnotations(
+                    jla.getRawClassAnnotations(annotationClass),
+                    jla.getConstantPool(annotationClass),
+                    annotationClass,
+                    Retention.class, Inherited.class
+                );
+            Retention ret = (Retention) metaAnnotations.get(Retention.class);
             retention = (ret == null ? RetentionPolicy.CLASS : ret.value());
-            inherited = annotationClass.isAnnotationPresent(Inherited.class);
+            inherited = metaAnnotations.containsKey(Inherited.class);
+        }
+        else {
+            retention = RetentionPolicy.RUNTIME;
+            inherited = false;
         }
     }
 
@@ -205,11 +223,10 @@
      * For debugging.
      */
     public String toString() {
-        StringBuffer s = new StringBuffer("Annotation Type:" + "\n");
-        s.append("   Member types: " + memberTypes + "\n");
-        s.append("   Member defaults: " + memberDefaults + "\n");
-        s.append("   Retention policy: " + retention + "\n");
-        s.append("   Inherited: " + inherited);
-        return s.toString();
+        return "Annotation Type:\n" +
+               "   Member types: " + memberTypes + "\n" +
+               "   Member defaults: " + memberDefaults + "\n" +
+               "   Retention policy: " + retention + "\n" +
+               "   Inherited: " + inherited;
     }
 }
--- a/src/share/classes/sun/security/pkcs11/Config.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/sun/security/pkcs11/Config.java	Mon Jul 22 17:37:15 2013 -0700
@@ -197,6 +197,10 @@
     // (false).
     private boolean useEcX963Encoding = false;
 
+    // Flag to indicate whether NSS should favour performance (false) or
+    // memory footprint (true).
+    private boolean nssOptimizeSpace = false;
+
     private Config(String filename, InputStream in) throws IOException {
         if (in == null) {
             if (filename.startsWith("--")) {
@@ -329,6 +333,10 @@
         return useEcX963Encoding;
     }
 
+    boolean getNssOptimizeSpace() {
+        return nssOptimizeSpace;
+    }
+
     private static String expand(final String s) throws IOException {
         try {
             return PropertyExpander.expand(s);
@@ -451,6 +459,8 @@
                 nssUseSecmodTrust = parseBooleanEntry(word);
             } else if (word.equals("useEcX963Encoding")) {
                 useEcX963Encoding = parseBooleanEntry(word);
+            } else if (word.equals("nssOptimizeSpace")) {
+                nssOptimizeSpace = parseBooleanEntry(word);
             } else {
                 throw new ConfigurationException
                         ("Unknown keyword '" + word + "', line " + st.lineno());
--- a/src/share/classes/sun/security/pkcs11/P11Key.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/sun/security/pkcs11/P11Key.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -65,6 +65,8 @@
  */
 abstract class P11Key implements Key, Length {
 
+    private static final long serialVersionUID = -2575874101938349339L;
+
     private final static String PUBLIC = "public";
     private final static String PRIVATE = "private";
     private final static String SECRET = "secret";
@@ -881,6 +883,29 @@
             return super.toString() +  "\n  x: " + x + "\n  p: " + params.getP()
                 + "\n  g: " + params.getG();
         }
+        public int hashCode() {
+            if (token.isValid() == false) {
+                return 0;
+            }
+            fetchValues();
+            return Objects.hash(x, params.getP(), params.getG());
+        }
+        public boolean equals(Object obj) {
+            if (this == obj) return true;
+            // equals() should never throw exceptions
+            if (token.isValid() == false) {
+                return false;
+            }
+            if (!(obj instanceof DHPrivateKey)) {
+                return false;
+            }
+            fetchValues();
+            DHPrivateKey other = (DHPrivateKey) obj;
+            DHParameterSpec otherParams = other.getParams();
+            return ((this.x.compareTo(other.getX()) == 0) &&
+                    (this.params.getP().compareTo(otherParams.getP()) == 0) &&
+                    (this.params.getG().compareTo(otherParams.getG()) == 0));
+        }
     }
 
     private static final class P11DHPublicKey extends P11Key
@@ -945,6 +970,29 @@
             return super.toString() +  "\n  y: " + y + "\n  p: " + params.getP()
                 + "\n  g: " + params.getG();
         }
+        public int hashCode() {
+            if (token.isValid() == false) {
+                return 0;
+            }
+            fetchValues();
+            return Objects.hash(y, params.getP(), params.getG());
+        }
+        public boolean equals(Object obj) {
+            if (this == obj) return true;
+            // equals() should never throw exceptions
+            if (token.isValid() == false) {
+                return false;
+            }
+            if (!(obj instanceof DHPublicKey)) {
+                return false;
+            }
+            fetchValues();
+            DHPublicKey other = (DHPublicKey) obj;
+            DHParameterSpec otherParams = other.getParams();
+            return ((this.y.compareTo(other.getY()) == 0) &&
+                    (this.params.getP().compareTo(otherParams.getP()) == 0) &&
+                    (this.params.getG().compareTo(otherParams.getG()) == 0));
+        }
     }
 
     private static final class P11ECPrivateKey extends P11Key
--- a/src/share/classes/sun/security/pkcs11/Secmod.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/sun/security/pkcs11/Secmod.java	Mon Jul 22 17:37:15 2013 -0700
@@ -158,11 +158,17 @@
      */
     public void initialize(String configDir, String nssLibDir)
             throws IOException {
-        initialize(DbMode.READ_WRITE, configDir, nssLibDir);
+        initialize(DbMode.READ_WRITE, configDir, nssLibDir, false);
     }
 
-    public synchronized void initialize(DbMode dbMode, String configDir, String nssLibDir)
+    public void initialize(DbMode dbMode, String configDir, String nssLibDir)
             throws IOException {
+        initialize(dbMode, configDir, nssLibDir, false);
+    }
+
+    public synchronized void initialize(DbMode dbMode, String configDir,
+        String nssLibDir, boolean nssOptimizeSpace) throws IOException {
+
         if (isInitialized()) {
             throw new IOException("NSS is already initialized");
         }
@@ -211,7 +217,8 @@
         }
 
         if (DEBUG) System.out.println("dir: " + configDir);
-        boolean initok = nssInit(dbMode.functionName, nssHandle, configDir);
+        boolean initok = nssInitialize(dbMode.functionName, nssHandle,
+            configDir, nssOptimizeSpace);
         if (DEBUG) System.out.println("init: " + initok);
         if (initok == false) {
             throw new IOException("NSS initialization failed");
@@ -764,7 +771,7 @@
 
     private static native boolean nssVersionCheck(long handle, String minVersion);
 
-    private static native boolean nssInit(String functionName, long handle, String configDir);
+    private static native boolean nssInitialize(String functionName, long handle, String configDir, boolean nssOptimizeSpace);
 
     private static native Object nssGetModuleList(long handle, String libDir);
 
--- a/src/share/classes/sun/security/pkcs11/SunPKCS11.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/sun/security/pkcs11/SunPKCS11.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -167,6 +167,7 @@
             try {
                 String nssLibraryDirectory = config.getNssLibraryDirectory();
                 String nssSecmodDirectory = config.getNssSecmodDirectory();
+                boolean nssOptimizeSpace = config.getNssOptimizeSpace();
 
                 if (secmod.isInitialized()) {
                     if (nssSecmodDirectory != null) {
@@ -204,7 +205,7 @@
                         }
                     }
                     secmod.initialize(nssDbMode, nssSecmodDirectory,
-                        nssLibraryDirectory);
+                        nssLibraryDirectory, nssOptimizeSpace);
                 }
             } catch (IOException e) {
                 // XXX which exception to throw
--- a/src/share/classes/sun/security/provider/certpath/RevocationChecker.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/classes/sun/security/provider/certpath/RevocationChecker.java	Mon Jul 22 17:37:15 2013 -0700
@@ -675,12 +675,8 @@
                                       responderURI, respCert, params.date(),
                                       ocspExtensions);
             }
-        } catch (Exception e) {
-            if (e instanceof CertPathValidatorException) {
-                throw (CertPathValidatorException) e;
-            } else {
-                throw new CertPathValidatorException(e);
-            }
+        } catch (IOException e) {
+            throw new CertPathValidatorException(e);
         }
 
         RevocationStatus rs =
--- a/src/share/lib/security/java.security-linux	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/lib/security/java.security-linux	Mon Jul 22 17:37:15 2013 -0700
@@ -177,7 +177,6 @@
 # corresponding RuntimePermission ("accessClassInPackage."+package) has
 # been granted.
 package.access=sun.,\
-               com.sun.corba.se.impl.,\
                com.sun.xml.internal.,\
                com.sun.imageio.,\
                com.sun.istack.internal.,\
@@ -222,7 +221,6 @@
 # checkPackageDefinition.
 #
 package.definition=sun.,\
-                   com.sun.corba.se.impl.,\
                    com.sun.xml.internal.,\
                    com.sun.imageio.,\
                    com.sun.istack.internal.,\
--- a/src/share/lib/security/java.security-macosx	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/lib/security/java.security-macosx	Mon Jul 22 17:37:15 2013 -0700
@@ -178,7 +178,6 @@
 # corresponding RuntimePermission ("accessClassInPackage."+package) has
 # been granted.
 package.access=sun.,\
-               com.sun.corba.se.impl.,\
                com.sun.xml.internal.,\
                com.sun.imageio.,\
                com.sun.istack.internal.,\
@@ -223,7 +222,6 @@
 # checkPackageDefinition.
 #
 package.definition=sun.,\
-                   com.sun.corba.se.impl.,\
                    com.sun.xml.internal.,\
                    com.sun.imageio.,\
                    com.sun.istack.internal.,\
--- a/src/share/lib/security/java.security-solaris	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/lib/security/java.security-solaris	Mon Jul 22 17:37:15 2013 -0700
@@ -179,7 +179,6 @@
 # corresponding RuntimePermission ("accessClassInPackage."+package) has
 # been granted.
 package.access=sun.,\
-               com.sun.corba.se.impl.,\
                com.sun.xml.internal.,\
                com.sun.imageio.,\
                com.sun.istack.internal.,\
@@ -223,7 +222,6 @@
 # checkPackageDefinition.
 #
 package.definition=sun.,\
-                   com.sun.corba.se.impl.,\
                    com.sun.xml.internal.,\
                    com.sun.imageio.,\
                    com.sun.istack.internal.,\
--- a/src/share/lib/security/java.security-windows	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/lib/security/java.security-windows	Mon Jul 22 17:37:15 2013 -0700
@@ -178,7 +178,6 @@
 # corresponding RuntimePermission ("accessClassInPackage."+package) has
 # been granted.
 package.access=sun.,\
-               com.sun.corba.se.impl.,\
                com.sun.xml.internal.,\
                com.sun.imageio.,\
                com.sun.istack.internal.,\
@@ -223,7 +222,6 @@
 # checkPackageDefinition.
 #
 package.definition=sun.,\
-                   com.sun.corba.se.impl.,\
                    com.sun.xml.internal.,\
                    com.sun.imageio.,\
                    com.sun.istack.internal.,\
--- a/src/share/native/sun/java2d/cmm/lcms/cmsopt.c	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsopt.c	Mon Jul 22 17:37:15 2013 -0700
@@ -548,6 +548,10 @@
         for (i=0; i < nOuts; i++) {
 
             cmsToneCurve* InversePostLin = cmsReverseToneCurve(Curves[i]);
+            if (InversePostLin == NULL) {
+                WhiteOut[i] = 0;
+                continue;
+            }
             WhiteOut[i] = cmsEvalToneCurve16(InversePostLin, WhitePointOut[i]);
             cmsFreeToneCurve(InversePostLin);
         }
--- a/src/share/native/sun/security/pkcs11/j2secmod.c	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/share/native/sun/security/pkcs11/j2secmod.c	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -51,20 +51,63 @@
     return (res == 0) ? JNI_FALSE : JNI_TRUE;
 }
 
-JNIEXPORT jboolean JNICALL Java_sun_security_pkcs11_Secmod_nssInit
-  (JNIEnv *env, jclass thisClass, jstring jFunctionName, jlong jHandle, jstring jConfigDir)
+/*
+ * Initializes NSS.
+ * The NSS_INIT_OPTIMIZESPACE flag is supplied by the caller.
+ * The NSS_Init* functions are mapped to the NSS_Initialize function.
+ */
+JNIEXPORT jboolean JNICALL Java_sun_security_pkcs11_Secmod_nssInitialize
+  (JNIEnv *env, jclass thisClass, jstring jFunctionName, jlong jHandle, jstring jConfigDir, jboolean jNssOptimizeSpace)
 {
-    const char *functionName = (*env)->GetStringUTFChars(env, jFunctionName, NULL);
-    const char *configDir = (jConfigDir == NULL) ? NULL : (*env)->GetStringUTFChars(env, jConfigDir, NULL);
-    FPTR_Init init = (FPTR_Init)findFunction(env, jHandle, functionName);
-    int res;
+    const char *functionName =
+        (*env)->GetStringUTFChars(env, jFunctionName, NULL);
+    const char *configDir = (jConfigDir == NULL)
+        ? NULL : (*env)->GetStringUTFChars(env, jConfigDir, NULL);
+    FPTR_Initialize initialize =
+        (FPTR_Initialize)findFunction(env, jHandle, "NSS_Initialize");
+    int res = 0;
+    unsigned int flags = 0x00;
 
-    (*env)->ReleaseStringUTFChars(env, jFunctionName, functionName);
-    if (init == NULL) {
-        return JNI_FALSE;
+    if (jNssOptimizeSpace == JNI_TRUE) {
+        flags = 0x20; // NSS_INIT_OPTIMIZESPACE flag
     }
 
-    res = init(configDir);
+    if (initialize != NULL) {
+        /*
+         * If the NSS_Init function is requested then call NSS_Initialize to
+         * open the Cert, Key and Security Module databases, read only.
+         */
+        if (strcmp("NSS_Init", functionName) == 0) {
+            flags = flags | 0x01; // NSS_INIT_READONLY flag
+            res = initialize(configDir, "", "", "secmod.db", flags);
+
+        /*
+         * If the NSS_InitReadWrite function is requested then call
+         * NSS_Initialize to open the Cert, Key and Security Module databases,
+         * read/write.
+         */
+        } else if (strcmp("NSS_InitReadWrite", functionName) == 0) {
+            res = initialize(configDir, "", "", "secmod.db", flags);
+
+        /*
+         * If the NSS_NoDB_Init function is requested then call
+         * NSS_Initialize without creating Cert, Key or Security Module
+         * databases.
+         */
+        } else if (strcmp("NSS_NoDB_Init", functionName) == 0) {
+            flags = flags | 0x02  // NSS_INIT_NOCERTDB flag
+                          | 0x04  // NSS_INIT_NOMODDB flag
+                          | 0x08  // NSS_INIT_FORCEOPEN flag
+                          | 0x10; // NSS_INIT_NOROOTINIT flag
+            res = initialize("", "", "", "", flags);
+
+        } else {
+            res = 2;
+        }
+    } else {
+        res = 1;
+    }
+    (*env)->ReleaseStringUTFChars(env, jFunctionName, functionName);
     if (configDir != NULL) {
         (*env)->ReleaseStringUTFChars(env, jConfigDir, configDir);
     }
--- a/src/solaris/classes/sun/awt/X11/XErrorHandlerUtil.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/solaris/classes/sun/awt/X11/XErrorHandlerUtil.java	Mon Jul 22 17:37:15 2013 -0700
@@ -105,9 +105,15 @@
      * Unsets a current synthetic error handler. Must be called with the acquired AWT lock.
      */
     public static void RESTORE_XERROR_HANDLER() {
+        RESTORE_XERROR_HANDLER(true);
+    }
+
+    private static void RESTORE_XERROR_HANDLER(boolean doXSync) {
         // Wait until all requests are processed by the X server
         // and only then uninstall the error handler.
-        XSync();
+        if (doXSync) {
+            XSync();
+        }
         current_error_handler = null;
     }
 
--- a/src/solaris/classes/sun/print/IPPPrintService.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/solaris/classes/sun/print/IPPPrintService.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1029,7 +1029,16 @@
             // now supports collation and that most OS has a way
             // of setting it, it is a safe assumption to just always
             // include SheetCollate as supported attribute.
-            catList.add(SheetCollate.class);
+
+            /*
+               In Linux, we use Postscript for rendering but Linux still
+               has issues in propagating Postscript-embedded setpagedevice
+               setting like collation.  Therefore, we temporarily exclude
+               Linux.
+            */
+            if (!UnixPrintServiceLookup.isLinux()) {
+                catList.add(SheetCollate.class);
+            }
         }
 
         // With the assumption that  Chromaticity is equivalent to
--- a/src/solaris/classes/sun/print/UnixPrintServiceLookup.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/solaris/classes/sun/print/UnixPrintServiceLookup.java	Mon Jul 22 17:37:15 2013 -0700
@@ -123,6 +123,10 @@
         return osname.equals("SunOS");
     }
 
+    static boolean isLinux() {
+        return (osname.equals("Linux"));
+    }
+
     static boolean isBSD() {
         return (osname.equals("Linux") ||
                 osname.contains("OS X"));
--- a/src/solaris/native/sun/awt/awt_util.h	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/solaris/native/sun/awt/awt_util.h	Mon Jul 22 17:37:15 2013 -0700
@@ -46,11 +46,11 @@
 
 /*
  * Expected types of arguments of the macro.
- * (JNIEnv*)
+ * (JNIEnv*, jboolean)
  */
-#define RESTORE_XERROR_HANDLER(env) do {                                                          \
+#define RESTORE_XERROR_HANDLER(env, doXSync) do {                                                 \
     JNU_CallStaticMethodByName(env, NULL, "sun/awt/X11/XErrorHandlerUtil",                        \
-        "RESTORE_XERROR_HANDLER", "()V");                                                         \
+        "RESTORE_XERROR_HANDLER", "(Z)V", doXSync);                                               \
 } while (0)
 
 /*
@@ -64,8 +64,18 @@
     do {                                                                                          \
         code;                                                                                     \
     } while (0);                                                                                  \
-    RESTORE_XERROR_HANDLER(env);                                                                  \
+    RESTORE_XERROR_HANDLER(env, JNI_TRUE);                                                        \
     if (handlerHasFlag == JNI_TRUE) {                                                             \
+        GET_HANDLER_ERROR_OCCURRED_FLAG(env, handlerRef, errorOccurredFlag);                      \
+    }                                                                                             \
+} while (0)
+
+/*
+ * Expected types of arguments of the macro.
+ * (JNIEnv*, jobject, jboolean)
+ */
+#define GET_HANDLER_ERROR_OCCURRED_FLAG(env, handlerRef, errorOccurredFlag) do {                  \
+    if (handlerRef != NULL) {                                                                     \
         errorOccurredFlag = JNU_CallMethodByName(env, NULL, handlerRef, "getErrorOccurredFlag",   \
             "()Z").z;                                                                             \
     }                                                                                             \
--- a/src/solaris/native/sun/java2d/opengl/GLXSurfaceData.c	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/solaris/native/sun/java2d/opengl/GLXSurfaceData.c	Mon Jul 22 17:37:15 2013 -0700
@@ -392,10 +392,12 @@
     attrlist[3] = height;
 
     errorOccurredFlag = JNI_FALSE;
-    EXEC_WITH_XERROR_HANDLER(env, "sun/awt/X11/XErrorHandler$GLXBadAllocHandler",
-        "()Lsun/awt/X11/XErrorHandler$GLXBadAllocHandler;", JNI_TRUE,
-        errorHandlerRef, errorOccurredFlag,
-        pbuffer = j2d_glXCreatePbuffer(awt_display, glxinfo->fbconfig, attrlist));
+    WITH_XERROR_HANDLER(env, "sun/awt/X11/XErrorHandler$GLXBadAllocHandler",
+        "()Lsun/awt/X11/XErrorHandler$GLXBadAllocHandler;", JNI_TRUE, errorHandlerRef);
+    pbuffer = j2d_glXCreatePbuffer(awt_display, glxinfo->fbconfig, attrlist);
+    XSync(awt_display, False);
+    RESTORE_XERROR_HANDLER(env, JNI_FALSE);
+    GET_HANDLER_ERROR_OCCURRED_FLAG(env, errorHandlerRef, errorOccurredFlag);
 
     if ((pbuffer == 0) || errorOccurredFlag) {
         J2dRlsTraceLn(J2D_TRACE_ERROR,
--- a/src/solaris/native/sun/security/pkcs11/j2secmod_md.h	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/solaris/native/sun/security/pkcs11/j2secmod_md.h	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,9 +25,14 @@
 
 // in nss.h:
 // extern PRBool NSS_VersionCheck(const char *importedVersion);
-// extern SECStatus NSS_Init(const char *configdir);
+// extern SECStatus NSS_Initialize(const char *configdir,
+//     const char *certPrefix, const char *keyPrefix,
+//     const char *secmodName, PRUint32 flags);
+
 typedef int (*FPTR_VersionCheck)(const char *importedVersion);
-typedef int (*FPTR_Init)(const char *configdir);
+typedef int (*FPTR_Initialize)(const char *configdir,
+        const char *certPrefix, const char *keyPrefix,
+        const char *secmodName, unsigned int flags);
 
 // in secmod.h
 //extern SECMODModule *SECMOD_LoadModule(char *moduleSpec,SECMODModule *parent,
--- a/src/windows/native/sun/security/pkcs11/j2secmod_md.h	Thu Jul 18 03:38:49 2013 -0700
+++ b/src/windows/native/sun/security/pkcs11/j2secmod_md.h	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,9 +27,14 @@
 
 // in nss.h:
 // extern PRBool NSS_VersionCheck(const char *importedVersion);
-// extern SECStatus NSS_Init(const char *configdir);
+// extern SECStatus NSS_Initialize(const char *configdir,
+//      const char *certPrefix, const char *keyPrefix,
+//      const char *secmodName, PRUint32 flags);
+
 typedef int __declspec(dllimport) (*FPTR_VersionCheck)(const char *importedVersion);
-typedef int __declspec(dllimport) (*FPTR_Init)(const char *configdir);
+typedef int __declspec(dllimport) (*FPTR_Initialize)(const char *configdir,
+        const char *certPrefix, const char *keyPrefix,
+        const char *secmodName, unsigned int flags);
 
 // in secmod.h
 //extern SECMODModule *SECMOD_LoadModule(char *moduleSpec,SECMODModule *parent,
--- a/test/ProblemList.txt	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/ProblemList.txt	Mon Jul 22 17:37:15 2013 -0700
@@ -137,10 +137,6 @@
 # 8015780
 java/lang/reflect/Method/GenericStringTest.java			generic-all
 
-# 8019500
-java/lang/management/MemoryMXBean/MemoryTestAllGC.sh            generic-all
-java/lang/management/MemoryMXBean/MemoryTest.java               generic-all
-
 ############################################################################
 
 # jdk_management
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/crypto/provider/Cipher/AES/TestCICOWithGCM.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 8012637
+ * @library ../UTIL
+ * @build TestUtil
+ * @run main TestCICOWithGCM
+ * @summary Test CipherInputStream/OutputStream with AES GCM mode.
+ * @author Valerie Peng
+ */
+
+import java.security.*;
+import javax.crypto.*;
+import javax.crypto.spec.*;
+import java.math.*;
+import java.io.*;
+import com.sun.crypto.provider.*;
+
+import java.util.*;
+
+public class TestCICOWithGCM {
+    public static void main(String[] args) throws Exception {
+        //init Secret Key
+        KeyGenerator kg = KeyGenerator.getInstance("AES", "SunJCE");
+        kg.init(128);
+        SecretKey key = kg.generateKey();
+
+        //do initialization of the plainText
+        byte[] plainText = new byte[800];
+        Random rdm = new Random();
+        rdm.nextBytes(plainText);
+
+        //init ciphers
+        Cipher encCipher = Cipher.getInstance("AES/GCM/NoPadding", "SunJCE");
+        encCipher.init(Cipher.ENCRYPT_MODE, key);
+        Cipher decCipher = Cipher.getInstance("AES/GCM/NoPadding", "SunJCE");
+        decCipher.init(Cipher.DECRYPT_MODE, key, encCipher.getParameters());
+
+        //init cipher streams
+        ByteArrayInputStream baInput = new ByteArrayInputStream(plainText);
+        CipherInputStream ciInput = new CipherInputStream(baInput, encCipher);
+        ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
+        CipherOutputStream ciOutput = new CipherOutputStream(baOutput, decCipher);
+
+        //do test
+        byte[] buffer = new byte[800];
+        int len = ciInput.read(buffer);
+        System.out.println("read " + len + " bytes from input buffer");
+
+        while (len != -1) {
+            ciOutput.write(buffer, 0, len);
+            System.out.println("wite " + len + " bytes to output buffer");
+            len = ciInput.read(buffer);
+            if (len != -1) {
+                System.out.println("read " + len + " bytes from input buffer");
+            } else {
+                System.out.println("finished reading");
+            }
+        }
+
+        ciOutput.flush();
+        ciInput.close();
+        ciOutput.close();
+        byte[] recovered = baOutput.toByteArray();
+        System.out.println("recovered " + recovered.length + " bytes");
+        if (!Arrays.equals(plainText, recovered)) {
+            throw new RuntimeException("diff check failed!");
+        } else {
+            System.out.println("diff check passed");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/crypto/provider/Cipher/DES/DESSecretKeySpec.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 6755701
+ * @summary Change SecretKeyFactory.generateSecret to allow SecretKeySpec to
+ * be passed and used for creating a DES and DESede keys. This avoids the error
+ * of "InvalidKeySpecException: Inappropriate key specification"
+ * @author Anthony Scarpino
+ */
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.SecretKeySpec;
+
+public class DESSecretKeySpec {
+
+    public static void main(String arg[]) throws Exception {
+        Cipher c;
+        byte[] key = new byte[]{'1','2','3','4','5','6','7','8',
+            '1','2','3','4','5','6','7','8',
+            '1','2','3','4','5','6','7','8'};
+
+
+        System.out.println("Testing DES key");
+        SecretKeySpec skey = new SecretKeySpec(key, "DES");
+        c = Cipher.getInstance("DES/CBC/PKCS5Padding", "SunJCE");
+        SecretKeyFactory.getInstance("DES").generateSecret(skey);
+
+        System.out.println("Testing DESede key");
+        skey = new SecretKeySpec(key, "DESede");
+        c = Cipher.getInstance("DESede/CBC/PKCS5Padding", "SunJCE");
+        SecretKeyFactory.getInstance("TripleDES").generateSecret(skey);
+    }
+}
--- a/test/com/sun/management/HotSpotDiagnosticMXBean/SetVMOption.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/com/sun/management/HotSpotDiagnosticMXBean/SetVMOption.java	Mon Jul 22 17:37:15 2013 -0700
@@ -27,6 +27,7 @@
  * @summary Basic Test for HotSpotDiagnosticMXBean.setVMOption()
  *          and getDiagnosticOptions().
  * @author  Mandy Chung
+ * @author  Jaroslav Bachorik
  *
  * @run main/othervm -XX:+PrintGCDetails SetVMOption
  */
@@ -36,7 +37,6 @@
 import com.sun.management.HotSpotDiagnosticMXBean;
 import com.sun.management.VMOption;
 import com.sun.management.VMOption.Origin;
-import sun.misc.Version;
 
 public class SetVMOption {
     private static String PRINT_GC_DETAILS = "PrintGCDetails";
@@ -47,17 +47,8 @@
     private static HotSpotDiagnosticMXBean mbean;
 
     public static void main(String[] args) throws Exception {
-        List<HotSpotDiagnosticMXBean> list =
-            ManagementFactory.getPlatformMXBeans(HotSpotDiagnosticMXBean.class);
-
-        // The following test is transitional only and should be removed
-        // once build 52 is promoted.
-        int build = Version.jvmBuildNumber();
-        if (build > 0 && build < 52) {
-             // JVM support is integrated in build 52
-             // this test is skipped if running with VM earlier than 52
-             return;
-        }
+        mbean =
+            ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
 
         VMOption option = findPrintGCDetailsOption();
         if (!option.getValue().equalsIgnoreCase(EXPECTED_VALUE)) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/Graphics2D/Test8004859/Test8004859.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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.Graphics2D;
+import java.awt.Rectangle;
+import java.awt.Shape;
+import java.awt.geom.NoninvertibleTransformException;
+import java.awt.image.BufferedImage;
+
+import sun.java2d.SunGraphics2D;
+
+/**
+ * @test
+ * @bug 8004859
+ * @summary getClipBounds/getClip should return equivalent bounds.
+ * @author Sergey Bylokhov
+ */
+public final class Test8004859 {
+
+    private static Shape[] clips = {new Rectangle(0, 0, 1, 1), new Rectangle(
+            100, 100, -100, -100)};
+
+    private static boolean status = true;
+
+    public static void main(final String[] args)
+            throws NoninvertibleTransformException {
+        final BufferedImage bi = new BufferedImage(300, 300,
+                                                   BufferedImage.TYPE_INT_RGB);
+        final Graphics2D g = (Graphics2D) bi.getGraphics();
+        test(g);
+        g.translate(2.0, 2.0);
+        test(g);
+        g.translate(-4.0, -4.0);
+        test(g);
+        g.scale(2.0, 2.0);
+        test(g);
+        g.scale(-4.0, -4.0);
+        test(g);
+        g.rotate(Math.toRadians(90));
+        test(g);
+        g.rotate(Math.toRadians(90));
+        test(g);
+        g.rotate(Math.toRadians(90));
+        test(g);
+        g.rotate(Math.toRadians(90));
+        test(g);
+        g.dispose();
+        if (!status) {
+            throw new RuntimeException("Test failed");
+        }
+    }
+
+    private static void test(final Graphics2D g) {
+        for (final Shape clip : clips) {
+            g.setClip(clip);
+            if (!g.getClip().equals(clip)) {
+                System.err.println("Expected clip: " + clip);
+                System.err.println("Actual clip: " + g.getClip());
+                System.err.println("bounds="+g.getClip().getBounds2D());
+                System.err.println("bounds="+g.getClip().getBounds());
+                status = false;
+            }
+            final Rectangle bounds = g.getClipBounds();
+            if (!clip.equals(bounds)) {
+                System.err.println("Expected getClipBounds(): " + clip);
+                System.err.println("Actual getClipBounds(): " + bounds);
+                status = false;
+            }
+            g.getClipBounds(bounds);
+            if (!clip.equals(bounds)) {
+                System.err.println("Expected getClipBounds(r): " + clip);
+                System.err.println("Actual getClipBounds(r): " + bounds);
+                status = false;
+            }
+            if (!clip.getBounds2D().isEmpty() && ((SunGraphics2D) g).clipRegion
+                    .isEmpty()) {
+                System.err.println("clipRegion should not be empty");
+                status = false;
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/GraphicsDevice/IncorrectDisplayModeExitFullscreen.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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.Color;
+import java.awt.DisplayMode;
+import java.awt.Frame;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
+import java.awt.Toolkit;
+
+import sun.awt.SunToolkit;
+
+/**
+ * @test
+ * @bug 8019587
+ * @author Sergey Bylokhov
+ */
+public class IncorrectDisplayModeExitFullscreen {
+
+    public static void main(final String[] args) {
+
+        final GraphicsDevice[] devices =
+                GraphicsEnvironment.getLocalGraphicsEnvironment()
+                                   .getScreenDevices();
+        if (devices.length < 2 || devices[0].getDisplayModes().length < 2
+                || !devices[0].isFullScreenSupported()
+                || !devices[1].isFullScreenSupported()) {
+            System.err.println("Testcase is not applicable");
+            return;
+        }
+        final DisplayMode defaultDM = devices[0].getDisplayMode();
+        final DisplayMode[] dms = devices[0].getDisplayModes();
+        DisplayMode nonDefaultDM = null;
+
+        for (final DisplayMode dm : dms) {
+            if (!dm.equals(defaultDM)) {
+                nonDefaultDM = dm;
+                break;
+            }
+        }
+        if (nonDefaultDM == null) {
+            System.err.println("Testcase is not applicable");
+            return;
+        }
+
+        final Frame frame = new Frame();
+        frame.setBackground(Color.GREEN);
+        frame.setUndecorated(true);
+        try {
+            devices[0].setFullScreenWindow(frame);
+            sleep();
+            devices[0].setDisplayMode(nonDefaultDM);
+            sleep();
+            devices[1].setFullScreenWindow(frame);
+            sleep();
+            if (!defaultDM.equals(devices[0].getDisplayMode())) {
+                throw new RuntimeException("DisplayMode is not restored");
+            }
+        } finally {
+            // cleaning up
+            devices[0].setFullScreenWindow(null);
+            devices[1].setFullScreenWindow(null);
+            frame.dispose();
+        }
+    }
+    private static void sleep() {
+        ((SunToolkit) Toolkit.getDefaultToolkit()).realSync();
+        try {
+            Thread.sleep(1500);
+        } catch (InterruptedException ignored) {
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/Window/MaximizeOffscreen/MaximizeOffscreenTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test @summary JVM crash if the frame maximized from offscreen
+ * @author Petr Pchelko
+ * @library ../../regtesthelpers
+ * @build Util
+ * @compile MaximizeOffscreenTest.java
+ * @run main/othervm MaximizeOffscreenTest
+ */
+
+import test.java.awt.regtesthelpers.Util;
+
+import javax.swing.*;
+import java.awt.*;
+
+public class MaximizeOffscreenTest {
+
+    private static JFrame frame;
+
+    public static void main(String[] args) throws Throwable {
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                constructTestUI();
+            }
+        });
+
+        Util.waitForIdle(null);
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                frame.setExtendedState(Frame.MAXIMIZED_BOTH);
+            }
+        });
+        Util.waitForIdle(null);
+    }
+
+    private static void constructTestUI() {
+        frame = new JFrame("Test frame");
+        frame.setUndecorated(true);
+        frame.setBounds(-1000, -1000, 100, 100);
+        frame.setVisible(true);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/beans/Introspector/Test6707231.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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.beans.PropertyDescriptor;
+
+/*
+ * @test
+ * @bug 6707231
+ * @summary Tests the boolean getter
+ * @author Sergey Malenkov
+ */
+
+public class Test6707231 {
+    public static void main(String[] args) throws Exception {
+        test(Bean.class, Bean.class);
+        test(Public.class, Public.class);
+        test(Private.class, Bean.class);
+    }
+
+    public static class Bean {
+        private boolean value;
+
+        public boolean isValue() {
+            return this.value;
+        }
+
+        public void setValue(boolean value) {
+            this.value = value;
+        }
+    }
+
+    public static class Public extends Bean {
+        public boolean isValue() {
+            return super.isValue();
+        }
+
+        public void setValue(boolean value) {
+            super.setValue(value);
+        }
+    }
+
+    private static class Private extends Bean {
+        public boolean isValue() {
+            return super.isValue();
+        }
+
+        public void setValue(boolean value) {
+            super.setValue(value);
+        }
+    }
+
+    private static void test(Class<?> actual, Class<?> expected) {
+        PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(actual, "value");
+        Class<?> getter = pd.getReadMethod().getDeclaringClass();
+        Class<?> setter = pd.getWriteMethod().getDeclaringClass();
+        if ((getter != expected) || (setter != expected)) {
+            throw new Error(actual.getName());
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/io/File/CheckPermission.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,379 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 8017212
+ * @summary Examine methods in File.java that access the file system do the
+ *          right permission check when a security manager exists.
+ * @author Dan Xu
+ */
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.io.FileFilter;
+import java.io.IOException;
+import java.security.Permission;
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class CheckPermission {
+
+    private static final String CHECK_PERMISSION_TEST = "CheckPermissionTest";
+
+    public enum FileOperation {
+        READ, WRITE, DELETE, EXEC
+    }
+
+    static class Checks {
+        private List<Permission> permissionsChecked = new ArrayList<>();
+        private Set<String> propertiesChecked = new HashSet<>();
+
+        private Map<FileOperation, List<String>> fileOperationChecked =
+            new EnumMap<>(FileOperation.class);
+
+        List<Permission> permissionsChecked() {
+            return permissionsChecked;
+        }
+
+        Set<String> propertiesChecked() {
+            return propertiesChecked;
+        }
+
+        List<String> fileOperationChecked(FileOperation op) {
+            return fileOperationChecked.get(op);
+        }
+
+        void addFileOperation(FileOperation op, String file) {
+            List<String> opList = fileOperationChecked.get(op);
+            if (opList == null) {
+                opList = new ArrayList<>();
+                fileOperationChecked.put(op, opList);
+            }
+            opList.add(file);
+        }
+    }
+
+    static ThreadLocal<Checks> myChecks = new ThreadLocal<>();
+
+    static void prepare() {
+        myChecks.set(new Checks());
+    }
+
+    static class LoggingSecurityManager extends SecurityManager {
+        static void install() {
+            System.setSecurityManager(new LoggingSecurityManager());
+        }
+
+        private void checkFileOperation(FileOperation op, String file) {
+            Checks checks = myChecks.get();
+            if (checks != null)
+                checks.addFileOperation(op, file);
+        }
+
+        @Override
+        public void checkRead(String file) {
+            checkFileOperation(FileOperation.READ, file);
+        }
+
+        @Override
+        public void checkWrite(String file) {
+            checkFileOperation(FileOperation.WRITE, file);
+        }
+
+        @Override
+        public void checkDelete(String file) {
+            checkFileOperation(FileOperation.DELETE, file);
+        }
+
+        @Override
+        public void checkExec(String file) {
+            checkFileOperation(FileOperation.EXEC, file);
+        }
+
+        @Override
+        public void checkPermission(Permission perm) {
+            Checks checks = myChecks.get();
+            if (checks != null)
+                checks.permissionsChecked().add(perm);
+        }
+
+        @Override
+        public void checkPropertyAccess(String key) {
+            Checks checks = myChecks.get();
+            if (checks != null)
+                checks.propertiesChecked().add(key);
+        }
+    }
+
+    static void assertCheckPermission(Class<? extends Permission> type,
+            String name)
+    {
+        for (Permission perm : myChecks.get().permissionsChecked()) {
+            if (type.isInstance(perm) && perm.getName().equals(name))
+                return;
+        }
+        throw new RuntimeException(type.getName() + "(\"" + name
+            + "\") not checked");
+    }
+
+    static void assertCheckPropertyAccess(String key) {
+        if (!myChecks.get().propertiesChecked().contains(key))
+            throw new RuntimeException("Property " + key + " not checked");
+    }
+
+    static void assertChecked(File file, List<String> list) {
+        if (list != null && !list.isEmpty()) {
+            for (String path : list) {
+                if (path.equals(file.getPath()))
+                    return;
+            }
+        }
+        throw new RuntimeException("Access not checked");
+    }
+
+    static void assertNotChecked(File file, List<String> list) {
+        if (list != null && !list.isEmpty()) {
+            for (String path : list) {
+                if (path.equals(file.getPath()))
+                    throw new RuntimeException("Access checked");
+            }
+        }
+    }
+
+    static void assertCheckOperation(File file, Set<FileOperation> ops) {
+        for (FileOperation op : ops)
+            assertChecked(file, myChecks.get().fileOperationChecked(op));
+    }
+
+    static void assertNotCheckOperation(File file, Set<FileOperation> ops) {
+        for (FileOperation op : ops)
+            assertNotChecked(file, myChecks.get().fileOperationChecked(op));
+    }
+
+    static void assertOnlyCheckOperation(File file,
+            EnumSet<FileOperation> ops)
+    {
+        assertCheckOperation(file, ops);
+        assertNotCheckOperation(file, EnumSet.complementOf(ops));
+    }
+
+    static File testFile, another;
+
+    static void setup() {
+        testFile = new File(CHECK_PERMISSION_TEST + System.currentTimeMillis());
+        if (testFile.exists()) {
+            testFile.delete();
+        }
+
+        another = new File(CHECK_PERMISSION_TEST + "Another"
+                           + System.currentTimeMillis());
+        if (another.exists()) {
+            another.delete();
+        }
+
+        LoggingSecurityManager.install();
+    }
+
+    public static void main(String[] args) throws IOException {
+        setup();
+
+        prepare();
+        testFile.canRead();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
+
+        prepare();
+        testFile.canWrite();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
+
+        prepare();
+        testFile.exists();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
+
+        prepare();
+        testFile.isDirectory();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
+
+        prepare();
+        testFile.isFile();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
+
+        prepare();
+        testFile.isHidden();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
+
+        prepare();
+        testFile.lastModified();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
+
+        prepare();
+        testFile.length();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
+
+        prepare();
+        testFile.createNewFile();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
+
+        prepare();
+        testFile.list();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
+
+        prepare();
+        testFile.list(new FilenameFilter() {
+            @Override
+            public boolean accept(File dir, String name) {
+                return false;
+            }
+        });
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
+
+        prepare();
+        testFile.listFiles();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
+
+        prepare();
+        testFile.listFiles(new FilenameFilter() {
+            @Override
+            public boolean accept(File dir, String name) {
+                return false;
+            }
+        });
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
+
+        prepare();
+        testFile.listFiles(new FileFilter() {
+            @Override
+            public boolean accept(File file) {
+                return false;
+            }
+        });
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
+
+        prepare();
+        testFile.mkdir();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
+
+        if (testFile.exists()) {
+            prepare();
+            testFile.mkdirs();
+            assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
+        }
+
+        if (!another.exists()) {
+            prepare();
+            another.mkdirs();
+            assertOnlyCheckOperation(another,
+                    EnumSet.of(FileOperation.READ, FileOperation.WRITE));
+        }
+
+        prepare();
+        another.delete();
+        assertOnlyCheckOperation(another, EnumSet.of(FileOperation.DELETE));
+
+        prepare();
+        boolean renRst = testFile.renameTo(another);
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
+        assertOnlyCheckOperation(another, EnumSet.of(FileOperation.WRITE));
+
+        if (renRst) {
+            if (testFile.exists())
+                throw new RuntimeException(testFile + " is already renamed to "
+                    + another);
+            testFile = another;
+        }
+
+        prepare();
+        testFile.setLastModified(0);
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
+
+        prepare();
+        testFile.setReadOnly();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
+
+        prepare();
+        testFile.setWritable(true, true);
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
+
+        prepare();
+        testFile.setWritable(true);
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
+
+        prepare();
+        testFile.setReadable(true, true);
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
+
+        prepare();
+        testFile.setReadable(true);
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
+
+        prepare();
+        testFile.setExecutable(true, true);
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
+
+        prepare();
+        testFile.setExecutable(true);
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
+
+        prepare();
+        testFile.canExecute();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.EXEC));
+
+        prepare();
+        testFile.getTotalSpace();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
+        assertCheckPermission(RuntimePermission.class,
+                "getFileSystemAttributes");
+
+        prepare();
+        testFile.getFreeSpace();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
+        assertCheckPermission(RuntimePermission.class,
+                "getFileSystemAttributes");
+
+        prepare();
+        testFile.getUsableSpace();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
+        assertCheckPermission(RuntimePermission.class,
+                "getFileSystemAttributes");
+
+        prepare();
+        File tmpFile = File.createTempFile(CHECK_PERMISSION_TEST, null);
+        assertOnlyCheckOperation(tmpFile, EnumSet.of(FileOperation.WRITE));
+        tmpFile.delete();
+        assertCheckOperation(tmpFile, EnumSet.of(FileOperation.DELETE));
+
+        prepare();
+        tmpFile = File.createTempFile(CHECK_PERMISSION_TEST, null, null);
+        assertOnlyCheckOperation(tmpFile, EnumSet.of(FileOperation.WRITE));
+        tmpFile.delete();
+        assertCheckOperation(tmpFile, EnumSet.of(FileOperation.DELETE));
+
+        prepare();
+        testFile.deleteOnExit();
+        assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.DELETE));
+    }
+}
--- a/test/java/io/File/NulFile.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/io/File/NulFile.java	Mon Jul 22 17:37:15 2013 -0700
@@ -612,8 +612,13 @@
             try {
                 File.createTempFile(prefix, suffix, directory);
             } catch (IOException ex) {
-                if (ExceptionMsg.equals(ex.getMessage()))
+                String err = "Unable to create temporary file";
+                if (err.equals(ex.getMessage()))
                     exceptionThrown = true;
+                else {
+                    throw new RuntimeException("Get IOException with message, "
+                            + ex.getMessage() + ", expect message, "+ err);
+                }
             }
         }
         if (!exceptionThrown) {
--- a/test/java/io/File/createTempFile/SpecialTempFile.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/io/File/createTempFile/SpecialTempFile.java	Mon Jul 22 17:37:15 2013 -0700
@@ -23,9 +23,8 @@
 
 /*
  * @test
- * @bug 8013827 8011950
+ * @bug 8013827 8011950 8017212
  * @summary Check whether File.createTempFile can handle special parameters
- *          on Windows platforms
  * @author Dan Xu
  */
 
@@ -64,6 +63,17 @@
     }
 
     public static void main(String[] args) throws Exception {
+        // Common test
+        final String name = "SpecialTempFile";
+        File f = new File(System.getProperty("java.io.tmpdir"), name);
+        if (!f.exists()) {
+            f.createNewFile();
+        }
+        String[] nulPre = { name + "\u0000" };
+        String[] nulSuf = { ".test" };
+        test("NulName", nulPre, nulSuf);
+
+        // Windows tests
         if (!System.getProperty("os.name").startsWith("Windows"))
             return;
 
--- a/test/java/lang/SecurityManager/CheckPackageAccess.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/lang/SecurityManager/CheckPackageAccess.java	Mon Jul 22 17:37:15 2013 -0700
@@ -22,31 +22,132 @@
  */
 
 /*
- * @test
- * @bug 7146431 8000450
- * @summary Test that internal packages cannot be accessed
+ *  @test
+ *  @bug 6741606 7146431 8000450
+ *  @summary Make sure all restricted packages listed in the package.access
+ *           property in the java.security file are blocked
+ *  @run main/othervm CheckPackageAccess
  */
 
+import java.security.Security;
+import java.util.Collections;
+import java.util.Arrays;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.StringTokenizer;
+
+/*
+ * The main benefit of this test is to catch merge errors or other types
+ * of issues where one or more of the packages are accidentally
+ * removed. This is why the packages that are known to be restricted have to
+ * be explicitly listed below.
+ */
 public class CheckPackageAccess {
 
+    /*
+     * This array should be updated whenever new packages are added to the
+     * package.access property in the java.security file
+     */
+    private static final String[] packages = {
+        "sun.",
+        "com.sun.xml.internal.",
+        "com.sun.imageio.",
+        "com.sun.istack.internal.",
+        "com.sun.jmx.",
+        "com.sun.proxy.",
+        "com.sun.org.apache.bcel.internal.",
+        "com.sun.org.apache.regexp.internal.",
+        "com.sun.org.apache.xerces.internal.",
+        "com.sun.org.apache.xpath.internal.",
+        "com.sun.org.apache.xalan.internal.extensions.",
+        "com.sun.org.apache.xalan.internal.lib.",
+        "com.sun.org.apache.xalan.internal.res.",
+        "com.sun.org.apache.xalan.internal.templates.",
+        "com.sun.org.apache.xalan.internal.utils.",
+        "com.sun.org.apache.xalan.internal.xslt.",
+        "com.sun.org.apache.xalan.internal.xsltc.cmdline.",
+        "com.sun.org.apache.xalan.internal.xsltc.compiler.",
+        "com.sun.org.apache.xalan.internal.xsltc.trax.",
+        "com.sun.org.apache.xalan.internal.xsltc.util.",
+        "com.sun.org.apache.xml.internal.res.",
+        "com.sun.org.apache.xml.internal.security.",
+        "com.sun.org.apache.xml.internal.serializer.utils.",
+        "com.sun.org.apache.xml.internal.utils.",
+        "com.sun.org.glassfish.",
+        "com.oracle.xmlns.internal.",
+        "com.oracle.webservices.internal.",
+        "oracle.jrockit.jfr.",
+        "org.jcp.xml.dsig.internal.",
+        "jdk.internal.",
+        "jdk.nashorn.internal.",
+        "jdk.nashorn.tools."
+    };
+
     public static void main(String[] args) throws Exception {
+        List<String> pkgs = new ArrayList<>(Arrays.asList(packages));
+        String osName = System.getProperty("os.name");
+        if (osName.contains("OS X")) {
+            pkgs.add("apple.");  // add apple package for OS X
+        } else if (osName.startsWith("Windows")) {
+            pkgs.add("com.sun.java.accessibility.");
+        }
 
-        String[] pkgs = new String[] {
-            "com.sun.corba.se.impl.",
-            "com.sun.org.apache.xerces.internal.utils.",
-            "com.sun.org.apache.xalan.internal.utils." };
-        SecurityManager sm = new SecurityManager();
-        System.setSecurityManager(sm);
-        for (String pkg : pkgs) {
-            System.out.println("Checking package access for " + pkg);
+        List<String> jspkgs =
+            getPackages(Security.getProperty("package.access"));
+
+        // Sort to ensure lists are comparable
+        Collections.sort(pkgs);
+        Collections.sort(jspkgs);
+
+        if (!pkgs.equals(jspkgs)) {
+            for (String p : pkgs)
+                if (!jspkgs.contains(p))
+                    System.out.println("In golden set, but not in j.s file: " + p);
+            for (String p : jspkgs)
+                if (!pkgs.contains(p))
+                    System.out.println("In j.s file, but not in golden set: " + p);
+
+
+            throw new RuntimeException("restricted packages are not " +
+                                       "consistent with java.security file");
+        }
+        System.setSecurityManager(new SecurityManager());
+        SecurityManager sm = System.getSecurityManager();
+        for (String pkg : packages) {
+            String subpkg = pkg + "foo";
             try {
                 sm.checkPackageAccess(pkg);
-                throw new Exception("Expected PackageAccess SecurityException not thrown");
+                throw new RuntimeException("Able to access " + pkg +
+                                           " package");
+            } catch (SecurityException se) { }
+            try {
+                sm.checkPackageAccess(subpkg);
+                throw new RuntimeException("Able to access " + subpkg +
+                                           " package");
             } catch (SecurityException se) { }
             try {
                 sm.checkPackageDefinition(pkg);
-                throw new Exception("Expected PackageDefinition SecurityException not thrown");
+                throw new RuntimeException("Able to define class in " + pkg +
+                                           " package");
+            } catch (SecurityException se) { }
+            try {
+                sm.checkPackageDefinition(subpkg);
+                throw new RuntimeException("Able to define class in " + subpkg +
+                                           " package");
             } catch (SecurityException se) { }
         }
+        System.out.println("Test passed");
+    }
+
+    private static List<String> getPackages(String p) {
+        List<String> packages = new ArrayList<>();
+        if (p != null && !p.equals("")) {
+            StringTokenizer tok = new StringTokenizer(p, ",");
+            while (tok.hasMoreElements()) {
+                String s = tok.nextToken().trim();
+                packages.add(s);
+            }
+        }
+        return packages;
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/lang/annotation/AnnotationType/AnnotationTypeDeadlockTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 7122142
+ * @summary Test deadlock situation when recursive annotations are parsed
+ */
+
+import java.lang.annotation.Retention;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+public class AnnotationTypeDeadlockTest {
+
+    @Retention(RUNTIME)
+    @AnnB
+    public @interface AnnA {
+    }
+
+    @Retention(RUNTIME)
+    @AnnA
+    public @interface AnnB {
+    }
+
+    static class Task extends Thread {
+        final CountDownLatch prepareLatch;
+        final AtomicInteger goLatch;
+        final Class<?> clazz;
+
+        Task(CountDownLatch prepareLatch, AtomicInteger goLatch, Class<?> clazz) {
+            super(clazz.getSimpleName());
+            setDaemon(true); // in case it deadlocks
+            this.prepareLatch = prepareLatch;
+            this.goLatch = goLatch;
+            this.clazz = clazz;
+        }
+
+        @Override
+        public void run() {
+            prepareLatch.countDown();  // notify we are prepared
+            while (goLatch.get() > 0); // spin-wait before go
+            clazz.getDeclaredAnnotations();
+        }
+    }
+
+    static void dumpState(Task task) {
+        System.err.println(
+            "Task[" + task.getName() + "].state: " +
+            task.getState() + " ..."
+        );
+        for (StackTraceElement ste : task.getStackTrace()) {
+            System.err.println("\tat " + ste);
+        }
+        System.err.println();
+    }
+
+    public static void main(String[] args) throws Exception {
+        CountDownLatch prepareLatch = new CountDownLatch(2);
+        AtomicInteger goLatch = new AtomicInteger(1);
+        Task taskA = new Task(prepareLatch, goLatch, AnnA.class);
+        Task taskB = new Task(prepareLatch, goLatch, AnnB.class);
+        taskA.start();
+        taskB.start();
+        // wait until both threads start-up
+        prepareLatch.await();
+        // let them go
+        goLatch.set(0);
+        // attempt to join them
+        taskA.join(5000L);
+        taskB.join(5000L);
+
+        if (taskA.isAlive() || taskB.isAlive()) {
+            dumpState(taskA);
+            dumpState(taskB);
+            throw new IllegalStateException(
+                taskA.getState() == Thread.State.BLOCKED &&
+                taskB.getState() == Thread.State.BLOCKED
+                ? "deadlock detected"
+                : "unexpected condition");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/lang/annotation/AnnotationType/AnnotationTypeRuntimeAssumptionTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,176 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @summary Test consistent parsing of ex-RUNTIME annotations that
+ *          were changed and separately compiled to have CLASS retention
+ */
+
+import sun.misc.IOUtils;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+import static java.lang.annotation.RetentionPolicy.CLASS;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+/**
+ * This test simulates a situation where there are two mutually recursive
+ * {@link RetentionPolicy#RUNTIME RUNTIME} annotations {@link AnnA_v1 AnnA_v1}
+ * and {@link AnnB AnnB} and then the first is changed to have
+ * {@link RetentionPolicy#CLASS CLASS} retention and separately compiled.
+ * When {@link AnnA_v1 AnnA_v1} annotation is looked-up on {@link AnnB AnnB}
+ * it still appears to have {@link RetentionPolicy#RUNTIME RUNTIME} retention.
+ */
+public class AnnotationTypeRuntimeAssumptionTest {
+
+    @Retention(RUNTIME)
+    @AnnB
+    public @interface AnnA_v1 {
+    }
+
+    // An alternative version of AnnA_v1 with CLASS retention instead.
+    // Used to simulate separate compilation (see AltClassLoader below).
+    @Retention(CLASS)
+    @AnnB
+    public @interface AnnA_v2 {
+    }
+
+    @Retention(RUNTIME)
+    @AnnA_v1
+    public @interface AnnB {
+    }
+
+    @AnnA_v1
+    public static class TestTask implements Runnable {
+        @Override
+        public void run() {
+            AnnA_v1 ann1 = TestTask.class.getDeclaredAnnotation(AnnA_v1.class);
+            if (ann1 != null) {
+                throw new IllegalStateException(
+                    "@" + ann1.annotationType().getSimpleName() +
+                    " found on: " + TestTask.class.getName() +
+                    " should not be visible at runtime");
+            }
+            AnnA_v1 ann2 = AnnB.class.getDeclaredAnnotation(AnnA_v1.class);
+            if (ann2 != null) {
+                throw new IllegalStateException(
+                    "@" + ann2.annotationType().getSimpleName() +
+                    " found on: " + AnnB.class.getName() +
+                    " should not be visible at runtime");
+            }
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        ClassLoader altLoader = new AltClassLoader(
+            AnnotationTypeRuntimeAssumptionTest.class.getClassLoader());
+
+        Runnable altTask = (Runnable) Class.forName(
+            TestTask.class.getName(),
+            true,
+            altLoader).newInstance();
+
+        altTask.run();
+    }
+
+    /**
+     * A ClassLoader implementation that loads alternative implementations of
+     * classes. If class name ends with "_v1" it locates instead a class with
+     * name ending with "_v2" and loads that class instead.
+     */
+    static class AltClassLoader extends ClassLoader {
+        AltClassLoader(ClassLoader parent) {
+            super(parent);
+        }
+
+        @Override
+        protected Class<?> loadClass(String name, boolean resolve)
+                throws ClassNotFoundException {
+            if (name.indexOf('.') < 0) { // root package is our class
+                synchronized (getClassLoadingLock(name)) {
+                    // First, check if the class has already been loaded
+                    Class<?> c = findLoadedClass(name);
+                    if (c == null) {
+                        c = findClass(name);
+                    }
+                    if (resolve) {
+                        resolveClass(c);
+                    }
+                    return c;
+                }
+            }
+            else { // not our class
+                return super.loadClass(name, resolve);
+            }
+        }
+
+        @Override
+        protected Class<?> findClass(String name)
+                throws ClassNotFoundException {
+            // special class name -> replace it with alternative name
+            if (name.endsWith("_v1")) {
+                String altName = name.substring(0, name.length() - 3) + "_v2";
+                String altPath = altName.replace('.', '/').concat(".class");
+                try (InputStream is = getResourceAsStream(altPath)) {
+                    if (is != null) {
+                        byte[] bytes = IOUtils.readFully(is, -1, true);
+                        // patch class bytes to contain original name
+                        for (int i = 0; i < bytes.length - 2; i++) {
+                            if (bytes[i] == '_' &&
+                                bytes[i + 1] == 'v' &&
+                                bytes[i + 2] == '2') {
+                                bytes[i + 2] = '1';
+                            }
+                        }
+                        return defineClass(name, bytes, 0, bytes.length);
+                    }
+                    else {
+                        throw new ClassNotFoundException(name);
+                    }
+                }
+                catch (IOException e) {
+                    throw new ClassNotFoundException(name, e);
+                }
+            }
+            else { // not special class name -> just load the class
+                String path = name.replace('.', '/').concat(".class");
+                try (InputStream is = getResourceAsStream(path)) {
+                    if (is != null) {
+                        byte[] bytes = IOUtils.readFully(is, -1, true);
+                        return defineClass(name, bytes, 0, bytes.length);
+                    }
+                    else {
+                        throw new ClassNotFoundException(name);
+                    }
+                }
+                catch (IOException e) {
+                    throw new ClassNotFoundException(name, e);
+                }
+            }
+        }
+    }
+}
--- a/test/java/lang/invoke/InvokeDynamicPrintArgs.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/lang/invoke/InvokeDynamicPrintArgs.java	Mon Jul 22 17:37:15 2013 -0700
@@ -22,6 +22,7 @@
  */
 
 /* @test
+ * @bug 7050328 8007035
  * @summary smoke test for invokedynamic instructions
  * @build indify.Indify
  * @compile InvokeDynamicPrintArgs.java
@@ -42,6 +43,7 @@
 import java.io.*;
 
 import java.lang.invoke.*;
+import java.security.*;
 import static java.lang.invoke.MethodHandles.*;
 import static java.lang.invoke.MethodType.*;
 
@@ -62,17 +64,10 @@
     }
 
     private static void checkConstantRefs() throws Throwable {
-        // check some constant references:
+        // check some constant references to its self class
         assertEquals(MT_bsm(), MH_bsm().type());
         assertEquals(MT_bsm2(), MH_bsm2().type());
-        try {
-            assertEquals(MT_bsm(), non_MH_bsm().type());
-            // if SM is installed, must throw before this point
-            assertEquals(false, System.getSecurityManager() != null);
-        } catch (SecurityException ex) {
-            // if SM is installed, must throw to this point
-            assertEquals(true, System.getSecurityManager() != null);
-        }
+        assertEquals(MT_bsm(), non_MH_bsm().type());
     }
     private static void assertEquals(Object exp, Object act) {
         if (exp == act || (exp != null && exp.equals(act)))  return;
@@ -80,21 +75,8 @@
     }
 
     private static void setSM() {
-        // Test for severe security manager interactions (7050328).
-        class SM extends SecurityManager {
-            public void checkPackageAccess(String pkg) {
-                if (pkg.startsWith("test."))
-                    throw new SecurityException("checkPackageAccess "+pkg);
-            }
-            public void checkMemberAccess(Class<?> clazz, int which) {
-                if (clazz == InvokeDynamicPrintArgs.class)
-                    throw new SecurityException("checkMemberAccess "+clazz.getName()+" #"+which);
-            }
-            // allow these others:
-            public void checkPermission(java.security.Permission perm) {
-            }
-        }
-        System.setSecurityManager(new SM());
+        Policy.setPolicy(new TestPolicy());
+        System.setSecurityManager(new SecurityManager());
     }
 
     private static PrintStream oldOut;
@@ -250,4 +232,22 @@
         if (System.getProperty("InvokeDynamicPrintArgs.allow-untransformed") != null)  return;
         throw new AssertionError("this code should be statically transformed away by Indify");
     }
+
+    static class TestPolicy extends Policy {
+        final PermissionCollection permissions = new Permissions();
+        TestPolicy() {
+            permissions.add(new java.io.FilePermission("<<ALL FILES>>", "read"));
+        }
+        public PermissionCollection getPermissions(ProtectionDomain domain) {
+            return permissions;
+        }
+
+        public PermissionCollection getPermissions(CodeSource codesource) {
+            return permissions;
+        }
+
+        public boolean implies(ProtectionDomain domain, Permission perm) {
+            return permissions.implies(perm);
+        }
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/lang/invoke/TestCatchExceptionWithVarargs.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8019184
+ * @summary MethodHandles.catchException() fails when methods have 8 args + varargs
+ */
+
+import java.util.*;
+import java.lang.invoke.*;
+
+public class TestCatchExceptionWithVarargs {
+
+    private static final Class<?> CLASS = TestCatchExceptionWithVarargs.class;
+    private static final int MAX_MH_ARITY = 254;
+
+    public static MethodHandle target;
+    public static MethodHandle handler;
+
+    private static Object firstArg;
+
+    static class MyException extends Exception {
+    }
+
+    public static Object target(Object... a) throws Exception {
+        if (a[0] != firstArg) {
+            throw new AssertionError("first argument different than expected: " + a[0] + " != " + firstArg);
+        }
+        throw new MyException();
+    }
+
+    public static Object handler(Object... a) {
+        if (a[0] != firstArg) {
+            throw new AssertionError("first argument different than expected: " + a[0] + " != " + firstArg);
+        }
+        return a[0];
+    }
+
+    static {
+        try {
+            MethodType mtype = MethodType.methodType(Object.class, Object[].class);
+            target = MethodHandles.lookup().findStatic(CLASS, "target", mtype);
+            handler = MethodHandles.lookup().findStatic(CLASS, "handler", mtype);
+        } catch (Exception e) {
+            throw new AssertionError(e);
+        }
+    }
+
+    public static void main(String[] args) throws Throwable {
+        List<Class<?>> ptypes = new LinkedList<>();
+        ptypes.add(Object[].class);
+
+        // We use MAX_MH_ARITY - 1 here to account for the Object[] argument.
+        for (int i = 1; i < MAX_MH_ARITY - 1; i++) {
+            ptypes.add(0, Object.class);
+
+            MethodHandle targetWithArgs = target.asType(MethodType.methodType(Object.class, ptypes));
+            MethodHandle handlerWithArgs = handler.asType(MethodType.methodType(Object.class, ptypes));
+            handlerWithArgs = MethodHandles.dropArguments(handlerWithArgs, 0, MyException.class);
+
+            MethodHandle gwc1 = MethodHandles.catchException(targetWithArgs, MyException.class, handlerWithArgs);
+
+            // The next line throws an IllegalArgumentException if there is a bug.
+            MethodHandle gwc2 = MethodHandles.catchException(gwc1, MyException.class, handlerWithArgs);
+
+            // This is only to verify that the method handles can actually be invoked and do the right thing.
+            firstArg = new Object();
+            Object o = gwc2.asSpreader(Object[].class, ptypes.size() - 1).invoke(firstArg, new Object[i]);
+            if (o != firstArg) {
+                throw new AssertionError("return value different than expected: " + o + " != " + firstArg);
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/lang/invoke/TestPrivateMember.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+
+/**
+ * @test
+ * @bug 8007035
+ * @summary Test MethodHandle of a private member
+ *
+ * @run main TestPrivateMember
+ */
+
+public class TestPrivateMember {
+    public static void main(String... args) throws Throwable {
+        System.setSecurityManager(new SecurityManager());
+        TestPrivateMember t = new TestPrivateMember();
+        t.test();
+    }
+
+    public TestPrivateMember() {
+    }
+
+    public void test() throws Throwable {
+        MethodHandles.Lookup lookup = MethodHandles.lookup();
+        MethodType mt = MethodType.methodType(void.class);
+        try {
+            MethodHandle mh = lookup.findStatic(Class.class, "checkInitted", mt);
+            throw new RuntimeException("IllegalAccessException not thrown");
+        } catch (IllegalAccessException e) {
+            // okay
+            System.out.println("Expected exception: " + e.getMessage());
+        }
+    }
+}
--- a/test/java/lang/management/MemoryMXBean/MemoryTest.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/lang/management/MemoryMXBean/MemoryTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -59,18 +59,21 @@
     // (or equivalent for other collectors)
     // Number of GC memory managers = 2
 
-    // 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};
+    // Hotspot VM 1.8+ after perm gen removal is expected to have two or
+    // three non-heap memory pools:
+    // - Code cache
+    // - Metaspace
+    // - Compressed Class Space (if compressed class pointers are used)
+    private static int[] expectedMinNumPools = {3, 2};
+    private static int[] expectedMaxNumPools = {3, 3};
     private static int expectedNumGCMgrs = 2;
-    private static int expectedNumMgrs = expectedNumGCMgrs + 1;
+    private static int expectedNumMgrs = expectedNumGCMgrs + 2;
     private static String[] types = { "heap", "non-heap" };
 
     public static void main(String args[]) throws Exception {
         Integer value = new Integer(args[0]);
         expectedNumGCMgrs = value.intValue();
-        expectedNumMgrs = expectedNumGCMgrs + 1;
+        expectedNumMgrs = expectedNumGCMgrs + 2;
 
         checkMemoryPools();
         checkMemoryManagers();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/lang/ref/EnqueuePollRace.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 8014890
+ * @summary Verify that a race between ReferenceQueue.enqueue() and poll() does not occur.
+ * @author thomas.schatzl@oracle.com
+ * @run main/othervm -XX:+UseSerialGC -Xmx10M EnqueuePollRace
+ */
+
+import java.lang.ref.*;
+
+public class EnqueuePollRace {
+
+    public static void main(String args[]) throws Exception {
+        new WeakRef().run();
+        System.out.println("Test passed.");
+    }
+
+    static class WeakRef {
+        ReferenceQueue<Object> queue = new ReferenceQueue<Object>();
+        final int numReferences = 100;
+        final Reference refs[] = new Reference[numReferences];
+        final int iterations = 1000;
+
+        void run() throws InterruptedException {
+            for (int i = 0; i < iterations; i++) {
+                queue = new ReferenceQueue<Object>();
+
+                for (int j = 0; j < refs.length; j++) {
+                    refs[j] = new WeakReference(new Object(), queue);
+                }
+
+                System.gc(); // enqueues references into the list of discovered references
+
+                // now manually enqueue all of them
+                for (int j = 0; j < refs.length; j++) {
+                    refs[j].enqueue();
+                }
+                // and get them back. There should be exactly numReferences
+                // entries in the queue now.
+                int foundReferences = 0;
+                while (queue.poll() != null) {
+                    foundReferences++;
+                }
+
+                if (foundReferences != refs.length) {
+                    throw new RuntimeException("Got " + foundReferences + " references in the queue, but expected " + refs.length);
+                }
+            }
+        }
+    }
+}
--- a/test/java/lang/ref/OOMEInReferenceHandler.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/lang/ref/OOMEInReferenceHandler.java	Mon Jul 22 17:37:15 2013 -0700
@@ -23,9 +23,9 @@
 
 /**
  * @test
- * @bug 7038914
+ * @bug 7038914 8016341
  * @summary Verify that the reference handler does not die after an OOME allocating the InterruptedException object
- * @run main/othervm -Xmx16M -XX:-UseTLAB OOMEInReferenceHandler
+ * @run main/othervm -Xmx24M -XX:-UseTLAB OOMEInReferenceHandler
  * @author peter.levart@gmail.com
  */
 
@@ -107,6 +107,6 @@
          }
 
          // no sure answer after 10 seconds
-         throw new IllegalStateException("Reference Handler thread stuck.");
+         throw new IllegalStateException("Reference Handler thread stuck. weakRef.get(): " + weakRef.get());
      }
 }
--- a/test/java/lang/reflect/Parameter/WithParameters.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/lang/reflect/Parameter/WithParameters.java	Mon Jul 22 17:37:15 2013 -0700
@@ -73,6 +73,10 @@
                 }
                 for(int i = 0; i < parameters.length; i++) {
                     Parameter p = parameters[i];
+                    if(!p.isNamePresent()) {
+                        System.err.println(p + ".isNamePresent == false");
+                        error++;
+                    }
                     if(!parameters[i].getName().equals(qux_names[i])) {
                         System.err.println("Wrong parameter name for " + parameters[i]);
                         error++;
--- a/test/java/lang/reflect/Parameter/WithoutParameters.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/lang/reflect/Parameter/WithoutParameters.java	Mon Jul 22 17:37:15 2013 -0700
@@ -69,6 +69,7 @@
 
         for(int i = 0; i < parameters.length; i++) {
             Parameter p = parameters[i];
+            errorIfTrue(p.isNamePresent(), p + ".isNamePresent == true");
             errorIfTrue(!p.getDeclaringExecutable().equals(e), p + ".getDeclaringExecutable != " + e);
             Objects.requireNonNull(p.getType(), "getType() should not be null");
             Objects.requireNonNull(p.getParameterizedType(), "getParameterizedType() should not be null");
--- a/test/java/math/BigDecimal/StrippingZerosTest.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/math/BigDecimal/StrippingZerosTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -45,8 +45,17 @@
             {new BigDecimal("1234.56780"),      new BigDecimal("1234.5678")},
             {new BigDecimal("1234.567800000"),  new BigDecimal("1234.5678")},
             {new BigDecimal("0"),               new BigDecimal("0")},
-            {new BigDecimal("0e100"),           new BigDecimal("0e100")},
-            {new BigDecimal("0e-100"),          new BigDecimal("0e-100")},
+            {new BigDecimal("0e2"),             BigDecimal.ZERO},
+            {new BigDecimal("0e-2"),            BigDecimal.ZERO},
+            {new BigDecimal("0e42"),            BigDecimal.ZERO},
+            {new BigDecimal("+0e42"),           BigDecimal.ZERO},
+            {new BigDecimal("-0e42"),           BigDecimal.ZERO},
+            {new BigDecimal("0e-42"),           BigDecimal.ZERO},
+            {new BigDecimal("+0e-42"),          BigDecimal.ZERO},
+            {new BigDecimal("-0e-42"),          BigDecimal.ZERO},
+            {new BigDecimal("0e-2"),            BigDecimal.ZERO},
+            {new BigDecimal("0e100"),           BigDecimal.ZERO},
+            {new BigDecimal("0e-100"),          BigDecimal.ZERO},
             {new BigDecimal("10"),              new BigDecimal("1e1")},
             {new BigDecimal("20"),              new BigDecimal("2e1")},
             {new BigDecimal("100"),             new BigDecimal("1e2")},
--- a/test/java/security/cert/CertPathValidator/OCSP/FailoverToCRL.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/security/cert/CertPathValidator/OCSP/FailoverToCRL.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
 
 /**
  * @test
- * @bug 6383095 8019259
+ * @bug 6383095
  * @summary CRL revoked certificate failures masked by OCSP failures
  *
  * Note that the certificate validity is from Mar 16 14:55:35 2009 GMT to
@@ -254,32 +254,12 @@
         CertPathValidator validator = CertPathValidator.getInstance("PKIX");
 
         try {
-            System.out.println("Validating cert via OCSP: no responder URL");
             validator.validate(path, params);
         } catch (CertPathValidatorException cpve) {
             if (cpve.getReason() != BasicReason.REVOKED) {
                 throw new Exception(
                     "unexpected exception, should be a REVOKED CPVE", cpve);
             }
-            System.out.println("  successful failover to using CRLs");
-        }
-
-        java.security.cert.PKIXRevocationChecker revocationChecker =
-            (java.security.cert.PKIXRevocationChecker)
-                validator.getRevocationChecker();
-        revocationChecker.setOCSPResponder(
-            new java.net.URI("bad_ocsp_responder_url"));
-        params.addCertPathChecker(revocationChecker);
-
-        try {
-            System.out.println("Validating cert via OCSP: bad responder URL");
-            validator.validate(path, params);
-        } catch (CertPathValidatorException cpve) {
-            if (cpve.getReason() != BasicReason.REVOKED) {
-                throw new Exception(
-                    "unexpected exception, should be a REVOKED CPVE", cpve);
-            }
-            System.out.println("  successful failover to using CRLs");
         }
     }
 }
--- a/test/java/util/Collection/MOAT.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/Collection/MOAT.java	Mon Jul 22 17:37:15 2013 -0700
@@ -71,6 +71,14 @@
         testCollection(new LinkedList<Integer>());
         testCollection(new LinkedList<Integer>().subList(0,0));
         testCollection(new TreeSet<Integer>());
+        testCollection(Collections.checkedList(new ArrayList<Integer>(), Integer.class));
+        testCollection(Collections.synchronizedList(new ArrayList<Integer>()));
+        testCollection(Collections.checkedSet(new HashSet<Integer>(), Integer.class));
+        testCollection(Collections.checkedSortedSet(new TreeSet<Integer>(), Integer.class));
+        testCollection(Collections.checkedNavigableSet(new TreeSet<Integer>(), Integer.class));
+        testCollection(Collections.synchronizedSet(new HashSet<Integer>()));
+        testCollection(Collections.synchronizedSortedSet(new TreeSet<Integer>()));
+        testCollection(Collections.synchronizedNavigableSet(new TreeSet<Integer>()));
 
         testCollection(new CopyOnWriteArrayList<Integer>());
         testCollection(new CopyOnWriteArrayList<Integer>().subList(0,0));
@@ -98,6 +106,12 @@
         testMap(new Hashtable<Integer,Integer>());
         testMap(new ConcurrentHashMap<Integer,Integer>(10, 0.5f));
         testMap(new ConcurrentSkipListMap<Integer,Integer>());
+        testMap(Collections.checkedMap(new HashMap<Integer,Integer>(), Integer.class, Integer.class));
+        testMap(Collections.checkedSortedMap(new TreeMap<Integer,Integer>(), Integer.class, Integer.class));
+        testMap(Collections.checkedNavigableMap(new TreeMap<Integer,Integer>(), Integer.class, Integer.class));
+        testMap(Collections.synchronizedMap(new HashMap<Integer,Integer>()));
+        testMap(Collections.synchronizedSortedMap(new TreeMap<Integer,Integer>()));
+        testMap(Collections.synchronizedNavigableMap(new TreeMap<Integer,Integer>()));
 
         // Empty collections
         final List<Integer> emptyArray = Arrays.asList(new Integer[]{});
@@ -117,19 +131,29 @@
         testCollection(emptySet);
         testEmptySet(emptySet);
         testEmptySet(EMPTY_SET);
+        testEmptySet(Collections.emptySet());
+        testEmptySet(Collections.emptySortedSet());
+        testEmptySet(Collections.emptyNavigableSet());
         testImmutableSet(emptySet);
 
         List<Integer> emptyList = emptyList();
         testCollection(emptyList);
         testEmptyList(emptyList);
         testEmptyList(EMPTY_LIST);
+        testEmptyList(Collections.emptyList());
         testImmutableList(emptyList);
 
         Map<Integer,Integer> emptyMap = emptyMap();
         testMap(emptyMap);
         testEmptyMap(emptyMap);
         testEmptyMap(EMPTY_MAP);
+        testEmptyMap(Collections.emptyMap());
+        testEmptyMap(Collections.emptySortedMap());
+        testEmptyMap(Collections.emptyNavigableMap());
         testImmutableMap(emptyMap);
+        testImmutableMap(Collections.emptyMap());
+        testImmutableMap(Collections.emptySortedMap());
+        testImmutableMap(Collections.emptyNavigableMap());
 
         // Singleton collections
         Set<Integer> singletonSet = singleton(1);
--- a/test/java/util/Collections/CheckedIdentityMap.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/Collections/CheckedIdentityMap.java	Mon Jul 22 17:37:15 2013 -0700
@@ -24,59 +24,42 @@
 /*
  * @test
  * @bug 6585904
+ * @run testng CheckedIdentityMap
  * @summary Checked collections with underlying maps with identity comparisons
  */
 
 import java.util.*;
 import static java.util.Collections.*;
 
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotEquals;
+
+import org.testng.annotations.Test;
+
 public class CheckedIdentityMap {
-    void test(String[] args) throws Throwable {
+
+    @Test
+    public void testHashCode() {
         Map<Integer, Integer> m1 = checkedMap(
             new IdentityHashMap<Integer, Integer>(),
             Integer.class, Integer.class);
         Map<Integer, Integer> m2 = checkedMap(
             new IdentityHashMap<Integer, Integer>(),
             Integer.class, Integer.class);
+        // NB: these are unique instances. Compare vs. Integer.valueOf(1)
         m1.put(new Integer(1), new Integer(1));
         m2.put(new Integer(1), new Integer(1));
 
         Map.Entry<Integer, Integer> e1 = m1.entrySet().iterator().next();
         Map.Entry<Integer, Integer> e2 = m2.entrySet().iterator().next();
-        check(! e1.equals(e2));
-        check(e1.hashCode() == hashCode(e1));
-        check(e2.hashCode() == hashCode(e2));
+
+        assertNotEquals(e1, e2);
+        assertEquals(e1.hashCode(), hashCode(e1));
+        assertEquals(e2.hashCode(), hashCode(e2));
     }
 
-    int hashCode(Map.Entry<?,?> e) {
+    static int hashCode(Map.Entry<?,?> e) {
         return (System.identityHashCode(e.getKey()) ^
                 System.identityHashCode(e.getValue()));
     }
-
-    //--------------------- Infrastructure ---------------------------
-    volatile int passed = 0, failed = 0;
-    void pass() {passed++;}
-    void fail() {failed++; Thread.dumpStack();}
-    void fail(String msg) {System.err.println(msg); fail();}
-    void unexpected(Throwable t) {failed++; t.printStackTrace();}
-    void check(boolean cond) {if (cond) pass(); else fail();}
-    void equal(Object x, Object y) {
-        if (x == null ? y == null : x.equals(y)) pass();
-        else fail(x + " not equal to " + y);}
-    public static void main(String[] args) throws Throwable {
-        new CheckedIdentityMap().instanceMain(args);}
-    void instanceMain(String[] args) throws Throwable {
-        try {test(args);} catch (Throwable t) {unexpected(t);}
-        System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
-        if (failed > 0) throw new AssertionError("Some tests failed");}
-    abstract class F {abstract void f() throws Throwable;}
-    void THROWS(Class<? extends Throwable> k, F... fs) {
-        for (F f : fs)
-            try {f.f(); fail("Expected " + k.getName() + " not thrown");}
-            catch (Throwable t) {
-                if (k.isAssignableFrom(t.getClass())) pass();
-                else unexpected(t);}}
-    Thread checkedThread(final Runnable r) {
-        return new Thread() {public void run() {
-            try {r.run();} catch (Throwable t) {unexpected(t);}}};}
 }
--- a/test/java/util/Collections/CheckedMapBash.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/Collections/CheckedMapBash.java	Mon Jul 22 17:37:15 2013 -0700
@@ -23,76 +23,83 @@
 
 /*
  * @test
- * @bug     4904067 5023830
+ * @bug     4904067 5023830 7129185
  * @summary Unit test for Collections.checkedMap
  * @author  Josh Bloch
+ * @run testng CheckedMapBash
  */
 
 import java.util.*;
+import java.util.function.Supplier;
+import org.testng.annotations.Test;
+import org.testng.annotations.DataProvider;
+
+import static org.testng.Assert.fail;
+import static org.testng.Assert.assertTrue;
 
 public class CheckedMapBash {
-    static Random rnd = new Random();
-    static Object nil = new Integer(0);
-
-    public static void main(String[] args) {
-        int numItr = 100;
-        int mapSize = 100;
-
-        // Linked List test
-        for (int i=0; i<numItr; i++) {
-            Map m = newMap();
-            Object head = nil;
+    static final Random rnd = new Random();
+    static final Object nil = new Integer(0);
+    static final int numItr = 100;
+    static final int mapSize = 100;
 
-            for (int j=0; j<mapSize; j++) {
-                Object newHead;
-                do {
-                    newHead = new Integer(rnd.nextInt());
-                } while (m.containsKey(newHead));
-                m.put(newHead, head);
-                head = newHead;
-            }
-            if (m.size() != mapSize)
-                fail("Size not as expected.");
-
-            {
-                HashMap hm = new HashMap(m);
-                if (! (hm.hashCode() == m.hashCode() &&
-                       hm.entrySet().hashCode() == m.entrySet().hashCode() &&
-                       hm.keySet().hashCode() == m.keySet().hashCode()))
-                    fail("Incorrect hashCode computation.");
+    @Test(dataProvider = "Bash.Supplier<Map<Integer,Integer>>")
+    public static void testCheckedMap(String description, Supplier<Map<Integer,Integer>> supplier) {
+        Map m = supplier.get();
+        Object head = nil;
 
-                if (! (hm.equals(m) &&
-                       hm.entrySet().equals(m.entrySet()) &&
-                       hm.keySet().equals(m.keySet()) &&
-                       m.equals(hm) &&
-                       m.entrySet().equals(hm.entrySet()) &&
-                       m.keySet().equals(hm.keySet())))
-                    fail("Incorrect equals computation.");
-            }
-
-            Map m2 = newMap(); m2.putAll(m);
-            m2.values().removeAll(m.keySet());
-            if (m2.size()!= 1 || !m2.containsValue(nil))
-                fail("Collection views test failed.");
+        for (int j=0; j<mapSize; j++) {
+            Object newHead;
+            do {
+                newHead = new Integer(rnd.nextInt());
+            } while (m.containsKey(newHead));
+            m.put(newHead, head);
+            head = newHead;
+        }
+        if (m.size() != mapSize)
+            fail("Size not as expected.");
 
-            int j=0;
-            while (head != nil) {
-                if (!m.containsKey(head))
-                    fail("Linked list doesn't contain a link.");
-                Object newHead = m.get(head);
-                if (newHead == null)
-                    fail("Could not retrieve a link.");
-                m.remove(head);
-                head = newHead;
-                j++;
-            }
-            if (!m.isEmpty())
-                fail("Map nonempty after removing all links.");
-            if (j != mapSize)
-                fail("Linked list size not as expected.");
+        {
+            HashMap hm = new HashMap(m);
+            if (! (hm.hashCode() == m.hashCode() &&
+                   hm.entrySet().hashCode() == m.entrySet().hashCode() &&
+                   hm.keySet().hashCode() == m.keySet().hashCode()))
+                fail("Incorrect hashCode computation.");
+
+            if (! (hm.equals(m) &&
+                   hm.entrySet().equals(m.entrySet()) &&
+                   hm.keySet().equals(m.keySet()) &&
+                   m.equals(hm) &&
+                   m.entrySet().equals(hm.entrySet()) &&
+                   m.keySet().equals(hm.keySet())))
+                fail("Incorrect equals computation.");
         }
 
-        Map m = newMap();
+        Map m2 = supplier.get(); m2.putAll(m);
+        m2.values().removeAll(m.keySet());
+        if (m2.size()!= 1 || !m2.containsValue(nil))
+            fail("Collection views test failed.");
+
+        int j=0;
+        while (head != nil) {
+            if (!m.containsKey(head))
+                fail("Linked list doesn't contain a link.");
+            Object newHead = m.get(head);
+            if (newHead == null)
+                fail("Could not retrieve a link.");
+            m.remove(head);
+            head = newHead;
+            j++;
+        }
+        if (!m.isEmpty())
+            fail("Map nonempty after removing all links.");
+        if (j != mapSize)
+            fail("Linked list size not as expected.");
+    }
+
+    @Test(dataProvider = "Supplier<Map<Integer,Integer>>")
+    public static void testCheckeMap2(String description, Supplier<Map<Integer,Integer>> supplier) {
+        Map m = supplier.get();
         for (int i=0; i<mapSize; i++)
             if (m.put(new Integer(i), new Integer(2*i)) != null)
                 fail("put returns a non-null value erroenously.");
@@ -101,7 +108,7 @@
                 fail("contains value "+i);
         if (m.put(nil, nil) == null)
             fail("put returns a null value erroenously.");
-        Map m2 = newMap(); m2.putAll(m);
+        Map m2 = supplier.get(); m2.putAll(m);
         if (!m.equals(m2))
             fail("Clone not equal to original. (1)");
         if (!m2.equals(m))
@@ -134,16 +141,36 @@
             fail("Iterator.remove() failed");
     }
 
-    static Map newMap() {
-        Map m = Collections.checkedMap(new HashMap(),
-                                       Integer.class, Integer.class);
 
-        if (!m.isEmpty())
-            fail("New instance non empty.");
-        return m;
+    @DataProvider(name = "Bash.Supplier<Map<Integer,Integer>>", parallel = true)
+    public static Iterator<Object[]> bashNavigableMapProvider() {
+        ArrayList<Object[]> iters = new ArrayList<>(makeCheckedMaps());
+        iters.ensureCapacity(numItr * iters.size());
+        for(int each=1; each < numItr; each++) {
+            iters.addAll( makeCheckedMaps());
+        }
+        return iters.iterator();
+    }
+
+    @DataProvider(name = "Supplier<Map<Integer,Integer>>", parallel = true)
+    public static Iterator<Object[]> navigableMapProvider() {
+        return makeCheckedMaps().iterator();
     }
 
-    static void fail(String s) {
-        throw new RuntimeException(s);
+    public static Collection<Object[]> makeCheckedMaps() {
+        return Arrays.asList(
+            new Object[]{"Collections.checkedMap(HashMap)",
+                (Supplier) () -> {return Collections.checkedMap(new HashMap(), Integer.class, Integer.class);}},
+            new Object[]{"Collections.checkedMap(TreeSet(reverseOrder)",
+                (Supplier) () -> {return Collections.checkedMap(new TreeMap(Collections.reverseOrder()), Integer.class, Integer.class);}},
+            new Object[]{"Collections.checkedMap(TreeSet).descendingSet()",
+                (Supplier) () -> {return Collections.checkedMap(new TreeMap().descendingMap(), Integer.class, Integer.class);}},
+            new Object[]{"Collections.checkedNavigableMap(TreeSet)",
+                (Supplier) () -> {return Collections.checkedNavigableMap(new TreeMap(), Integer.class, Integer.class);}},
+            new Object[]{"Collections.checkedNavigableMap(TreeSet(reverseOrder)",
+                (Supplier) () -> {return Collections.checkedNavigableMap(new TreeMap(Collections.reverseOrder()), Integer.class, Integer.class);}},
+            new Object[]{"Collections.checkedNavigableMap().descendingSet()",
+                (Supplier) () -> {return Collections.checkedNavigableMap(new TreeMap().descendingMap(), Integer.class, Integer.class);}}
+            );
     }
 }
--- a/test/java/util/Collections/CheckedSetBash.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/Collections/CheckedSetBash.java	Mon Jul 22 17:37:15 2013 -0700
@@ -23,82 +23,93 @@
 
 /*
  * @test
- * @bug     4904067
+ * @bug     4904067 7129185
  * @summary Unit test for Collections.checkedSet
  * @author  Josh Bloch
+ * @run testng CheckedSetBash
  */
 
 import java.util.*;
+import java.util.function.Supplier;
+import org.testng.annotations.Test;
+import org.testng.annotations.DataProvider;
+
+import static org.testng.Assert.fail;
+import static org.testng.Assert.assertTrue;
 
 public class CheckedSetBash {
-    static Random rnd = new Random();
+    static final int numItr = 100;
+    static final int setSize = 100;
+    static final Random rnd = new Random();
 
-    public static void main(String[] args) {
-        int numItr = 100;
-        int setSize = 100;
+    @Test(dataProvider = "Supplier<Set<Integer>>")
+    public static void testCheckedSet(String description, Supplier<Set<Integer>> supplier) {
+
+        Set<Integer> s1 = supplier.get();
+        assertTrue(s1.isEmpty());
+
+        AddRandoms(s1, setSize);
 
-        for (int i=0; i<numItr; i++) {
-            Set s1 = newSet();
-            AddRandoms(s1, setSize);
+        Set<Integer> s2 = supplier.get();
+
+        assertTrue(s2.isEmpty());
+
+        AddRandoms(s2, setSize);
 
-            Set s2 = newSet();
-            AddRandoms(s2, setSize);
-
-            Set intersection = clone(s1);
-            intersection.retainAll(s2);
-            Set diff1 = clone(s1); diff1.removeAll(s2);
-            Set diff2 = clone(s2); diff2.removeAll(s1);
-            Set union = clone(s1); union.addAll(s2);
+        Set<Integer> intersection = clone(s1, supplier);
+        intersection.retainAll(s2);
+        Set<Integer> diff1 = clone(s1, supplier); diff1.removeAll(s2);
+        Set<Integer> diff2 = clone(s2, supplier); diff2.removeAll(s1);
+        Set<Integer> union = clone(s1, supplier); union.addAll(s2);
 
-            if (diff1.removeAll(diff2))
-                fail("Set algebra identity 2 failed");
-            if (diff1.removeAll(intersection))
-                fail("Set algebra identity 3 failed");
-            if (diff2.removeAll(diff1))
-                fail("Set algebra identity 4 failed");
-            if (diff2.removeAll(intersection))
-                fail("Set algebra identity 5 failed");
-            if (intersection.removeAll(diff1))
-                fail("Set algebra identity 6 failed");
-            if (intersection.removeAll(diff1))
-                fail("Set algebra identity 7 failed");
+        if (diff1.removeAll(diff2))
+            fail("Set algebra identity 2 failed");
+        if (diff1.removeAll(intersection))
+            fail("Set algebra identity 3 failed");
+        if (diff2.removeAll(diff1))
+            fail("Set algebra identity 4 failed");
+        if (diff2.removeAll(intersection))
+            fail("Set algebra identity 5 failed");
+        if (intersection.removeAll(diff1))
+            fail("Set algebra identity 6 failed");
+        if (intersection.removeAll(diff1))
+            fail("Set algebra identity 7 failed");
 
-            intersection.addAll(diff1); intersection.addAll(diff2);
-            if (!intersection.equals(union))
-                fail("Set algebra identity 1 failed");
+        intersection.addAll(diff1); intersection.addAll(diff2);
+        if (!intersection.equals(union))
+            fail("Set algebra identity 1 failed");
 
-            if (new HashSet(union).hashCode() != union.hashCode())
-                fail("Incorrect hashCode computation.");
+        if (new HashSet(union).hashCode() != union.hashCode())
+            fail("Incorrect hashCode computation.");
 
-            Iterator e = union.iterator();
-            while (e.hasNext())
-                if (!intersection.remove(e.next()))
-                    fail("Couldn't remove element from copy.");
-            if (!intersection.isEmpty())
-                fail("Copy nonempty after deleting all elements.");
+        Iterator e = union.iterator();
+        while (e.hasNext())
+            if (!intersection.remove(e.next()))
+                fail("Couldn't remove element from copy.");
+        if (!intersection.isEmpty())
+            fail("Copy nonempty after deleting all elements.");
 
-            e = union.iterator();
-            while (e.hasNext()) {
-                Object o = e.next();
-                if (!union.contains(o))
-                    fail("Set doesn't contain one of its elements.");
-                e.remove();
-                if (union.contains(o))
-                    fail("Set contains element after deletion.");
-            }
-            if (!union.isEmpty())
-                fail("Set nonempty after deleting all elements.");
+        e = union.iterator();
+        while (e.hasNext()) {
+            Object o = e.next();
+            if (!union.contains(o))
+                fail("Set doesn't contain one of its elements.");
+            e.remove();
+            if (union.contains(o))
+                fail("Set contains element after deletion.");
+        }
+        if (!union.isEmpty())
+            fail("Set nonempty after deleting all elements.");
 
-            s1.clear();
-            if (!s1.isEmpty())
-                fail("Set nonempty after clear.");
-        }
+        s1.clear();
+        if (!s1.isEmpty())
+            fail("Set nonempty after clear.");
     }
 
     // Done inefficiently so as to exercise toArray
-    static Set clone(Set s) {
-        Set clone = newSet();
-        List arrayList = Arrays.asList(s.toArray());
+    static <T> Set<T> clone(Set<T> s, Supplier<Set<T>> supplier) {
+        Set<T> clone = supplier.get();
+        List<T> arrayList = Arrays.asList((T[]) s.toArray());
         clone.addAll(arrayList);
         if (!s.equals(clone))
             fail("Set not equal to copy.");
@@ -109,13 +120,6 @@
         return clone;
     }
 
-    static Set newSet() {
-        Set s = Collections.checkedSet(new HashSet(), Integer.class);
-        if (!s.isEmpty())
-            fail("New instance non empty.");
-        return s;
-    }
-
     static void AddRandoms(Set s, int n) {
         for (int i=0; i<n; i++) {
             int r = rnd.nextInt() % n;
@@ -136,8 +140,30 @@
         }
     }
 
-    static void fail(String s) {
-        throw new RuntimeException(s);
+    @DataProvider(name = "Supplier<Set<Integer>>", parallel = true)
+    public static Iterator<Object[]> navigableSetsProvider() {
+        ArrayList<Object[]> iters = new ArrayList<>(makeCheckedSets());
+        iters.ensureCapacity(numItr * iters.size());
+        for(int each=1; each < numItr; each++) {
+            iters.addAll( makeCheckedSets());
+        }
+        return iters.iterator();
+    }
 
+    public static Collection<Object[]> makeCheckedSets() {
+        return Arrays.asList(
+            new Object[]{"Collections.checkedSet(HashSet)",
+                (Supplier) () -> {return Collections.checkedSet(new HashSet(), Integer.class);}},
+            new Object[]{"Collections.checkedSet(TreeSet(reverseOrder)",
+                (Supplier) () -> {return Collections.checkedSet(new TreeSet(Collections.reverseOrder()), Integer.class);}},
+            new Object[]{"Collections.checkedSet(TreeSet).descendingSet()",
+                (Supplier) () -> {return Collections.checkedSet(new TreeSet().descendingSet(), Integer.class);}},
+            new Object[]{"Collections.checkedNavigableSet(TreeSet)",
+                (Supplier) () -> {return Collections.checkedNavigableSet(new TreeSet(), Integer.class);}},
+            new Object[]{"Collections.checkedNavigableSet(TreeSet(reverseOrder)",
+                (Supplier) () -> {return Collections.checkedNavigableSet(new TreeSet(Collections.reverseOrder()), Integer.class);}},
+            new Object[]{"Collections.checkedNavigableSet().descendingSet()",
+                (Supplier) () -> {return Collections.checkedNavigableSet(new TreeSet().descendingSet(), Integer.class);}}
+            );
     }
 }
--- a/test/java/util/Collections/EmptyCollectionSerialization.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/Collections/EmptyCollectionSerialization.java	Mon Jul 22 17:37:15 2013 -0700
@@ -23,13 +23,20 @@
 
 /*
  * @test
- * @bug     4684279
+ * @bug     4684279 7129185
  * @summary Empty utility collections should be singletons
  * @author  Josh Bloch
+ * @run testng EmptyCollectionSerialization
  */
 
 import java.util.*;
+import java.util.function.Supplier;
 import java.io.*;
+import org.testng.annotations.Test;
+import org.testng.annotations.DataProvider;
+
+import static org.testng.Assert.fail;
+import static org.testng.Assert.assertSame;
 
 public class EmptyCollectionSerialization {
     private static Object patheticDeepCopy(Object o) throws Exception {
@@ -45,16 +52,48 @@
         return ois.readObject();
     }
 
-    private static boolean isSingleton(Object o) throws Exception {
-        return patheticDeepCopy(o) == o;
+    @Test(dataProvider="SerializableSingletons")
+    public static void serializableSingletons(String description, Supplier<Object> o) {
+        try {
+            Object singleton = o.get();
+            assertSame(o.get(), singleton, description + ": broken Supplier not returning singleton");
+            Object copy = patheticDeepCopy(singleton);
+            assertSame( copy, singleton, description + ": " +
+                copy.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(copy)) +
+                " is not the singleton " +
+                singleton.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(singleton)));
+        } catch(Exception all) {
+            fail(description + ": Unexpected Exception", all);
+        }
+    }
+
+    @DataProvider(name = "SerializableSingletons", parallel = true)
+    public static Iterator<Object[]> navigableMapProvider() {
+        return makeSingletons().iterator();
     }
 
-    public static void main(String[] args) throws Exception {
-        if (!isSingleton(Collections.EMPTY_SET))
-            throw new Exception("EMPTY_SET");
-        if (!isSingleton(Collections.EMPTY_LIST))
-            throw new Exception("EMPTY_LIST");
-        if (!isSingleton(Collections.EMPTY_MAP))
-            throw new Exception("EMPTY_MAP");
+    public static Collection<Object[]> makeSingletons() {
+        return Arrays.asList(
+            new Object[]{"Collections.EMPTY_LIST",
+                (Supplier) () -> {return Collections.EMPTY_LIST;}},
+            new Object[]{"Collections.EMPTY_MAP",
+                (Supplier) () -> {return Collections.EMPTY_MAP;}},
+            new Object[]{"Collections.EMPTY_SET",
+                (Supplier) () -> {return Collections.EMPTY_SET;}},
+            new Object[]{"Collections.singletonMap()",
+                (Supplier) () -> {return Collections.emptyList();}},
+            new Object[]{"Collections.emptyMap()",
+                (Supplier) () -> {return Collections.emptyMap();}},
+            new Object[]{"Collections.emptySet()",
+                (Supplier) () -> {return Collections.emptySet();}},
+            new Object[]{"Collections.emptySortedSet()",
+                (Supplier) () -> {return Collections.emptySortedSet();}},
+            new Object[]{"Collections.emptySortedMap()",
+                (Supplier) () -> {return Collections.emptySortedMap();}},
+            new Object[]{"Collections.emptyNavigableSet()",
+                (Supplier) () -> {return Collections.emptyNavigableSet();}},
+            new Object[]{"Collections.emptyNavigableMap()",
+                (Supplier) () -> {return Collections.emptyNavigableMap();}}
+            );
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/Collections/EmptyNavigableMap.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,373 @@
+/*
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 4533691 7129185
+ * @summary Unit test for Collections.emptyNavigableMap
+ * @run testng EmptyNavigableMap
+ */
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.NavigableMap;
+import java.util.SortedMap;
+import java.util.TreeMap;
+import org.testng.annotations.Test;
+import org.testng.annotations.DataProvider;
+
+import static org.testng.Assert.fail;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertSame;
+
+public class EmptyNavigableMap {
+
+    public static <T> void assertInstance(T actual, Class<? extends T> expected) {
+        assertInstance(expected.isInstance(actual), null);
+    }
+
+    public static <T> void assertInstance(T actual, Class<? extends T> expected, String message) {
+        assertTrue(expected.isInstance(actual), ((null != message) ? message : "")
+            + " " + (actual == null ? "<null>" : actual.getClass().getSimpleName()) + " != " + expected.getSimpleName() + ". ");
+    }
+
+    public static <T extends Throwable> void assertEmptyNavigableMap(Object obj) {
+        assertInstance(obj, NavigableMap.class);
+        assertTrue(((NavigableMap)obj).isEmpty() && (((NavigableMap)obj).size() == 0));
+    }
+
+    public static <T extends Throwable> void assertEmptyNavigableMap(Object obj, String message) {
+        assertInstance(obj, NavigableMap.class, message);
+        assertTrue(((NavigableMap)obj).isEmpty() && (((NavigableMap)obj).size() == 0),
+            ((null != message) ? message : "") + " Not empty. ");
+    }
+
+    public interface Thrower<T extends Throwable> {
+
+        public void run() throws T;
+    }
+
+    public static <T extends Throwable> void assertThrows(Thrower<T> thrower, Class<T> throwable) {
+        assertThrows(thrower, throwable, null);
+    }
+
+    public static <T extends Throwable> void assertThrows(Thrower<T> thrower, Class<T> throwable, String message) {
+        Throwable result;
+        try {
+            thrower.run();
+            fail(((null != message) ? message : "") + "Failed to throw " + throwable.getCanonicalName() + ". ");
+            return;
+        } catch (Throwable caught) {
+            result = caught;
+        }
+
+        assertInstance(result, throwable, ((null != message) ? message : "") + "Failed to throw " + throwable.getCanonicalName() + ". ");
+    }
+
+    public static final boolean isDescending(SortedMap<?,?> set) {
+        if (null == set.comparator()) {
+            // natural order
+            return false;
+        }
+
+        if (Collections.reverseOrder() == set.comparator()) {
+            // reverse natural order.
+            return true;
+        }
+
+        if (set.comparator().equals(Collections.reverseOrder(Collections.reverseOrder(set.comparator())))) {
+            // it's a Collections.reverseOrder(Comparator).
+            return true;
+        }
+
+        throw new IllegalStateException("can't determine ordering for " + set);
+    }
+
+    /**
+     * Tests that the comparator is {@code null}.
+     */
+    @Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
+    public void testComparatorIsNull(String description, NavigableMap<?,?> navigableMap) {
+        Comparator comparator = navigableMap.comparator();
+
+        assertTrue(comparator == null || comparator == Collections.reverseOrder(), description + ": Comparator (" + comparator + ") is not null.");
+    }
+
+    /**
+     * Tests that contains requires Comparable
+     */
+    @Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
+    public void testContainsRequiresComparable(String description, NavigableMap<?,?> navigableMap) {
+        assertThrows(() -> {
+            navigableMap.containsKey(new Object());
+        },
+            ClassCastException.class,
+            description + ": Compareable should be required");
+    }
+
+    /**
+     * Tests that the contains method returns {@code false}.
+     */
+    @Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
+    public void testContains(String description, NavigableMap<?,?> navigableMap) {
+        assertFalse(navigableMap.containsKey(new Integer(1)),
+            description + ": Should not contain any elements.");
+        assertFalse(navigableMap.containsValue(new Integer(1)),
+            description + ": Should not contain any elements.");
+    }
+
+    /**
+     * Tests that the containsAll method returns {@code false}.
+     */
+    @Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
+    public void testContainsAll(String description, NavigableMap<?,?> navigableMap) {
+        TreeMap treeMap = new TreeMap();
+        treeMap.put("1", 1);
+        treeMap.put("2", 2);
+        treeMap.put("3", 3);
+
+        assertFalse(navigableMap.equals(treeMap), "Should not contain any elements.");
+    }
+
+    /**
+     * Tests that the iterator is empty.
+     */
+    @Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
+    public void testEmptyIterator(String description, NavigableMap<?,?> navigableMap) {
+        assertFalse(navigableMap.keySet().iterator().hasNext(), "The iterator is not empty.");
+        assertFalse(navigableMap.values().iterator().hasNext(), "The iterator is not empty.");
+        assertFalse(navigableMap.entrySet().iterator().hasNext(), "The iterator is not empty.");
+    }
+
+    /**
+     * Tests that the set is empty.
+     */
+    @Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
+    public void testIsEmpty(String description, NavigableMap<?,?> navigableMap) {
+        assertTrue(navigableMap.isEmpty(), "The set is not empty.");
+    }
+
+    /**
+     * Tests the headMap() method.
+     */
+    @Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
+    public void testHeadMap(String description, NavigableMap navigableMap) {
+        assertThrows(
+            () -> { NavigableMap ss = navigableMap.headMap(null, false); },
+            NullPointerException.class,
+            description + ": Must throw NullPointerException for null element");
+
+        assertThrows(
+            () -> { NavigableMap ss = navigableMap.headMap(new Object(), true); },
+            ClassCastException.class,
+            description + ": Must throw ClassCastException for non-Comparable element");
+
+        NavigableMap ss = navigableMap.headMap("1", false);
+
+        assertEmptyNavigableMap(ss, description + ": Returned value is not empty navigable set.");
+    }
+
+    /**
+     * Tests that the size is 0.
+     */
+    @Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
+    public void testSizeIsZero(String description, NavigableMap<?,?> navigableMap) {
+        assertTrue(0 == navigableMap.size(), "The size of the set is not 0.");
+    }
+
+    /**
+     * Tests the subMap() method.
+     */
+    @Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
+    public void testSubMap(String description, NavigableMap navigableMap) {
+        assertThrows(
+            () -> {
+                SortedMap ss = navigableMap.subMap(null, BigInteger.TEN);
+            },
+            NullPointerException.class,
+            description + ": Must throw NullPointerException for null element");
+
+        assertThrows(
+            () -> {
+                SortedMap ss = navigableMap.subMap(BigInteger.ZERO, null);
+            },
+            NullPointerException.class,
+            description + ": Must throw NullPointerException for null element");
+
+        assertThrows(
+            () -> {
+                SortedMap ss = navigableMap.subMap(null, null);
+            },
+            NullPointerException.class,
+            description + ": Must throw NullPointerException for null element");
+
+        Object obj1 = new Object();
+        Object obj2 = new Object();
+
+        assertThrows(
+            () -> {
+                SortedMap ss = navigableMap.subMap(obj1, BigInteger.TEN);
+            },
+            ClassCastException.class, description
+            + ": Must throw ClassCastException for parameter which is not Comparable.");
+
+        assertThrows(
+            () -> {
+                SortedMap ss = navigableMap.subMap(BigInteger.ZERO, obj2);
+            },
+            ClassCastException.class, description
+            + ": Must throw ClassCastException for parameter which is not Comparable.");
+
+        assertThrows(
+            () -> {
+                SortedMap ss = navigableMap.subMap(obj1, obj2);
+            },
+            ClassCastException.class, description
+            + ": Must throw ClassCastException for parameter which is not Comparable.");
+
+        // minimal range
+        navigableMap.subMap(BigInteger.ZERO, false, BigInteger.ZERO, false);
+        navigableMap.subMap(BigInteger.ZERO, false, BigInteger.ZERO, true);
+        navigableMap.subMap(BigInteger.ZERO, true, BigInteger.ZERO, false);
+        navigableMap.subMap(BigInteger.ZERO, true, BigInteger.ZERO, true);
+
+        Object first = isDescending(navigableMap) ? BigInteger.TEN : BigInteger.ZERO;
+        Object last = (BigInteger.ZERO == first) ? BigInteger.TEN : BigInteger.ZERO;
+
+            assertThrows(
+                () -> {
+                    navigableMap.subMap(last, true, first, false);
+                },
+                IllegalArgumentException.class, description
+                + ": Must throw IllegalArgumentException when fromElement is not less then then toElement.");
+
+        navigableMap.subMap(first, true, last, false);
+    }
+
+    @Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
+    public void testSubMapRanges(String description, NavigableMap navigableMap) {
+        Object first = isDescending(navigableMap) ? BigInteger.TEN : BigInteger.ZERO;
+        Object last = (BigInteger.ZERO == first) ? BigInteger.TEN : BigInteger.ZERO;
+
+        NavigableMap subMap = navigableMap.subMap(first, true, last, true);
+
+        // same subset
+        subMap.subMap(first, true, last, true);
+
+        // slightly smaller
+        NavigableMap ns = subMap.subMap(first, false, last, false);
+        // slight exapansion
+        assertThrows(() -> {
+            ns.subMap(first, true, last, true);
+        },
+            IllegalArgumentException.class,
+            description + ": Expansion should not be allowed");
+
+        // much smaller
+        subMap.subMap(first, false, BigInteger.ONE, false);
+    }
+
+    @Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
+    public void testheadMapRanges(String description, NavigableMap navigableMap) {
+        NavigableMap subMap = navigableMap.headMap(BigInteger.ONE, true);
+
+        // same subset
+        subMap.headMap(BigInteger.ONE, true);
+
+        // slightly smaller
+        NavigableMap ns = subMap.headMap(BigInteger.ONE, false);
+
+        // slight exapansion
+        assertThrows(() -> {
+            ns.headMap(BigInteger.ONE, true);
+        },
+            IllegalArgumentException.class,
+            description + ": Expansion should not be allowed");
+
+        // much smaller
+        subMap.headMap(isDescending(subMap) ? BigInteger.TEN : BigInteger.ZERO, true);
+    }
+
+    @Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
+    public void testTailMapRanges(String description, NavigableMap navigableMap) {
+        NavigableMap subMap = navigableMap.tailMap(BigInteger.ONE, true);
+
+        // same subset
+        subMap.tailMap(BigInteger.ONE, true);
+
+        // slightly smaller
+        NavigableMap ns = subMap.tailMap(BigInteger.ONE, false);
+
+        // slight exapansion
+        assertThrows(() -> {
+            ns.tailMap(BigInteger.ONE, true);
+        },
+            IllegalArgumentException.class,
+            description + ": Expansion should not be allowed");
+
+        // much smaller
+        subMap.tailMap(isDescending(subMap) ? BigInteger.ZERO : BigInteger.TEN, false);
+    }
+
+    /**
+     * Tests the tailMap() method.
+     */
+    @Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
+    public void testTailMap(String description, NavigableMap navigableMap) {
+        assertThrows(() -> {
+            navigableMap.tailMap(null);
+        },
+            NullPointerException.class,
+            description + ": Must throw NullPointerException for null element");
+
+        assertThrows(() -> {
+            navigableMap.tailMap(new Object());
+        }, ClassCastException.class);
+
+        NavigableMap ss = navigableMap.tailMap("1", true);
+
+        assertEmptyNavigableMap(ss, description + ": Returned value is not empty navigable set.");
+    }
+
+    @DataProvider(name = "NavigableMap<?,?>", parallel = true)
+    public static Iterator<Object[]> navigableMapsProvider() {
+        return makeNavigableMaps().iterator();
+    }
+
+    public static Collection<Object[]> makeNavigableMaps() {
+        return Arrays.asList(
+            new Object[]{"UnmodifiableNavigableMap(TreeMap)", Collections.unmodifiableNavigableMap(new TreeMap())},
+            new Object[]{"UnmodifiableNavigableMap(TreeMap.descendingMap()", Collections.unmodifiableNavigableMap(new TreeMap().descendingMap())},
+            new Object[]{"UnmodifiableNavigableMap(TreeMap.descendingMap().descendingMap()", Collections.unmodifiableNavigableMap(new TreeMap().descendingMap().descendingMap())},
+            new Object[]{"emptyNavigableMap()", Collections.emptyNavigableMap()},
+            new Object[]{"emptyNavigableMap().descendingMap()", Collections.emptyNavigableMap().descendingMap()},
+            new Object[]{"emptyNavigableMap().descendingMap().descendingMap()", Collections.emptyNavigableMap().descendingMap().descendingMap()}
+        );
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/Collections/EmptyNavigableSet.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,410 @@
+/*
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 4533691 7129185
+ * @summary Unit test for Collections.emptyNavigableSet
+ * @run testng EmptyNavigableSet
+ */
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.NavigableSet;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import org.testng.annotations.Test;
+import org.testng.annotations.DataProvider;
+
+import static org.testng.Assert.fail;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertSame;
+
+public class EmptyNavigableSet {
+
+    public static <T> void assertInstance(T actual, Class<? extends T> expected) {
+        assertInstance(expected.isInstance(actual), null);
+    }
+
+    public static <T> void assertInstance(T actual, Class<? extends T> expected, String message) {
+        assertTrue(expected.isInstance(actual), ((null != message) ? message : "")
+            + " " + (actual == null ? "<null>" : actual.getClass().getSimpleName()) + " != " + expected.getSimpleName() + ". ");
+    }
+
+    public static <T extends Throwable> void assertEmptyNavigableSet(Object obj) {
+        assertInstance(obj, NavigableSet.class);
+        assertTrue(((NavigableSet)obj).isEmpty() && (((NavigableSet)obj).size() == 0));
+    }
+
+    public static <T extends Throwable> void assertEmptyNavigableSet(Object obj, String message) {
+        assertInstance(obj, NavigableSet.class, message);
+        assertTrue(((NavigableSet)obj).isEmpty() && (((NavigableSet)obj).size() == 0),
+            ((null != message) ? message : "") + " Not empty. ");
+    }
+
+    public interface Thrower<T extends Throwable> {
+
+        public void run() throws T;
+    }
+
+    public static <T extends Throwable> void assertThrows(Thrower<T> thrower, Class<T> throwable) {
+        assertThrows(thrower, throwable, null);
+    }
+
+    public static <T extends Throwable> void assertThrows(Thrower<T> thrower, Class<T> throwable, String message) {
+        Throwable result;
+        try {
+            thrower.run();
+            fail(((null != message) ? message : "") + "Failed to throw " + throwable.getCanonicalName() + ". ");
+            return;
+        } catch (Throwable caught) {
+            result = caught;
+        }
+
+        assertInstance(result, throwable, ((null != message) ? message : "") + "Failed to throw " + throwable.getCanonicalName() + ". ");
+    }
+
+    public static final boolean isDescending(SortedSet<?> set) {
+        if (null == set.comparator()) {
+            // natural order
+            return false;
+        }
+
+        if (Collections.reverseOrder() == set.comparator()) {
+            // reverse natural order.
+            return true;
+        }
+
+        if (set.comparator().equals(Collections.reverseOrder(Collections.reverseOrder(set.comparator())))) {
+            // it's a Collections.reverseOrder(Comparator).
+            return true;
+        }
+
+        throw new IllegalStateException("can't determine ordering for " + set);
+    }
+
+    /**
+     * Tests that the comparator is {@code null}.
+     */
+    @Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
+    public void testComparatorIsNull(String description, NavigableSet<?> navigableSet) {
+        Comparator comparator = navigableSet.comparator();
+
+        assertTrue(comparator == null || comparator == Collections.reverseOrder(), description + ": Comparator (" + comparator + ") is not null.");
+    }
+
+    /**
+     * Tests that contains requires Comparable
+     */
+    @Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
+    public void testContainsRequiresComparable(String description, NavigableSet<?> navigableSet) {
+        assertThrows(() -> {
+            navigableSet.contains(new Object());
+        },
+            ClassCastException.class,
+            description + ": Compareable should be required");
+    }
+
+    /**
+     * Tests that the contains method returns {@code false}.
+     */
+    @Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
+    public void testContains(String description, NavigableSet<?> navigableSet) {
+        assertFalse(navigableSet.contains(new Integer(1)),
+            description + ": Should not contain any elements.");
+    }
+
+    /**
+     * Tests that the containsAll method returns {@code false}.
+     */
+    @Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
+    public void testContainsAll(String description, NavigableSet<?> navigableSet) {
+        TreeSet treeSet = new TreeSet();
+        treeSet.add("1");
+        treeSet.add("2");
+        treeSet.add("3");
+
+        assertFalse(navigableSet.containsAll(treeSet), "Should not contain any elements.");
+    }
+
+    /**
+     * Tests that the iterator is empty.
+     */
+    @Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
+    public void testEmptyIterator(String description, NavigableSet<?> navigableSet) {
+        Iterator emptyIterator = navigableSet.iterator();
+
+        assertFalse((emptyIterator != null) && (emptyIterator.hasNext()),
+            "The iterator is not empty.");
+    }
+
+    /**
+     * Tests that the set is empty.
+     */
+    @Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
+    public void testIsEmpty(String description, NavigableSet<?> navigableSet) {
+        assertTrue(navigableSet.isEmpty(), "The set is not empty.");
+    }
+
+    /**
+     * Tests that the first() method throws NoSuchElementException
+     */
+    @Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
+    public void testFirst(String description, NavigableSet<?> navigableSet) {
+        assertThrows(() -> {
+            navigableSet.first();
+        }, NoSuchElementException.class, description);
+    }
+
+    /**
+     * Tests the headSet() method.
+     */
+    @Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
+    public void testHeadSet(String description, NavigableSet navigableSet) {
+        assertThrows(
+            () -> { NavigableSet ns = navigableSet.headSet(null, false); },
+            NullPointerException.class,
+            description + ": Must throw NullPointerException for null element");
+
+        assertThrows(
+            () -> { NavigableSet ns = navigableSet.headSet(new Object(), true); },
+            ClassCastException.class,
+            description + ": Must throw ClassCastException for non-Comparable element");
+
+        NavigableSet ns = navigableSet.headSet("1", false);
+
+        assertEmptyNavigableSet(ns, description + ": Returned value is not empty navigable set.");
+    }
+
+    /**
+     * Tests that the last() method throws NoSuchElementException
+     */
+    @Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
+    public void testLast(String description, NavigableSet<?> navigableSet) {
+        assertThrows(() -> {
+            navigableSet.last();
+        }, NoSuchElementException.class, description);
+    }
+
+    /**
+     * Tests that the size is 0.
+     */
+    @Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
+    public void testSizeIsZero(String description, NavigableSet<?> navigableSet) {
+        assertTrue(0 == navigableSet.size(), "The size of the set is not 0.");
+    }
+
+    /**
+     * Tests the subSet() method.
+     */
+    @Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
+    public void testSubSet(String description, NavigableSet navigableSet) {
+        assertThrows(
+            () -> {
+                SortedSet ss = navigableSet.subSet(null, BigInteger.TEN);
+            },
+            NullPointerException.class,
+            description + ": Must throw NullPointerException for null element");
+
+        assertThrows(
+            () -> {
+                SortedSet ss = navigableSet.subSet(BigInteger.ZERO, null);
+            },
+            NullPointerException.class,
+            description + ": Must throw NullPointerException for null element");
+
+        assertThrows(
+            () -> {
+                SortedSet ss = navigableSet.subSet(null, null);
+            },
+            NullPointerException.class,
+            description + ": Must throw NullPointerException for null element");
+
+        Object obj1 = new Object();
+        Object obj2 = new Object();
+
+        assertThrows(
+            () -> {
+                SortedSet ss = navigableSet.subSet(obj1, BigInteger.TEN);
+            },
+            ClassCastException.class, description
+            + ": Must throw ClassCastException for parameter which is not Comparable.");
+
+        assertThrows(
+            () -> {
+                SortedSet ss = navigableSet.subSet(BigInteger.ZERO, obj2);
+            },
+            ClassCastException.class, description
+            + ": Must throw ClassCastException for parameter which is not Comparable.");
+
+        assertThrows(
+            () -> {
+                SortedSet ss = navigableSet.subSet(obj1, obj2);
+            },
+            ClassCastException.class, description
+            + ": Must throw ClassCastException for parameter which is not Comparable.");
+
+        // minimal range
+        navigableSet.subSet(BigInteger.ZERO, false, BigInteger.ZERO, false);
+        navigableSet.subSet(BigInteger.ZERO, false, BigInteger.ZERO, true);
+        navigableSet.subSet(BigInteger.ZERO, true, BigInteger.ZERO, false);
+        navigableSet.subSet(BigInteger.ZERO, true, BigInteger.ZERO, true);
+
+        Object first = isDescending(navigableSet) ? BigInteger.TEN : BigInteger.ZERO;
+        Object last = (BigInteger.ZERO == first) ? BigInteger.TEN : BigInteger.ZERO;
+
+            assertThrows(
+                () -> {
+                    navigableSet.subSet(last, true, first, false);
+                },
+                IllegalArgumentException.class, description
+                + ": Must throw IllegalArgumentException when fromElement is not less then then toElement.");
+
+        navigableSet.subSet(first, true, last, false);
+    }
+
+    @Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
+    public void testSubSetRanges(String description, NavigableSet navigableSet) {
+        Object first = isDescending(navigableSet) ? BigInteger.TEN : BigInteger.ZERO;
+        Object last = (BigInteger.ZERO == first) ? BigInteger.TEN : BigInteger.ZERO;
+
+        NavigableSet subSet = navigableSet.subSet(first, true, last, true);
+
+        // same subset
+        subSet.subSet(first, true, last, true);
+
+        // slightly smaller
+        NavigableSet ns = subSet.subSet(first, false, last, false);
+        // slight exapansion
+        assertThrows(() -> {
+            ns.subSet(first, true, last, true);
+        },
+            IllegalArgumentException.class,
+            description + ": Expansion should not be allowed");
+
+        // much smaller
+        subSet.subSet(first, false, BigInteger.ONE, false);
+    }
+
+    @Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
+    public void testheadSetRanges(String description, NavigableSet navigableSet) {
+        NavigableSet subSet = navigableSet.headSet(BigInteger.ONE, true);
+
+        // same subset
+        subSet.headSet(BigInteger.ONE, true);
+
+        // slightly smaller
+        NavigableSet ns = subSet.headSet(BigInteger.ONE, false);
+
+        // slight exapansion
+        assertThrows(() -> {
+            ns.headSet(BigInteger.ONE, true);
+        },
+            IllegalArgumentException.class,
+            description + ": Expansion should not be allowed");
+
+        // much smaller
+        subSet.headSet(isDescending(subSet) ? BigInteger.TEN : BigInteger.ZERO, true);
+    }
+
+    @Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
+    public void testTailSetRanges(String description, NavigableSet navigableSet) {
+        NavigableSet subSet = navigableSet.tailSet(BigInteger.ONE, true);
+
+        // same subset
+        subSet.tailSet(BigInteger.ONE, true);
+
+        // slightly smaller
+        NavigableSet ns = subSet.tailSet(BigInteger.ONE, false);
+
+        // slight exapansion
+        assertThrows(() -> {
+            ns.tailSet(BigInteger.ONE, true);
+        },
+            IllegalArgumentException.class,
+            description + ": Expansion should not be allowed");
+
+        // much smaller
+        subSet.tailSet(isDescending(subSet) ? BigInteger.ZERO : BigInteger.TEN, false);
+    }
+
+    /**
+     * Tests the tailSet() method.
+     */
+    @Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
+    public void testTailSet(String description, NavigableSet navigableSet) {
+        assertThrows(() -> {
+            navigableSet.tailSet(null);
+        },
+            NullPointerException.class,
+            description + ": Must throw NullPointerException for null element");
+
+        assertThrows(() -> {
+            navigableSet.tailSet(new Object());
+        }, ClassCastException.class);
+
+        NavigableSet ss = navigableSet.tailSet("1", true);
+
+        assertEmptyNavigableSet(ss, description + ": Returned value is not empty navigable set.");
+    }
+
+    /**
+     * Tests that the array has a size of 0.
+     */
+    @Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
+    public void testToArray(String description, NavigableSet<?> navigableSet) {
+        Object[] emptyNavigableSetArray = navigableSet.toArray();
+
+        assertTrue(emptyNavigableSetArray.length == 0, "Returned non-empty Array.");
+
+        emptyNavigableSetArray = new Object[20];
+
+        Object[] result = navigableSet.toArray(emptyNavigableSetArray);
+
+        assertSame(emptyNavigableSetArray, result);
+
+        assertTrue(result[0] == null);
+    }
+
+    @DataProvider(name = "NavigableSet<?>", parallel = true)
+    public static Iterator<Object[]> navigableSetsProvider() {
+        return makeNavigableSets().iterator();
+    }
+
+    public static Collection<Object[]> makeNavigableSets() {
+        return Arrays.asList(
+            new Object[]{"UnmodifiableNavigableSet(TreeSet)", Collections.unmodifiableNavigableSet(new TreeSet())},
+            new Object[]{"UnmodifiableNavigableSet(TreeSet.descendingSet()", Collections.unmodifiableNavigableSet(new TreeSet().descendingSet())},
+            new Object[]{"UnmodifiableNavigableSet(TreeSet.descendingSet().descendingSet()", Collections.unmodifiableNavigableSet(new TreeSet().descendingSet().descendingSet())},
+            new Object[]{"emptyNavigableSet()", Collections.emptyNavigableSet()},
+            new Object[]{"emptyNavigableSet().descendingSet()", Collections.emptyNavigableSet().descendingSet()},
+            new Object[]{"emptyNavigableSet().descendingSet().descendingSet()", Collections.emptyNavigableSet().descendingSet().descendingSet()}
+        );
+    }
+}
--- a/test/java/util/Collections/EmptySortedSet.java	Thu Jul 18 03:38:49 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,351 +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.
- *
- * 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 4533691
- * @summary Unit test for Collections.emptySortedSet
- */
-
-import java.lang.reflect.Method;
-import java.math.BigInteger;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-public class EmptySortedSet {
-    static int status = 0;
-    private static final String FAILED = " failed. ";
-    private static final String PERIOD = ".";
-    private final String thisClassName = this.getClass().getName();
-
-    public static void main(String[] args) throws Exception {
-        new EmptySortedSet();
-    }
-
-    public EmptySortedSet() throws Exception {
-        run();
-    }
-
-    /**
-     * Returns {@code true} if the {@link Object} passed in is an empty
-     * {@link SortedSet}.
-     *
-     * @param obj the object to test
-     * @return {@code true} if the {@link Object} is an empty {@link SortedSet}
-     *         otherwise {@code false}.
-     */
-    private boolean isEmptySortedSet(Object obj) {
-        boolean isEmptySortedSet = false;
-
-        // We determine if the object is an empty sorted set by testing if it's
-        // an instance of SortedSet, and if so, if it's empty.  Currently the
-        // testing doesn't include checks of the other methods.
-        if (obj instanceof SortedSet) {
-            SortedSet ss = (SortedSet) obj;
-
-            if ((ss.isEmpty()) && (ss.size() == 0)) {
-                isEmptySortedSet = true;
-            }
-        }
-
-        return isEmptySortedSet;
-    }
-
-    private void run() throws Exception {
-        Method[] methods = this.getClass().getDeclaredMethods();
-
-        for (int i = 0; i < methods.length; i++) {
-            Method method = methods[i];
-            String methodName = method.getName();
-
-            if (methodName.startsWith("test")) {
-                try {
-                    Object obj = method.invoke(this, new Object[0]);
-                } catch(Exception e) {
-                    throw new Exception(this.getClass().getName() + "." +
-                            methodName + " test failed, test exception "
-                            + "follows\n" + e.getCause());
-                }
-            }
-        }
-    }
-
-    private void throwException(String methodName, String reason)
-            throws Exception
-    {
-        StringBuilder sb = new StringBuilder(thisClassName);
-        sb.append(PERIOD);
-        sb.append(methodName);
-        sb.append(FAILED);
-        sb.append(reason);
-        throw new Exception(sb.toString());
-    }
-
-    /**
-     *
-     */
-    private void test00() throws Exception {
-        //throwException("test00", "This test has not been implemented yet.");
-    }
-
-    /**
-     * Tests that the comparator is {@code null}.
-     */
-    private void testComparatorIsNull() throws Exception {
-        SortedSet sortedSet = Collections.emptySortedSet();
-        Comparator comparator = sortedSet.comparator();
-
-        if (comparator != null) {
-            throwException("testComparatorIsNull", "Comparator is not null.");
-        }
-    }
-
-    /**
-     * Tests that the contains method returns {@code false}.
-     */
-    private void testContains() throws Exception {
-        SortedSet sortedSet = Collections.emptySortedSet();
-
-        if (sortedSet.contains(new Object())) {
-            throwException("testContains", "Should not contain any elements.");
-        }
-    }
-
-    /**
-     * Tests that the containsAll method returns {@code false}.
-     */
-    private void testContainsAll() throws Exception {
-        SortedSet sortedSet = Collections.emptySortedSet();
-        TreeSet treeSet = new TreeSet();
-        treeSet.add("1");
-        treeSet.add("2");
-        treeSet.add("3");
-
-        if (sortedSet.containsAll(treeSet)) {
-            throwException("testContainsAll",
-                    "Should not contain any elements.");
-        }
-    }
-
-    /**
-     * Tests that the iterator is empty.
-     */
-    private void testEmptyIterator() throws Exception {
-        SortedSet sortedSet = Collections.emptySortedSet();
-        Iterator emptyIterator = sortedSet.iterator();
-
-        if ((emptyIterator != null) && (emptyIterator.hasNext())) {
-            throwException("testEmptyIterator", "The iterator is not empty.");
-        }
-    }
-
-    /**
-     * Tests that the set is empty.
-     */
-    private void testIsEmpty() throws Exception {
-        SortedSet sortedSet = Collections.emptySortedSet();
-
-        if ((sortedSet != null) && (!sortedSet.isEmpty())) {
-            throwException("testSizeIsZero", "The set is not empty.");
-        }
-    }
-
-    /**
-     * Tests that the first() method throws NoSuchElementException
-     */
-    private void testFirst() throws Exception {
-        SortedSet sortedSet = Collections.emptySortedSet();
-
-        try {
-            sortedSet.first();
-            throwException("testFirst",
-                    "NoSuchElemenException was not thrown.");
-        } catch(NoSuchElementException nsee) {
-            // Do nothing
-        }
-    }
-
-    /**
-     * Tests the headSet() method.
-     */
-    private void testHeadSet() throws Exception {
-        SortedSet sortedSet = Collections.emptySortedSet();
-        SortedSet ss;
-
-        try {
-            ss = sortedSet.headSet(null);
-            throwException("testHeadSet",
-                    "Must throw NullPointerException for null element");
-        } catch(NullPointerException npe) {
-            // Do nothing
-        }
-
-        try {
-            ss = sortedSet.headSet(new Object());
-            throwException("testHeadSet",
-                    "Must throw ClassCastException for non-Comparable element");
-        } catch(ClassCastException cce) {
-            // Do nothing.
-        }
-
-        ss = sortedSet.headSet("1");
-
-        if ((ss == null) || !isEmptySortedSet(ss)) {
-            throwException("testHeadSet",
-                    "Returned value is null or not an EmptySortedSet.");
-        }
-    }
-
-    /**
-     * Tests that the last() method throws NoSuchElementException
-     */
-    private void testLast() throws Exception {
-        SortedSet sortedSet = Collections.emptySortedSet();
-
-        try {
-            sortedSet.last();
-            throwException("testLast",
-                    "NoSuchElemenException was not thrown.");
-        } catch(NoSuchElementException nsee) {
-            // Do nothing
-        }
-    }
-
-    /**
-     * Tests that the size is 0.
-     */
-    private void testSizeIsZero() throws Exception {
-        SortedSet sortedSet = Collections.emptySortedSet();
-        int size = sortedSet.size();
-
-        if (size > 0) {
-            throwException("testSizeIsZero",
-                    "The size of the set is greater then 0.");
-        }
-    }
-
-    /**
-     * Tests the subSet() method.
-     */
-    private void testSubSet() throws Exception {
-        SortedSet sortedSet = Collections.emptySortedSet();
-        SortedSet ss = sortedSet.headSet("1");
-
-        try {
-            ss = sortedSet.subSet(null, BigInteger.TEN);
-            ss = sortedSet.subSet(BigInteger.ZERO, null);
-            ss = sortedSet.subSet(null, null);
-            throwException("testSubSet",
-                    "Must throw NullPointerException for null element");
-        } catch(NullPointerException npe) {
-            // Do nothing
-        }
-
-        try {
-            Object obj1 = new Object();
-            Object obj2 = new Object();
-            ss = sortedSet.subSet(obj1, BigInteger.TEN);
-            ss = sortedSet.subSet(BigInteger.ZERO, obj2);
-            ss = sortedSet.subSet(obj1, obj2);
-            throwException("testSubSet",
-                    "Must throw ClassCastException for parameter which is "
-                    + "not Comparable.");
-        } catch(ClassCastException cce) {
-            // Do nothing.
-        }
-
-        try {
-            ss = sortedSet.subSet(BigInteger.ZERO, BigInteger.ZERO);
-            ss = sortedSet.subSet(BigInteger.TEN, BigInteger.ZERO);
-            throwException("testSubSet",
-                    "Must throw IllegalArgumentException when fromElement is "
-                    + "not less then then toElement.");
-        } catch(IllegalArgumentException iae) {
-            // Do nothing.
-        }
-
-        ss = sortedSet.subSet(BigInteger.ZERO, BigInteger.TEN);
-
-        if (!isEmptySortedSet(ss)) {
-            throw new Exception("Returned value is not empty sorted set.");
-        }
-    }
-
-    /**
-     * Tests the tailSet() method.
-     */
-    private void testTailSet() throws Exception {
-        SortedSet sortedSet = Collections.emptySortedSet();
-        SortedSet ss;
-
-        try {
-            ss = sortedSet.tailSet(null);
-            throwException("testTailSet",
-                    "Must throw NullPointerException for null element");
-        } catch(NullPointerException npe) {
-            // Do nothing
-        }
-
-        try {
-            SortedSet ss2 = sortedSet.tailSet(new Object());
-            throwException("testTailSet",
-                    "Must throw ClassCastException for non-Comparable element");
-        } catch(ClassCastException cce) {
-            // Do nothing.
-        }
-
-        ss = sortedSet.tailSet("1");
-
-        if ((ss == null) || !isEmptySortedSet(ss)) {
-            throwException("testTailSet",
-                    "Returned value is null or not an EmptySortedSet.");
-        }
-    }
-
-    /**
-     * Tests that the array has a size of 0.
-     */
-    private void testToArray() throws Exception {
-        SortedSet sortedSet = Collections.emptySortedSet();
-        Object[] emptySortedSetArray = sortedSet.toArray();
-
-        if ((emptySortedSetArray == null) || (emptySortedSetArray.length > 0)) {
-            throwException("testToArray",
-                    "Returned null array or array with length > 0.");
-        }
-
-        String[] strings = new String[2];
-        strings[0] = "1";
-        strings[1] = "2";
-        emptySortedSetArray = sortedSet.toArray(strings);
-
-        if ((emptySortedSetArray == null) || (emptySortedSetArray[0] != null)) {
-            throwException("testToArray",
-                    "Returned null array or array with length > 0.");
-        }
-    }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/Collections/UnmodifiableMapEntrySet.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,164 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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
+ * @run testng UnmodifiableMapEntrySet
+ * @summary Unit tests for wrapping classes should delegate to default methods
+ */
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Spliterator;
+import java.util.TreeMap;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+import org.testng.annotations.Test;
+import org.testng.annotations.DataProvider;
+
+import static org.testng.Assert.assertEquals;
+
+@Test(groups = "unit")
+public class UnmodifiableMapEntrySet {
+    static Object[][] collections;
+
+    static <M extends Map<Integer, Integer>> M fillMap(int size, M m) {
+        for (int i = 0; i < size; i++) {
+            m.put(i, i);
+        }
+        return m;
+    }
+
+    @DataProvider(name="maps")
+    static Object[][] mapCases() {
+        if (collections != null) {
+            return collections;
+        }
+
+        List<Object[]> cases = new ArrayList<>();
+        for (int size : new int[] {1, 2, 16}) {
+            cases.add(new Object[] {
+                    String.format("new HashMap(%d)", size),
+                    (Supplier<Map<Integer, Integer>>)
+                    () -> Collections.unmodifiableMap(fillMap(size, new HashMap<>())) });
+            cases.add(new Object[] {
+                    String.format("new TreeMap(%d)", size),
+                    (Supplier<Map<Integer, Integer>>)
+                    () -> Collections.unmodifiableSortedMap(fillMap(size, new TreeMap<>())) });
+        }
+
+        return cases.toArray(new Object[0][]);
+    }
+
+    static class EntryConsumer implements Consumer<Map.Entry<Integer, Integer>> {
+        int updates;
+        @Override
+        public void accept(Map.Entry<Integer, Integer> me) {
+            try {
+                me.setValue(Integer.MAX_VALUE);
+                updates++;
+            } catch (UnsupportedOperationException e) {
+            }
+        }
+
+        void assertNoUpdates() {
+            assertEquals(updates, 0, "Updates to entries");
+        }
+    }
+
+    void testWithEntryConsumer(Consumer<EntryConsumer> c) {
+        EntryConsumer ec = new EntryConsumer();
+        c.accept(ec);
+        ec.assertNoUpdates();
+    }
+
+    @Test(dataProvider = "maps")
+    public void testForEach(String d, Supplier<Map<Integer, Integer>> ms) {
+        testWithEntryConsumer(
+                ec -> ms.get().entrySet().forEach(ec));
+    }
+
+    @Test(dataProvider = "maps")
+    public void testIteratorForEachRemaining(String d, Supplier<Map<Integer, Integer>> ms) {
+        testWithEntryConsumer(
+                ec -> ms.get().entrySet().iterator().forEachRemaining(ec));
+    }
+
+    @Test(dataProvider = "maps")
+    public void testIteratorNext(String d, Supplier<Map<Integer, Integer>> ms) {
+        testWithEntryConsumer(ec -> {
+            for (Map.Entry<Integer, Integer> me : ms.get().entrySet()) {
+                ec.accept(me);
+            }
+        });
+    }
+
+    @Test(dataProvider = "maps")
+    public void testSpliteratorForEachRemaining(String d, Supplier<Map<Integer, Integer>> ms) {
+        testSpliterator(
+                ms.get().entrySet()::spliterator,
+                // Higher order function returning a consumer that
+                // traverses all spliterator elements using an EntryConsumer
+                s -> ec -> s.forEachRemaining(ec));
+    }
+
+    @Test(dataProvider = "maps")
+    public void testSpliteratorTryAdvance(String d, Supplier<Map<Integer, Integer>> ms) {
+        testSpliterator(
+                ms.get().entrySet()::spliterator,
+                // Higher order function returning a consumer that
+                // traverses all spliterator elements using an EntryConsumer
+                s -> ec -> { while (s.tryAdvance(ec)); });
+    }
+
+    void testSpliterator(Supplier<Spliterator<Map.Entry<Integer, Integer>>> ss,
+                         // Higher order function that given a spliterator returns a
+                         // consumer for that spliterator which traverses elements
+                         // using an EntryConsumer
+                         Function<Spliterator<Map.Entry<Integer, Integer>>, Consumer<EntryConsumer>> sc) {
+        testWithEntryConsumer(sc.apply(ss.get()));
+
+        Spliterator<Map.Entry<Integer, Integer>> s = ss.get();
+        Spliterator<Map.Entry<Integer, Integer>> split = s.trySplit();
+        if (split != null) {
+            testWithEntryConsumer(sc.apply(split));
+            testWithEntryConsumer(sc.apply(s));
+        }
+    }
+
+    @Test(dataProvider = "maps")
+    public void testStreamForEach(String d, Supplier<Map<Integer, Integer>> ms) {
+        testWithEntryConsumer(ec -> ms.get().entrySet().stream().forEach(ec));
+    }
+
+    @Test(dataProvider = "maps")
+    public void testParallelStreamForEach(String d, Supplier<Map<Integer, Integer>> ms) {
+        testWithEntryConsumer(ec -> ms.get().entrySet().parallelStream().forEach(ec));
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/HashMap/OverrideIsEmpty.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * Portions Copyright (c) 2013 IBM Corporation
+ */
+
+/**
+ * @test
+ * @bug 8019381
+ * @summary Verify that we do not get exception when we override isEmpty()
+ *          in a subclass of HashMap
+ * @author zhangshj@linux.vnet.ibm.com
+ */
+
+import java.util.function.BiFunction;
+import java.util.HashMap;
+
+public class OverrideIsEmpty {
+    public static class NotEmptyHashMap<K,V> extends HashMap<K,V> {
+        private K alwaysExistingKey;
+        private V alwaysExistingValue;
+
+        @Override
+        public V get(Object key) {
+            if (key == alwaysExistingKey) {
+                return alwaysExistingValue;
+            }
+            return super.get(key);
+        }
+
+        @Override
+        public int size() {
+            return super.size() + 1;
+        }
+
+        @Override
+        public boolean isEmpty() {
+            return size() == 0;
+        }
+    }
+
+    public static void main(String[] args) {
+        NotEmptyHashMap<Object, Object> map = new NotEmptyHashMap<>();
+        Object key = new Object();
+        Object value = new Object();
+        map.get(key);
+        map.remove(key);
+        map.replace(key, value, null);
+        map.replace(key, value);
+        map.computeIfPresent(key, new BiFunction<Object, Object, Object>() {
+            public Object apply(Object key, Object oldValue) {
+                return oldValue;
+            }
+        });
+    }
+}
+
--- a/test/java/util/Map/LockStep.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/Map/LockStep.java	Mon Jul 22 17:37:15 2013 -0700
@@ -100,7 +100,14 @@
                     new Hashtable(16),
                     new TreeMap(),
                     new ConcurrentHashMap(16),
-                    new ConcurrentSkipListMap() });
+                    new ConcurrentSkipListMap(),
+                    Collections.checkedMap(new HashMap(16), Integer.class, Integer.class),
+                    Collections.checkedSortedMap(new TreeMap(), Integer.class, Integer.class),
+                    Collections.checkedNavigableMap(new TreeMap(), Integer.class, Integer.class),
+                    Collections.synchronizedMap(new HashMap(16)),
+                    Collections.synchronizedSortedMap(new TreeMap()),
+                    Collections.synchronizedNavigableMap(new TreeMap())
+                    });
 
             for (int j = 0; j < 10; j++)
                 put(maps, r.nextInt(100), r.nextInt(100));
--- a/test/java/util/NavigableMap/LockStep.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/NavigableMap/LockStep.java	Mon Jul 22 17:37:15 2013 -0700
@@ -55,11 +55,19 @@
 
         lockSteps(new TreeMap(),
                   new ConcurrentSkipListMap());
+        lockSteps(new TreeMap(),
+                  Collections.checkedNavigableMap(new TreeMap(), Integer.class, Integer.class));
+        lockSteps(new TreeMap(),
+                  Collections.synchronizedNavigableMap(new TreeMap()));
         lockSteps(new TreeMap(reverseOrder()),
                   new ConcurrentSkipListMap(reverseOrder()));
 
         lockSteps(new TreeSet(),
                   new ConcurrentSkipListSet());
+        lockSteps(new TreeSet(),
+                  Collections.checkedNavigableSet(new TreeSet(), Integer.class));
+        lockSteps(new TreeSet(),
+                  Collections.synchronizedNavigableSet(new TreeSet()));
         lockSteps(new TreeSet(reverseOrder()),
                   new ConcurrentSkipListSet(reverseOrder()));
     }
@@ -181,7 +189,15 @@
         testEmptyCollection(m.values());
     }
 
-    static final Random rnd = new Random();
+    static final Random rnd;
+
+    static {
+        // sufficiently random for this test
+        long seed = System.nanoTime();
+        System.out.println(LockStep.class.getCanonicalName() + ": Trial random seed: " + seed );
+
+        rnd = new Random(seed);
+    }
 
     static void equalNext(final Iterator<?> it, Object expected) {
         if (maybe(2))
@@ -208,8 +224,15 @@
             check(s.descendingSet().descendingSet().comparator() == null);
         equal(s.isEmpty(), s.size() == 0);
         equal2(s, s.descendingSet());
-        if (maybe(4) && s instanceof Serializable)
-            equal2(s, serialClone(s));
+        if (maybe(4) && s instanceof Serializable) {
+            try {
+                equal2(s, serialClone(s));
+            } catch(RuntimeException uhoh) {
+                if(!(uhoh.getCause() instanceof NotSerializableException)) {
+                    throw uhoh;
+                }
+            }
+        }
         Comparator cmp = comparator(s);
         if (s.isEmpty()) {
             THROWS(NoSuchElementException.class,
@@ -276,6 +299,15 @@
         check(! it2.hasNext());
     }
 
+    static void equalSetsLeaf(final Set s1, final Set s2) {
+        equal2(s1,            s2);
+        equal( s1.size(),     s2.size());
+        equal( s1.isEmpty(),  s2.isEmpty());
+        equal( s1.hashCode(), s2.hashCode());
+        equal( s1.toString(), s2.toString());
+        equal( s1.containsAll(s2), s2.containsAll(s1));
+    }
+
     static void equalNavigableSetsLeaf(final NavigableSet s1,
                                        final NavigableSet s2) {
         equal2(s1,            s2);
@@ -448,8 +480,7 @@
     static void equalNavigableMaps(NavigableMap m1,
                                    NavigableMap m2) {
         equalNavigableMapsLeaf(m1, m2);
-        equalNavigableSetsLeaf((NavigableSet) m1.keySet(),
-                               (NavigableSet) m2.keySet());
+        equalSetsLeaf(m1.keySet(), m2.keySet());
         equalNavigableSets(m1.navigableKeySet(),
                            m2.navigableKeySet());
         equalNavigableSets(m1.descendingKeySet(),
@@ -836,5 +867,7 @@
     @SuppressWarnings("unchecked")
     static <T> T serialClone(T obj) {
         try { return (T) readObject(serializedForm(obj)); }
-        catch (Exception e) { throw new RuntimeException(e); }}
+        catch (Error|RuntimeException e) { throw e; }
+        catch (Throwable e) { throw new RuntimeException(e); }
+    }
 }
--- a/test/java/util/Optional/Basic.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/Optional/Basic.java	Mon Jul 22 17:37:15 2013 -0700
@@ -58,36 +58,36 @@
         assertSame(Boolean.FALSE, empty.orElseGet(()-> Boolean.FALSE));
     }
 
-        @Test(expectedExceptions=NoSuchElementException.class)
-        public void testEmptyGet() {
-            Optional<Boolean> empty = Optional.empty();
+    @Test(expectedExceptions=NoSuchElementException.class)
+    public void testEmptyGet() {
+        Optional<Boolean> empty = Optional.empty();
 
-            Boolean got = empty.get();
-        }
+        Boolean got = empty.get();
+    }
 
-        @Test(expectedExceptions=NullPointerException.class)
-        public void testEmptyOrElseGetNull() {
-            Optional<Boolean> empty = Optional.empty();
+    @Test(expectedExceptions=NullPointerException.class)
+    public void testEmptyOrElseGetNull() {
+        Optional<Boolean> empty = Optional.empty();
 
-            Boolean got = empty.orElseGet(null);
-        }
+        Boolean got = empty.orElseGet(null);
+    }
 
-        @Test(expectedExceptions=NullPointerException.class)
-        public void testEmptyOrElseThrowNull() throws Throwable {
-            Optional<Boolean> empty = Optional.empty();
+    @Test(expectedExceptions=NullPointerException.class)
+    public void testEmptyOrElseThrowNull() throws Throwable {
+        Optional<Boolean> empty = Optional.empty();
 
-            Boolean got = empty.orElseThrow(null);
-        }
+        Boolean got = empty.orElseThrow(null);
+    }
 
-        @Test(expectedExceptions=ObscureException.class)
-        public void testEmptyOrElseThrow() throws Exception {
-            Optional<Boolean> empty = Optional.empty();
+    @Test(expectedExceptions=ObscureException.class)
+    public void testEmptyOrElseThrow() throws Exception {
+        Optional<Boolean> empty = Optional.empty();
 
-            Boolean got = empty.orElseThrow(ObscureException::new);
-        }
+        Boolean got = empty.orElseThrow(ObscureException::new);
+    }
 
-        @Test(groups = "unit")
-        public void testPresent() {
+    @Test(groups = "unit")
+    public void testPresent() {
         Optional<Boolean> empty = Optional.empty();
         Optional<String> presentEmptyString = Optional.of("");
         Optional<Boolean> present = Optional.of(Boolean.TRUE);
@@ -116,6 +116,116 @@
         assertSame(Boolean.TRUE, present.<RuntimeException>orElseThrow(ObscureException::new));
     }
 
+    @Test(groups = "unit")
+    public void testOfNullable() {
+        Optional<String> instance = Optional.ofNullable(null);
+        assertFalse(instance.isPresent());
+
+        instance = Optional.ofNullable("Duke");
+        assertTrue(instance.isPresent());
+        assertEquals(instance.get(), "Duke");
+    }
+
+    @Test(groups = "unit")
+    public void testFilter() {
+        // Null mapper function
+        Optional<String> empty = Optional.empty();
+        Optional<String> duke = Optional.of("Duke");
+
+        try {
+            Optional<String> result = empty.filter(null);
+            fail("Should throw NPE on null mapping function");
+        } catch (NullPointerException npe) {
+            // expected
+        }
+
+        Optional<String> result = empty.filter(String::isEmpty);
+        assertFalse(result.isPresent());
+
+        result = duke.filter(String::isEmpty);
+        assertFalse(result.isPresent());
+        result = duke.filter(s -> s.startsWith("D"));
+        assertTrue(result.isPresent());
+        assertEquals(result.get(), "Duke");
+
+        Optional<String> emptyString = Optional.of("");
+        result = emptyString.filter(String::isEmpty);
+        assertTrue(result.isPresent());
+        assertEquals(result.get(), "");
+    }
+
+    @Test(groups = "unit")
+    public void testMap() {
+        Optional<String> empty = Optional.empty();
+        Optional<String> duke = Optional.of("Duke");
+
+        // Null mapper function
+        try {
+            Optional<Boolean> b = empty.map(null);
+            fail("Should throw NPE on null mapping function");
+        } catch (NullPointerException npe) {
+            // expected
+        }
+
+        // Map an empty value
+        Optional<Boolean> b = empty.map(String::isEmpty);
+        assertFalse(b.isPresent());
+
+        // Map into null
+        b = empty.map(n -> null);
+        assertFalse(b.isPresent());
+        b = duke.map(s -> null);
+        assertFalse(b.isPresent());
+
+        // Map to value
+        Optional<Integer> l = duke.map(String::length);
+        assertEquals(l.get().intValue(), 4);
+    }
+
+    @Test(groups = "unit")
+    public void testFlatMap() {
+        Optional<String> empty = Optional.empty();
+        Optional<String> duke = Optional.of("Duke");
+
+        // Null mapper function
+        try {
+            Optional<Boolean> b = empty.flatMap(null);
+            fail("Should throw NPE on null mapping function");
+        } catch (NullPointerException npe) {
+            // expected
+        }
+
+        // Map into null
+        try {
+            Optional<Boolean> b = duke.flatMap(s -> null);
+            fail("Should throw NPE when mapper return null");
+        } catch (NullPointerException npe) {
+            // expected
+        }
+
+        // Empty won't invoke mapper function
+        try {
+            Optional<Boolean> b = empty.flatMap(s -> null);
+            assertFalse(b.isPresent());
+        } catch (NullPointerException npe) {
+            fail("Mapper function should not be invoked");
+        }
+
+        // Map an empty value
+        Optional<Integer> l = empty.flatMap(s -> Optional.of(s.length()));
+        assertFalse(l.isPresent());
+
+        // Map to value
+        Optional<Integer> fixture = Optional.of(Integer.MAX_VALUE);
+        l = duke.flatMap(s -> Optional.of(s.length()));
+        assertTrue(l.isPresent());
+        assertEquals(l.get().intValue(), 4);
+
+        // Verify same instance
+        l = duke.flatMap(s -> fixture);
+        assertSame(l, fixture);
+    }
+
     private static class ObscureException extends RuntimeException {
 
     }
--- a/test/java/util/Spliterator/SpliteratorCollisions.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/Spliterator/SpliteratorCollisions.java	Mon Jul 22 17:37:15 2013 -0700
@@ -48,7 +48,6 @@
 import java.util.TreeSet;
 import java.util.function.Consumer;
 import java.util.function.Function;
-import java.util.function.LongConsumer;
 import java.util.function.Supplier;
 import java.util.function.UnaryOperator;
 
@@ -677,11 +676,11 @@
 
     private static <T> Map<T, HashableInteger> toBoxedMultiset(Iterable<T> c) {
         Map<T, HashableInteger> result = new HashMap<>();
-        c.forEach((Consumer) e -> {
-            if (result.containsKey((T)e)) {
-                result.put((T)e, new HashableInteger(((HashableInteger)result.get(e)).value + 1, 10));
+        c.forEach(e -> {
+            if (result.containsKey(e)) {
+                result.put(e, new HashableInteger(result.get(e).value + 1, 10));
             } else {
-                result.put((T)e, new HashableInteger(1, 10));
+                result.put(e, new HashableInteger(1, 10));
             }
         });
         return result;
--- a/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -321,6 +321,21 @@
             db.addCollection(
                     c -> new AbstractSortedSetImpl(c));
 
+            class IterableWrapper implements Iterable<Integer> {
+                final Iterable<Integer> it;
+
+                IterableWrapper(Iterable<Integer> it) {
+                    this.it = it;
+                }
+
+                @Override
+                public Iterator<Integer> iterator() {
+                    return it.iterator();
+                }
+            }
+            db.add("new Iterable.spliterator()",
+                   () -> new IterableWrapper(exp).spliterator());
+
             //
 
             db.add("Arrays.asList().spliterator()",
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/StringJoiner/MergeTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 8017231
+ * @summary test  StringJoiner::merge
+ * @run testng MergeTest
+ */
+
+import java.util.StringJoiner;
+import java.util.stream.Stream;
+import org.testng.annotations.Test;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.fail;
+
+@Test
+public class MergeTest {
+    public void testNull() {
+        StringJoiner sj = new StringJoiner(",", "{", "}");
+        try {
+            sj.merge(null);
+            fail("Should throw NullPointerException!");
+        } catch (NullPointerException npe) {
+            // expected
+        }
+    }
+
+    public void testSimple() {
+        StringJoiner sj = new StringJoiner(",", "{", "}");
+        StringJoiner other = new StringJoiner(",", "[", "]");
+        Stream.of("a", "b", "c").forEachOrdered(sj::add);
+        Stream.of("d", "e", "f").forEachOrdered(other::add);
+
+        sj.merge(other);
+        assertEquals(sj.toString(), "{a,b,c,d,e,f}");
+    }
+
+    public void testEmptyOther() {
+        StringJoiner sj = new StringJoiner(",", "{", "}");
+        StringJoiner other = new StringJoiner(",", "[", "]");
+        Stream.of("a", "b", "c").forEachOrdered(sj::add);
+
+        sj.merge(other);
+        assertEquals(sj.toString(), "{a,b,c}");
+
+        other.setEmptyValue("EMPTY");
+        sj.merge(other);
+        assertEquals(sj.toString(), "{a,b,c}");
+    }
+
+    public void testEmptyThis() {
+        StringJoiner sj = new StringJoiner(",", "{", "}");
+        StringJoiner other = new StringJoiner(":", "[", "]");
+        Stream.of("d", "e", "f").forEachOrdered(other::add);
+
+        sj.merge(other);
+        assertEquals(sj.toString(), "{d:e:f}");
+
+        sj = new StringJoiner(",", "{", "}").setEmptyValue("EMPTY");
+        assertEquals(sj.toString(), "EMPTY");
+        sj.merge(other);
+        assertEquals(sj.toString(), "{d:e:f}");
+    }
+
+    public void testEmptyBoth() {
+        StringJoiner sj = new StringJoiner(",", "{", "}");
+        StringJoiner other = new StringJoiner(":", "[", "]");
+
+        sj.merge(other);
+        assertEquals(sj.toString(), "{}");
+
+        other.setEmptyValue("NOTHING");
+        sj.merge(other);
+        assertEquals(sj.toString(), "{}");
+
+        sj = new StringJoiner(",", "{", "}").setEmptyValue("EMPTY");
+        assertEquals(sj.toString(), "EMPTY");
+        sj.merge(other);
+        assertEquals(sj.toString(), "EMPTY");
+    }
+
+    public void testCascadeEmpty() {
+        StringJoiner sj = new StringJoiner(",", "{", "}");
+        StringJoiner o1 = new StringJoiner(":", "[", "]").setEmptyValue("Empty1");
+        StringJoiner o2 = new StringJoiner(",", "<", ">").setEmptyValue("Empty2");
+
+        o1.merge(o2);
+        assertEquals(o1.toString(), "Empty1");
+
+        sj.merge(o1);
+        assertEquals(sj.toString(), "{}");
+    }
+
+    public void testDelimiter() {
+        StringJoiner sj = new StringJoiner(",", "{", "}");
+        StringJoiner other = new StringJoiner(":", "[", "]");
+        Stream.of("a", "b", "c").forEachOrdered(sj::add);
+        Stream.of("d", "e", "f").forEachOrdered(other::add);
+
+        sj.merge(other);
+        assertEquals(sj.toString(), "{a,b,c,d:e:f}");
+    }
+}
\ No newline at end of file
--- a/test/java/util/StringJoiner/StringJoinerTest.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/StringJoiner/StringJoinerTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -27,6 +27,7 @@
  * @run testng StringJoinerTest
  * @author Jim Gish
  */
+import java.util.ArrayList;
 import java.util.StringJoiner;
 import org.testng.annotations.Test;
 import static org.testng.Assert.assertEquals;
@@ -44,7 +45,6 @@
     private static final String FIVE = "Five";
     private static final String DASH = "-";
 
-    /* Uncomment when we have streams
     public void addAddAll() {
         StringJoiner sj = new StringJoiner(DASH, "{", "}");
         sj.add(ONE);
@@ -52,7 +52,7 @@
         ArrayList<String> nextOne = new ArrayList<>();
         nextOne.add(TWO);
         nextOne.add(THREE);
-        nextOne.stream().forEach(sj::add);
+        nextOne.stream().forEachOrdered(sj::add);
 
         String expected = "{"+ONE+DASH+TWO+DASH+THREE+"}";
         assertEquals(sj.toString(), expected);
@@ -64,7 +64,7 @@
         ArrayList<String> firstOne = new ArrayList<>();
         firstOne.add(ONE);
         firstOne.add(TWO);
-        firstOne.stream().forEach(sj::add);
+        firstOne.stream().forEachOrdered(sj::add);
 
         sj.add(THREE);
 
@@ -79,29 +79,17 @@
         firstOne.add(ONE);
         firstOne.add(TWO);
         firstOne.add(THREE);
-        firstOne.stream().forEach(sj::add);
+        firstOne.stream().forEachOrdered(sj::add);
 
         ArrayList<String> nextOne = new ArrayList<>();
         nextOne.add(FOUR);
         nextOne.add(FIVE);
-        nextOne.stream().forEach(sj::add);
+        nextOne.stream().forEachOrdered(sj::add);
 
         String expected = "{"+ONE+DASH+TWO+DASH+THREE+DASH+FOUR+DASH+FIVE+"}";
         assertEquals(sj.toString(), expected);
     }
 
-    public void testInto() {
-        ArrayList<String> list = new ArrayList<>();
-        list.add(ONE);
-        list.add(TWO);
-        list.add(THREE);
-
-        StringJoiner target = new StringJoiner(",", "{", "}");
-        assertEquals(target.toString(), "{" + ONE + "," + TWO + "," + THREE +
-            "}");
-    }
-    */
-
     public void addCharSequence() {
         StringJoiner sj = new StringJoiner(",");
         CharSequence cs_one = ONE;
--- a/test/java/util/stream/bootlib/java/util/stream/DoubleStreamTestScenario.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/stream/bootlib/java/util/stream/DoubleStreamTestScenario.java	Mon Jul 22 17:37:15 2013 -0700
@@ -140,9 +140,9 @@
         void _run(TestData<T, S_IN> data, DoubleConsumer b, Function<S_IN, DoubleStream> m) {
             DoubleStream s = m.apply(data.parallelStream());
             Spliterator.OfDouble sp = s.spliterator();
-            DoubleStream ss = StreamSupport.doubleParallelStream(() -> sp,
-                                                                 StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s))
-                                                                 | (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED));
+            DoubleStream ss = StreamSupport.doubleStream(() -> sp,
+                                                         StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s))
+                                                         | (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED), true);
             for (double t : ss.toArray())
                 b.accept(t);
         }
--- a/test/java/util/stream/bootlib/java/util/stream/IntStreamTestScenario.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/stream/bootlib/java/util/stream/IntStreamTestScenario.java	Mon Jul 22 17:37:15 2013 -0700
@@ -140,9 +140,10 @@
         void _run(TestData<T, S_IN> data, IntConsumer b, Function<S_IN, IntStream> m) {
             IntStream s = m.apply(data.parallelStream());
             Spliterator.OfInt sp = s.spliterator();
-            IntStream ss = StreamSupport.intParallelStream(() -> sp,
-                                                           StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s))
-                                                           | (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED));
+            IntStream ss = StreamSupport.intStream(() -> sp,
+                                                   StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s))
+                                                   | (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED),
+                                                   true);
             for (int t : ss.toArray())
                 b.accept(t);
         }
--- a/test/java/util/stream/bootlib/java/util/stream/LambdaTestHelpers.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/stream/bootlib/java/util/stream/LambdaTestHelpers.java	Mon Jul 22 17:37:15 2013 -0700
@@ -360,35 +360,26 @@
     private static<T> Map<T, Integer> toBoxedMultiset(Iterator<T> it) {
         Map<Object, Integer> result = new HashMap<>();
 
-        it.forEachRemaining(new OmnivorousConsumer<T>() {
-            @Override
-            public void accept(T t) {
-                add(t);
-            }
-
-            @Override
-            public void accept(int value) {
-                add(value);
-            }
-
-            @Override
-            public void accept(long value) {
-                add(value);
-            }
-
-            @Override
-            public void accept(double value) {
-                add(value);
-            }
-
-            void add(Object o) {
+        it.forEachRemaining(toBoxingConsumer(o -> {
                 if (result.containsKey(o))
                     result.put(o, result.get(o) + 1);
                 else
                     result.put(o, 1);
-            }
+            }));
+
+        return (Map<T, Integer>) result;
+    }
 
-        });
+    @SuppressWarnings("unchecked")
+    public static<T> Map<T, Integer> toBoxedMultiset(Spliterator<T> it) {
+        Map<Object, Integer> result = new HashMap<>();
+
+        it.forEachRemaining(toBoxingConsumer(o -> {
+                if (result.containsKey(o))
+                    result.put(o, result.get(o) + 1);
+                else
+                    result.put(o, 1);
+            }));
 
         return (Map<T, Integer>) result;
     }
--- a/test/java/util/stream/bootlib/java/util/stream/LongStreamTestScenario.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/stream/bootlib/java/util/stream/LongStreamTestScenario.java	Mon Jul 22 17:37:15 2013 -0700
@@ -140,9 +140,9 @@
         void _run(TestData<T, S_IN> data, LongConsumer b, Function<S_IN, LongStream> m) {
             LongStream s = m.apply(data.parallelStream());
             Spliterator.OfLong sp = s.spliterator();
-            LongStream ss = StreamSupport.longParallelStream(() -> sp,
-                                                             StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s))
-                                                             | (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED));
+            LongStream ss = StreamSupport.longStream(() -> sp,
+                                                     StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s))
+                                                     | (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED), true);
             for (long t : ss.toArray())
                 b.accept(t);
         }
--- a/test/java/util/stream/bootlib/java/util/stream/StreamTestScenario.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/stream/bootlib/java/util/stream/StreamTestScenario.java	Mon Jul 22 17:37:15 2013 -0700
@@ -151,9 +151,9 @@
         void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
             Stream<U> s = m.apply(data.parallelStream());
             Spliterator<U> sp = s.spliterator();
-            Stream<U> ss = StreamSupport.parallelStream(() -> sp,
-                                                        StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s))
-                                                        | (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED));
+            Stream<U> ss = StreamSupport.stream(() -> sp,
+                                                StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s))
+                                                | (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED), true);
             for (Object t : ss.toArray())
                 b.accept((U) t);
         }
--- a/test/java/util/stream/bootlib/java/util/stream/TestData.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/stream/bootlib/java/util/stream/TestData.java	Mon Jul 22 17:37:15 2013 -0700
@@ -87,8 +87,8 @@
 
         public static <T> OfRef<T> ofSpinedBuffer(String name, SpinedBuffer<T> buffer) {
             return new AbstractTestData.RefTestData<>(name, buffer,
-                                                      b -> StreamSupport.stream(b.spliterator()),
-                                                      b -> StreamSupport.parallelStream(b.spliterator()),
+                                                      b -> StreamSupport.stream(b.spliterator(), false),
+                                                      b -> StreamSupport.stream(b.spliterator(), true),
                                                       SpinedBuffer::spliterator,
                                                       b -> (int) b.count());
         }
@@ -103,8 +103,8 @@
 
         public static <T> OfRef<T> ofRefNode(String name, Node<T> node) {
             return new AbstractTestData.RefTestData<>(name, node,
-                                                      n -> StreamSupport.stream(n::spliterator, Spliterator.SIZED | Spliterator.ORDERED),
-                                                      n -> StreamSupport.parallelStream(n::spliterator, Spliterator.SIZED | Spliterator.ORDERED),
+                                                      n -> StreamSupport.stream(n::spliterator, Spliterator.SIZED | Spliterator.ORDERED, false),
+                                                      n -> StreamSupport.stream(n::spliterator, Spliterator.SIZED | Spliterator.ORDERED, true),
                                                       Node::spliterator,
                                                       n -> (int) n.count());
         }
@@ -117,8 +117,8 @@
 
         public static OfInt ofSpinedBuffer(String name, SpinedBuffer.OfInt buffer) {
             return new AbstractTestData.IntTestData<>(name, buffer,
-                                                      b -> StreamSupport.intStream(b.spliterator()),
-                                                      b -> StreamSupport.intParallelStream(b.spliterator()),
+                                                      b -> StreamSupport.intStream(b.spliterator(), false),
+                                                      b -> StreamSupport.intStream(b.spliterator(), true),
                                                       SpinedBuffer.OfInt::spliterator,
                                                       b -> (int) b.count());
         }
@@ -134,8 +134,8 @@
         public static OfInt ofNode(String name, Node.OfInt node) {
             int characteristics = Spliterator.SIZED | Spliterator.ORDERED;
             return new AbstractTestData.IntTestData<>(name, node,
-                                                      n -> StreamSupport.intStream(n::spliterator, characteristics),
-                                                      n -> StreamSupport.intParallelStream(n::spliterator, characteristics),
+                                                      n -> StreamSupport.intStream(n::spliterator, characteristics, false),
+                                                      n -> StreamSupport.intStream(n::spliterator, characteristics, true),
                                                       Node.OfInt::spliterator,
                                                       n -> (int) n.count());
         }
@@ -148,8 +148,8 @@
 
         public static OfLong ofSpinedBuffer(String name, SpinedBuffer.OfLong buffer) {
             return new AbstractTestData.LongTestData<>(name, buffer,
-                                                      b -> StreamSupport.longStream(b.spliterator()),
-                                                      b -> StreamSupport.longParallelStream(b.spliterator()),
+                                                      b -> StreamSupport.longStream(b.spliterator(), false),
+                                                      b -> StreamSupport.longStream(b.spliterator(), true),
                                                       SpinedBuffer.OfLong::spliterator,
                                                       b -> (int) b.count());
         }
@@ -165,8 +165,8 @@
         public static OfLong ofNode(String name, Node.OfLong node) {
             int characteristics = Spliterator.SIZED | Spliterator.ORDERED;
             return new AbstractTestData.LongTestData<>(name, node,
-                                                      n -> StreamSupport.longStream(n::spliterator, characteristics),
-                                                      n -> StreamSupport.longParallelStream(n::spliterator, characteristics),
+                                                      n -> StreamSupport.longStream(n::spliterator, characteristics, false),
+                                                      n -> StreamSupport.longStream(n::spliterator, characteristics, true),
                                                       Node.OfLong::spliterator,
                                                       n -> (int) n.count());
         }
@@ -179,8 +179,8 @@
 
         public static OfDouble ofSpinedBuffer(String name, SpinedBuffer.OfDouble buffer) {
             return new AbstractTestData.DoubleTestData<>(name, buffer,
-                                                         b -> StreamSupport.doubleStream(b.spliterator()),
-                                                         b -> StreamSupport.doubleParallelStream(b.spliterator()),
+                                                         b -> StreamSupport.doubleStream(b.spliterator(), false),
+                                                         b -> StreamSupport.doubleStream(b.spliterator(), true),
                                                          SpinedBuffer.OfDouble::spliterator,
                                                          b -> (int) b.count());
         }
@@ -196,8 +196,8 @@
         public static OfDouble ofNode(String name, Node.OfDouble node) {
             int characteristics = Spliterator.SIZED | Spliterator.ORDERED;
             return new AbstractTestData.DoubleTestData<>(name, node,
-                                                         n -> StreamSupport.doubleStream(n::spliterator, characteristics),
-                                                         n -> StreamSupport.doubleParallelStream(n::spliterator, characteristics),
+                                                         n -> StreamSupport.doubleStream(n::spliterator, characteristics, false),
+                                                         n -> StreamSupport.doubleStream(n::spliterator, characteristics, true),
                                                          Node.OfDouble::spliterator,
                                                          n -> (int) n.count());
         }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/ConcatOpTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.openjdk.tests.java.util.stream;
+
+import java.util.stream.OpTestCase;
+import java.util.stream.StreamTestDataProvider;
+
+import org.testng.annotations.Test;
+
+import java.util.stream.Stream;
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
+import java.util.stream.DoubleStream;
+import java.util.stream.TestData;
+
+import static java.util.stream.LambdaTestHelpers.*;
+
+public class ConcatOpTest extends OpTestCase {
+
+    // Sanity to make sure all type of stream source works
+    @Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class)
+    public void testOpsSequential(String name, TestData.OfRef<Integer> data) {
+        exerciseOpsInt(data,
+                       s -> Stream.concat(s, data.stream()),
+                       s -> IntStream.concat(s, data.stream().mapToInt(Integer::intValue)),
+                       s -> LongStream.concat(s, data.stream().mapToLong(Integer::longValue)),
+                       s -> DoubleStream.concat(s, data.stream().mapToDouble(Integer::doubleValue)));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/ConcatTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,229 @@
+/*
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.openjdk.tests.java.util.stream;
+
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Factory;
+import org.testng.annotations.Test;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Spliterator;
+import java.util.TreeSet;
+import java.util.stream.DoubleStream;
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
+import java.util.stream.Stream;
+
+import static java.util.stream.LambdaTestHelpers.*;
+import static org.testng.Assert.*;
+
+@Test
+public class ConcatTest {
+    private static Object[][] cases;
+
+    static {
+        List<Integer> part1 = Arrays.asList(5, 3, 4, 1, 2, 6, 2, 4);
+        List<Integer> part2 = Arrays.asList(8, 8, 6, 6, 9, 7, 10, 9);
+        List<Integer> p1p2 = Arrays.asList(5, 3, 4, 1, 2, 6, 2, 4, 8, 8, 6, 6, 9, 7, 10, 9);
+        List<Integer> p2p1 = Arrays.asList(8, 8, 6, 6, 9, 7, 10, 9, 5, 3, 4, 1, 2, 6, 2, 4);
+        List<Integer> empty = new LinkedList<>(); // To be ordered
+        assertTrue(empty.isEmpty());
+        LinkedHashSet<Integer> distinctP1 = new LinkedHashSet<>(part1);
+        LinkedHashSet<Integer> distinctP2 = new LinkedHashSet<>(part2);
+        TreeSet<Integer> sortedP1 = new TreeSet<>(part1);
+        TreeSet<Integer> sortedP2 = new TreeSet<>(part2);
+
+        cases = new Object[][] {
+            { "regular", part1, part2, p1p2 },
+            { "reverse regular", part2, part1, p2p1 },
+            { "front distinct", distinctP1, part2, Arrays.asList(5, 3, 4, 1, 2, 6, 8, 8, 6, 6, 9, 7, 10, 9) },
+            { "back distinct", part1, distinctP2, Arrays.asList(5, 3, 4, 1, 2, 6, 2, 4, 8, 6, 9, 7, 10) },
+            { "both distinct", distinctP1, distinctP2, Arrays.asList(5, 3, 4, 1, 2, 6, 8, 6, 9, 7, 10) },
+            { "front sorted", sortedP1, part2, Arrays.asList(1, 2, 3, 4, 5, 6, 8, 8, 6, 6, 9, 7, 10, 9) },
+            { "back sorted", part1, sortedP2, Arrays.asList(5, 3, 4, 1, 2, 6, 2, 4, 6, 7, 8, 9, 10) },
+            { "both sorted", sortedP1, sortedP2, Arrays.asList(1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10) },
+            { "reverse both sorted", sortedP2, sortedP1, Arrays.asList(6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6) },
+            { "empty something", empty, part1, part1 },
+            { "something empty", part1, empty, part1 },
+            { "empty empty", empty, empty, empty }
+        };
+    }
+
+    @DataProvider(name = "cases")
+    private static Object[][] getCases() {
+        return cases;
+    }
+
+    @Factory(dataProvider = "cases")
+    public static Object[] createTests(String scenario, Collection<Integer> c1, Collection<Integer> c2, Collection<Integer> expected) {
+        return new Object[] {
+            new ConcatTest(scenario, c1, c2, expected)
+        };
+    }
+
+    protected final String scenario;
+    protected final Collection<Integer> c1;
+    protected final Collection<Integer> c2;
+    protected final Collection<Integer> expected;
+
+    public ConcatTest(String scenario, Collection<Integer> c1, Collection<Integer> c2, Collection<Integer> expected) {
+        this.scenario = scenario;
+        this.c1 = c1;
+        this.c2 = c2;
+        this.expected = expected;
+
+        // verify prerequisite
+        Stream<Integer> s1s = c1.stream();
+        Stream<Integer> s2s = c2.stream();
+        Stream<Integer> s1p = c1.parallelStream();
+        Stream<Integer> s2p = c2.parallelStream();
+        assertTrue(s1p.isParallel());
+        assertTrue(s2p.isParallel());
+        assertFalse(s1s.isParallel());
+        assertFalse(s2s.isParallel());
+
+        assertTrue(s1s.spliterator().hasCharacteristics(Spliterator.ORDERED));
+        assertTrue(s1p.spliterator().hasCharacteristics(Spliterator.ORDERED));
+        assertTrue(s2s.spliterator().hasCharacteristics(Spliterator.ORDERED));
+        assertTrue(s2p.spliterator().hasCharacteristics(Spliterator.ORDERED));
+    }
+
+    private <T> void assertConcatContent(Spliterator<T> sp, boolean ordered, Spliterator<T> expected) {
+        // concat stream cannot guarantee uniqueness
+        assertFalse(sp.hasCharacteristics(Spliterator.DISTINCT), scenario);
+        // concat stream cannot guarantee sorted
+        assertFalse(sp.hasCharacteristics(Spliterator.SORTED), scenario);
+        // concat stream is ordered if both are ordered
+        assertEquals(sp.hasCharacteristics(Spliterator.ORDERED), ordered, scenario);
+
+        // Verify elements
+        if (ordered) {
+            assertEquals(toBoxedList(sp),
+                         toBoxedList(expected),
+                         scenario);
+        } else {
+            assertEquals(toBoxedMultiset(sp),
+                         toBoxedMultiset(expected),
+                         scenario);
+        }
+    }
+
+    private void assertRefConcat(Stream<Integer> s1, Stream<Integer> s2, boolean parallel, boolean ordered) {
+        Stream<Integer> result = Stream.concat(s1, s2);
+        assertEquals(result.isParallel(), parallel);
+        assertConcatContent(result.spliterator(), ordered, expected.spliterator());
+    }
+
+    private void assertIntConcat(Stream<Integer> s1, Stream<Integer> s2, boolean parallel, boolean ordered) {
+        IntStream result = IntStream.concat(s1.mapToInt(Integer::intValue),
+                                            s2.mapToInt(Integer::intValue));
+        assertEquals(result.isParallel(), parallel);
+        assertConcatContent(result.spliterator(), ordered,
+                            expected.stream().mapToInt(Integer::intValue).spliterator());
+    }
+
+    private void assertLongConcat(Stream<Integer> s1, Stream<Integer> s2, boolean parallel, boolean ordered) {
+        LongStream result = LongStream.concat(s1.mapToLong(Integer::longValue),
+                                              s2.mapToLong(Integer::longValue));
+        assertEquals(result.isParallel(), parallel);
+        assertConcatContent(result.spliterator(), ordered,
+                            expected.stream().mapToLong(Integer::longValue).spliterator());
+    }
+
+    private void assertDoubleConcat(Stream<Integer> s1, Stream<Integer> s2, boolean parallel, boolean ordered) {
+        DoubleStream result = DoubleStream.concat(s1.mapToDouble(Integer::doubleValue),
+                                                  s2.mapToDouble(Integer::doubleValue));
+        assertEquals(result.isParallel(), parallel);
+        assertConcatContent(result.spliterator(), ordered,
+                            expected.stream().mapToDouble(Integer::doubleValue).spliterator());
+    }
+
+    public void testRefConcat() {
+        // sequential + sequential -> sequential
+        assertRefConcat(c1.stream(), c2.stream(), false, true);
+        // parallel + parallel -> parallel
+        assertRefConcat(c1.parallelStream(), c2.parallelStream(), true, true);
+        // sequential + parallel -> parallel
+        assertRefConcat(c1.stream(), c2.parallelStream(), true, true);
+        // parallel + sequential -> parallel
+        assertRefConcat(c1.parallelStream(), c2.stream(), true, true);
+
+        // not ordered
+        assertRefConcat(c1.stream().unordered(), c2.stream(), false, false);
+        assertRefConcat(c1.stream(), c2.stream().unordered(), false, false);
+        assertRefConcat(c1.parallelStream().unordered(), c2.stream().unordered(), true, false);
+    }
+
+    public void testIntConcat() {
+        // sequential + sequential -> sequential
+        assertIntConcat(c1.stream(), c2.stream(), false, true);
+        // parallel + parallel -> parallel
+        assertIntConcat(c1.parallelStream(), c2.parallelStream(), true, true);
+        // sequential + parallel -> parallel
+        assertIntConcat(c1.stream(), c2.parallelStream(), true, true);
+        // parallel + sequential -> parallel
+        assertIntConcat(c1.parallelStream(), c2.stream(), true, true);
+
+        // not ordered
+        assertIntConcat(c1.stream().unordered(), c2.stream(), false, false);
+        assertIntConcat(c1.stream(), c2.stream().unordered(), false, false);
+        assertIntConcat(c1.parallelStream().unordered(), c2.stream().unordered(), true, false);
+    }
+
+    public void testLongConcat() {
+        // sequential + sequential -> sequential
+        assertLongConcat(c1.stream(), c2.stream(), false, true);
+        // parallel + parallel -> parallel
+        assertLongConcat(c1.parallelStream(), c2.parallelStream(), true, true);
+        // sequential + parallel -> parallel
+        assertLongConcat(c1.stream(), c2.parallelStream(), true, true);
+        // parallel + sequential -> parallel
+        assertLongConcat(c1.parallelStream(), c2.stream(), true, true);
+
+        // not ordered
+        assertLongConcat(c1.stream().unordered(), c2.stream(), false, false);
+        assertLongConcat(c1.stream(), c2.stream().unordered(), false, false);
+        assertLongConcat(c1.parallelStream().unordered(), c2.stream().unordered(), true, false);
+    }
+
+    public void testDoubleConcat() {
+        // sequential + sequential -> sequential
+        assertDoubleConcat(c1.stream(), c2.stream(), false, true);
+        // parallel + parallel -> parallel
+        assertDoubleConcat(c1.parallelStream(), c2.parallelStream(), true, true);
+        // sequential + parallel -> parallel
+        assertDoubleConcat(c1.stream(), c2.parallelStream(), true, true);
+        // parallel + sequential -> parallel
+        assertDoubleConcat(c1.parallelStream(), c2.stream(), true, true);
+
+        // not ordered
+        assertDoubleConcat(c1.stream().unordered(), c2.stream(), false, false);
+        assertDoubleConcat(c1.stream(), c2.stream().unordered(), false, false);
+        assertDoubleConcat(c1.parallelStream().unordered(), c2.stream().unordered(), true, false);
+    }
+}
--- a/test/java/util/stream/test/org/openjdk/tests/java/util/stream/DistinctOpTest.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/DistinctOpTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -86,8 +86,8 @@
     static class SortedTestData<T> extends TestData.AbstractTestData.RefTestData<T, List<T>> {
         SortedTestData(List<T> coll) {
             super("SortedTestData", coll,
-                  c -> StreamSupport.stream(Spliterators.spliterator(c.toArray(), Spliterator.ORDERED | Spliterator.SORTED)),
-                  c -> StreamSupport.parallelStream(Spliterators.spliterator(c.toArray(), Spliterator.ORDERED | Spliterator.SORTED)),
+                  c -> StreamSupport.stream(Spliterators.spliterator(c.toArray(), Spliterator.ORDERED | Spliterator.SORTED), false),
+                  c -> StreamSupport.stream(Spliterators.spliterator(c.toArray(), Spliterator.ORDERED | Spliterator.SORTED), true),
                   c -> Spliterators.spliterator(c.toArray(), Spliterator.ORDERED | Spliterator.SORTED),
                   List::size);
         }
--- a/test/java/util/stream/test/org/openjdk/tests/java/util/stream/InfiniteStreamWithLimitOpTest.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/InfiniteStreamWithLimitOpTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -306,7 +306,7 @@
     private TestData.OfLong proxiedLongRange(long l, long u) {
         return TestData.Factory.ofLongSupplier(
                 String.format("[%d, %d)", l, u),
-                () -> StreamSupport.longStream(proxyNotSubsized(LongStream.range(l, u).spliterator())));
+                () -> StreamSupport.longStream(proxyNotSubsized(LongStream.range(l, u).spliterator()), false));
     }
 
     @Test(dataProvider = "Stream.limit")
--- a/test/java/util/stream/test/org/openjdk/tests/java/util/stream/MatchOpTest.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/MatchOpTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -155,7 +155,7 @@
         }
 
         Supplier<Iterator<Integer>> source = () -> Arrays.asList(1, 2, 3, 4).iterator();
-        Supplier<Stream<Integer>> s = () -> StreamSupport.stream(Spliterators.spliteratorUnknownSize(new CycleIterator(source), 0));
+        Supplier<Stream<Integer>> s = () -> StreamSupport.stream(Spliterators.spliteratorUnknownSize(new CycleIterator(source), 0), false);
 
         assertFalse(s.get().allMatch(i -> i > 3));
         assertTrue(s.get().anyMatch(i -> i > 3));
@@ -240,7 +240,7 @@
         }
 
         Supplier<PrimitiveIterator.OfInt> source = () -> Arrays.stream(new int[]{1, 2, 3, 4}).iterator();
-        Supplier<IntStream> s = () -> StreamSupport.intStream(Spliterators.spliteratorUnknownSize(new CycleIterator(source), 0));
+        Supplier<IntStream> s = () -> StreamSupport.intStream(Spliterators.spliteratorUnknownSize(new CycleIterator(source), 0), false);
 
         assertFalse(s.get().allMatch(i -> i > 3));
         assertTrue(s.get().anyMatch(i -> i > 3));
@@ -325,7 +325,7 @@
         }
 
         Supplier<PrimitiveIterator.OfLong> source = () -> Arrays.stream(new long[]{1, 2, 3, 4}).iterator();
-        Supplier<LongStream> s = () -> StreamSupport.longStream(Spliterators.spliteratorUnknownSize(new CycleIterator(source), 0));
+        Supplier<LongStream> s = () -> StreamSupport.longStream(Spliterators.spliteratorUnknownSize(new CycleIterator(source), 0), false);
 
         assertFalse(s.get().allMatch(i -> i > 3));
         assertTrue(s.get().anyMatch(i -> i > 3));
@@ -410,7 +410,7 @@
         }
 
         Supplier<PrimitiveIterator.OfDouble> source = () -> Arrays.stream(new double[]{1, 2, 3, 4}).iterator();
-        Supplier<DoubleStream> s = () -> StreamSupport.doubleStream(Spliterators.spliteratorUnknownSize(new CycleIterator(source), 0));
+        Supplier<DoubleStream> s = () -> StreamSupport.doubleStream(Spliterators.spliteratorUnknownSize(new CycleIterator(source), 0), false);
 
         assertFalse(s.get().allMatch(i -> i > 3));
         assertTrue(s.get().anyMatch(i -> i > 3));
--- a/test/java/util/stream/test/org/openjdk/tests/java/util/stream/RangeTest.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/RangeTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -226,116 +226,114 @@
         assertEquals(first, LongStream.iterate(0, i -> i + 1).parallel().filter(i -> i > 10000).findFirst().getAsLong());
     }
 
-    // Enable when Stream.concat is present and range implementations are
-    // updated to use that
-//    private static void assertSizedAndSubSized(Spliterator<?> s) {
-//        assertTrue(s.hasCharacteristics(Spliterator.SIZED | Spliterator.SUBSIZED));
-//    }
-//
-//    private static void assertNotSizedAndSubSized(Spliterator<?> s) {
-//        assertFalse(s.hasCharacteristics(Spliterator.SIZED | Spliterator.SUBSIZED));
-//    }
-//
-//    public void testLongLongRange() {
-//        // Test [Long.MIN_VALUE, Long.MAX_VALUE)
-//        // This will concatenate streams of three ranges
-//        //   [Long.MIN_VALUE, x) [x, 0) [0, Long.MAX_VALUE)
-//        // where x = Long.divideUnsigned(0 - Long.MIN_VALUE, 2) + 1
-//        {
-//            Spliterator.OfLong s = LongStream.range(Long.MIN_VALUE, Long.MAX_VALUE).spliterator();
-//
-//            assertEquals(s.estimateSize(), Long.MAX_VALUE);
-//            assertNotSizedAndSubSized(s);
-//
-//            Spliterator.OfLong s1 = s.trySplit();
-//            assertNotSizedAndSubSized(s1);
-//            assertSizedAndSubSized(s);
-//
-//            Spliterator.OfLong s2 = s1.trySplit();
-//            assertSizedAndSubSized(s1);
-//            assertSizedAndSubSized(s2);
-//
-//            assertTrue(s.estimateSize() == Long.MAX_VALUE);
-//            assertTrue(s1.estimateSize() < Long.MAX_VALUE);
-//            assertTrue(s2.estimateSize() < Long.MAX_VALUE);
-//
-//            assertEquals(s.estimateSize() + s1.estimateSize() + s2.estimateSize(),
-//                         Long.MAX_VALUE - Long.MIN_VALUE);
-//        }
-//
-//        long[][] ranges = { {Long.MIN_VALUE, 0}, {-1, Long.MAX_VALUE} };
-//        for (int i = 0; i < ranges.length; i++) {
-//            long start = ranges[i][0];
-//            long end = ranges[i][1];
-//
-//            Spliterator.OfLong s = LongStream.range(start, end).spliterator();
-//
-//            assertEquals(s.estimateSize(), Long.MAX_VALUE);
-//            assertNotSizedAndSubSized(s);
-//
-//            Spliterator.OfLong s1 = s.trySplit();
-//            assertSizedAndSubSized(s1);
-//            assertSizedAndSubSized(s);
-//
-//            assertTrue(s.estimateSize() < Long.MAX_VALUE);
-//            assertTrue(s1.estimateSize() < Long.MAX_VALUE);
-//
-//            assertEquals(s.estimateSize() + s1.estimateSize(), end - start);
-//        }
-//    }
-//
-//    public void testLongLongRangeClosed() {
-//        // Test [Long.MIN_VALUE, Long.MAX_VALUE]
-//        // This will concatenate streams of four ranges
-//        //   [Long.MIN_VALUE, x) [x, 0) [0, y) [y, Long.MAX_VALUE]
-//        // where x = Long.divideUnsigned(0 - Long.MIN_VALUE, 2) + 1
-//        //       y = Long.divideUnsigned(Long.MAX_VALUE, 2) + 1
-//
-//        {
-//            Spliterator.OfLong s = LongStream.rangeClosed(Long.MIN_VALUE, Long.MAX_VALUE).spliterator();
-//
-//            assertEquals(s.estimateSize(), Long.MAX_VALUE);
-//            assertNotSizedAndSubSized(s);
-//
-//            Spliterator.OfLong s1 = s.trySplit();
-//            assertNotSizedAndSubSized(s1);
-//            assertNotSizedAndSubSized(s);
-//
-//            Spliterator.OfLong s2 = s1.trySplit();
-//            assertSizedAndSubSized(s1);
-//            assertSizedAndSubSized(s2);
-//
-//            Spliterator.OfLong s3 = s.trySplit();
-//            assertSizedAndSubSized(s3);
-//            assertSizedAndSubSized(s);
-//
-//            assertTrue(s.estimateSize() < Long.MAX_VALUE);
-//            assertTrue(s3.estimateSize() < Long.MAX_VALUE);
-//            assertTrue(s1.estimateSize() < Long.MAX_VALUE);
-//            assertTrue(s2.estimateSize() < Long.MAX_VALUE);
-//
-//            assertEquals(s.estimateSize() + s3.estimateSize() + s1.estimateSize() + s2.estimateSize(),
-//                         Long.MAX_VALUE - Long.MIN_VALUE + 1);
-//        }
-//
-//        long[][] ranges = { {Long.MIN_VALUE, 0}, {-1, Long.MAX_VALUE} };
-//        for (int i = 0; i < ranges.length; i++) {
-//            long start = ranges[i][0];
-//            long end = ranges[i][1];
-//
-//            Spliterator.OfLong s = LongStream.rangeClosed(start, end).spliterator();
-//
-//            assertEquals(s.estimateSize(), Long.MAX_VALUE);
-//            assertNotSizedAndSubSized(s);
-//
-//            Spliterator.OfLong s1 = s.trySplit();
-//            assertSizedAndSubSized(s1);
-//            assertSizedAndSubSized(s);
-//
-//            assertTrue(s.estimateSize() < Long.MAX_VALUE);
-//            assertTrue(s1.estimateSize() < Long.MAX_VALUE);
-//
-//            assertEquals(s.estimateSize() + s1.estimateSize(), end - start + 1);
-//        }
-//    }
+    private static void assertSizedAndSubSized(Spliterator<?> s) {
+        assertTrue(s.hasCharacteristics(Spliterator.SIZED | Spliterator.SUBSIZED));
+    }
+
+    private static void assertNotSizedAndSubSized(Spliterator<?> s) {
+        assertFalse(s.hasCharacteristics(Spliterator.SIZED | Spliterator.SUBSIZED));
+    }
+
+    public void testLongLongRange() {
+        // Test [Long.MIN_VALUE, Long.MAX_VALUE)
+        // This will concatenate streams of three ranges
+        //   [Long.MIN_VALUE, x) [x, 0) [0, Long.MAX_VALUE)
+        // where x = Long.divideUnsigned(0 - Long.MIN_VALUE, 2) + 1
+        {
+            Spliterator.OfLong s = LongStream.range(Long.MIN_VALUE, Long.MAX_VALUE).spliterator();
+
+            assertEquals(s.estimateSize(), Long.MAX_VALUE);
+            assertNotSizedAndSubSized(s);
+
+            Spliterator.OfLong s1 = s.trySplit();
+            assertNotSizedAndSubSized(s1);
+            assertSizedAndSubSized(s);
+
+            Spliterator.OfLong s2 = s1.trySplit();
+            assertSizedAndSubSized(s1);
+            assertSizedAndSubSized(s2);
+
+            assertTrue(s.estimateSize() == Long.MAX_VALUE);
+            assertTrue(s1.estimateSize() < Long.MAX_VALUE);
+            assertTrue(s2.estimateSize() < Long.MAX_VALUE);
+
+            assertEquals(s.estimateSize() + s1.estimateSize() + s2.estimateSize(),
+                         Long.MAX_VALUE - Long.MIN_VALUE);
+        }
+
+        long[][] ranges = { {Long.MIN_VALUE, 0}, {-1, Long.MAX_VALUE} };
+        for (int i = 0; i < ranges.length; i++) {
+            long start = ranges[i][0];
+            long end = ranges[i][1];
+
+            Spliterator.OfLong s = LongStream.range(start, end).spliterator();
+
+            assertEquals(s.estimateSize(), Long.MAX_VALUE);
+            assertNotSizedAndSubSized(s);
+
+            Spliterator.OfLong s1 = s.trySplit();
+            assertSizedAndSubSized(s1);
+            assertSizedAndSubSized(s);
+
+            assertTrue(s.estimateSize() < Long.MAX_VALUE);
+            assertTrue(s1.estimateSize() < Long.MAX_VALUE);
+
+            assertEquals(s.estimateSize() + s1.estimateSize(), end - start);
+        }
+    }
+
+    public void testLongLongRangeClosed() {
+        // Test [Long.MIN_VALUE, Long.MAX_VALUE]
+        // This will concatenate streams of four ranges
+        //   [Long.MIN_VALUE, x) [x, 0) [0, y) [y, Long.MAX_VALUE]
+        // where x = Long.divideUnsigned(0 - Long.MIN_VALUE, 2) + 1
+        //       y = Long.divideUnsigned(Long.MAX_VALUE, 2) + 1
+
+        {
+            Spliterator.OfLong s = LongStream.rangeClosed(Long.MIN_VALUE, Long.MAX_VALUE).spliterator();
+
+            assertEquals(s.estimateSize(), Long.MAX_VALUE);
+            assertNotSizedAndSubSized(s);
+
+            Spliterator.OfLong s1 = s.trySplit();
+            assertNotSizedAndSubSized(s1);
+            assertNotSizedAndSubSized(s);
+
+            Spliterator.OfLong s2 = s1.trySplit();
+            assertSizedAndSubSized(s1);
+            assertSizedAndSubSized(s2);
+
+            Spliterator.OfLong s3 = s.trySplit();
+            assertSizedAndSubSized(s3);
+            assertSizedAndSubSized(s);
+
+            assertTrue(s.estimateSize() < Long.MAX_VALUE);
+            assertTrue(s3.estimateSize() < Long.MAX_VALUE);
+            assertTrue(s1.estimateSize() < Long.MAX_VALUE);
+            assertTrue(s2.estimateSize() < Long.MAX_VALUE);
+
+            assertEquals(s.estimateSize() + s3.estimateSize() + s1.estimateSize() + s2.estimateSize(),
+                         Long.MAX_VALUE - Long.MIN_VALUE + 1);
+        }
+
+        long[][] ranges = { {Long.MIN_VALUE, 0}, {-1, Long.MAX_VALUE} };
+        for (int i = 0; i < ranges.length; i++) {
+            long start = ranges[i][0];
+            long end = ranges[i][1];
+
+            Spliterator.OfLong s = LongStream.rangeClosed(start, end).spliterator();
+
+            assertEquals(s.estimateSize(), Long.MAX_VALUE);
+            assertNotSizedAndSubSized(s);
+
+            Spliterator.OfLong s1 = s.trySplit();
+            assertSizedAndSubSized(s1);
+            assertSizedAndSubSized(s);
+
+            assertTrue(s.estimateSize() < Long.MAX_VALUE);
+            assertTrue(s1.estimateSize() < Long.MAX_VALUE);
+
+            assertEquals(s.estimateSize() + s1.estimateSize(), end - start + 1);
+        }
+    }
 }
--- a/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SliceOpTest.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SliceOpTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -26,13 +26,16 @@
 
 import java.util.*;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
 import java.util.function.Function;
+import java.util.stream.Collectors;
 import java.util.stream.DoubleStream;
 import java.util.stream.IntStream;
 import java.util.stream.LambdaTestHelpers;
 import java.util.stream.LongStream;
 import java.util.stream.OpTestCase;
 import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
 import java.util.stream.StreamTestDataProvider;
 import java.util.stream.TestData;
 
@@ -192,6 +195,53 @@
         }
     }
 
+    public void testSkipLimitOpsWithNonSplittingSpliterator() {
+        class NonSplittingNotSubsizedOrderedSpliterator<T> implements Spliterator<T> {
+            Spliterator<T> s;
+
+            NonSplittingNotSubsizedOrderedSpliterator(Spliterator<T> s) {
+                assert s.hasCharacteristics(Spliterator.ORDERED);
+                this.s = s;
+            }
+
+            @Override
+            public boolean tryAdvance(Consumer<? super T> action) {
+                return s.tryAdvance(action);
+            }
+
+            @Override
+            public void forEachRemaining(Consumer<? super T> action) {
+                s.forEachRemaining(action);
+            }
+
+            @Override
+            public Spliterator<T> trySplit() {
+                return null;
+            }
+
+            @Override
+            public long estimateSize() {
+                return s.estimateSize();
+            }
+
+            @Override
+            public int characteristics() {
+                return s.characteristics() & ~(Spliterator.SUBSIZED);
+            }
+
+            @Override
+            public Comparator<? super T> getComparator() {
+                return s.getComparator();
+            }
+        }
+        List<Integer> list = IntStream.range(0, 100).boxed().collect(Collectors.toList());
+        TestData.OfRef<Integer> data = TestData.Factory.ofSupplier(
+                "Non splitting, not SUBSIZED, ORDERED, stream",
+                () -> StreamSupport.stream(new NonSplittingNotSubsizedOrderedSpliterator<>(list.spliterator()), false));
+
+        testSkipLimitOps("testSkipLimitOpsWithNonSplittingSpliterator", data);
+    }
+
     @Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class)
     public void testLimitOps(String name, TestData.OfRef<Integer> data) {
         List<Integer> limits = sizes(data.size());
--- a/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SortedOpTest.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SortedOpTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -78,7 +78,7 @@
     }
 
     private <T> Stream<T> unknownSizeStream(List<T> l) {
-        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(l.iterator(), 0));
+        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(l.iterator(), 0), false);
     }
 
     @Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class)
@@ -150,7 +150,7 @@
     }
 
     private IntStream unknownSizeIntStream(int[] a) {
-        return StreamSupport.intStream(Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(a)), 0));
+        return StreamSupport.intStream(Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(a)), 0), false);
     }
 
     @Test(dataProvider = "IntStreamTestData", dataProviderClass = IntStreamTestDataProvider.class)
@@ -193,7 +193,7 @@
     }
 
     private LongStream unknownSizeLongStream(long[] a) {
-        return StreamSupport.longStream(Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(a)), 0));
+        return StreamSupport.longStream(Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(a)), 0), false);
     }
 
     @Test(dataProvider = "LongStreamTestData", dataProviderClass = LongStreamTestDataProvider.class)
@@ -236,7 +236,7 @@
     }
 
     private DoubleStream unknownSizeDoubleStream(double[] a) {
-        return StreamSupport.doubleStream(Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(a)), 0));
+        return StreamSupport.doubleStream(Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(a)), 0), false);
     }
 
     @Test(dataProvider = "DoubleStreamTestData", dataProviderClass = DoubleStreamTestDataProvider.class)
--- a/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamBuilderTest.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamBuilderTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -35,7 +35,6 @@
 import java.util.stream.LongStream;
 import java.util.stream.OpTestCase;
 import java.util.stream.Stream;
-import java.util.stream.StreamBuilder;
 import java.util.stream.TestData;
 
 import static java.util.stream.Collectors.toList;
@@ -89,7 +88,7 @@
 
     @Test(dataProvider = "sizes")
     public void testAfterBuilding(int size) {
-        StreamBuilder<Integer> sb = Stream.builder();
+        Stream.Builder<Integer> sb = Stream.builder();
         IntStream.range(0, size).boxed().forEach(sb);
         sb.build();
 
@@ -101,15 +100,15 @@
     @Test(dataProvider = "sizes")
     public void testStreamBuilder(int size) {
         testStreamBuilder(size, (s) -> {
-            StreamBuilder<Integer> sb = Stream.builder();
+            Stream.Builder<Integer> sb = Stream.builder();
             IntStream.range(0, s).boxed().forEach(sb);
             return sb.build();
         });
 
         testStreamBuilder(size, (s) -> {
-            StreamBuilder<Integer> sb = Stream.builder();
+            Stream.Builder<Integer> sb = Stream.builder();
             IntStream.range(0, s).boxed().forEach(i -> {
-                StreamBuilder<Integer> _sb = sb.add(i);
+                Stream.Builder<Integer> _sb = sb.add(i);
                 assertTrue(sb == _sb);
             });
             return sb.build();
@@ -151,7 +150,7 @@
 
     @Test(dataProvider = "sizes")
     public void testIntAfterBuilding(int size) {
-        StreamBuilder.OfInt sb = IntStream.builder();
+        IntStream.Builder sb = IntStream.builder();
         IntStream.range(0, size).forEach(sb);
         sb.build();
 
@@ -163,15 +162,15 @@
     @Test(dataProvider = "sizes")
     public void testIntStreamBuilder(int size) {
         testIntStreamBuilder(size, (s) -> {
-            StreamBuilder.OfInt sb = IntStream.builder();
+            IntStream.Builder sb = IntStream.builder();
             IntStream.range(0, s).forEach(sb);
             return sb.build();
         });
 
         testIntStreamBuilder(size, (s) -> {
-            StreamBuilder.OfInt sb = IntStream.builder();
+            IntStream.Builder sb = IntStream.builder();
             IntStream.range(0, s).forEach(i -> {
-                StreamBuilder.OfInt _sb = sb.add(i);
+                IntStream.Builder _sb = sb.add(i);
                 assertTrue(sb == _sb);
             });
             return sb.build();
@@ -213,7 +212,7 @@
 
     @Test(dataProvider = "sizes")
     public void testLongAfterBuilding(int size) {
-        StreamBuilder.OfLong sb = LongStream.builder();
+        LongStream.Builder sb = LongStream.builder();
         LongStream.range(0, size).forEach(sb);
         sb.build();
 
@@ -225,15 +224,15 @@
     @Test(dataProvider = "sizes")
     public void testLongStreamBuilder(int size) {
         testLongStreamBuilder(size, (s) -> {
-            StreamBuilder.OfLong sb = LongStream.builder();
+            LongStream.Builder sb = LongStream.builder();
             LongStream.range(0, s).forEach(sb);
             return sb.build();
         });
 
         testLongStreamBuilder(size, (s) -> {
-            StreamBuilder.OfLong sb = LongStream.builder();
+            LongStream.Builder sb = LongStream.builder();
             LongStream.range(0, s).forEach(i -> {
-                StreamBuilder.OfLong _sb = sb.add(i);
+                LongStream.Builder _sb = sb.add(i);
                 assertTrue(sb == _sb);
             });
             return sb.build();
@@ -274,7 +273,7 @@
 
     @Test(dataProvider = "sizes")
     public void testDoubleAfterBuilding(int size) {
-        StreamBuilder.OfDouble sb = DoubleStream.builder();
+        DoubleStream.Builder sb = DoubleStream.builder();
         IntStream.range(0, size).asDoubleStream().forEach(sb);
         sb.build();
 
@@ -286,15 +285,15 @@
     @Test(dataProvider = "sizes")
     public void testDoubleStreamBuilder(int size) {
         testDoubleStreamBuilder(size, (s) -> {
-            StreamBuilder.OfDouble sb = DoubleStream.builder();
+            DoubleStream.Builder sb = DoubleStream.builder();
             IntStream.range(0, s).asDoubleStream().forEach(sb);
             return sb.build();
         });
 
         testDoubleStreamBuilder(size, (s) -> {
-            StreamBuilder.OfDouble sb = DoubleStream.builder();
+            DoubleStream.Builder sb = DoubleStream.builder();
             IntStream.range(0, s).asDoubleStream().forEach(i -> {
-                StreamBuilder.OfDouble _sb = sb.add(i);
+                DoubleStream.Builder _sb = sb.add(i);
                 assertTrue(sb == _sb);
             });
             return sb.build();
--- a/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamSpliteratorTest.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamSpliteratorTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -266,7 +266,7 @@
                     setContext("proxyEstimateSize", proxyEstimateSize);
                     Spliterator<Integer> sp = intermediateOp.apply(l.stream()).spliterator();
                     ProxyNoExactSizeSpliterator<Integer> psp = new ProxyNoExactSizeSpliterator<>(sp, proxyEstimateSize);
-                    Stream<Integer> s = StreamSupport.parallelStream(psp);
+                    Stream<Integer> s = StreamSupport.stream(psp, true);
                     terminalOp.accept(s);
                     Assert.assertTrue(psp.splits > 0,
                                       String.format("Number of splits should be greater that zero when proxyEstimateSize is %s",
@@ -290,14 +290,14 @@
             withData(data).
                     stream((Stream<Integer> in) -> {
                         Stream<Integer> out = f.apply(in);
-                        return StreamSupport.stream(() -> out.spliterator(), OpTestCase.getStreamFlags(out));
+                        return StreamSupport.stream(() -> out.spliterator(), OpTestCase.getStreamFlags(out), false);
                     }).
                     exercise();
 
             withData(data).
                     stream((Stream<Integer> in) -> {
                         Stream<Integer> out = f.apply(in);
-                        return StreamSupport.parallelStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out));
+                        return StreamSupport.stream(() -> out.spliterator(), OpTestCase.getStreamFlags(out), true);
                     }).
                     exercise();
         }
@@ -362,7 +362,7 @@
                     // @@@ Need way to obtain the target size
                     Spliterator.OfInt sp = intermediateOp.apply(IntStream.range(0, 1000)).spliterator();
                     ProxyNoExactSizeSpliterator.OfInt psp = new ProxyNoExactSizeSpliterator.OfInt(sp, proxyEstimateSize);
-                    IntStream s = StreamSupport.intParallelStream(psp);
+                    IntStream s = StreamSupport.intStream(psp, true);
                     terminalOp.accept(s);
                     Assert.assertTrue(psp.splits > 0,
                                       String.format("Number of splits should be greater that zero when proxyEstimateSize is %s",
@@ -386,14 +386,14 @@
             withData(data).
                     stream(in -> {
                         IntStream out = f.apply(in);
-                        return StreamSupport.intStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out));
+                        return StreamSupport.intStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out), false);
                     }).
                     exercise();
 
             withData(data).
                     stream((in) -> {
                         IntStream out = f.apply(in);
-                        return StreamSupport.intParallelStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out));
+                        return StreamSupport.intStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out), true);
                     }).
                     exercise();
         }
@@ -455,7 +455,7 @@
                     // @@@ Need way to obtain the target size
                     Spliterator.OfLong sp = intermediateOp.apply(LongStream.range(0, 1000)).spliterator();
                     ProxyNoExactSizeSpliterator.OfLong psp = new ProxyNoExactSizeSpliterator.OfLong(sp, proxyEstimateSize);
-                    LongStream s = StreamSupport.longParallelStream(psp);
+                    LongStream s = StreamSupport.longStream(psp, true);
                     terminalOp.accept(s);
                     Assert.assertTrue(psp.splits > 0,
                                       String.format("Number of splits should be greater that zero when proxyEstimateSize is %s",
@@ -479,14 +479,14 @@
             withData(data).
                     stream(in -> {
                         LongStream out = f.apply(in);
-                        return StreamSupport.longStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out));
+                        return StreamSupport.longStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out), false);
                     }).
                     exercise();
 
             withData(data).
                     stream((in) -> {
                         LongStream out = f.apply(in);
-                        return StreamSupport.longParallelStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out));
+                        return StreamSupport.longStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out), true);
                     }).
                     exercise();
         }
@@ -548,7 +548,7 @@
                     // @@@ Need way to obtain the target size
                     Spliterator.OfDouble sp = intermediateOp.apply(IntStream.range(0, 1000).asDoubleStream()).spliterator();
                     ProxyNoExactSizeSpliterator.OfDouble psp = new ProxyNoExactSizeSpliterator.OfDouble(sp, proxyEstimateSize);
-                    DoubleStream s = StreamSupport.doubleParallelStream(psp);
+                    DoubleStream s = StreamSupport.doubleStream(psp, true);
                     terminalOp.accept(s);
                     Assert.assertTrue(psp.splits > 0,
                                       String.format("Number of splits should be greater that zero when proxyEstimateSize is %s",
@@ -572,14 +572,14 @@
             withData(data).
                     stream(in -> {
                         DoubleStream out = f.apply(in);
-                        return StreamSupport.doubleStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out));
+                        return StreamSupport.doubleStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out), false);
                     }).
                     exercise();
 
             withData(data).
                     stream((in) -> {
                         DoubleStream out = f.apply(in);
-                        return StreamSupport.doubleParallelStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out));
+                        return StreamSupport.doubleStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out), true);
                     }).
                     exercise();
         }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/management/MBeanServer/MBeanFallbackTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 javax.management.MBeanServer;
+import javax.management.MBeanServerFactory;
+import javax.management.NotCompliantMBeanException;
+import javax.management.ObjectName;
+
+/*
+ * @test
+ * @bug 8010285
+ * @summary Test fallback for private MBean interfaces.
+ *          It needs to be a separate class because the "jdk.jmx.mbeans.allowNonPublic"
+ *          system property must be set before c.s.j.m.MBeanAnalyzer has been loaded.
+ * @author Jaroslav Bachorik
+ * @run clean MBeanFallbackTest
+ * @run build MBeanFallbackTest
+ * @run main MBeanFallbackTest
+ */
+public class MBeanFallbackTest {
+    private static interface PrivateMBean {
+        public int[] getInts();
+    }
+
+    public static class Private implements PrivateMBean {
+        public int[] getInts() {
+            return new int[]{1,2,3};
+        }
+    }
+
+    private static int failures = 0;
+
+    public static void main(String[] args) throws Exception {
+        System.setProperty("jdk.jmx.mbeans.allowNonPublic", "true");
+        testPrivate(PrivateMBean.class, new Private());
+
+        if (failures == 0)
+            System.out.println("Test passed");
+        else
+            throw new Exception("TEST FAILURES: " + failures);
+    }
+
+    private static void fail(String msg) {
+        failures++;
+        System.out.println("FAIL: " + msg);
+    }
+
+    private static void success(String msg) {
+        System.out.println("OK: " + msg);
+    }
+
+    private static void testPrivate(Class<?> iface, Object bean) throws Exception {
+        try {
+            System.out.println("Registering a private MBean " +
+                                iface.getName() + " ...");
+
+            MBeanServer mbs = MBeanServerFactory.newMBeanServer();
+            ObjectName on = new ObjectName("test:type=Compliant");
+
+            mbs.registerMBean(bean, on);
+            success("Registered a private MBean - " + iface.getName());
+        } catch (Exception e) {
+            Throwable t = e;
+            while (t != null && !(t instanceof NotCompliantMBeanException)) {
+                t = t.getCause();
+            }
+            if (t != null) {
+                fail("MBean not registered");
+            } else {
+                throw e;
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/management/MBeanServer/MBeanTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,158 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 javax.management.MBeanServer;
+import javax.management.MBeanServerFactory;
+import javax.management.NotCompliantMBeanException;
+import javax.management.ObjectName;
+
+/*
+ * @test
+ * @bug 8010285
+ * @summary General MBean test.
+ * @author Jaroslav Bachorik
+ * @run clean MBeanTest
+ * @run build MBeanTest
+ * @run main MBeanTest
+ */
+public class MBeanTest {
+    private static interface PrivateMBean {
+        public int[] getInts();
+    }
+
+    public static class Private implements PrivateMBean {
+        public int[] getInts() {
+            return new int[]{1,2,3};
+        }
+    }
+
+    public static interface NonCompliantMBean {
+        public boolean getInt();
+        public boolean isInt();
+        public void setInt(int a);
+        public void setInt(long b);
+    }
+
+    public static class NonCompliant implements NonCompliantMBean {
+        public boolean getInt() {
+            return false;
+        }
+
+        public boolean isInt() {
+            return true;
+        }
+
+        public void setInt(int a) {
+        }
+
+        public void setInt(long b) {
+        }
+    }
+
+    public static interface CompliantMBean {
+        public boolean isFlag();
+        public int getInt();
+        public void setInt(int value);
+    }
+
+    public static class Compliant implements CompliantMBean {
+        public boolean isFlag() {
+            return false;
+        }
+
+        public int getInt() {
+            return 1;
+        }
+
+        public void setInt(int value) {
+        }
+    }
+
+    private static int failures = 0;
+
+    public static void main(String[] args) throws Exception {
+        testCompliant(CompliantMBean.class, new Compliant());
+        testNonCompliant(PrivateMBean.class, new Private());
+        testNonCompliant(NonCompliantMBean.class, new NonCompliant());
+
+        if (failures == 0)
+            System.out.println("Test passed");
+        else
+            throw new Exception("TEST FAILURES: " + failures);
+    }
+
+    private static void fail(String msg) {
+        failures++;
+        System.out.println("FAIL: " + msg);
+    }
+
+    private static void success(String msg) {
+        System.out.println("OK: " + msg);
+    }
+
+    private static void testNonCompliant(Class<?> iface, Object bean) throws Exception {
+        try {
+            System.out.println("Registering a non-compliant MBean " +
+                                iface.getName() + " ...");
+
+            MBeanServer mbs = MBeanServerFactory.newMBeanServer();
+            ObjectName on = new ObjectName("test:type=NonCompliant");
+
+            mbs.registerMBean(bean, on);
+
+            fail("Registered a non-compliant MBean - " + iface.getName());
+        } catch (Exception e) {
+            Throwable t = e;
+            while (t != null && !(t instanceof NotCompliantMBeanException)) {
+                t = t.getCause();
+            }
+            if (t != null) {
+                success("MBean not registered");
+            } else {
+                throw e;
+            }
+        }
+    }
+    private static void testCompliant(Class<?> iface, Object bean) throws Exception {
+        try {
+            System.out.println("Registering a compliant MBean " +
+                                iface.getName() + " ...");
+
+            MBeanServer mbs = MBeanServerFactory.newMBeanServer();
+            ObjectName on = new ObjectName("test:type=Compliant");
+
+            mbs.registerMBean(bean, on);
+            success("Registered a compliant MBean - " + iface.getName());
+        } catch (Exception e) {
+            Throwable t = e;
+            while (t != null && !(t instanceof NotCompliantMBeanException)) {
+                t = t.getCause();
+            }
+            if (t != null) {
+                fail("MBean not registered");
+            } else {
+                throw e;
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/management/mxbean/MXBeanFallbackTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8010285
+ * @summary Test for the private MXBean interface fallback.
+ *          It needs to be a separate class because the "jdk.jmx.mbeans.allowNonPublic"
+ *          system property must be set before c.s.j.m.MBeanAnalyzer has been loaded.
+ * @author Jaroslav Bachorik
+ * @run clean MXBeanFallbackTest
+ * @run build MXBeanFallbackTest
+ * @run main MXBeanFallbackTest
+ */
+
+import javax.management.MBeanServer;
+import javax.management.MBeanServerFactory;
+import javax.management.NotCompliantMBeanException;
+import javax.management.ObjectName;
+
+public class MXBeanFallbackTest {
+    public static void main(String[] args) throws Exception {
+        System.setProperty("jdk.jmx.mbeans.allowNonPublic", "true");
+        testPrivateMXBean("Private", new Private());
+
+        if (failures == 0)
+            System.out.println("Test passed");
+        else
+            throw new Exception("TEST FAILURES: " + failures);
+    }
+
+    private static int failures = 0;
+
+    private static interface PrivateMXBean {
+        public int[] getInts();
+    }
+
+    public static class Private implements PrivateMXBean {
+        public int[] getInts() {
+            return new int[]{1,2,3};
+        }
+    }
+
+    private static void testPrivateMXBean(String type, Object bean) throws Exception {
+        System.out.println(type + " MXBean test...");
+        MBeanServer mbs = MBeanServerFactory.newMBeanServer();
+        ObjectName on = new ObjectName("test:type=" + type);
+        try {
+            mbs.registerMBean(bean, on);
+            success("Private MXBean registered");
+        } catch (NotCompliantMBeanException e) {
+            failure("Failed to register the private MXBean - " +
+                     bean.getClass().getInterfaces()[0].getName());
+        }
+    }
+
+    private static void success(String what) {
+        System.out.println("OK: " + what);
+    }
+
+    private static void failure(String what) {
+        System.out.println("FAILED: " + what);
+        failures++;
+    }
+}
--- a/test/javax/management/mxbean/MXBeanTest.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/javax/management/mxbean/MXBeanTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,9 +23,10 @@
 
 /*
  * @test
- * @bug 6175517 6278707 6318827 6305746 6392303 6600709
+ * @bug 6175517 6278707 6318827 6305746 6392303 6600709 8010285
  * @summary General MXBean test.
  * @author Eamonn McManus
+ * @author Jaroslav Bachorik
  * @run clean MXBeanTest MerlinMXBean TigerMXBean
  * @run build MXBeanTest MerlinMXBean TigerMXBean
  * @run main MXBeanTest
@@ -51,6 +52,7 @@
 import javax.management.MBeanServerConnection;
 import javax.management.MBeanServerFactory;
 import javax.management.MBeanServerInvocationHandler;
+import javax.management.NotCompliantMBeanException;
 import javax.management.ObjectName;
 import javax.management.StandardMBean;
 import javax.management.openmbean.ArrayType;
@@ -75,6 +77,8 @@
         testExplicitMXBean();
         testSubclassMXBean();
         testIndirectMXBean();
+        testNonCompliantMXBean("Private", new Private());
+        testNonCompliantMXBean("NonCompliant", new NonCompliant());
 
         if (failures == 0)
             System.out.println("Test passed");
@@ -84,6 +88,39 @@
 
     private static int failures = 0;
 
+    private static interface PrivateMXBean {
+        public int[] getInts();
+    }
+
+    public static class Private implements PrivateMXBean {
+        public int[] getInts() {
+            return new int[]{1,2,3};
+        }
+    }
+
+    public static interface NonCompliantMXBean {
+        public boolean getInt();
+        public boolean isInt();
+        public void setInt(int a);
+        public void setInt(long b);
+    }
+
+    public static class NonCompliant implements NonCompliantMXBean {
+        public boolean getInt() {
+            return false;
+        }
+
+        public boolean isInt() {
+            return true;
+        }
+
+        public void setInt(int a) {
+        }
+
+        public void setInt(long b) {
+        }
+    }
+
     public static interface ExplicitMXBean {
         public int[] getInts();
     }
@@ -110,6 +147,19 @@
         }
     }
 
+    private static void testNonCompliantMXBean(String type, Object bean) throws Exception {
+        System.out.println(type + " MXBean test...");
+        MBeanServer mbs = MBeanServerFactory.newMBeanServer();
+        ObjectName on = new ObjectName("test:type=" + type);
+        try {
+            mbs.registerMBean(bean, on);
+            failure(bean.getClass().getInterfaces()[0].getName() + " is not a compliant "
+                + "MXBean interface");
+        } catch (NotCompliantMBeanException e) {
+            success("Non-compliant MXBean not registered");
+        }
+    }
+
     private static void testExplicitMXBean() throws Exception {
         System.out.println("Explicit MXBean test...");
         MBeanServer mbs = MBeanServerFactory.newMBeanServer();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/management/proxy/JMXProxyFallbackTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 javax.management.JMX;
+import javax.management.MBeanServer;
+import javax.management.MBeanServerFactory;
+import javax.management.NotCompliantMBeanException;
+import javax.management.ObjectName;
+
+/*
+ * @test
+ * @bug 8010285
+ * @summary Tests the fallback for creating JMX proxies for private interfaces
+ *          It needs to be a separate class because the "jdk.jmx.mbeans.allowNonPublic"
+ *          system property must be set before c.s.j.m.MBeanAnalyzer has been loaded.
+ * @author Jaroslav Bachorik
+ * @run clean JMXProxyFallbackTest
+ * @run build JMXProxyFallbackTest
+ * @run main JMXProxyFallbackTest
+ */
+public class JMXProxyFallbackTest {
+    private static interface PrivateMBean {
+        public int[] getInts();
+    }
+
+    private static interface PrivateMXBean {
+        public int[] getInts();
+    }
+
+    public static class Private implements PrivateMXBean, PrivateMBean {
+        public int[] getInts() {
+            return new int[]{1,2,3};
+        }
+    }
+
+    private static int failures = 0;
+
+    public static void main(String[] args) throws Exception {
+        System.setProperty("jdk.jmx.mbeans.allowNonPublic", "true");
+        testPrivate(PrivateMBean.class);
+        testPrivate(PrivateMXBean.class);
+
+        if (failures == 0)
+            System.out.println("Test passed");
+        else
+            throw new Exception("TEST FAILURES: " + failures);
+    }
+
+    private static void fail(String msg) {
+        failures++;
+        System.out.println("FAIL: " + msg);
+    }
+
+    private static void success(String msg) {
+        System.out.println("OK: " + msg);
+    }
+
+    private static void testPrivate(Class<?> iface) throws Exception {
+        try {
+            System.out.println("Creating a proxy for private M(X)Bean " +
+                                iface.getName() + " ...");
+
+            MBeanServer mbs = MBeanServerFactory.newMBeanServer();
+            ObjectName on = new ObjectName("test:type=Proxy");
+
+            JMX.newMBeanProxy(mbs, on, iface);
+            success("Created a proxy for private M(X)Bean - " + iface.getName());
+        } catch (Exception e) {
+            Throwable t = e;
+            while (t != null && !(t instanceof NotCompliantMBeanException)) {
+                t = t.getCause();
+            }
+            if (t != null) {
+                fail("Proxy not created");
+            } else {
+                throw e;
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/management/proxy/JMXProxyTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,191 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 javax.management.JMX;
+import javax.management.MBeanServer;
+import javax.management.MBeanServerFactory;
+import javax.management.NotCompliantMBeanException;
+import javax.management.ObjectName;
+
+/*
+ * @test
+ * @bug 8010285
+ * @summary Tests that javax.management.JMX creates proxies only for the
+ *          compliant MBeans/MXBeans
+ * @author Jaroslav Bachorik
+ * @run clean JMXProxyTest
+ * @run build JMXProxyTest
+ * @run main JMXProxyTest
+ */
+public class JMXProxyTest {
+    private static interface PrivateMBean {
+        public int[] getInts();
+    }
+
+    private static interface PrivateMXBean {
+        public int[] getInts();
+    }
+
+    public static class Private implements PrivateMXBean, PrivateMBean {
+        public int[] getInts() {
+            return new int[]{1,2,3};
+        }
+    }
+
+    public static interface NonCompliantMBean {
+        public boolean getInt();
+        public boolean isInt();
+        public void setInt(int a);
+        public void setInt(long b);
+    }
+
+    public static interface NonCompliantMXBean {
+        public boolean getInt();
+        public boolean isInt();
+        public void setInt(int a);
+        public void setInt(long b);
+    }
+
+    public static class NonCompliant implements NonCompliantMXBean, NonCompliantMBean {
+        public boolean getInt() {
+            return false;
+        }
+
+        public boolean isInt() {
+            return true;
+        }
+
+        public void setInt(int a) {
+        }
+
+        public void setInt(long b) {
+        }
+    }
+
+    public static interface CompliantMBean {
+        public boolean isFlag();
+        public int getInt();
+        public void setInt(int value);
+    }
+
+    public static interface CompliantMXBean {
+        public boolean isFlag();
+        public int getInt();
+        public void setInt(int value);
+    }
+
+    public static class Compliant implements CompliantMXBean, CompliantMBean {
+        public boolean isFlag() {
+            return false;
+        }
+
+        public int getInt() {
+            return 1;
+        }
+
+        public void setInt(int value) {
+        }
+    }
+
+    private static int failures = 0;
+
+    public static void main(String[] args) throws Exception {
+        testCompliant(CompliantMBean.class, false);
+        testCompliant(CompliantMXBean.class, true);
+        testNonCompliant(PrivateMBean.class, false);
+        testNonCompliant(PrivateMXBean.class, true);
+        testNonCompliant(NonCompliantMBean.class, false);
+        testNonCompliant(NonCompliantMXBean.class, true);
+
+        if (failures == 0)
+            System.out.println("Test passed");
+        else
+            throw new Exception("TEST FAILURES: " + failures);
+    }
+
+    private static void fail(String msg) {
+        failures++;
+        System.out.println("FAIL: " + msg);
+    }
+
+    private static void success(String msg) {
+        System.out.println("OK: " + msg);
+    }
+
+    private static void testNonCompliant(Class<?> iface, boolean isMx) throws Exception {
+        try {
+            System.out.println("Creating a proxy for non-compliant " +
+                               (isMx ? "MXBean" : "MBean") + " " +
+                               iface.getName() + " ...");
+
+            MBeanServer mbs = MBeanServerFactory.newMBeanServer();
+            ObjectName on = new ObjectName("test:type=Proxy");
+
+            if (isMx) {
+                JMX.newMXBeanProxy(mbs, on, iface);
+            } else {
+                JMX.newMBeanProxy(mbs, on, iface);
+            }
+            fail("Created a proxy for non-compliant " +
+                 (isMx ? "MXBean" : "MBean") + " - " + iface.getName());
+        } catch (Exception e) {
+            Throwable t = e;
+            while (t != null && !(t instanceof NotCompliantMBeanException)) {
+                t = t.getCause();
+            }
+            if (t != null) {
+                success("Proxy not created");
+            } else {
+                throw e;
+            }
+        }
+    }
+    private static void testCompliant(Class<?> iface, boolean isMx) throws Exception {
+        try {
+            System.out.println("Creating a proxy for compliant " +
+                               (isMx ? "MXBean" : "MBean") + " " +
+                               iface.getName() + " ...");
+
+            MBeanServer mbs = MBeanServerFactory.newMBeanServer();
+            ObjectName on = new ObjectName("test:type=Proxy");
+
+            if (isMx) {
+                JMX.newMXBeanProxy(mbs, on, iface);
+            } else {
+                JMX.newMBeanProxy(mbs, on, iface);
+            }
+            success("Created a proxy for compliant " +
+                    (isMx ? "MXBean" : "MBean") + " - " + iface.getName());
+        } catch (Exception e) {
+            Throwable t = e;
+            while (t != null && !(t instanceof NotCompliantMBeanException)) {
+                t = t.getCause();
+            }
+            if (t != null) {
+                fail("Proxy not created");
+            } else {
+                throw e;
+            }
+        }
+    }
+}
--- a/test/javax/swing/JMenuItem/ActionListenerCalledTwice/ActionListenerCalledTwiceTest.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/javax/swing/JMenuItem/ActionListenerCalledTwice/ActionListenerCalledTwiceTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -35,10 +35,11 @@
 import javax.swing.*;
 
 public class ActionListenerCalledTwiceTest {
-    static String menuItems[] = { "Item1", "Item2" };
+    static String menuItems[] = { "Item1", "Item2", "Item3" };
     static KeyStroke keyStrokes[] = {
         KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.META_MASK),
-        KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)
+        KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),
+        KeyStroke.getKeyStroke(KeyEvent.VK_UP, InputEvent.SHIFT_MASK),
     };
 
     static volatile int listenerCallCounter = 0;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/swing/text/html/parser/Test8017492.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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.util.Vector;
+import javax.swing.text.html.HTML;
+import javax.swing.text.html.HTMLDocument;
+import javax.swing.text.html.HTMLEditorKit;
+import javax.swing.text.html.parser.DTD;
+import javax.swing.text.html.parser.Element;
+import sun.awt.SunToolkit;
+
+/*
+ * @test
+ * @bug 8017492
+ * @run main/othervm Test8017492
+ * @summary Tests for OutOfMemoryError/NegativeArraySizeException
+ * @author Sergey Malenkov
+ */
+
+public class Test8017492 {
+    public static void main(String[] args) throws Exception {
+        Runnable task = new Runnable() {
+            @Override
+            public void run() {
+                try {
+                    SunToolkit.createNewAppContext();
+                    DTD dtd = DTD.getDTD("dtd");
+                    dtd.elements = new Vector<Element>() {
+                        @Override
+                        public synchronized int size() {
+                            return Integer.MAX_VALUE;
+                        }
+                    };
+                    dtd.getElement("element");
+                }
+                catch (Exception exception) {
+                    throw new Error("unexpected", exception);
+                }
+            }
+        };
+        // run task with different AppContext
+        Thread thread = new Thread(new ThreadGroup("$$$"), task);
+        thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
+            @Override
+            public void uncaughtException(Thread thread, Throwable throwable) {
+                throwable.printStackTrace();
+                System.exit(1);
+            }
+        });
+        thread.start();
+        thread.join();
+        // add error handling
+        HTMLDocument document = new HTMLDocument() {
+            @Override
+            public HTMLEditorKit.ParserCallback getReader(int pos) {
+                return getReader(pos, 0, 0, null);
+            }
+
+            @Override
+            public HTMLEditorKit.ParserCallback getReader(int pos, int popDepth, int pushDepth, HTML.Tag insertTag) {
+                return new HTMLDocument.HTMLReader(pos, popDepth, pushDepth, insertTag) {
+                    @Override
+                    public void handleError(String error, int pos) {
+                        throw new Error(error);
+                    }
+                };
+            }
+        };
+        // run parser
+        new HTMLEditorKit().insertHTML(document, 0, "<html><body>text", 0, 0, null);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/xml/jaxp/common/8020430/JAXP15RegTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 8020430
+ * @summary test that setProperty for XMLOutputFactory works properly
+ * @run main/othervm JAXP15RegTest
+ */
+import java.security.Policy;
+import javax.xml.stream.XMLOutputFactory;
+
+/**
+ * @author huizhe.wang@oracle.com
+ */
+public class JAXP15RegTest extends TestBase {
+
+    public JAXP15RegTest(String name) {
+        super(name);
+    }
+
+    private boolean hasSM;
+    private Policy _orig;
+
+
+    /**
+     * @param args the command line arguments
+     */
+    public static void main(String[] args) {
+        JAXP15RegTest test = new JAXP15RegTest("JAXP 1.5 regression");
+        test.setUp();
+        test.testXMLOutputFactory();
+        test.tearDown();
+    }
+
+
+    public void testXMLOutputFactory() {
+        XMLOutputFactory factory = XMLOutputFactory.newInstance();
+        factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
+        success("testXMLOutputFactory passed");
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/xml/jaxp/common/8020430/TestBase.java	Mon Jul 22 17:37:15 2013 -0700
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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.security.Policy;
+
+/**
+ *
+ *
+ * @author huizhe.wang@oracle.com
+ */
+public class TestBase {
+    String filePath;
+    boolean hasSM;
+    String curDir;
+    Policy origPolicy;
+
+    String testName;
+    static String errMessage;
+
+    int passed = 0, failed = 0;
+
+    /**
+     * Creates a new instance of StreamReader
+     */
+    public TestBase(String name) {
+        testName = name;
+    }
+
+    //junit @Override
+    protected void setUp() {
+        if (System.getSecurityManager() != null) {
+            hasSM = true;
+            System.setSecurityManager(null);
+        }
+
+        filePath = System.getProperty("test.src");
+        if (filePath == null) {
+            //current directory
+            filePath = System.getProperty("user.dir");
+        }
+        origPolicy = Policy.getPolicy();
+
+    }
+
+    //junit @Override
+    public void tearDown() {
+        // turn off security manager and restore policy
+        System.setSecurityManager(null);
+        Policy.setPolicy(origPolicy);
+        if (hasSM) {
+            System.setSecurityManager(new SecurityManager());
+        }
+        System.out.println("\nNumber of tests passed: " + passed);
+        System.out.println("Number of tests failed: " + failed + "\n");
+
+        if (errMessage != null ) {
+            throw new RuntimeException(errMessage);
+        }
+    }
+
+    void fail(String errMsg) {
+        if (errMessage == null) {
+            errMessage = errMsg;
+        } else {
+            errMessage = errMessage + "\n" + errMsg;
+        }
+        failed++;
+    }
+
+    void success(String msg) {
+        passed++;
+        System.out.println(msg);
+    }
+
+}
--- a/test/sun/security/krb5/auto/ReplayCacheTestProc.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/sun/security/krb5/auto/ReplayCacheTestProc.java	Mon Jul 22 17:37:15 2013 -0700
@@ -98,6 +98,14 @@
             kdc.writeKtab(OneKDC.KTAB);
             KDC.saveConfig(OneKDC.KRB5_CONF, kdc);
 
+            if (mode != -1) {
+                // A special native server to check basic sanity
+                if (ns(-1).waitFor() != 0) {
+                    Proc.d("Native mode sanity check failed, revert to java");
+                    mode = -1;
+                }
+            }
+
             pc = Proc.create("ReplayCacheTestProc").debug("C")
                     .args("client")
                     .start();
@@ -164,6 +172,11 @@
                         result[i].csize);
             }
             if (!finalOut) throw new Exception();
+        } else if (args[0].equals("N-1")) {
+            // Native mode sanity check
+            Proc.d("Detect start");
+            Context s = Context.fromUserKtab("*", OneKDC.KTAB, true);
+            s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID);
         } else if (args[0].equals("client")) {
             while (true) {
                 String title = Proc.textIn();
--- a/test/sun/security/krb5/auto/SaslGSS.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/sun/security/krb5/auto/SaslGSS.java	Mon Jul 22 17:37:15 2013 -0700
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8012082
+ * @bug 8012082 8019267
  * @summary SASL: auth-conf negotiated, but unencrypted data is accepted,
   *         reset to unencrypt
  * @compile -XDignore.symbol.file SaslGSS.java
@@ -37,9 +37,16 @@
 import javax.security.sasl.RealmCallback;
 import javax.security.sasl.Sasl;
 import javax.security.sasl.SaslServer;
+import java.io.ByteArrayOutputStream;
 import java.io.IOException;
+import java.io.PrintStream;
 import java.util.HashMap;
 import java.util.Locale;
+import java.util.logging.ConsoleHandler;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
 import org.ietf.jgss.*;
 import sun.security.jgss.GSSUtil;
 
@@ -79,14 +86,28 @@
                     }
                 });
 
-        // Handshake
+        ByteArrayOutputStream bout = new ByteArrayOutputStream();
+        PrintStream oldErr = System.err;
+        System.setErr(new PrintStream(bout));
+
+        Logger.getLogger("javax.security.sasl").setLevel(Level.ALL);
+        Handler h = new ConsoleHandler();
+        h.setLevel(Level.ALL);
+        Logger.getLogger("javax.security.sasl").addHandler(h);
+
         byte[] token = new byte[0];
-        token = sc.initSecContext(token, 0, token.length);
-        token = ss.evaluateResponse(token);
-        token = sc.unwrap(token, 0, token.length, new MessageProp(0, false));
-        token[0] = (byte)(((token[0] & 4) != 0) ? 4 : 2);
-        token = sc.wrap(token, 0, token.length, new MessageProp(0, false));
-        ss.evaluateResponse(token);
+
+        try {
+            // Handshake
+            token = sc.initSecContext(token, 0, token.length);
+            token = ss.evaluateResponse(token);
+            token = sc.unwrap(token, 0, token.length, new MessageProp(0, false));
+            token[0] = (byte)(((token[0] & 4) != 0) ? 4 : 2);
+            token = sc.wrap(token, 0, token.length, new MessageProp(0, false));
+            ss.evaluateResponse(token);
+        } finally {
+            System.setErr(oldErr);
+        }
 
         // Talk
         // 1. Client sends a auth-int message
@@ -102,5 +123,15 @@
         if (!qop.getPrivacy()) {
             throw new Exception();
         }
+
+        for (String s: bout.toString().split("\\n")) {
+            if (s.contains("KRB5SRV04") && s.contains("NULL")) {
+                return;
+            }
+        }
+        System.out.println("=======================");
+        System.out.println(bout.toString());
+        System.out.println("=======================");
+        throw new Exception("Haven't seen KRB5SRV04 with NULL");
     }
 }
--- a/test/sun/security/pkcs11/Signature/TestRSAKeyLength.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/sun/security/pkcs11/Signature/TestRSAKeyLength.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,7 +36,7 @@
         main(new TestRSAKeyLength());
     }
     public void main(Provider p) throws Exception {
-        boolean isValidKeyLength[] = { true, true, false, false };
+        boolean isValidKeyLength[] = { true, true, true, false, false };
         String algos[] = { "SHA1withRSA", "SHA224withRSA", "SHA256withRSA",
                            "SHA384withRSA", "SHA512withRSA" };
         KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", p);
@@ -45,6 +45,10 @@
         PrivateKey privKey = kp.getPrivate();
         PublicKey pubKey = kp.getPublic();
 
+        if (algos.length != isValidKeyLength.length) {
+            throw new Exception("Internal Error: number of test algos" +
+                " and results length mismatch!");
+        }
         for (int i = 0; i < algos.length; i++) {
             Signature sig = Signature.getInstance(algos[i], p);
             System.out.println("Testing RSA signature " + algos[i]);
--- a/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/CookieHttpsClientTest.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/CookieHttpsClientTest.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -21,15 +21,14 @@
  * questions.
  */
 
+// SunJSSE does not support dynamic system properties, no way to re-use
+// system properties in samevm/agentvm mode.
+
 /*
  * @test
  * @bug 7129083
  * @summary Cookiemanager does not store cookies if url is read
  *          before setting cookiemanager
- *
- *     SunJSSE does not support dynamic system properties, no way to re-use
- *     system properties in samevm/agentvm mode.
- *
  * @run main/othervm CookieHttpsClientTest
  */
 
@@ -186,10 +185,10 @@
 
     public static void main(String args[]) throws Exception {
         String keyFilename =
-            System.getProperty("test.src", "./") + "/" + pathToStores +
+            System.getProperty("test.src", ".") + "/" + pathToStores +
                 "/" + keyStoreFile;
         String trustFilename =
-            System.getProperty("test.src", "./") + "/" + pathToStores +
+            System.getProperty("test.src", ".") + "/" + pathToStores +
                 "/" + trustStoreFile;
 
         System.setProperty("javax.net.ssl.keyStore", keyFilename);
@@ -205,40 +204,83 @@
 
     Thread clientThread = null;
     Thread serverThread = null;
+
     /*
      * Primary constructor, used to drive remainder of the test.
      *
      * Fork off the other side, then do your work.
      */
     CookieHttpsClientTest() throws Exception {
-        if (separateServerThread) {
-            startServer(true);
-            startClient(false);
-        } else {
-            startClient(true);
-            startServer(false);
+        Exception startException = null;
+        try {
+            if (separateServerThread) {
+                startServer(true);
+                startClient(false);
+            } else {
+                startClient(true);
+                startServer(false);
+            }
+        } catch (Exception e) {
+            startException = e;
         }
 
         /*
          * Wait for other side to close down.
          */
         if (separateServerThread) {
-            serverThread.join();
+            if (serverThread != null) {
+                serverThread.join();
+            }
         } else {
-            clientThread.join();
+            if (clientThread != null) {
+                clientThread.join();
+            }
         }
 
         /*
          * When we get here, the test is pretty much over.
-         *
-         * If the main thread excepted, that propagates back
-         * immediately.  If the other thread threw an exception, we
-         * should report back.
+         * Which side threw the error?
+         */
+        Exception local;
+        Exception remote;
+
+        if (separateServerThread) {
+            remote = serverException;
+            local = clientException;
+        } else {
+            remote = clientException;
+            local = serverException;
+        }
+
+        Exception exception = null;
+
+        /*
+         * Check various exception conditions.
          */
-        if (serverException != null)
-            throw serverException;
-        if (clientException != null)
-            throw clientException;
+        if ((local != null) && (remote != null)) {
+            // If both failed, return the curthread's exception.
+            local.initCause(remote);
+            exception = local;
+        } else if (local != null) {
+            exception = local;
+        } else if (remote != null) {
+            exception = remote;
+        } else if (startException != null) {
+            exception = startException;
+        }
+
+        /*
+         * If there was an exception *AND* a startException,
+         * output it.
+         */
+        if (exception != null) {
+            if (exception != startException) {
+                exception.addSuppressed(startException);
+            }
+            throw exception;
+        }
+
+        // Fall-through: no exception to throw!
     }
 
     void startServer(boolean newThread) throws Exception {
@@ -261,7 +303,13 @@
             };
             serverThread.start();
         } else {
-            doServerSide();
+            try {
+                doServerSide();
+            } catch (Exception e) {
+                serverException = e;
+            } finally {
+                serverReady = true;
+            }
         }
     }
 
@@ -277,12 +325,16 @@
                          */
                         System.err.println("Client died...");
                         clientException = e;
-                   }
+                    }
                 }
             };
             clientThread.start();
         } else {
-            doClientSide();
+            try {
+                doClientSide();
+            } catch (Exception e) {
+                clientException = e;
+            }
         }
     }
 }
--- a/test/sun/security/ssl/templates/SSLEngineTemplate.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/sun/security/ssl/templates/SSLEngineTemplate.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -21,14 +21,14 @@
  * questions.
  */
 
+// SunJSSE does not support dynamic system properties, no way to re-use
+// system properties in samevm/agentvm mode.
+
 /*
  * @test
  * @bug 1234567
  * @summary SSLEngine has not yet caused Solaris kernel to panic
  * @run main/othervm SSLEngineTemplate
- *
- *     SunJSSE does not support dynamic system properties, no way to re-use
- *     system properties in samevm/agentvm mode.
  */
 
 /**
--- a/test/sun/security/ssl/templates/SSLSocketSSLEngineTemplate.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/sun/security/ssl/templates/SSLSocketSSLEngineTemplate.java	Mon Jul 22 17:37:15 2013 -0700
@@ -309,14 +309,25 @@
         } catch (Exception e) {
             serverException = e;
         } finally {
-            socket.close();
+            if (socket != null) {
+                socket.close();
+            }
 
             // Wait for the client to join up with us.
-            thread.join();
+            if (thread != null) {
+                thread.join();
+            }
+
             if (serverException != null) {
+                if (clientException != null) {
+                    serverException.initCause(clientException);
+                }
                 throw serverException;
             }
             if (clientException != null) {
+                if (serverException != null) {
+                    clientException.initCause(serverException);
+                }
                 throw clientException;
             }
         }
--- a/test/sun/security/ssl/templates/SSLSocketTemplate.java	Thu Jul 18 03:38:49 2013 -0700
+++ b/test/sun/security/ssl/templates/SSLSocketTemplate.java	Mon Jul 22 17:37:15 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -21,14 +21,14 @@
  * questions.
  */
 
+// SunJSSE does not support dynamic system properties, no way to re-use
+// system properties in samevm/agentvm mode.
+
 /*
  * @test
  * @bug 1234567
  * @summary Use this template to help speed your client/server tests.
  * @run main/othervm SSLSocketTemplate
- *
- *     SunJSSE does not support dynamic system properties, no way to re-use
- *     system properties in samevm/agentvm mode.
  * @author Brad Wetmore
  */
 
@@ -180,6 +180,7 @@
      * Fork off the other side, then do your work.
      */
     SSLSocketTemplate() throws Exception {
+        Exception startException = null;
         try {
             if (separateServerThread) {
                 startServer(true);
@@ -189,16 +190,20 @@
                 startServer(false);
             }
         } catch (Exception e) {
-            // swallow for now.  Show later
+            startException = e;
         }
 
         /*
          * Wait for other side to close down.
          */
         if (separateServerThread) {
-            serverThread.join();
+            if (serverThread != null) {
+                serverThread.join();
+            }
         } else {
-            clientThread.join();
+            if (clientThread != null) {
+                clientThread.join();
+            }
         }
 
         /*
@@ -207,36 +212,44 @@
          */
         Exception local;
         Exception remote;
-        String whichRemote;
 
         if (separateServerThread) {
             remote = serverException;
             local = clientException;
-            whichRemote = "server";
         } else {
             remote = clientException;
             local = serverException;
-            whichRemote = "client";
+        }
+
+        Exception exception = null;
+
+        /*
+         * Check various exception conditions.
+         */
+        if ((local != null) && (remote != null)) {
+            // If both failed, return the curthread's exception.
+            local.initCause(remote);
+            exception = local;
+        } else if (local != null) {
+            exception = local;
+        } else if (remote != null) {
+            exception = remote;
+        } else if (startException != null) {
+            exception = startException;
         }
 
         /*
-         * If both failed, return the curthread's exception, but also
-         * print the remote side Exception
+         * If there was an exception *AND* a startException,
+         * output it.
          */
-        if ((local != null) && (remote != null)) {
-            System.out.println(whichRemote + " also threw:");
-            remote.printStackTrace();
-            System.out.println();
-            throw local;
+        if (exception != null) {
+            if (exception != startException) {
+                exception.addSuppressed(startException);
+            }
+            throw exception;
         }
 
-        if (remote != null) {
-            throw remote;
-        }
-
-        if (local != null) {
-            throw local;
-        }
+        // Fall-through: no exception to throw!
     }
 
     void startServer(boolean newThread) throws Exception {