Merge
authorlana
Fri, 26 Jul 2013 14:01:00 -0700
changeset 19113 68d137b7e79f
parent 19112 3bf2022fbd9a (current diff)
parent 18978 edb01c460d4c (diff)
child 19114 558ea2ab19f7
Merge
jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties
jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java
jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java
jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java
jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java
jdk/src/share/classes/java/util/stream/StreamBuilder.java
jdk/src/share/classes/javax/security/auth/callback/package.html
jdk/src/share/classes/javax/security/auth/kerberos/package.html
jdk/src/share/classes/javax/security/auth/login/package.html
jdk/src/share/classes/javax/security/auth/package.html
jdk/src/share/classes/javax/security/auth/spi/package.html
jdk/src/share/classes/javax/security/auth/x500/package.html
jdk/src/share/classes/javax/security/cert/package.html
jdk/src/share/classes/javax/security/sasl/package.html
jdk/test/java/util/Collections/EmptySortedSet.java
langtools/test/tools/javac/generics/6723444/T6723444.out
langtools/test/tools/javac/generics/7015430/T7015430.out
nashorn/src/jdk/nashorn/internal/ir/ExecuteNode.java
nashorn/test/script/currently-failing/JDK-8006529.js
--- a/.hgtags	Thu Jul 25 13:02:37 2013 -0700
+++ b/.hgtags	Fri Jul 26 14:01:00 2013 -0700
@@ -220,3 +220,5 @@
 ea73f01b9053e7165e7ba80f242bafecbc6af712 jdk8-b96
 0a85476a0b9cb876d5666d45097dac68bef3fce1 jdk8-b97
 711eb4aa87de68de78250e0549980936bab53d54 jdk8-b98
+2d3875b0d18b3ad1c2bebf385a697e309e4005a4 jdk8-b99
+3d34036aae4ea90b2ca59712d5a69db3221f0875 jdk8-b100
--- a/.hgtags-top-repo	Thu Jul 25 13:02:37 2013 -0700
+++ b/.hgtags-top-repo	Fri Jul 26 14:01:00 2013 -0700
@@ -220,3 +220,5 @@
 c156084add486f941c12d886a0b1b2854795d557 jdk8-b96
 a1c1e8bf71f354f3aec0214cf13d6668811e021d jdk8-b97
 0d0c983a817bbe8518a5ff201306334a8de267f2 jdk8-b98
+59dc9da813794c924a0383c2a6241af94defdfed jdk8-b99
+d2dcb110e9dbaf9903c05b211df800e78e4b394e jdk8-b100
--- a/corba/.hgtags	Thu Jul 25 13:02:37 2013 -0700
+++ b/corba/.hgtags	Fri Jul 26 14:01:00 2013 -0700
@@ -220,3 +220,5 @@
 3357c2776431d51a8de326a85e0f41420e40774f jdk8-b96
 469995a8e97424f450c880606d689bf345277b19 jdk8-b97
 3370fb6146e47a6cc05a213fc213e12fc0a38d07 jdk8-b98
+3f67804ab61303782df57e54989ef5e0e4629beb jdk8-b99
+8d492f1dfd1b131a4c7886ee6b59528609f7e4fe jdk8-b100
--- a/hotspot/.hgtags	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/.hgtags	Fri Jul 26 14:01:00 2013 -0700
@@ -359,3 +359,7 @@
 c9dd82da51ed34a28f7c6b3245163ee962e94572 hs25-b40
 30b5b75c42ac5174b640fbef8aa87527668e8400 jdk8-b98
 2b9946e10587f74ef75ae8145bea484df4a2738b hs25-b41
+81b6cb70717c66375846b78bb174594ec3aa998e jdk8-b99
+9f71e36a471ae4a668e08827d33035963ed10c08 hs25-b42
+5787fac72e760c6a5fd9efa113b0c75caf554136 jdk8-b100
+46487ba40ff225654d0c51787ed3839bafcbd9f3 hs25-b43
--- a/hotspot/make/hotspot_version	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/make/hotspot_version	Fri Jul 26 14:01:00 2013 -0700
@@ -35,7 +35,7 @@
 
 HS_MAJOR_VER=25
 HS_MINOR_VER=0
-HS_BUILD_NUMBER=41
+HS_BUILD_NUMBER=43
 
 JDK_MAJOR_VER=1
 JDK_MINOR_VER=8
--- a/hotspot/make/linux/makefiles/vm.make	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/make/linux/makefiles/vm.make	Fri Jul 26 14:01:00 2013 -0700
@@ -46,6 +46,7 @@
   include $(MAKEFILES_DIR)/zeroshark.make
 else
   include $(MAKEFILES_DIR)/$(BUILDARCH).make
+  -include $(HS_ALT_MAKE)/$(Platform_os_family)/makefiles/$(BUILDARCH).make
 endif
 
 # set VPATH so make knows where to look for source files
@@ -211,6 +212,12 @@
 Src_Files_EXCLUDE += \*x86_32\*
 endif
 
+# Alternate vm.make
+# This has to be included here to allow changes to the source
+# directories and excluded files before they are expanded
+# by the definition of Src_Files.
+-include $(HS_ALT_MAKE)/$(Platform_os_family)/makefiles/vm.make
+
 # Locate all source files in the given directory, excluding files in Src_Files_EXCLUDE.
 define findsrc
 	$(notdir $(shell find $(1)/. ! -name . -prune \
@@ -380,4 +387,4 @@
 
 install: install_jvm install_jsig install_saproc
 
-.PHONY: default build install install_jvm
+.PHONY: default build install install_jvm $(HS_ALT_MAKE)/$(Platform_os_family)/makefiles/$(BUILDARCH).make $(HS_ALT_MAKE)/$(Platform_os_family)/makefiles/vm.make
--- a/hotspot/make/windows/makefiles/compile.make	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/make/windows/makefiles/compile.make	Fri Jul 26 14:01:00 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
@@ -110,6 +110,7 @@
 #      1400 is for VS2005
 #      1500 is for VS2008
 #      1600 is for VS2010
+#      1700 is for VS2012
 #    Do not confuse this MSC_VER with the predefined macro _MSC_VER that the
 #    compiler provides, when MSC_VER==1399, _MSC_VER will be 1400.
 #    Normally they are the same, but a pre-release of the VS2005 compilers
@@ -142,6 +143,9 @@
 !if "$(MSC_VER)" == "1600"
 COMPILER_NAME=VS2010
 !endif
+!if "$(MSC_VER)" == "1700"
+COMPILER_NAME=VS2012
+!endif
 !endif
 
 # By default, we do not want to use the debug version of the msvcrt.dll file
@@ -151,9 +155,13 @@
 MS_RUNTIME_OPTION = /MTd /D "_DEBUG"
 !endif
 
+# VS2012 and later won't work with:
+#     /D _STATIC_CPPLIB /D _DISABLE_DEPRECATE_STATIC_CPPLIB
+!if "$(MSC_VER)" < "1700"
 # Always add the _STATIC_CPPLIB flag
 STATIC_CPPLIB_OPTION = /D _STATIC_CPPLIB /D _DISABLE_DEPRECATE_STATIC_CPPLIB
 MS_RUNTIME_OPTION = $(MS_RUNTIME_OPTION) $(STATIC_CPPLIB_OPTION)
+!endif
 CXX_FLAGS=$(CXX_FLAGS) $(MS_RUNTIME_OPTION)
 
 # How /GX option is spelled
@@ -221,6 +229,22 @@
 !endif
 !endif
 
+!if "$(COMPILER_NAME)" == "VS2012"
+PRODUCT_OPT_OPTION   = /O2 /Oy-
+FASTDEBUG_OPT_OPTION = /O2 /Oy-
+DEBUG_OPT_OPTION     = /Od
+GX_OPTION = /EHsc
+LD_FLAGS = /manifest $(LD_FLAGS)
+# Manifest Tool - used in VS2005 and later to adjust manifests stored
+# as resources inside build artifacts.
+!if "x$(MT)" == "x"
+MT=mt.exe
+!endif
+!if "$(BUILDARCH)" == "i486"
+LD_FLAGS = /SAFESEH $(LD_FLAGS)
+!endif
+!endif
+
 # If NO_OPTIMIZATIONS is defined in the environment, turn everything off
 !ifdef NO_OPTIMIZATIONS
 PRODUCT_OPT_OPTION   = $(DEBUG_OPT_OPTION)
--- a/hotspot/make/windows/makefiles/sanity.make	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/make/windows/makefiles/sanity.make	Fri Jul 26 14:01:00 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -27,9 +27,9 @@
 all: checkCL checkLink
 
 checkCL:
-	@ if "$(MSC_VER)" NEQ "1310" if "$(MSC_VER)" NEQ "1399" if "$(MSC_VER)" NEQ "1400" if "$(MSC_VER)" NEQ "1500" if "$(MSC_VER)" NEQ "1600" \
+	@ if "$(MSC_VER)" NEQ "1310" if "$(MSC_VER)" NEQ "1399" if "$(MSC_VER)" NEQ "1400" if "$(MSC_VER)" NEQ "1500" if "$(MSC_VER)" NEQ "1600" if "$(MSC_VER)" NEQ "1700" \
 	echo *** WARNING *** unrecognized cl.exe version $(MSC_VER) ($(RAW_MSC_VER)).  Use FORCE_MSC_VER to override automatic detection.
 
 checkLink:
-	@ if "$(LD_VER)" NEQ "710" if "$(LD_VER)" NEQ "800" if "$(LD_VER)" NEQ "900" if "$(LD_VER)" NEQ "1000" \
+	@ if "$(LD_VER)" NEQ "710" if "$(LD_VER)" NEQ "800" if "$(LD_VER)" NEQ "900" if "$(LD_VER)" NEQ "1000" if "$(LD_VER)" NEQ "1100" \
 	echo *** WARNING *** unrecognized link.exe version $(LD_VER) ($(RAW_LD_VER)).  Use FORCE_LD_VER to override automatic detection.
--- a/hotspot/make/windows/makefiles/vm.make	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/make/windows/makefiles/vm.make	Fri Jul 26 14:01:00 2013 -0700
@@ -132,6 +132,10 @@
 
 !if "$(USE_PRECOMPILED_HEADER)" != "0"
 CXX_USE_PCH=/Fp"vm.pch" /Yu"precompiled.hpp"
+!if "$(COMPILER_NAME)" == "VS2012"
+# VS2012 requires this object file to be listed:
+LD_FLAGS=$(LD_FLAGS) _build_pch_file.obj
+!endif
 !else
 CXX_USE_PCH=$(CXX_DONT_USE_PCH)
 !endif
--- a/hotspot/src/cpu/sparc/vm/frame_sparc.inline.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/frame_sparc.inline.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -240,10 +240,10 @@
 #endif // CC_INTERP
 
 
-inline JavaCallWrapper* frame::entry_frame_call_wrapper() const {
+inline JavaCallWrapper** frame::entry_frame_call_wrapper_addr() const {
   // note: adjust this code if the link argument in StubGenerator::call_stub() changes!
   const Argument link = Argument(0, false);
-  return (JavaCallWrapper*)sp()[link.as_in().as_register()->sp_offset_in_saved_window()];
+  return (JavaCallWrapper**)&sp()[link.as_in().as_register()->sp_offset_in_saved_window()];
 }
 
 
--- a/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -410,6 +410,51 @@
     return start;
   }
 
+  // Safefetch stubs.
+  void generate_safefetch(const char* name, int size, address* entry,
+                          address* fault_pc, address* continuation_pc) {
+    // safefetch signatures:
+    //   int      SafeFetch32(int*      adr, int      errValue);
+    //   intptr_t SafeFetchN (intptr_t* adr, intptr_t errValue);
+    //
+    // arguments:
+    //   o0 = adr
+    //   o1 = errValue
+    //
+    // result:
+    //   o0  = *adr or errValue
+
+    StubCodeMark mark(this, "StubRoutines", name);
+
+    // Entry point, pc or function descriptor.
+    __ align(CodeEntryAlignment);
+    *entry = __ pc();
+
+    __ mov(O0, G1);  // g1 = o0
+    __ mov(O1, O0);  // o0 = o1
+    // Load *adr into c_rarg1, may fault.
+    *fault_pc = __ pc();
+    switch (size) {
+      case 4:
+        // int32_t
+        __ ldsw(G1, 0, O0);  // o0 = [g1]
+        break;
+      case 8:
+        // int64_t
+        __ ldx(G1, 0, O0);   // o0 = [g1]
+        break;
+      default:
+        ShouldNotReachHere();
+    }
+
+    // return errValue or *adr
+    *continuation_pc = __ pc();
+    // By convention with the trap handler we ensure there is a non-CTI
+    // instruction in the trap shadow.
+    __ nop();
+    __ retl();
+    __ delayed()->nop();
+  }
 
   //------------------------------------------------------------------------------------------------------------------------
   // Continuation point for throwing of implicit exceptions that are not handled in
@@ -3315,6 +3360,14 @@
 
     // Don't initialize the platform math functions since sparc
     // doesn't have intrinsics for these operations.
+
+    // Safefetch stubs.
+    generate_safefetch("SafeFetch32", sizeof(int),     &StubRoutines::_safefetch32_entry,
+                                                       &StubRoutines::_safefetch32_fault_pc,
+                                                       &StubRoutines::_safefetch32_continuation_pc);
+    generate_safefetch("SafeFetchN", sizeof(intptr_t), &StubRoutines::_safefetchN_entry,
+                                                       &StubRoutines::_safefetchN_fault_pc,
+                                                       &StubRoutines::_safefetchN_continuation_pc);
   }
 
 
--- a/hotspot/src/cpu/x86/vm/frame_x86.inline.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/cpu/x86/vm/frame_x86.inline.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -272,11 +272,10 @@
 
 // Entry frames
 
-inline JavaCallWrapper* frame::entry_frame_call_wrapper() const {
- return (JavaCallWrapper*)at(entry_frame_call_wrapper_offset);
+inline JavaCallWrapper** frame::entry_frame_call_wrapper_addr() const {
+ return (JavaCallWrapper**)addr_at(entry_frame_call_wrapper_offset);
 }
 
-
 // Compiled frames
 
 inline int frame::local_offset_for_compiler(int local_index, int nof_args, int max_nof_locals, int max_nof_monitors) {
--- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -2766,6 +2766,39 @@
     return start;
   }
 
+  // Safefetch stubs.
+  void generate_safefetch(const char* name, int size, address* entry,
+                          address* fault_pc, address* continuation_pc) {
+    // safefetch signatures:
+    //   int      SafeFetch32(int*      adr, int      errValue);
+    //   intptr_t SafeFetchN (intptr_t* adr, intptr_t errValue);
+
+    StubCodeMark mark(this, "StubRoutines", name);
+
+    // Entry point, pc or function descriptor.
+    *entry = __ pc();
+
+    __ movl(rax, Address(rsp, 0x8));
+    __ movl(rcx, Address(rsp, 0x4));
+    // Load *adr into eax, may fault.
+    *fault_pc = __ pc();
+    switch (size) {
+      case 4:
+        // int32_t
+        __ movl(rax, Address(rcx, 0));
+        break;
+      case 8:
+        // int64_t
+        Unimplemented();
+        break;
+      default:
+        ShouldNotReachHere();
+    }
+
+    // Return errValue or *adr.
+    *continuation_pc = __ pc();
+    __ ret(0);
+  }
 
  public:
   // Information about frame layout at time of blocking runtime call.
@@ -2978,6 +3011,14 @@
       StubRoutines::_cipherBlockChaining_encryptAESCrypt = generate_cipherBlockChaining_encryptAESCrypt();
       StubRoutines::_cipherBlockChaining_decryptAESCrypt = generate_cipherBlockChaining_decryptAESCrypt();
     }
+
+    // Safefetch stubs.
+    generate_safefetch("SafeFetch32", sizeof(int), &StubRoutines::_safefetch32_entry,
+                                                   &StubRoutines::_safefetch32_fault_pc,
+                                                   &StubRoutines::_safefetch32_continuation_pc);
+    StubRoutines::_safefetchN_entry           = StubRoutines::_safefetch32_entry;
+    StubRoutines::_safefetchN_fault_pc        = StubRoutines::_safefetch32_fault_pc;
+    StubRoutines::_safefetchN_continuation_pc = StubRoutines::_safefetch32_continuation_pc;
   }
 
 
--- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -279,7 +279,7 @@
       __ stmxcsr(mxcsr_save);
       __ movl(rax, mxcsr_save);
       __ andl(rax, MXCSR_MASK);    // Only check control and mask bits
-      ExternalAddress mxcsr_std(StubRoutines::x86::mxcsr_std());
+      ExternalAddress mxcsr_std(StubRoutines::addr_mxcsr_std());
       __ cmp32(rax, mxcsr_std);
       __ jcc(Assembler::equal, skip_ldmx);
       __ ldmxcsr(mxcsr_std);
@@ -729,17 +729,18 @@
 
     if (CheckJNICalls) {
       Label ok_ret;
+      ExternalAddress mxcsr_std(StubRoutines::addr_mxcsr_std());
       __ push(rax);
       __ subptr(rsp, wordSize);      // allocate a temp location
       __ stmxcsr(mxcsr_save);
       __ movl(rax, mxcsr_save);
       __ andl(rax, MXCSR_MASK);    // Only check control and mask bits
-      __ cmpl(rax, *(int *)(StubRoutines::x86::mxcsr_std()));
+      __ cmp32(rax, mxcsr_std);
       __ jcc(Assembler::equal, ok_ret);
 
       __ warn("MXCSR changed by native JNI code, use -XX:+RestoreMXCSROnJNICall");
 
-      __ ldmxcsr(ExternalAddress(StubRoutines::x86::mxcsr_std()));
+      __ ldmxcsr(mxcsr_std);
 
       __ bind(ok_ret);
       __ addptr(rsp, wordSize);
@@ -3357,7 +3358,45 @@
     return start;
   }
 
-
+  // Safefetch stubs.
+  void generate_safefetch(const char* name, int size, address* entry,
+                          address* fault_pc, address* continuation_pc) {
+    // safefetch signatures:
+    //   int      SafeFetch32(int*      adr, int      errValue);
+    //   intptr_t SafeFetchN (intptr_t* adr, intptr_t errValue);
+    //
+    // arguments:
+    //   c_rarg0 = adr
+    //   c_rarg1 = errValue
+    //
+    // result:
+    //   PPC_RET  = *adr or errValue
+
+    StubCodeMark mark(this, "StubRoutines", name);
+
+    // Entry point, pc or function descriptor.
+    *entry = __ pc();
+
+    // Load *adr into c_rarg1, may fault.
+    *fault_pc = __ pc();
+    switch (size) {
+      case 4:
+        // int32_t
+        __ movl(c_rarg1, Address(c_rarg0, 0));
+        break;
+      case 8:
+        // int64_t
+        __ movq(c_rarg1, Address(c_rarg0, 0));
+        break;
+      default:
+        ShouldNotReachHere();
+    }
+
+    // return errValue or *adr
+    *continuation_pc = __ pc();
+    __ movq(rax, c_rarg1);
+    __ ret(0);
+  }
 
   // This is a version of CBC/AES Decrypt which does 4 blocks in a loop at a time
   // to hide instruction latency
@@ -3729,12 +3768,35 @@
     return stub->entry_point();
   }
 
+  void create_control_words() {
+    // Round to nearest, 53-bit mode, exceptions masked
+    StubRoutines::_fpu_cntrl_wrd_std   = 0x027F;
+    // Round to zero, 53-bit mode, exception mased
+    StubRoutines::_fpu_cntrl_wrd_trunc = 0x0D7F;
+    // Round to nearest, 24-bit mode, exceptions masked
+    StubRoutines::_fpu_cntrl_wrd_24    = 0x007F;
+    // Round to nearest, 64-bit mode, exceptions masked
+    StubRoutines::_fpu_cntrl_wrd_64    = 0x037F;
+    // Round to nearest, 64-bit mode, exceptions masked
+    StubRoutines::_mxcsr_std           = 0x1F80;
+    // Note: the following two constants are 80-bit values
+    //       layout is critical for correct loading by FPU.
+    // Bias for strict fp multiply/divide
+    StubRoutines::_fpu_subnormal_bias1[0]= 0x00000000; // 2^(-15360) == 0x03ff 8000 0000 0000 0000
+    StubRoutines::_fpu_subnormal_bias1[1]= 0x80000000;
+    StubRoutines::_fpu_subnormal_bias1[2]= 0x03ff;
+    // Un-Bias for strict fp multiply/divide
+    StubRoutines::_fpu_subnormal_bias2[0]= 0x00000000; // 2^(+15360) == 0x7bff 8000 0000 0000 0000
+    StubRoutines::_fpu_subnormal_bias2[1]= 0x80000000;
+    StubRoutines::_fpu_subnormal_bias2[2]= 0x7bff;
+  }
+
   // Initialization
   void generate_initial() {
     // Generates all stubs and initializes the entry points
 
-    // This platform-specific stub is needed by generate_call_stub()
-    StubRoutines::x86::_mxcsr_std        = generate_fp_mask("mxcsr_std",        0x0000000000001F80);
+    // This platform-specific settings are needed by generate_call_stub()
+    create_control_words();
 
     // entry points that exist in all platforms Note: This is code
     // that could be shared among different platforms - however the
@@ -3833,6 +3895,14 @@
       StubRoutines::_cipherBlockChaining_encryptAESCrypt = generate_cipherBlockChaining_encryptAESCrypt();
       StubRoutines::_cipherBlockChaining_decryptAESCrypt = generate_cipherBlockChaining_decryptAESCrypt_Parallel();
     }
+
+    // Safefetch stubs.
+    generate_safefetch("SafeFetch32", sizeof(int),     &StubRoutines::_safefetch32_entry,
+                                                       &StubRoutines::_safefetch32_fault_pc,
+                                                       &StubRoutines::_safefetch32_continuation_pc);
+    generate_safefetch("SafeFetchN", sizeof(intptr_t), &StubRoutines::_safefetchN_entry,
+                                                       &StubRoutines::_safefetchN_fault_pc,
+                                                       &StubRoutines::_safefetchN_continuation_pc);
   }
 
  public:
--- a/hotspot/src/cpu/x86/vm/stubRoutines_x86_64.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/cpu/x86/vm/stubRoutines_x86_64.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -42,4 +42,3 @@
 address StubRoutines::x86::_float_sign_flip = NULL;
 address StubRoutines::x86::_double_sign_mask = NULL;
 address StubRoutines::x86::_double_sign_flip = NULL;
-address StubRoutines::x86::_mxcsr_std = NULL;
--- a/hotspot/src/cpu/x86/vm/stubRoutines_x86_64.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/cpu/x86/vm/stubRoutines_x86_64.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -52,7 +52,6 @@
   static address _float_sign_flip;
   static address _double_sign_mask;
   static address _double_sign_flip;
-  static address _mxcsr_std;
 
  public:
 
@@ -106,11 +105,6 @@
     return _double_sign_flip;
   }
 
-  static address mxcsr_std()
-  {
-    return _mxcsr_std;
-  }
-
 # include "stubRoutines_x86.hpp"
 
 };
--- a/hotspot/src/os/bsd/vm/attachListener_bsd.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os/bsd/vm/attachListener_bsd.cpp	Fri Jul 26 14:01:00 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
@@ -437,6 +437,30 @@
   return op;
 }
 
+
+// Performs initialization at vm startup
+// For BSD we remove any stale .java_pid file which could cause
+// an attaching process to think we are ready to receive on the
+// domain socket before we are properly initialized
+
+void AttachListener::vm_start() {
+  char fn[UNIX_PATH_MAX];
+  struct stat64 st;
+  int ret;
+
+  int n = snprintf(fn, UNIX_PATH_MAX, "%s/.java_pid%d",
+           os::get_temp_directory(), os::current_process_id());
+  assert(n < (int)UNIX_PATH_MAX, "java_pid file name buffer overflow");
+
+  RESTARTABLE(::stat64(fn, &st), ret);
+  if (ret == 0) {
+    ret = ::unlink(fn);
+    if (ret == -1) {
+      debug_only(warning("failed to remove stale attach pid file at %s", fn));
+    }
+  }
+}
+
 int AttachListener::pd_init() {
   JavaThread* thread = JavaThread::current();
   ThreadBlockInVM tbivm(thread);
--- a/hotspot/src/os/linux/vm/attachListener_linux.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os/linux/vm/attachListener_linux.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2010, 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
@@ -432,6 +432,30 @@
   return op;
 }
 
+
+// Performs initialization at vm startup
+// For Linux we remove any stale .java_pid file which could cause
+// an attaching process to think we are ready to receive on the
+// domain socket before we are properly initialized
+
+void AttachListener::vm_start() {
+  char fn[UNIX_PATH_MAX];
+  struct stat64 st;
+  int ret;
+
+  int n = snprintf(fn, UNIX_PATH_MAX, "%s/.java_pid%d",
+           os::get_temp_directory(), os::current_process_id());
+  assert(n < (int)UNIX_PATH_MAX, "java_pid file name buffer overflow");
+
+  RESTARTABLE(::stat64(fn, &st), ret);
+  if (ret == 0) {
+    ret = ::unlink(fn);
+    if (ret == -1) {
+      debug_only(warning("failed to remove stale attach pid file at %s", fn));
+    }
+  }
+}
+
 int AttachListener::pd_init() {
   JavaThread* thread = JavaThread::current();
   ThreadBlockInVM tbivm(thread);
--- a/hotspot/src/os/linux/vm/jsig.c	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os/linux/vm/jsig.c	Fri Jul 26 14:01:00 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2010, 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
@@ -107,7 +107,7 @@
 
   signal_lock();
 
-  sigused = (MASK(sig) & jvmsigs) != 0;
+  sigused = (sig < MAXSIGNUM) && ((MASK(sig) & jvmsigs) != 0);
   if (jvm_signal_installed && sigused) {
     /* jvm has installed its signal handler for this signal. */
     /* Save the handler. Don't really install it. */
@@ -116,7 +116,7 @@
 
     signal_unlock();
     return oldhandler;
-  } else if (jvm_signal_installing) {
+  } else if (sig < MAXSIGNUM && jvm_signal_installing) {
     /* jvm is installing its signal handlers. Install the new
      * handlers and save the old ones. jvm uses sigaction().
      * Leave the piece here just in case. */
@@ -165,7 +165,7 @@
 
   signal_lock();
 
-  sigused = (MASK(sig) & jvmsigs) != 0;
+  sigused = (sig < MAXSIGNUM) && ((MASK(sig) & jvmsigs) != 0);
   if (jvm_signal_installed && sigused) {
     /* jvm has installed its signal handler for this signal. */
     /* Save the handler. Don't really install it. */
@@ -178,7 +178,7 @@
 
     signal_unlock();
     return 0;
-  } else if (jvm_signal_installing) {
+  } else if (sig < MAXSIGNUM && jvm_signal_installing) {
     /* jvm is installing its signal handlers. Install the new
      * handlers and save the old ones. */
     res = call_os_sigaction(sig, act, &oldAct);
--- a/hotspot/src/os/posix/vm/os_posix.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os/posix/vm/os_posix.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -259,3 +259,52 @@
 FILE* os::open(int fd, const char* mode) {
   return ::fdopen(fd, mode);
 }
+
+os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() {
+  assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread");
+}
+
+/*
+ * See the caveats for this class in os_posix.hpp
+ * Protects the callback call so that SIGSEGV / SIGBUS jumps back into this
+ * method and returns false. If none of the signals are raised, returns true.
+ * The callback is supposed to provide the method that should be protected.
+ */
+bool os::WatcherThreadCrashProtection::call(os::CrashProtectionCallback& cb) {
+  assert(Thread::current()->is_Watcher_thread(), "Only for WatcherThread");
+  assert(!WatcherThread::watcher_thread()->has_crash_protection(),
+      "crash_protection already set?");
+
+  if (sigsetjmp(_jmpbuf, 1) == 0) {
+    // make sure we can see in the signal handler that we have crash protection
+    // installed
+    WatcherThread::watcher_thread()->set_crash_protection(this);
+    cb.call();
+    // and clear the crash protection
+    WatcherThread::watcher_thread()->set_crash_protection(NULL);
+    return true;
+  }
+  // this happens when we siglongjmp() back
+  WatcherThread::watcher_thread()->set_crash_protection(NULL);
+  return false;
+}
+
+void os::WatcherThreadCrashProtection::restore() {
+  assert(WatcherThread::watcher_thread()->has_crash_protection(),
+      "must have crash protection");
+
+  siglongjmp(_jmpbuf, 1);
+}
+
+void os::WatcherThreadCrashProtection::check_crash_protection(int sig,
+    Thread* thread) {
+
+  if (thread != NULL &&
+      thread->is_Watcher_thread() &&
+      WatcherThread::watcher_thread()->has_crash_protection()) {
+
+    if (sig == SIGSEGV || sig == SIGBUS) {
+      WatcherThread::watcher_thread()->crash_protection()->restore();
+    }
+  }
+}
--- a/hotspot/src/os/posix/vm/os_posix.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os/posix/vm/os_posix.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -37,5 +37,24 @@
 
 };
 
+/*
+ * Crash protection for the watcher thread. Wrap the callback
+ * with a sigsetjmp and in case of a SIGSEGV/SIGBUS we siglongjmp
+ * back.
+ * To be able to use this - don't take locks, don't rely on destructors,
+ * don't make OS library calls, don't allocate memory, don't print,
+ * don't call code that could leave the heap / memory in an inconsistent state,
+ * or anything else where we are not in control if we suddenly jump out.
+ */
+class WatcherThreadCrashProtection : public StackObj {
+public:
+  WatcherThreadCrashProtection();
+  bool call(os::CrashProtectionCallback& cb);
+
+  static void check_crash_protection(int signal, Thread* thread);
+private:
+  void restore();
+  sigjmp_buf _jmpbuf;
+};
 
 #endif
--- a/hotspot/src/os/solaris/vm/attachListener_solaris.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os/solaris/vm/attachListener_solaris.cpp	Fri Jul 26 14:01:00 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
@@ -576,6 +576,30 @@
   return op;
 }
 
+
+// Performs initialization at vm startup
+// For Solaris we remove any stale .java_pid file which could cause
+// an attaching process to think we are ready to receive a door_call
+// before we are properly initialized
+
+void AttachListener::vm_start() {
+  char fn[PATH_MAX+1];
+  struct stat64 st;
+  int ret;
+
+  int n = snprintf(fn, sizeof(fn), "%s/.java_pid%d",
+           os::get_temp_directory(), os::current_process_id());
+  assert(n < sizeof(fn), "java_pid file name buffer overflow");
+
+  RESTARTABLE(::stat64(fn, &st), ret);
+  if (ret == 0) {
+    ret = ::unlink(fn);
+    if (ret == -1) {
+      debug_only(warning("failed to remove stale attach pid file at %s", fn));
+    }
+  }
+}
+
 int AttachListener::pd_init() {
   JavaThread* thread = JavaThread::current();
   ThreadBlockInVM tbivm(thread);
--- a/hotspot/src/os/windows/vm/attachListener_windows.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os/windows/vm/attachListener_windows.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2010, 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
@@ -358,6 +358,10 @@
   return op;
 }
 
+void AttachListener::vm_start() {
+  // nothing to do
+}
+
 int AttachListener::pd_init() {
   return Win32AttachListener::init();
 }
--- a/hotspot/src/os/windows/vm/os_windows.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os/windows/vm/os_windows.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -2323,6 +2323,11 @@
 #endif
   Thread* t = ThreadLocalStorage::get_thread_slow();          // slow & steady
 
+  // Handle SafeFetch32 and SafeFetchN exceptions.
+  if (StubRoutines::is_safefetch_fault(pc)) {
+    return Handle_Exception(exceptionInfo, StubRoutines::continuation_for_safefetch_fault(pc));
+  }
+
 #ifndef _WIN64
   // Execution protection violation - win32 running on AMD64 only
   // Handled first to avoid misdiagnosis as a "normal" access violation;
@@ -4684,6 +4689,34 @@
   }
 }
 
+os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() {
+  assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread");
+}
+
+/*
+ * See the caveats for this class in os_windows.hpp
+ * Protects the callback call so that raised OS EXCEPTIONS causes a jump back
+ * into this method and returns false. If no OS EXCEPTION was raised, returns
+ * true.
+ * The callback is supposed to provide the method that should be protected.
+ */
+bool os::WatcherThreadCrashProtection::call(os::CrashProtectionCallback& cb) {
+  assert(Thread::current()->is_Watcher_thread(), "Only for WatcherThread");
+  assert(!WatcherThread::watcher_thread()->has_crash_protection(),
+      "crash_protection already set?");
+
+  bool success = true;
+  __try {
+    WatcherThread::watcher_thread()->set_crash_protection(this);
+    cb.call();
+  } __except(EXCEPTION_EXECUTE_HANDLER) {
+    // only for protection, nothing to do
+    success = false;
+  }
+  WatcherThread::watcher_thread()->set_crash_protection(NULL);
+  return success;
+}
+
 // An Event wraps a win32 "CreateEvent" kernel handle.
 //
 // We have a number of choices regarding "CreateEvent" win32 handle leakage:
--- a/hotspot/src/os/windows/vm/os_windows.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os/windows/vm/os_windows.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -102,6 +102,20 @@
   static LONG WINAPI serialize_fault_filter(struct _EXCEPTION_POINTERS* e);
 };
 
+/*
+ * Crash protection for the watcher thread. Wrap the callback
+ * with a __try { call() }
+ * To be able to use this - don't take locks, don't rely on destructors,
+ * don't make OS library calls, don't allocate memory, don't print,
+ * don't call code that could leave the heap / memory in an inconsistent state,
+ * or anything else where we are not in control if we suddenly jump out.
+ */
+class WatcherThreadCrashProtection : public StackObj {
+public:
+  WatcherThreadCrashProtection();
+  bool call(os::CrashProtectionCallback& cb);
+};
+
 class PlatformEvent : public CHeapObj<mtInternal> {
   private:
     double CachePad [4] ;   // increase odds that _Event is sole occupant of cache line
--- a/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_32.s	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_32.s	Fri Jul 26 14:01:00 2013 -0700
@@ -63,24 +63,6 @@
         popl     %eax
         ret
 
-        .globl  SYMBOL(SafeFetch32), SYMBOL(Fetch32PFI), SYMBOL(Fetch32Resume)
-        .globl  SYMBOL(SafeFetchN)
-        ## TODO: avoid exposing Fetch32PFI and Fetch32Resume.
-        ## Instead, the signal handler would call a new SafeFetchTriage(FaultingEIP)
-        ## routine to vet the address.  If the address is the faulting LD then
-        ## SafeFetchTriage() would return the resume-at EIP, otherwise null.
-        ELF_TYPE(SafeFetch32,@function)
-        .p2align 4,,15
-SYMBOL(SafeFetch32):
-SYMBOL(SafeFetchN):
-         movl    0x8(%esp), %eax
-         movl    0x4(%esp), %ecx
-SYMBOL(Fetch32PFI):
-         movl    (%ecx), %eax
-SYMBOL(Fetch32Resume):
-         ret
-
-
         .globl  SYMBOL(SpinPause)
         ELF_TYPE(SpinPause,@function)
         .p2align 4,,15
--- a/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_64.s	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_64.s	Fri Jul 26 14:01:00 2013 -0700
@@ -46,28 +46,6 @@
 
 	.text
 
-        .globl SYMBOL(SafeFetch32), SYMBOL(Fetch32PFI), SYMBOL(Fetch32Resume)
-        .p2align 4,,15
-        ELF_TYPE(SafeFetch32,@function)
-        // Prototype: int SafeFetch32 (int * Adr, int ErrValue) 
-SYMBOL(SafeFetch32):
-        movl    %esi, %eax
-SYMBOL(Fetch32PFI):
-        movl    (%rdi), %eax
-SYMBOL(Fetch32Resume):
-        ret
-
-        .globl SYMBOL(SafeFetchN), SYMBOL(FetchNPFI), SYMBOL(FetchNResume)
-        .p2align 4,,15
-        ELF_TYPE(SafeFetchN,@function)
-        // Prototype: intptr_t SafeFetchN (intptr_t * Adr, intptr_t ErrValue) 
-SYMBOL(SafeFetchN):
-        movq    %rsi, %rax
-SYMBOL(FetchNPFI):
-        movq    (%rdi), %rax
-SYMBOL(FetchNResume):
-        ret
-
         .globl SYMBOL(SpinPause)
         .p2align 4,,15
         ELF_TYPE(SpinPause,@function)
--- a/hotspot/src/os_cpu/bsd_x86/vm/orderAccess_bsd_x86.inline.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/bsd_x86/vm/orderAccess_bsd_x86.inline.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -72,7 +72,7 @@
 inline juint    OrderAccess::load_acquire(volatile juint*   p) { return *p; }
 inline julong   OrderAccess::load_acquire(volatile julong*  p) { return Atomic::load((volatile jlong*)p); }
 inline jfloat   OrderAccess::load_acquire(volatile jfloat*  p) { return *p; }
-inline jdouble  OrderAccess::load_acquire(volatile jdouble* p) { return *p; }
+inline jdouble  OrderAccess::load_acquire(volatile jdouble* p) { return jdouble_cast(Atomic::load((volatile jlong*)p)); }
 
 inline intptr_t OrderAccess::load_ptr_acquire(volatile intptr_t*   p) { return *p; }
 inline void*    OrderAccess::load_ptr_acquire(volatile void*       p) { return *(void* volatile *)p; }
@@ -87,7 +87,7 @@
 inline void     OrderAccess::release_store(volatile juint*   p, juint   v) { *p = v; }
 inline void     OrderAccess::release_store(volatile julong*  p, julong  v) { Atomic::store((jlong)v, (volatile jlong*)p); }
 inline void     OrderAccess::release_store(volatile jfloat*  p, jfloat  v) { *p = v; }
-inline void     OrderAccess::release_store(volatile jdouble* p, jdouble v) { *p = v; }
+inline void     OrderAccess::release_store(volatile jdouble* p, jdouble v) { release_store((volatile jlong*)p, jlong_cast(v)); }
 
 inline void     OrderAccess::release_store_ptr(volatile intptr_t* p, intptr_t v) { *p = v; }
 inline void     OrderAccess::release_store_ptr(volatile void*     p, void*    v) { *(void* volatile *)p = v; }
@@ -190,7 +190,7 @@
 inline void     OrderAccess::release_store_fence(volatile julong*  p, julong  v) { release_store_fence((volatile jlong*)p,  (jlong)v);  }
 
 inline void     OrderAccess::release_store_fence(volatile jfloat*  p, jfloat  v) { *p = v; fence(); }
-inline void     OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { *p = v; fence(); }
+inline void     OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { release_store_fence((volatile jlong*)p, jdouble_cast(v)); }
 
 inline void     OrderAccess::release_store_ptr_fence(volatile intptr_t* p, intptr_t v) {
 #ifdef AMD64
--- a/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -385,13 +385,6 @@
   trap_page_fault = 0xE
 };
 
-extern "C" void Fetch32PFI () ;
-extern "C" void Fetch32Resume () ;
-#ifdef AMD64
-extern "C" void FetchNPFI () ;
-extern "C" void FetchNResume () ;
-#endif // AMD64
-
 extern "C" JNIEXPORT int
 JVM_handle_bsd_signal(int sig,
                         siginfo_t* info,
@@ -401,6 +394,10 @@
 
   Thread* t = ThreadLocalStorage::get_thread_slow();
 
+  // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away
+  // (no destructors can be run)
+  os::WatcherThreadCrashProtection::check_crash_protection(sig, t);
+
   SignalHandlerMark shm(t);
 
   // Note: it's not uncommon that JNI code uses signal/sigset to install
@@ -454,16 +451,10 @@
   if (info != NULL && uc != NULL && thread != NULL) {
     pc = (address) os::Bsd::ucontext_get_pc(uc);
 
-    if (pc == (address) Fetch32PFI) {
-       uc->context_pc = intptr_t(Fetch32Resume) ;
-       return 1 ;
+    if (StubRoutines::is_safefetch_fault(pc)) {
+      uc->context_pc = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc));
+      return 1;
     }
-#ifdef AMD64
-    if (pc == (address) FetchNPFI) {
-       uc->context_pc = intptr_t (FetchNResume) ;
-       return 1 ;
-    }
-#endif // AMD64
 
     // Handle ALL stack overflow variations here
     if (sig == SIGSEGV || sig == SIGBUS) {
--- a/hotspot/src/os_cpu/linux_sparc/vm/linux_sparc.s	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/linux_sparc/vm/linux_sparc.s	Fri Jul 26 14:01:00 2013 -0700
@@ -21,42 +21,6 @@
 # questions.
 #
 
-    # Prototype: int SafeFetch32 (int * adr, int ErrValue)
-    # The "ld" at Fetch32 is potentially faulting instruction.
-    # If the instruction traps the trap handler will arrange
-    # for control to resume at Fetch32Resume.  
-    # By convention with the trap handler we ensure there is a non-CTI
-    # instruction in the trap shadow.  
-        
-
-    .globl  SafeFetch32, Fetch32PFI, Fetch32Resume
-    .globl  SafeFetchN
-    .align  32
-    .type    SafeFetch32,@function
-SafeFetch32:        
-    mov     %o0, %g1
-    mov     %o1, %o0
-Fetch32PFI:
-    # <-- Potentially faulting instruction
-    ld      [%g1], %o0         
-Fetch32Resume:
-    nop
-    retl
-    nop
-
-    .globl  SafeFetchN, FetchNPFI, FetchNResume
-    .type    SafeFetchN,@function
-    .align  32
-SafeFetchN:
-    mov     %o0, %g1
-    mov     %o1, %o0
-FetchNPFI:
-    ldn     [%g1], %o0
-FetchNResume:
-    nop
-    retl
-    nop
-
     # Possibilities:
     # -- membar
     # -- CAS (SP + BIAS, G0, G0)
--- a/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -366,18 +366,9 @@
 
 // Utility functions
 
-extern "C" void Fetch32PFI();
-extern "C" void Fetch32Resume();
-extern "C" void FetchNPFI();
-extern "C" void FetchNResume();
-
 inline static bool checkPrefetch(sigcontext* uc, address pc) {
-  if (pc == (address) Fetch32PFI) {
-    set_cont_address(uc, address(Fetch32Resume));
-    return true;
-  }
-  if (pc == (address) FetchNPFI) {
-    set_cont_address(uc, address(FetchNResume));
+  if (StubRoutines::is_safefetch_fault(pc)) {
+    set_cont_address(uc, address(StubRoutines::continuation_for_safefetch_fault(pc)));
     return true;
   }
   return false;
@@ -553,6 +544,10 @@
 
   Thread* t = ThreadLocalStorage::get_thread_slow();
 
+  // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away
+  // (no destructors can be run)
+  os::WatcherThreadCrashProtection::check_crash_protection(sig, t);
+
   SignalHandlerMark shm(t);
 
   // Note: it's not uncommon that JNI code uses signal/sigset to install
--- a/hotspot/src/os_cpu/linux_x86/vm/linux_x86_32.s	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/linux_x86/vm/linux_x86_32.s	Fri Jul 26 14:01:00 2013 -0700
@@ -42,24 +42,6 @@
 
 	.text
 
-        .globl  SafeFetch32, Fetch32PFI, Fetch32Resume
-        .globl  SafeFetchN
-        ## TODO: avoid exposing Fetch32PFI and Fetch32Resume.
-        ## Instead, the signal handler would call a new SafeFetchTriage(FaultingEIP)
-        ## routine to vet the address.  If the address is the faulting LD then
-        ## SafeFetchTriage() would return the resume-at EIP, otherwise null.
-	.type    SafeFetch32,@function
-        .p2align 4,,15
-SafeFetch32:
-SafeFetchN:
-         movl    0x8(%esp), %eax
-         movl    0x4(%esp), %ecx
-Fetch32PFI:
-         movl    (%ecx), %eax
-Fetch32Resume:
-         ret
-
-
         .globl  SpinPause
 	.type   SpinPause,@function
         .p2align 4,,15
--- a/hotspot/src/os_cpu/linux_x86/vm/linux_x86_64.s	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/linux_x86/vm/linux_x86_64.s	Fri Jul 26 14:01:00 2013 -0700
@@ -38,28 +38,6 @@
 
 	.text
 
-        .globl SafeFetch32, Fetch32PFI, Fetch32Resume
-        .align  16
-        .type   SafeFetch32,@function
-        // Prototype: int SafeFetch32 (int * Adr, int ErrValue) 
-SafeFetch32:
-        movl    %esi, %eax
-Fetch32PFI:
-        movl    (%rdi), %eax
-Fetch32Resume:
-        ret
-
-        .globl SafeFetchN, FetchNPFI, FetchNResume
-        .align  16
-        .type   SafeFetchN,@function
-        // Prototype: intptr_t SafeFetchN (intptr_t * Adr, intptr_t ErrValue) 
-SafeFetchN:
-        movq    %rsi, %rax
-FetchNPFI:
-        movq    (%rdi), %rax
-FetchNResume:
-        ret
-
         .globl SpinPause
         .align 16
         .type  SpinPause,@function
--- a/hotspot/src/os_cpu/linux_x86/vm/orderAccess_linux_x86.inline.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/linux_x86/vm/orderAccess_linux_x86.inline.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -72,7 +72,7 @@
 inline juint    OrderAccess::load_acquire(volatile juint*   p) { return *p; }
 inline julong   OrderAccess::load_acquire(volatile julong*  p) { return Atomic::load((volatile jlong*)p); }
 inline jfloat   OrderAccess::load_acquire(volatile jfloat*  p) { return *p; }
-inline jdouble  OrderAccess::load_acquire(volatile jdouble* p) { return *p; }
+inline jdouble  OrderAccess::load_acquire(volatile jdouble* p) { return jdouble_cast(Atomic::load((volatile jlong*)p)); }
 
 inline intptr_t OrderAccess::load_ptr_acquire(volatile intptr_t*   p) { return *p; }
 inline void*    OrderAccess::load_ptr_acquire(volatile void*       p) { return *(void* volatile *)p; }
@@ -87,7 +87,7 @@
 inline void     OrderAccess::release_store(volatile juint*   p, juint   v) { *p = v; }
 inline void     OrderAccess::release_store(volatile julong*  p, julong  v) { Atomic::store((jlong)v, (volatile jlong*)p); }
 inline void     OrderAccess::release_store(volatile jfloat*  p, jfloat  v) { *p = v; }
-inline void     OrderAccess::release_store(volatile jdouble* p, jdouble v) { *p = v; }
+inline void     OrderAccess::release_store(volatile jdouble* p, jdouble v) { release_store((volatile jlong *)p, jlong_cast(v)); }
 
 inline void     OrderAccess::release_store_ptr(volatile intptr_t* p, intptr_t v) { *p = v; }
 inline void     OrderAccess::release_store_ptr(volatile void*     p, void*    v) { *(void* volatile *)p = v; }
@@ -129,7 +129,7 @@
 inline void     OrderAccess::store_fence(juint*   p, juint   v) { store_fence((jint*)p,   (jint)v);   }
 inline void     OrderAccess::store_fence(julong*  p, julong  v) { store_fence((jlong*)p,  (jlong)v);  }
 inline void     OrderAccess::store_fence(jfloat*  p, jfloat  v) { *p = v; fence(); }
-inline void     OrderAccess::store_fence(jdouble* p, jdouble v) { *p = v; fence(); }
+inline void     OrderAccess::store_fence(jdouble* p, jdouble v) { store_fence((jlong*)p, jlong_cast(v)); }
 
 inline void     OrderAccess::store_ptr_fence(intptr_t* p, intptr_t v) {
 #ifdef AMD64
@@ -190,7 +190,7 @@
 inline void     OrderAccess::release_store_fence(volatile julong*  p, julong  v) { release_store_fence((volatile jlong*)p,  (jlong)v);  }
 
 inline void     OrderAccess::release_store_fence(volatile jfloat*  p, jfloat  v) { *p = v; fence(); }
-inline void     OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { *p = v; fence(); }
+inline void     OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { release_store_fence((volatile jlong*)p, jlong_cast(v)); }
 
 inline void     OrderAccess::release_store_ptr_fence(volatile intptr_t* p, intptr_t v) {
 #ifdef AMD64
--- a/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -209,13 +209,6 @@
   trap_page_fault = 0xE
 };
 
-extern "C" void Fetch32PFI () ;
-extern "C" void Fetch32Resume () ;
-#ifdef AMD64
-extern "C" void FetchNPFI () ;
-extern "C" void FetchNResume () ;
-#endif // AMD64
-
 extern "C" JNIEXPORT int
 JVM_handle_linux_signal(int sig,
                         siginfo_t* info,
@@ -225,6 +218,10 @@
 
   Thread* t = ThreadLocalStorage::get_thread_slow();
 
+  // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away
+  // (no destructors can be run)
+  os::WatcherThreadCrashProtection::check_crash_protection(sig, t);
+
   SignalHandlerMark shm(t);
 
   // Note: it's not uncommon that JNI code uses signal/sigset to install
@@ -278,16 +275,10 @@
   if (info != NULL && uc != NULL && thread != NULL) {
     pc = (address) os::Linux::ucontext_get_pc(uc);
 
-    if (pc == (address) Fetch32PFI) {
-       uc->uc_mcontext.gregs[REG_PC] = intptr_t(Fetch32Resume) ;
-       return 1 ;
+    if (StubRoutines::is_safefetch_fault(pc)) {
+      uc->uc_mcontext.gregs[REG_PC] = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc));
+      return 1;
     }
-#ifdef AMD64
-    if (pc == (address) FetchNPFI) {
-       uc->uc_mcontext.gregs[REG_PC] = intptr_t (FetchNResume) ;
-       return 1 ;
-    }
-#endif // AMD64
 
 #ifndef AMD64
     // Halt if SI_KERNEL before more crashes get misdiagnosed as Java bugs
--- a/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -303,11 +303,6 @@
 #endif
 }
 
-extern "C" void Fetch32PFI () ;
-extern "C" void Fetch32Resume () ;
-extern "C" void FetchNPFI () ;
-extern "C" void FetchNResume () ;
-
 extern "C" JNIEXPORT int
 JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid,
                           int abort_if_unrecognized) {
@@ -315,6 +310,10 @@
 
   Thread* t = ThreadLocalStorage::get_thread_slow();
 
+  // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away
+  // (no destructors can be run)
+  os::WatcherThreadCrashProtection::check_crash_protection(sig, t);
+
   SignalHandlerMark shm(t);
 
   if(sig == SIGPIPE || sig == SIGXFSZ) {
@@ -379,17 +378,10 @@
     npc = (address) uc->uc_mcontext.gregs[REG_nPC];
 
     // SafeFetch() support
-    // Implemented with either a fixed set of addresses such
-    // as Fetch32*, or with Thread._OnTrap.
-    if (uc->uc_mcontext.gregs[REG_PC] == intptr_t(Fetch32PFI)) {
-      uc->uc_mcontext.gregs [REG_PC]  = intptr_t(Fetch32Resume) ;
-      uc->uc_mcontext.gregs [REG_nPC] = intptr_t(Fetch32Resume) + 4 ;
-      return true ;
-    }
-    if (uc->uc_mcontext.gregs[REG_PC] == intptr_t(FetchNPFI)) {
-      uc->uc_mcontext.gregs [REG_PC]  = intptr_t(FetchNResume) ;
-      uc->uc_mcontext.gregs [REG_nPC] = intptr_t(FetchNResume) + 4 ;
-      return true ;
+    if (StubRoutines::is_safefetch_fault(pc)) {
+      uc->uc_mcontext.gregs[REG_PC] = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc));
+      uc->uc_mcontext.gregs[REG_nPC] = uc->uc_mcontext.gregs[REG_PC] + 4;
+      return 1;
     }
 
     // Handle ALL stack overflow variations here
--- a/hotspot/src/os_cpu/solaris_sparc/vm/solaris_sparc.s	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/solaris_sparc/vm/solaris_sparc.s	Fri Jul 26 14:01:00 2013 -0700
@@ -21,47 +21,6 @@
 !! questions.
 !!
 
-    !! Prototype: int SafeFetch32 (int * adr, int ErrValue)
-    !! The "ld" at Fetch32 is potentially faulting instruction.
-    !! If the instruction traps the trap handler will arrange
-    !! for control to resume at Fetch32Resume.  
-    !! By convention with the trap handler we ensure there is a non-CTI
-    !! instruction in the trap shadow.  
-    !!
-    !! The reader might be tempted to move this service to .il.
-    !! Don't.  Sun's CC back-end reads and optimize code emitted 
-    !! by the .il "call", in some cases optimizing the code, completely eliding it,
-    !! or by moving the code from the "call site". 
-        
-     !! ASM better know we may use G6 for our own purposes
-    .register %g6, #ignore
-        
-    .globl  SafeFetch32
-    .align  32
-    .global Fetch32PFI, Fetch32Resume 
-SafeFetch32:
-    mov     %o0, %g1
-    mov     %o1, %o0
-Fetch32PFI:
-    ld      [%g1], %o0          !! <-- Potentially faulting instruction
-Fetch32Resume:
-    nop
-    retl
-    nop
-
-    .globl  SafeFetchN
-    .align  32
-    .globl  FetchNPFI, FetchNResume
-SafeFetchN:
-    mov     %o0, %g1
-    mov     %o1, %o0
-FetchNPFI:
-    ldn     [%g1], %o0
-FetchNResume:
-    nop
-    retl
-    nop
-
     !! Possibilities:
     !! -- membar
     !! -- CAS (SP + BIAS, G0, G0)
--- a/hotspot/src/os_cpu/solaris_x86/vm/orderAccess_solaris_x86.inline.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/solaris_x86/vm/orderAccess_solaris_x86.inline.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -88,7 +88,7 @@
 inline juint    OrderAccess::load_acquire(volatile juint*   p) { return *p; }
 inline julong   OrderAccess::load_acquire(volatile julong*  p) { return Atomic::load((volatile jlong*)p); }
 inline jfloat   OrderAccess::load_acquire(volatile jfloat*  p) { return *p; }
-inline jdouble  OrderAccess::load_acquire(volatile jdouble* p) { return *p; }
+inline jdouble  OrderAccess::load_acquire(volatile jdouble* p) { return jdouble_cast(Atomic::load((volatile jlong*)p)); }
 
 inline intptr_t OrderAccess::load_ptr_acquire(volatile intptr_t*   p) { return *p; }
 inline void*    OrderAccess::load_ptr_acquire(volatile void*       p) { return *(void* volatile *)p; }
@@ -103,7 +103,7 @@
 inline void     OrderAccess::release_store(volatile juint*   p, juint   v) { *p = v; }
 inline void     OrderAccess::release_store(volatile julong*  p, julong  v) { Atomic::store((jlong)v, (volatile jlong*)p); }
 inline void     OrderAccess::release_store(volatile jfloat*  p, jfloat  v) { *p = v; }
-inline void     OrderAccess::release_store(volatile jdouble* p, jdouble v) { *p = v; }
+inline void     OrderAccess::release_store(volatile jdouble* p, jdouble v) { release_store((volatile jlong*)p, jlong_cast(v)); }
 
 inline void     OrderAccess::release_store_ptr(volatile intptr_t* p, intptr_t v) { *p = v; }
 inline void     OrderAccess::release_store_ptr(volatile void*     p, void*    v) { *(void* volatile *)p = v; }
@@ -129,9 +129,9 @@
 inline void     OrderAccess::release_store_fence(volatile jubyte*  p, jubyte  v) { *p = v; fence(); }
 inline void     OrderAccess::release_store_fence(volatile jushort* p, jushort v) { *p = v; fence(); }
 inline void     OrderAccess::release_store_fence(volatile juint*   p, juint   v) { *p = v; fence(); }
-inline void     OrderAccess::release_store_fence(volatile julong*  p, julong  v) { release_store(p, v); fence(); }
+inline void     OrderAccess::release_store_fence(volatile julong*  p, julong  v) { release_store((jlong *)p, (jlong)v); fence(); }
 inline void     OrderAccess::release_store_fence(volatile jfloat*  p, jfloat  v) { *p = v; fence(); }
-inline void     OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { *p = v; fence(); }
+inline void     OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { release_store_fence((volatile jlong*)p, jlong_cast(v)); }
 
 inline void     OrderAccess::release_store_ptr_fence(volatile intptr_t* p, intptr_t v) { *p = v; fence(); }
 inline void     OrderAccess::release_store_ptr_fence(volatile void*     p, void*    v) { *(void* volatile *)p = v; fence(); }
--- a/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -352,13 +352,6 @@
 
 }
 
-extern "C" void Fetch32PFI () ;
-extern "C" void Fetch32Resume () ;
-#ifdef AMD64
-extern "C" void FetchNPFI () ;
-extern "C" void FetchNResume () ;
-#endif // AMD64
-
 extern "C" JNIEXPORT int
 JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid,
                           int abort_if_unrecognized) {
@@ -374,6 +367,10 @@
 
   Thread* t = ThreadLocalStorage::get_thread_slow();  // slow & steady
 
+  // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away
+  // (no destructors can be run)
+  os::WatcherThreadCrashProtection::check_crash_protection(sig, t);
+
   SignalHandlerMark shm(t);
 
   if(sig == SIGPIPE || sig == SIGXFSZ) {
@@ -436,17 +433,10 @@
     // factor me: getPCfromContext
     pc = (address) uc->uc_mcontext.gregs[REG_PC];
 
-    // SafeFetch32() support
-    if (pc == (address) Fetch32PFI) {
-      uc->uc_mcontext.gregs[REG_PC] = intptr_t(Fetch32Resume) ;
-      return true ;
+    if (StubRoutines::is_safefetch_fault(pc)) {
+      uc->uc_mcontext.gregs[REG_PC] = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc));
+      return true;
     }
-#ifdef AMD64
-    if (pc == (address) FetchNPFI) {
-       uc->uc_mcontext.gregs [REG_PC] = intptr_t(FetchNResume) ;
-       return true ;
-    }
-#endif // AMD64
 
     // Handle ALL stack overflow variations here
     if (sig == SIGSEGV && info->si_code == SEGV_ACCERR) {
--- a/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_32.s	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_32.s	Fri Jul 26 14:01:00 2013 -0700
@@ -54,20 +54,6 @@
 	popl     %eax
 	ret
 
-       .align  16
-       .globl  SafeFetch32
-       .globl  SafeFetchN
-       .globl  Fetch32PFI, Fetch32Resume
-SafeFetch32:
-SafeFetchN:
-        movl    0x8(%esp), %eax
-        movl    0x4(%esp), %ecx
-Fetch32PFI:
-        movl    (%ecx), %eax
-Fetch32Resume:
-        ret
-
-
         .align  16
         .globl  SpinPause
 SpinPause:
--- a/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_64.s	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_64.s	Fri Jul 26 14:01:00 2013 -0700
@@ -21,54 +21,34 @@
 / questions.
 /
 
-	.globl fs_load
-	.globl fs_thread
+        .globl fs_load
+        .globl fs_thread
 
         // NOTE WELL!  The _Copy functions are called directly
-	// from server-compiler-generated code via CallLeafNoFP,
-	// which means that they *must* either not use floating
-	// point or use it in the same manner as does the server
-	// compiler.
+        // from server-compiler-generated code via CallLeafNoFP,
+        // which means that they *must* either not use floating
+        // point or use it in the same manner as does the server
+        // compiler.
 
         .globl _Copy_arrayof_conjoint_bytes
         .globl _Copy_conjoint_jshorts_atomic
-	.globl _Copy_arrayof_conjoint_jshorts
+        .globl _Copy_arrayof_conjoint_jshorts
         .globl _Copy_conjoint_jints_atomic
         .globl _Copy_arrayof_conjoint_jints
-	.globl _Copy_conjoint_jlongs_atomic
+        .globl _Copy_conjoint_jlongs_atomic
         .globl _Copy_arrayof_conjoint_jlongs
 
-	.section .text,"ax"
+        .section .text,"ax"
 
         / Fast thread accessors, used by threadLS_solaris_amd64.cpp
-	.align   16
+        .align   16
 fs_load:
-	movq %fs:(%rdi),%rax
-	ret
-
-	.align   16
-fs_thread:
-	movq %fs:0x0,%rax
-	ret
-
-        .globl SafeFetch32, Fetch32PFI, Fetch32Resume
-        .align  16
-        // Prototype: int SafeFetch32 (int * Adr, int ErrValue) 
-SafeFetch32:
-        movl    %esi, %eax
-Fetch32PFI:
-        movl    (%rdi), %eax
-Fetch32Resume:
+        movq %fs:(%rdi),%rax
         ret
 
-        .globl SafeFetchN, FetchNPFI, FetchNResume
-        .align  16
-        // Prototype: intptr_t SafeFetchN (intptr_t * Adr, intptr_t ErrValue) 
-SafeFetchN:
-        movq    %rsi, %rax
-FetchNPFI:
-        movq    (%rdi), %rax
-FetchNResume:
+        .align   16
+fs_thread:
+        movq %fs:0x0,%rax
         ret
 
         .globl  SpinPause
@@ -78,7 +58,7 @@
         nop
         movq    $1, %rax
         ret
-        
+
 
         / Support for void Copy::arrayof_conjoint_bytes(void* from,
         /                                               void* to,
@@ -340,7 +320,7 @@
         addq     $4,%rdx
         jg       1b
         ret
-	
+
         / Support for void Copy::arrayof_conjoint_jlongs(jlong* from,
         /                                                jlong* to,
         /                                                size_t count)
--- a/hotspot/src/os_cpu/windows_x86/vm/orderAccess_windows_x86.inline.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/windows_x86/vm/orderAccess_windows_x86.inline.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -71,7 +71,7 @@
 inline juint    OrderAccess::load_acquire(volatile juint*   p) { return *p; }
 inline julong   OrderAccess::load_acquire(volatile julong*  p) { return Atomic::load((volatile jlong*)p); }
 inline jfloat   OrderAccess::load_acquire(volatile jfloat*  p) { return *p; }
-inline jdouble  OrderAccess::load_acquire(volatile jdouble* p) { return *p; }
+inline jdouble  OrderAccess::load_acquire(volatile jdouble* p) { return jdouble_cast(Atomic::load((volatile jlong*)p)); }
 
 inline intptr_t OrderAccess::load_ptr_acquire(volatile intptr_t*   p) { return *p; }
 inline void*    OrderAccess::load_ptr_acquire(volatile void*       p) { return *(void* volatile *)p; }
@@ -86,7 +86,7 @@
 inline void     OrderAccess::release_store(volatile juint*   p, juint   v) { *p = v; }
 inline void     OrderAccess::release_store(volatile julong*  p, julong  v) { Atomic::store((jlong)v, (volatile jlong*)p); }
 inline void     OrderAccess::release_store(volatile jfloat*  p, jfloat  v) { *p = v; }
-inline void     OrderAccess::release_store(volatile jdouble* p, jdouble v) { *p = v; }
+inline void     OrderAccess::release_store(volatile jdouble* p, jdouble v) { release_store((volatile jlong*)p, jlong_cast(v)); }
 
 inline void     OrderAccess::release_store_ptr(volatile intptr_t* p, intptr_t v) { *p = v; }
 inline void     OrderAccess::release_store_ptr(volatile void*     p, void*    v) { *(void* volatile *)p = v; }
@@ -195,7 +195,7 @@
 inline void     OrderAccess::release_store_fence(volatile juint*   p, juint   v) { release_store_fence((volatile jint*)p,   (jint)v);   }
 inline void     OrderAccess::release_store_fence(volatile julong*  p, julong  v) { release_store_fence((volatile jlong*)p,  (jlong)v);  }
 inline void     OrderAccess::release_store_fence(volatile jfloat*  p, jfloat  v) { *p = v; fence(); }
-inline void     OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { *p = v; fence(); }
+inline void     OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { release_store_fence((volatile jlong*)p, jlong_cast(v)); }
 
 inline void     OrderAccess::release_store_ptr_fence(volatile intptr_t* p, intptr_t v) {
 #ifdef AMD64
--- a/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -518,24 +518,6 @@
   st->cr();
 }
 
-extern "C" int SafeFetch32 (int * adr, int Err) {
-   int rv = Err ;
-   _try {
-       rv = *((volatile int *) adr) ;
-   } __except(EXCEPTION_EXECUTE_HANDLER) {
-   }
-   return rv ;
-}
-
-extern "C" intptr_t SafeFetchN (intptr_t * adr, intptr_t Err) {
-   intptr_t rv = Err ;
-   _try {
-       rv = *((volatile intptr_t *) adr) ;
-   } __except(EXCEPTION_EXECUTE_HANDLER) {
-   }
-   return rv ;
-}
-
 extern "C" int SpinPause () {
 #ifdef AMD64
    return 0 ;
--- a/hotspot/src/os_cpu/windows_x86/vm/unwind_windows_x86.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/os_cpu/windows_x86/vm/unwind_windows_x86.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 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,10 +29,15 @@
 #ifdef AMD64
 typedef unsigned char UBYTE;
 
+#if _MSC_VER < 1700
+
+/* Not needed for VS2012 compiler, comes from winnt.h. */
 #define UNW_FLAG_EHANDLER  0x01
 #define UNW_FLAG_UHANDLER  0x02
 #define UNW_FLAG_CHAININFO 0x04
 
+#endif
+
 // This structure is used to define an UNWIND_INFO that
 // only has an ExceptionHandler.  There are no UnwindCodes
 // declared.
@@ -59,6 +64,9 @@
 } RUNTIME_FUNCTION, *PRUNTIME_FUNCTION;
 */
 
+#if _MSC_VER < 1700
+
+/* Not needed for VS2012 compiler, comes from winnt.h. */
 typedef struct _DISPATCHER_CONTEXT {
     ULONG64 ControlPc;
     ULONG64 ImageBase;
@@ -71,6 +79,8 @@
     PVOID HandlerData;
 } DISPATCHER_CONTEXT, *PDISPATCHER_CONTEXT;
 
+#endif
+
 #if _MSC_VER < 1500
 
 /* Not needed for VS2008 compiler, comes from winnt.h. */
--- a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -138,6 +138,16 @@
   return false;
 }
 
+// return true if all argument elements of vars are returned
+bool BCEscapeAnalyzer::returns_all(ArgumentMap vars) {
+  for (int i = 0; i < _arg_size; i++) {
+    if (vars.contains(i) && !_arg_returned.test(i)) {
+      return false;
+    }
+  }
+  return true;
+}
+
 void BCEscapeAnalyzer::clear_bits(ArgumentMap vars, VectorSet &bm) {
   for (int i = 0; i < _arg_size; i++) {
     if (vars.contains(i)) {
@@ -166,6 +176,11 @@
     if (vars.contains_unknown() || vars.contains_vars()) {
       _return_allocated = false;
     }
+    if (_return_local && vars.contains_vars() && !returns_all(vars)) {
+      // Return result should be invalidated if args in new
+      // state are not recorded in return state.
+      _return_local = false;
+    }
   }
 }
 
--- a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -80,6 +80,7 @@
   void set_returned(ArgumentMap vars);
   bool is_argument(ArgumentMap vars);
   bool is_arg_stack(ArgumentMap vars);
+  bool returns_all(ArgumentMap vars);
   void clear_bits(ArgumentMap vars, VectorSet &bs);
   void set_method_escape(ArgumentMap vars);
   void set_global_escape(ArgumentMap vars, bool merge = false);
--- a/hotspot/src/share/vm/classfile/classFileParser.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/classfile/classFileParser.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -3647,8 +3647,7 @@
   // If RedefineClasses() was used before the retransformable
   // agent attached, then the cached class bytes may not be the
   // original class bytes.
-  unsigned char *cached_class_file_bytes = NULL;
-  jint cached_class_file_length;
+  JvmtiCachedClassFileData *cached_class_file = NULL;
   Handle class_loader(THREAD, loader_data->class_loader());
   bool has_default_methods = false;
   ResourceMark rm(THREAD);
@@ -3680,10 +3679,7 @@
       if (h_class_being_redefined != NULL) {
         instanceKlassHandle ikh_class_being_redefined =
           instanceKlassHandle(THREAD, (*h_class_being_redefined)());
-        cached_class_file_bytes =
-          ikh_class_being_redefined->get_cached_class_file_bytes();
-        cached_class_file_length =
-          ikh_class_being_redefined->get_cached_class_file_len();
+        cached_class_file = ikh_class_being_redefined->get_cached_class_file();
       }
     }
 
@@ -3691,9 +3687,7 @@
     unsigned char* end_ptr = cfs->buffer() + cfs->length();
 
     JvmtiExport::post_class_file_load_hook(name, class_loader(), protection_domain,
-                                           &ptr, &end_ptr,
-                                           &cached_class_file_bytes,
-                                           &cached_class_file_length);
+                                           &ptr, &end_ptr, &cached_class_file);
 
     if (ptr != cfs->buffer()) {
       // JVMTI agent has modified class file data.
@@ -4011,10 +4005,9 @@
       }
     }
 
-    if (cached_class_file_bytes != NULL) {
+    if (cached_class_file != NULL) {
       // JVMTI: we have an InstanceKlass now, tell it about the cached bytes
-      this_klass->set_cached_class_file(cached_class_file_bytes,
-                                        cached_class_file_length);
+      this_klass->set_cached_class_file(cached_class_file);
     }
 
     // Fill in field values obtained by parse_classfile_attributes
--- a/hotspot/src/share/vm/classfile/vmSymbols.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/classfile/vmSymbols.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -53,8 +53,6 @@
   template(java_lang_Object,                          "java/lang/Object")                         \
   template(java_lang_Class,                           "java/lang/Class")                          \
   template(java_lang_String,                          "java/lang/String")                         \
-  template(java_lang_StringValue,                     "java/lang/StringValue")                    \
-  template(java_lang_StringCache,                     "java/lang/StringValue$StringCache")        \
   template(java_lang_Thread,                          "java/lang/Thread")                         \
   template(java_lang_ThreadGroup,                     "java/lang/ThreadGroup")                    \
   template(java_lang_Cloneable,                       "java/lang/Cloneable")                      \
@@ -106,7 +104,6 @@
   template(java_util_Vector,                          "java/util/Vector")                         \
   template(java_util_AbstractList,                    "java/util/AbstractList")                   \
   template(java_util_Hashtable,                       "java/util/Hashtable")                      \
-  template(java_util_HashMap,                         "java/util/HashMap")                        \
   template(java_lang_Compiler,                        "java/lang/Compiler")                       \
   template(sun_misc_Signal,                           "sun/misc/Signal")                          \
   template(java_lang_AssertionStatusDirectives,       "java/lang/AssertionStatusDirectives")      \
@@ -367,8 +364,6 @@
   template(offset_name,                               "offset")                                   \
   template(count_name,                                "count")                                    \
   template(hash_name,                                 "hash")                                     \
-  template(frontCacheEnabled_name,                    "frontCacheEnabled")                        \
-  template(stringCacheEnabled_name,                   "stringCacheEnabled")                       \
   template(numberOfLeadingZeros_name,                 "numberOfLeadingZeros")                     \
   template(numberOfTrailingZeros_name,                "numberOfTrailingZeros")                    \
   template(bitCount_name,                             "bitCount")                                 \
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -873,7 +873,7 @@
   size_t alloc_byte_size = alloc_word_size * HeapWordSize;
 
   if ((cur_used_bytes + alloc_byte_size) > marking_initiating_used_threshold) {
-    if (gcs_are_young()) {
+    if (gcs_are_young() && !_last_young_gc) {
       ergo_verbose5(ErgoConcCycles,
         "request concurrent cycle initiation",
         ergo_format_reason("occupancy higher than threshold")
@@ -931,7 +931,7 @@
   last_pause_included_initial_mark = during_initial_mark_pause();
   if (last_pause_included_initial_mark) {
     record_concurrent_mark_init_end(0.0);
-  } else if (!_last_young_gc && need_to_start_conc_mark("end of GC")) {
+  } else if (need_to_start_conc_mark("end of GC")) {
     // Note: this might have already been set, if during the last
     // pause we decided to start a cycle but at the beginning of
     // this pause we decided to postpone it. That's OK.
--- a/hotspot/src/share/vm/memory/resourceArea.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/memory/resourceArea.hpp	Fri Jul 26 14:01:00 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
@@ -83,6 +83,10 @@
   Chunk *_chunk;                // saved arena chunk
   char *_hwm, *_max;
   size_t _size_in_bytes;
+#ifdef ASSERT
+  Thread* _thread;
+  ResourceMark* _previous_resource_mark;
+#endif //ASSERT
 
   void initialize(Thread *thread) {
     _area = thread->resource_area();
@@ -92,6 +96,11 @@
     _size_in_bytes = _area->size_in_bytes();
     debug_only(_area->_nesting++;)
     assert( _area->_nesting > 0, "must stack allocate RMs" );
+#ifdef ASSERT
+    _thread = thread;
+    _previous_resource_mark = thread->current_resource_mark();
+    thread->set_current_resource_mark(this);
+#endif // ASSERT
   }
  public:
 
@@ -111,6 +120,17 @@
     _size_in_bytes = r->_size_in_bytes;
     debug_only(_area->_nesting++;)
     assert( _area->_nesting > 0, "must stack allocate RMs" );
+#ifdef ASSERT
+    Thread* thread = ThreadLocalStorage::thread();
+    if (thread != NULL) {
+      _thread = thread;
+      _previous_resource_mark = thread->current_resource_mark();
+      thread->set_current_resource_mark(this);
+    } else {
+      _thread = NULL;
+      _previous_resource_mark = NULL;
+    }
+#endif // ASSERT
   }
 
   void reset_to_mark() {
@@ -137,6 +157,11 @@
     assert( _area->_nesting > 0, "must stack allocate RMs" );
     debug_only(_area->_nesting--;)
     reset_to_mark();
+#ifdef ASSERT
+    if (_thread != NULL) {
+      _thread->set_current_resource_mark(_previous_resource_mark);
+    }
+#endif // ASSERT
   }
 
 
--- a/hotspot/src/share/vm/oops/cpCache.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/oops/cpCache.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -140,8 +140,15 @@
     _f1 = f1;
   }
   void release_set_f1(Metadata* f1);
-  void set_f2(intx f2)                           { assert(_f2 == 0 || _f2 == f2,            "illegal field change"); _f2 = f2; }
-  void set_f2_as_vfinal_method(Method* f2)     { assert(_f2 == 0 || _f2 == (intptr_t) f2, "illegal field change"); assert(is_vfinal(), "flags must be set"); _f2 = (intptr_t) f2; }
+  void set_f2(intx f2) {
+    intx existing_f2 = _f2; // read once
+    assert(existing_f2 == 0 || existing_f2 == f2, "illegal field change");
+    _f2 = f2;
+  }
+  void set_f2_as_vfinal_method(Method* f2) {
+    assert(is_vfinal(), "flags must be set");
+    set_f2((intx)f2);
+  }
   int make_flags(TosState state, int option_bits, int field_index_or_method_params);
   void set_flags(intx flags)                     { _flags = flags; }
   bool init_flags_atomic(intx flags);
--- a/hotspot/src/share/vm/oops/instanceKlass.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/oops/instanceKlass.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -48,6 +48,7 @@
 #include "oops/symbol.hpp"
 #include "prims/jvmtiExport.hpp"
 #include "prims/jvmtiRedefineClassesTrace.hpp"
+#include "prims/jvmtiRedefineClasses.hpp"
 #include "prims/methodComparator.hpp"
 #include "runtime/fieldDescriptor.hpp"
 #include "runtime/handles.inline.hpp"
@@ -291,7 +292,7 @@
   set_initial_method_idnum(0);
   _dependencies = NULL;
   set_jvmti_cached_class_field_map(NULL);
-  set_cached_class_file(NULL, 0);
+  set_cached_class_file(NULL);
   set_initial_method_idnum(0);
   set_minor_version(0);
   set_major_version(0);
@@ -2357,10 +2358,9 @@
   }
 
   // deallocate the cached class file
-  if (_cached_class_file_bytes != NULL) {
-    os::free(_cached_class_file_bytes, mtClass);
-    _cached_class_file_bytes = NULL;
-    _cached_class_file_len = 0;
+  if (_cached_class_file != NULL) {
+    os::free(_cached_class_file, mtClass);
+    _cached_class_file = NULL;
   }
 
   // Decrement symbol reference counts associated with the unloaded class.
@@ -3530,6 +3530,14 @@
   return m;
 }
 
+jint InstanceKlass::get_cached_class_file_len() {
+  return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
+}
+
+unsigned char * InstanceKlass::get_cached_class_file_bytes() {
+  return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
+}
+
 
 // Construct a PreviousVersionNode entry for the array hung off
 // the InstanceKlass.
--- a/hotspot/src/share/vm/oops/instanceKlass.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/oops/instanceKlass.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -133,6 +133,8 @@
   uint _count;
 };
 
+struct JvmtiCachedClassFileData;
+
 class InstanceKlass: public Klass {
   friend class VMStructs;
   friend class ClassFileParser;
@@ -249,8 +251,8 @@
   // InstanceKlass. See PreviousVersionWalker below.
   GrowableArray<PreviousVersionNode *>* _previous_versions;
   // JVMTI fields can be moved to their own structure - see 6315920
-  unsigned char * _cached_class_file_bytes;       // JVMTI: cached class file, before retransformable agent modified it in CFLH
-  jint            _cached_class_file_len;         // JVMTI: length of above
+  // JVMTI: cached class file, before retransformable agent modified it in CFLH
+  JvmtiCachedClassFileData* _cached_class_file;
 
   volatile u2     _idnum_allocated_count;         // JNI/JVMTI: increments with the addition of methods, old ids don't change
 
@@ -615,11 +617,12 @@
   static void purge_previous_versions(InstanceKlass* ik);
 
   // JVMTI: Support for caching a class file before it is modified by an agent that can do retransformation
-  void set_cached_class_file(unsigned char *class_file_bytes,
-                             jint class_file_len)     { _cached_class_file_len = class_file_len;
-                                                        _cached_class_file_bytes = class_file_bytes; }
-  jint get_cached_class_file_len()                    { return _cached_class_file_len; }
-  unsigned char * get_cached_class_file_bytes()       { return _cached_class_file_bytes; }
+  void set_cached_class_file(JvmtiCachedClassFileData *data) {
+    _cached_class_file = data;
+  }
+  JvmtiCachedClassFileData * get_cached_class_file() { return _cached_class_file; }
+  jint get_cached_class_file_len();
+  unsigned char * get_cached_class_file_bytes();
 
   // JVMTI: Support for caching of field indices, types, and offsets
   void set_jvmti_cached_class_field_map(JvmtiCachedClassFieldMap* descriptor) {
--- a/hotspot/src/share/vm/oops/method.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/oops/method.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -1163,6 +1163,7 @@
   newm->constMethod()->set_constMethod_size(new_const_method_size);
   newm->set_method_size(new_method_size);
   assert(newm->code_size() == new_code_length, "check");
+  assert(newm->method_parameters_length() == method_parameters_len, "check");
   assert(newm->checked_exceptions_length() == checked_exceptions_len, "check");
   assert(newm->exception_table_length() == exception_table_len, "check");
   assert(newm->localvariable_table_length() == localvariable_len, "check");
@@ -1174,6 +1175,12 @@
            new_compressed_linenumber_table,
            new_compressed_linenumber_size);
   }
+  // Copy method_parameters
+  if (method_parameters_len > 0) {
+    memcpy(newm->method_parameters_start(),
+           m->method_parameters_start(),
+           method_parameters_len * sizeof(MethodParametersElement));
+  }
   // Copy checked_exceptions
   if (checked_exceptions_len > 0) {
     memcpy(newm->checked_exceptions_start(),
--- a/hotspot/src/share/vm/opto/bytecodeInfo.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/opto/bytecodeInfo.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -297,15 +297,6 @@
     }
   }
 
-  if (UseStringCache) {
-    // Do not inline StringCache::profile() method used only at the beginning.
-    if (callee_method->name() == ciSymbol::profile_name() &&
-        callee_method->holder()->name() == ciSymbol::java_lang_StringCache()) {
-      set_msg("profiling method");
-      return true;
-    }
-  }
-
   // use frequency-based objections only for non-trivial methods
   if (callee_method->code_size() <= MaxTrivialSize) {
     return false;
--- a/hotspot/src/share/vm/opto/matcher.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/opto/matcher.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -2305,26 +2305,26 @@
 // atomic instruction acting as a store_load barrier without any
 // intervening volatile load, and thus we don't need a barrier here.
 // We retain the Node to act as a compiler ordering barrier.
-bool Matcher::post_store_load_barrier(const Node *vmb) {
-  Compile *C = Compile::current();
-  assert( vmb->is_MemBar(), "" );
-  assert( vmb->Opcode() != Op_MemBarAcquire, "" );
-  const MemBarNode *mem = (const MemBarNode*)vmb;
+bool Matcher::post_store_load_barrier(const Node* vmb) {
+  Compile* C = Compile::current();
+  assert(vmb->is_MemBar(), "");
+  assert(vmb->Opcode() != Op_MemBarAcquire, "");
+  const MemBarNode* membar = vmb->as_MemBar();
 
-  // Get the Proj node, ctrl, that can be used to iterate forward
-  Node *ctrl = NULL;
-  DUIterator_Fast imax, i = mem->fast_outs(imax);
-  while( true ) {
-    ctrl = mem->fast_out(i);            // Throw out-of-bounds if proj not found
-    assert( ctrl->is_Proj(), "only projections here" );
-    ProjNode *proj = (ProjNode*)ctrl;
-    if( proj->_con == TypeFunc::Control &&
-        !C->node_arena()->contains(ctrl) ) // Unmatched old-space only
+  // Get the Ideal Proj node, ctrl, that can be used to iterate forward
+  Node* ctrl = NULL;
+  for (DUIterator_Fast imax, i = membar->fast_outs(imax); i < imax; i++) {
+    Node* p = membar->fast_out(i);
+    assert(p->is_Proj(), "only projections here");
+    if ((p->as_Proj()->_con == TypeFunc::Control) &&
+        !C->node_arena()->contains(p)) { // Unmatched old-space only
+      ctrl = p;
       break;
-    i++;
+    }
   }
+  assert((ctrl != NULL), "missing control projection");
 
-  for( DUIterator_Fast jmax, j = ctrl->fast_outs(jmax); j < jmax; j++ ) {
+  for (DUIterator_Fast jmax, j = ctrl->fast_outs(jmax); j < jmax; j++) {
     Node *x = ctrl->fast_out(j);
     int xop = x->Opcode();
 
@@ -2336,37 +2336,36 @@
     // that a monitor exit operation contains a serializing instruction.
 
     if (xop == Op_MemBarVolatile ||
-        xop == Op_FastLock ||
         xop == Op_CompareAndSwapL ||
         xop == Op_CompareAndSwapP ||
         xop == Op_CompareAndSwapN ||
-        xop == Op_CompareAndSwapI)
+        xop == Op_CompareAndSwapI) {
       return true;
+    }
+
+    // Op_FastLock previously appeared in the Op_* list above.
+    // With biased locking we're no longer guaranteed that a monitor
+    // enter operation contains a serializing instruction.
+    if ((xop == Op_FastLock) && !UseBiasedLocking) {
+      return true;
+    }
 
     if (x->is_MemBar()) {
       // We must retain this membar if there is an upcoming volatile
-      // load, which will be preceded by acquire membar.
-      if (xop == Op_MemBarAcquire)
+      // load, which will be followed by acquire membar.
+      if (xop == Op_MemBarAcquire) {
         return false;
-      // For other kinds of barriers, check by pretending we
-      // are them, and seeing if we can be removed.
-      else
-        return post_store_load_barrier((const MemBarNode*)x);
+      } else {
+        // For other kinds of barriers, check by pretending we
+        // are them, and seeing if we can be removed.
+        return post_store_load_barrier(x->as_MemBar());
+      }
     }
 
-    // Delicate code to detect case of an upcoming fastlock block
-    if( x->is_If() && x->req() > 1 &&
-        !C->node_arena()->contains(x) ) { // Unmatched old-space only
-      Node *iff = x;
-      Node *bol = iff->in(1);
-      // The iff might be some random subclass of If or bol might be Con-Top
-      if (!bol->is_Bool())  return false;
-      assert( bol->req() > 1, "" );
-      return (bol->in(1)->Opcode() == Op_FastUnlock);
+    // probably not necessary to check for these
+    if (x->is_Call() || x->is_SafePoint() || x->is_block_proj()) {
+      return false;
     }
-    // probably not necessary to check for these
-    if (x->is_Call() || x->is_SafePoint() || x->is_block_proj())
-      return false;
   }
   return false;
 }
--- a/hotspot/src/share/vm/opto/parse3.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/opto/parse3.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -294,25 +294,7 @@
   // If reference is volatile, prevent following volatiles ops from
   // floating up before the volatile write.
   if (is_vol) {
-    // First place the specific membar for THIS volatile index. This first
-    // membar is dependent on the store, keeping any other membars generated
-    // below from floating up past the store.
-    int adr_idx = C->get_alias_index(adr_type);
-    insert_mem_bar_volatile(Op_MemBarVolatile, adr_idx, store);
-
-    // Now place a membar for AliasIdxBot for the unknown yet-to-be-parsed
-    // volatile alias indices. Skip this if the membar is redundant.
-    if (adr_idx != Compile::AliasIdxBot) {
-      insert_mem_bar_volatile(Op_MemBarVolatile, Compile::AliasIdxBot, store);
-    }
-
-    // Finally, place alias-index-specific membars for each volatile index
-    // that isn't the adr_idx membar. Typically there's only 1 or 2.
-    for( int i = Compile::AliasIdxRaw; i < C->num_alias_types(); i++ ) {
-      if (i != adr_idx && C->alias_type(i)->is_volatile()) {
-        insert_mem_bar_volatile(Op_MemBarVolatile, i, store);
-      }
-    }
+    insert_mem_bar(Op_MemBarVolatile); // Use fat membar
   }
 
   // If the field is final, the rules of Java say we are in <init> or <clinit>.
--- a/hotspot/src/share/vm/prims/forte.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/prims/forte.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -31,6 +31,7 @@
 #include "oops/oop.inline.hpp"
 #include "oops/oop.inline2.hpp"
 #include "prims/forte.hpp"
+#include "runtime/javaCalls.hpp"
 #include "runtime/thread.hpp"
 #include "runtime/vframe.hpp"
 #include "runtime/vframeArray.hpp"
@@ -308,10 +309,14 @@
 
   for (loop_count = 0; loop_count < loop_max; loop_count++) {
 
-    if (candidate.is_first_frame()) {
+    if (candidate.is_entry_frame()) {
+      // jcw is NULL if the java call wrapper couldn't be found
+      JavaCallWrapper *jcw = candidate.entry_frame_call_wrapper_if_safe(thread);
       // If initial frame is frame from StubGenerator and there is no
       // previous anchor, there are no java frames associated with a method
-      return false;
+      if (jcw == NULL || jcw->is_first_frame()) {
+        return false;
+      }
     }
 
     if (candidate.is_interpreted_frame()) {
--- a/hotspot/src/share/vm/prims/jniCheck.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/prims/jniCheck.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -126,6 +126,7 @@
 static const char * fatal_non_weak_method = "non-weak methodID passed to JNI call";
 static const char * fatal_unknown_array_object = "Unknown array object passed to JNI array operations";
 static const char * fatal_object_array_expected = "Object array expected but not received for JNI array operation";
+static const char * fatal_prim_type_array_expected = "Primitive type array expected but not received for JNI array operation";
 static const char * fatal_non_array  = "Non-array passed to JNI array operations";
 static const char * fatal_element_type_mismatch = "Array element type mismatch in JNI";
 static const char * fatal_should_be_static = "Non-static field ID passed to JNI";
@@ -278,30 +279,49 @@
     ReportJNIFatalError(thr, fatal_non_string);
 }
 
-static inline void
-checkArray(JavaThread* thr, jarray jArray, int elementType)
+static inline arrayOop
+check_is_array(JavaThread* thr, jarray jArray)
 {
   ASSERT_OOPS_ALLOWED;
   arrayOop aOop;
 
   aOop = (arrayOop)jniCheck::validate_object(thr, jArray);
-  if (aOop == NULL || !aOop->is_array())
+  if (aOop == NULL || !aOop->is_array()) {
     ReportJNIFatalError(thr, fatal_non_array);
+  }
+  return aOop;
+}
+
+static inline arrayOop
+check_is_primitive_array(JavaThread* thr, jarray jArray) {
+  arrayOop aOop = check_is_array(thr, jArray);
 
-  if (elementType != -1) {
-    if (aOop->is_typeArray()) {
-      BasicType array_type = TypeArrayKlass::cast(aOop->klass())->element_type();
-      if (array_type != elementType)
-        ReportJNIFatalError(thr, fatal_element_type_mismatch);
-      } else if (aOop->is_objArray()) {
-        if ( T_OBJECT != elementType)
-          ReportJNIFatalError(thr, fatal_object_array_expected);
-      } else {
-        ReportJNIFatalError(thr, fatal_unknown_array_object);
-    }
+  if (!aOop->is_typeArray()) {
+     ReportJNIFatalError(thr, fatal_prim_type_array_expected);
+  }
+  return aOop;
+}
+
+static inline void
+check_primitive_array_type(JavaThread* thr, jarray jArray, BasicType elementType)
+{
+  BasicType array_type;
+  arrayOop aOop;
+
+  aOop = check_is_primitive_array(thr, jArray);
+  array_type = TypeArrayKlass::cast(aOop->klass())->element_type();
+  if (array_type != elementType) {
+    ReportJNIFatalError(thr, fatal_element_type_mismatch);
   }
 }
 
+static inline void
+check_is_obj_array(JavaThread* thr, jarray jArray) {
+  arrayOop aOop = check_is_array(thr, jArray);
+  if (!aOop->is_objArray()) {
+    ReportJNIFatalError(thr, fatal_object_array_expected);
+  }
+}
 
 oop jniCheck::validate_handle(JavaThread* thr, jobject obj) {
   if (JNIHandles::is_frame_handle(thr, obj) ||
@@ -1417,7 +1437,7 @@
                              jarray array))
     functionEnter(thr);
     IN_VM(
-      checkArray(thr, array, -1);
+      check_is_array(thr, array);
     )
     jsize result = UNCHECKED()->GetArrayLength(env,array);
     functionExit(env);
@@ -1441,7 +1461,7 @@
                                     jsize index))
     functionEnter(thr);
     IN_VM(
-      checkArray(thr, array, T_OBJECT);
+      check_is_obj_array(thr, array);
     )
     jobject result = UNCHECKED()->GetObjectArrayElement(env,array,index);
     functionExit(env);
@@ -1455,7 +1475,7 @@
                                     jobject val))
     functionEnter(thr);
     IN_VM(
-      checkArray(thr, array, T_OBJECT);
+      check_is_obj_array(thr, array);
     )
     UNCHECKED()->SetObjectArrayElement(env,array,index,val);
     functionExit(env);
@@ -1487,7 +1507,7 @@
                                          jboolean *isCopy)) \
     functionEnter(thr); \
     IN_VM( \
-      checkArray(thr, array, ElementTag); \
+      check_primitive_array_type(thr, array, ElementTag); \
     ) \
     ElementType *result = UNCHECKED()->Get##Result##ArrayElements(env, \
                                                                   array, \
@@ -1513,7 +1533,7 @@
                                              jint mode)) \
     functionEnterExceptionAllowed(thr); \
     IN_VM( \
-      checkArray(thr, array, ElementTag); \
+      check_primitive_array_type(thr, array, ElementTag); \
       ASSERT_OOPS_ALLOWED; \
       typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(array)); \
       /* cannot check validity of copy, unless every request is logged by
@@ -1543,7 +1563,7 @@
                                        ElementType *buf)) \
     functionEnter(thr); \
     IN_VM( \
-      checkArray(thr, array, ElementTag); \
+      check_primitive_array_type(thr, array, ElementTag); \
     ) \
     UNCHECKED()->Get##Result##ArrayRegion(env,array,start,len,buf); \
     functionExit(env); \
@@ -1567,7 +1587,7 @@
                                        const ElementType *buf)) \
     functionEnter(thr); \
     IN_VM( \
-      checkArray(thr, array, ElementTag); \
+      check_primitive_array_type(thr, array, ElementTag); \
     ) \
     UNCHECKED()->Set##Result##ArrayRegion(env,array,start,len,buf); \
     functionExit(env); \
@@ -1669,7 +1689,7 @@
                                         jboolean *isCopy))
     functionEnterCritical(thr);
     IN_VM(
-      checkArray(thr, array, -1);
+      check_is_primitive_array(thr, array);
     )
     void *result = UNCHECKED()->GetPrimitiveArrayCritical(env, array, isCopy);
     functionExit(env);
@@ -1683,7 +1703,7 @@
                                             jint mode))
     functionEnterCriticalExceptionAllowed(thr);
     IN_VM(
-      checkArray(thr, array, -1);
+      check_is_primitive_array(thr, array);
     )
     /* The Hotspot JNI code does not use the parameters, so just check the
      * array parameter as a minor sanity check
--- a/hotspot/src/share/vm/prims/jvmtiExport.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiExport.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -41,6 +41,7 @@
 #include "prims/jvmtiRawMonitor.hpp"
 #include "prims/jvmtiTagMap.hpp"
 #include "prims/jvmtiThreadState.inline.hpp"
+#include "prims/jvmtiRedefineClasses.hpp"
 #include "runtime/arguments.hpp"
 #include "runtime/handles.hpp"
 #include "runtime/interfaceSupport.hpp"
@@ -516,8 +517,7 @@
   jint                 _curr_len;
   unsigned char *      _curr_data;
   JvmtiEnv *           _curr_env;
-  jint *               _cached_length_ptr;
-  unsigned char **     _cached_data_ptr;
+  JvmtiCachedClassFileData ** _cached_class_file_ptr;
   JvmtiThreadState *   _state;
   KlassHandle *        _h_class_being_redefined;
   JvmtiClassLoadKind   _load_kind;
@@ -526,8 +526,7 @@
   inline JvmtiClassFileLoadHookPoster(Symbol* h_name, Handle class_loader,
                                       Handle h_protection_domain,
                                       unsigned char **data_ptr, unsigned char **end_ptr,
-                                      unsigned char **cached_data_ptr,
-                                      jint *cached_length_ptr) {
+                                      JvmtiCachedClassFileData **cache_ptr) {
     _h_name = h_name;
     _class_loader = class_loader;
     _h_protection_domain = h_protection_domain;
@@ -537,8 +536,7 @@
     _curr_len = *end_ptr - *data_ptr;
     _curr_data = *data_ptr;
     _curr_env = NULL;
-    _cached_length_ptr = cached_length_ptr;
-    _cached_data_ptr = cached_data_ptr;
+    _cached_class_file_ptr = cache_ptr;
 
     _state = _thread->jvmti_thread_state();
     if (_state != NULL) {
@@ -615,15 +613,20 @@
     }
     if (new_data != NULL) {
       // this agent has modified class data.
-      if (caching_needed && *_cached_data_ptr == NULL) {
+      if (caching_needed && *_cached_class_file_ptr == NULL) {
         // data has been changed by the new retransformable agent
         // and it hasn't already been cached, cache it
-        *_cached_data_ptr = (unsigned char *)os::malloc(_curr_len, mtInternal);
-        if (*_cached_data_ptr == NULL) {
-          vm_exit_out_of_memory(_curr_len, OOM_MALLOC_ERROR, "unable to allocate cached copy of original class bytes");
+        JvmtiCachedClassFileData *p;
+        p = (JvmtiCachedClassFileData *)os::malloc(
+          offset_of(JvmtiCachedClassFileData, data) + _curr_len, mtInternal);
+        if (p == NULL) {
+          vm_exit_out_of_memory(offset_of(JvmtiCachedClassFileData, data) + _curr_len,
+            OOM_MALLOC_ERROR,
+            "unable to allocate cached copy of original class bytes");
         }
-        memcpy(*_cached_data_ptr, _curr_data, _curr_len);
-        *_cached_length_ptr = _curr_len;
+        p->length = _curr_len;
+        memcpy(p->data, _curr_data, _curr_len);
+        *_cached_class_file_ptr = p;
       }
 
       if (_curr_data != *_data_ptr) {
@@ -662,13 +665,11 @@
                                             Handle h_protection_domain,
                                             unsigned char **data_ptr,
                                             unsigned char **end_ptr,
-                                            unsigned char **cached_data_ptr,
-                                            jint *cached_length_ptr) {
+                                            JvmtiCachedClassFileData **cache_ptr) {
   JvmtiClassFileLoadHookPoster poster(h_name, class_loader,
                                       h_protection_domain,
                                       data_ptr, end_ptr,
-                                      cached_data_ptr,
-                                      cached_length_ptr);
+                                      cache_ptr);
   poster.post();
 }
 
--- a/hotspot/src/share/vm/prims/jvmtiExport.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiExport.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -323,8 +323,7 @@
   static void post_class_file_load_hook(Symbol* h_name, Handle class_loader,
                                         Handle h_protection_domain,
                                         unsigned char **data_ptr, unsigned char **end_ptr,
-                                        unsigned char **cached_data_ptr,
-                                        jint *cached_length_ptr) NOT_JVMTI_RETURN;
+                                        JvmtiCachedClassFileData **cache_ptr) NOT_JVMTI_RETURN;
   static void post_native_method_bind(Method* method, address* function_ptr) NOT_JVMTI_RETURN;
   static void post_compiled_method_load(nmethod *nm) NOT_JVMTI_RETURN;
   static void post_dynamic_code_generated(const char *name, const void *code_begin, const void *code_end) NOT_JVMTI_RETURN;
--- a/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -3342,9 +3342,7 @@
   // should get cleared in the_class too.
   if (the_class->get_cached_class_file_bytes() == 0) {
     // the_class doesn't have a cache yet so copy it
-    the_class->set_cached_class_file(
-      scratch_class->get_cached_class_file_bytes(),
-      scratch_class->get_cached_class_file_len());
+    the_class->set_cached_class_file(scratch_class->get_cached_class_file());
   }
 #ifndef PRODUCT
   else {
@@ -3357,7 +3355,7 @@
 
   // NULL out in scratch class to not delete twice.  The class to be redefined
   // always owns these bytes.
-  scratch_class->set_cached_class_file(NULL, 0);
+  scratch_class->set_cached_class_file(NULL);
 
   // Replace inner_classes
   Array<u2>* old_inner_classes = the_class->inner_classes();
--- a/hotspot/src/share/vm/prims/jvmtiRedefineClasses.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiRedefineClasses.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -331,6 +331,11 @@
 //   coordinate a cleanup of these constants with Runtime.
 //
 
+struct JvmtiCachedClassFileData {
+  jint length;
+  unsigned char data[1];
+};
+
 class VM_RedefineClasses: public VM_Operation {
  private:
   // These static fields are needed by ClassLoaderDataGraph::classes_do()
@@ -509,5 +514,12 @@
   // Modifiable test must be shared between IsModifiableClass query
   // and redefine implementation
   static bool is_modifiable_class(oop klass_mirror);
+
+  static jint get_cached_class_file_len(JvmtiCachedClassFileData *cache) {
+    return cache == NULL ? 0 : cache->length;
+  }
+  static unsigned char * get_cached_class_file_bytes(JvmtiCachedClassFileData *cache) {
+    return cache == NULL ? NULL : cache->data;
+  }
 };
 #endif // SHARE_VM_PRIMS_JVMTIREDEFINECLASSES_HPP
--- a/hotspot/src/share/vm/runtime/arguments.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/runtime/arguments.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -263,6 +263,7 @@
   { "UseISM",                        JDK_Version::jdk(8), JDK_Version::jdk(9) },
   { "UsePermISM",                    JDK_Version::jdk(8), JDK_Version::jdk(9) },
   { "UseMPSS",                       JDK_Version::jdk(8), JDK_Version::jdk(9) },
+  { "UseStringCache",                JDK_Version::jdk(8), JDK_Version::jdk(9) },
 #ifdef PRODUCT
   { "DesiredMethodLimit",
                            JDK_Version::jdk_update(7, 2), JDK_Version::jdk(8) },
--- a/hotspot/src/share/vm/runtime/frame.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/runtime/frame.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -221,9 +221,20 @@
 
 
 bool frame::entry_frame_is_first() const {
-  return entry_frame_call_wrapper()->anchor()->last_Java_sp() == NULL;
+  return entry_frame_call_wrapper()->is_first_frame();
 }
 
+JavaCallWrapper* frame::entry_frame_call_wrapper_if_safe(JavaThread* thread) const {
+  JavaCallWrapper** jcw = entry_frame_call_wrapper_addr();
+  address addr = (address) jcw;
+
+  // addr must be within the usable part of the stack
+  if (thread->is_in_usable_stack(addr)) {
+    return *jcw;
+  }
+
+  return NULL;
+}
 
 bool frame::should_be_deoptimized() const {
   if (_deopt_state == is_deoptimized ||
--- a/hotspot/src/share/vm/runtime/frame.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/runtime/frame.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -353,7 +353,9 @@
 
  public:
   // Entry frames
-  JavaCallWrapper* entry_frame_call_wrapper() const;
+  JavaCallWrapper* entry_frame_call_wrapper() const { return *entry_frame_call_wrapper_addr(); }
+  JavaCallWrapper* entry_frame_call_wrapper_if_safe(JavaThread* thread) const;
+  JavaCallWrapper** entry_frame_call_wrapper_addr() const;
   intptr_t* entry_frame_argument_at(int offset) const;
 
   // tells whether there is another chunk of Delta stack above
--- a/hotspot/src/share/vm/runtime/globals.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/runtime/globals.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -2589,9 +2589,6 @@
   product(bool, AggressiveOpts, false,                                      \
           "Enable aggressive optimizations - see arguments.cpp")            \
                                                                             \
-  product(bool, UseStringCache, false,                                      \
-          "Enable String cache capabilities on String.java")                \
-                                                                            \
   /* statistics */                                                          \
   develop(bool, CountCompiledCalls, false,                                  \
           "counts method invocations")                                      \
--- a/hotspot/src/share/vm/runtime/javaCalls.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/runtime/javaCalls.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -80,6 +80,8 @@
   oop              receiver()               { return _receiver; }
   void             oops_do(OopClosure* f);
 
+  bool             is_first_frame() const   { return _anchor.last_Java_sp() == NULL; }
+
 };
 
 
--- a/hotspot/src/share/vm/runtime/mutex.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/runtime/mutex.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -1370,6 +1370,10 @@
     debug_only(if (rank() != Mutex::special) \
       thread->check_for_valid_safepoint_state(false);)
   }
+  if (thread->is_Watcher_thread()) {
+    assert(!WatcherThread::watcher_thread()->has_crash_protection(),
+        "locking not allowed when crash protection is set");
+  }
 }
 
 void Monitor::check_block_state(Thread *thread) {
--- a/hotspot/src/share/vm/runtime/os.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/runtime/os.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -595,6 +595,22 @@
   NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
   NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
 
+#ifdef ASSERT
+  // checking for the WatcherThread and crash_protection first
+  // since os::malloc can be called when the libjvm.{dll,so} is
+  // first loaded and we don't have a thread yet.
+  // try to find the thread after we see that the watcher thread
+  // exists and has crash protection.
+  WatcherThread *wt = WatcherThread::watcher_thread();
+  if (wt != NULL && wt->has_crash_protection()) {
+    Thread* thread = ThreadLocalStorage::get_thread_slow();
+    if (thread == wt) {
+      assert(!wt->has_crash_protection(),
+          "Can't malloc with crash protection from WatcherThread");
+    }
+  }
+#endif
+
   if (size == 0) {
     // return a valid pointer if size is zero
     // if NULL is returned the calling functions assume out of memory.
--- a/hotspot/src/share/vm/runtime/os.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/runtime/os.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -32,15 +32,18 @@
 #include "utilities/top.hpp"
 #ifdef TARGET_OS_FAMILY_linux
 # include "jvm_linux.h"
+# include <setjmp.h>
 #endif
 #ifdef TARGET_OS_FAMILY_solaris
 # include "jvm_solaris.h"
+# include <setjmp.h>
 #endif
 #ifdef TARGET_OS_FAMILY_windows
 # include "jvm_windows.h"
 #endif
 #ifdef TARGET_OS_FAMILY_bsd
 # include "jvm_bsd.h"
+# include <setjmp.h>
 #endif
 
 // os defines the interface to operating system; this includes traditional
@@ -730,6 +733,10 @@
 #include "runtime/os_ext.hpp"
 
  public:
+  class CrashProtectionCallback : public StackObj {
+  public:
+    virtual void call() = 0;
+  };
 
   // Platform dependent stuff
 #ifdef TARGET_OS_FAMILY_linux
@@ -908,6 +915,7 @@
                                 char pathSep);
   static bool set_boot_path(char fileSep, char pathSep);
   static char** split_path(const char* path, int* n);
+
 };
 
 // Note that "PAUSE" is almost always used with synchronization
@@ -915,8 +923,6 @@
 // of the global SpinPause() with C linkage.
 // It'd also be eligible for inlining on many platforms.
 
-extern "C" int SpinPause () ;
-extern "C" int SafeFetch32 (int * adr, int errValue) ;
-extern "C" intptr_t SafeFetchN (intptr_t * adr, intptr_t errValue) ;
+extern "C" int SpinPause();
 
 #endif // SHARE_VM_RUNTIME_OS_HPP
--- a/hotspot/src/share/vm/runtime/stubRoutines.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/runtime/stubRoutines.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -136,6 +136,13 @@
 double (* StubRoutines::_intrinsic_cos   )(double) = NULL;
 double (* StubRoutines::_intrinsic_tan   )(double) = NULL;
 
+address StubRoutines::_safefetch32_entry                 = NULL;
+address StubRoutines::_safefetch32_fault_pc              = NULL;
+address StubRoutines::_safefetch32_continuation_pc       = NULL;
+address StubRoutines::_safefetchN_entry                  = NULL;
+address StubRoutines::_safefetchN_fault_pc               = NULL;
+address StubRoutines::_safefetchN_continuation_pc        = NULL;
+
 // Initialization
 //
 // Note: to break cycle with universe initialization, stubs are generated in two phases.
--- a/hotspot/src/share/vm/runtime/stubRoutines.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/runtime/stubRoutines.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -221,6 +221,14 @@
   static double (*_intrinsic_cos)(double);
   static double (*_intrinsic_tan)(double);
 
+  // Safefetch stubs.
+  static address _safefetch32_entry;
+  static address _safefetch32_fault_pc;
+  static address _safefetch32_continuation_pc;
+  static address _safefetchN_entry;
+  static address _safefetchN_fault_pc;
+  static address _safefetchN_continuation_pc;
+
  public:
   // Initialization/Testing
   static void    initialize1();                            // must happen before universe::genesis
@@ -382,6 +390,34 @@
   }
 
   //
+  // Safefetch stub support
+  //
+
+  typedef int      (*SafeFetch32Stub)(int*      adr, int      errValue);
+  typedef intptr_t (*SafeFetchNStub) (intptr_t* adr, intptr_t errValue);
+
+  static SafeFetch32Stub SafeFetch32_stub() { return CAST_TO_FN_PTR(SafeFetch32Stub, _safefetch32_entry); }
+  static SafeFetchNStub  SafeFetchN_stub()  { return CAST_TO_FN_PTR(SafeFetchNStub,  _safefetchN_entry); }
+
+  static bool is_safefetch_fault(address pc) {
+    return pc != NULL &&
+          (pc == _safefetch32_fault_pc ||
+           pc == _safefetchN_fault_pc);
+  }
+
+  static address continuation_for_safefetch_fault(address pc) {
+    assert(_safefetch32_continuation_pc != NULL &&
+           _safefetchN_continuation_pc  != NULL,
+           "not initialized");
+
+    if (pc == _safefetch32_fault_pc) return _safefetch32_continuation_pc;
+    if (pc == _safefetchN_fault_pc)  return _safefetchN_continuation_pc;
+
+    ShouldNotReachHere();
+    return NULL;
+  }
+
+  //
   // Default versions of the above arraycopy functions for platforms which do
   // not have specialized versions
   //
@@ -400,4 +436,15 @@
   static void arrayof_oop_copy_uninit(HeapWord* src, HeapWord* dest, size_t count);
 };
 
+// Safefetch allows to load a value from a location that's not known
+// to be valid. If the load causes a fault, the error value is returned.
+inline int SafeFetch32(int* adr, int errValue) {
+  assert(StubRoutines::SafeFetch32_stub(), "stub not yet generated");
+  return StubRoutines::SafeFetch32_stub()(adr, errValue);
+}
+inline intptr_t SafeFetchN(intptr_t* adr, intptr_t errValue) {
+  assert(StubRoutines::SafeFetchN_stub(), "stub not yet generated");
+  return StubRoutines::SafeFetchN_stub()(adr, errValue);
+}
+
 #endif // SHARE_VM_RUNTIME_STUBROUTINES_HPP
--- a/hotspot/src/share/vm/runtime/thread.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/runtime/thread.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -218,6 +218,7 @@
   // allocated data structures
   set_osthread(NULL);
   set_resource_area(new (mtThread)ResourceArea());
+  DEBUG_ONLY(_current_resource_mark = NULL;)
   set_handle_area(new (mtThread) HandleArea(NULL));
   set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, true));
   set_active_handles(NULL);
@@ -953,6 +954,14 @@
 }
 
 
+bool Thread::is_in_usable_stack(address adr) const {
+  size_t stack_guard_size = os::uses_stack_guard_pages() ? (StackYellowPages + StackRedPages) * os::vm_page_size() : 0;
+  size_t usable_stack_size = _stack_size - stack_guard_size;
+
+  return ((adr < stack_base()) && (adr >= stack_base() - usable_stack_size));
+}
+
+
 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter
 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being
 // used for compilation in the future. If that change is made, the need for these methods
@@ -1217,7 +1226,7 @@
 bool WatcherThread::_startable = false;
 volatile bool  WatcherThread::_should_terminate = false;
 
-WatcherThread::WatcherThread() : Thread() {
+WatcherThread::WatcherThread() : Thread(), _crash_protection(NULL) {
   assert(watcher_thread() == NULL, "we can only allocate one WatcherThread");
   if (os::create_thread(this, os::watcher_thread)) {
     _watcher_thread = this;
@@ -3481,44 +3490,6 @@
 
     initialize_class(vmSymbols::java_lang_String(), CHECK_0);
 
-    if (AggressiveOpts) {
-      {
-        // Forcibly initialize java/util/HashMap and mutate the private
-        // static final "frontCacheEnabled" field before we start creating instances
-#ifdef ASSERT
-        Klass* tmp_k = SystemDictionary::find(vmSymbols::java_util_HashMap(), Handle(), Handle(), CHECK_0);
-        assert(tmp_k == NULL, "java/util/HashMap should not be loaded yet");
-#endif
-        Klass* k_o = SystemDictionary::resolve_or_null(vmSymbols::java_util_HashMap(), Handle(), Handle(), CHECK_0);
-        KlassHandle k = KlassHandle(THREAD, k_o);
-        guarantee(k.not_null(), "Must find java/util/HashMap");
-        instanceKlassHandle ik = instanceKlassHandle(THREAD, k());
-        ik->initialize(CHECK_0);
-        fieldDescriptor fd;
-        // Possible we might not find this field; if so, don't break
-        if (ik->find_local_field(vmSymbols::frontCacheEnabled_name(), vmSymbols::bool_signature(), &fd)) {
-          k()->java_mirror()->bool_field_put(fd.offset(), true);
-        }
-      }
-
-      if (UseStringCache) {
-        // Forcibly initialize java/lang/StringValue and mutate the private
-        // static final "stringCacheEnabled" field before we start creating instances
-        Klass* k_o = SystemDictionary::resolve_or_null(vmSymbols::java_lang_StringValue(), Handle(), Handle(), CHECK_0);
-        // Possible that StringValue isn't present: if so, silently don't break
-        if (k_o != NULL) {
-          KlassHandle k = KlassHandle(THREAD, k_o);
-          instanceKlassHandle ik = instanceKlassHandle(THREAD, k());
-          ik->initialize(CHECK_0);
-          fieldDescriptor fd;
-          // Possible we might not find this field: if so, silently don't break
-          if (ik->find_local_field(vmSymbols::stringCacheEnabled_name(), vmSymbols::bool_signature(), &fd)) {
-            k()->java_mirror()->bool_field_put(fd.offset(), true);
-          }
-        }
-      }
-    }
-
     // Initialize java_lang.System (needed before creating the thread)
     initialize_class(vmSymbols::java_lang_System(), CHECK_0);
     initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK_0);
@@ -3636,6 +3607,7 @@
 
   // Start Attach Listener if +StartAttachListener or it can't be started lazily
   if (!DisableAttachMechanism) {
+    AttachListener::vm_start();
     if (StartAttachListener || AttachListener::init_at_startup()) {
       AttachListener::init();
     }
--- a/hotspot/src/share/vm/runtime/thread.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/runtime/thread.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -86,6 +86,8 @@
 class ThreadClosure;
 class IdealGraphPrinter;
 
+DEBUG_ONLY(class ResourceMark;)
+
 class WorkerThread;
 
 // Class hierarchy
@@ -519,6 +521,9 @@
   // Check if address is in the stack of the thread (not just for locks).
   // Warning: the method can only be used on the running thread
   bool is_in_stack(address adr) const;
+  // Check if address is in the usable part of the stack (excludes protected
+  // guard pages)
+  bool is_in_usable_stack(address adr) const;
 
   // Sets this thread as starting thread. Returns failure if thread
   // creation fails due to lack of memory, too many threads etc.
@@ -531,6 +536,8 @@
   // Thread local resource area for temporary allocation within the VM
   ResourceArea* _resource_area;
 
+  DEBUG_ONLY(ResourceMark* _current_resource_mark;)
+
   // Thread local handle area for allocation of handles within the VM
   HandleArea* _handle_area;
   GrowableArray<Metadata*>* _metadata_handles;
@@ -585,6 +592,8 @@
 
   // Deadlock detection
   bool allow_allocation()                        { return _allow_allocation_count == 0; }
+  ResourceMark* current_resource_mark()          { return _current_resource_mark; }
+  void set_current_resource_mark(ResourceMark* rm) { _current_resource_mark = rm; }
 #endif
 
   void check_for_valid_safepoint_state(bool potential_vm_operation) PRODUCT_RETURN;
@@ -724,6 +733,8 @@
 
   static bool _startable;
   volatile static bool _should_terminate; // updated without holding lock
+
+  os::WatcherThreadCrashProtection* _crash_protection;
  public:
   enum SomeConstants {
     delay_interval = 10                          // interrupt delay in milliseconds
@@ -751,6 +762,14 @@
   // Otherwise the first task to enroll will trigger the start
   static void make_startable();
 
+  void set_crash_protection(os::WatcherThreadCrashProtection* crash_protection) {
+    assert(Thread::current()->is_Watcher_thread(), "Can only be set by WatcherThread");
+    _crash_protection = crash_protection;
+  }
+
+  bool has_crash_protection() const { return _crash_protection != NULL; }
+  os::WatcherThreadCrashProtection* crash_protection() const { return _crash_protection; }
+
  private:
   int sleep() const;
 };
--- a/hotspot/src/share/vm/services/attachListener.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/services/attachListener.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -50,6 +50,7 @@
 
 class AttachListener: AllStatic {
  public:
+  static void vm_start() NOT_SERVICES_RETURN;
   static void init()  NOT_SERVICES_RETURN;
   static void abort() NOT_SERVICES_RETURN;
 
--- a/hotspot/src/share/vm/services/memTracker.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/services/memTracker.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -81,13 +81,13 @@
   } else if (strcmp(option_line, "=detail") == 0) {
     // detail relies on a stack-walking ability that may not
     // be available depending on platform and/or compiler flags
-    if (PLATFORM_NMT_DETAIL_SUPPORTED) {
+#if PLATFORM_NATIVE_STACK_WALKING_SUPPORTED
       _tracking_level = NMT_detail;
-    } else {
+#else
       jio_fprintf(defaultStream::error_stream(),
-        "NMT detail is not supported on this platform.  Using NMT summary instead.");
+        "NMT detail is not supported on this platform.  Using NMT summary instead.\n");
       _tracking_level = NMT_summary;
-    }
+#endif
   } else if (strcmp(option_line, "=off") != 0) {
     vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
   }
@@ -385,6 +385,7 @@
 #define SAFE_SEQUENCE_THRESHOLD    30
 #define HIGH_GENERATION_THRESHOLD  60
 #define MAX_RECORDER_THREAD_RATIO  30
+#define MAX_RECORDER_PER_THREAD    100
 
 void MemTracker::sync() {
   assert(_tracking_level > NMT_off, "NMT is not enabled");
@@ -437,6 +438,11 @@
         // means that worker thread is lagging behind in processing them.
         if (!AutoShutdownNMT) {
           _slowdown_calling_thread = (MemRecorder::_instance_count > MAX_RECORDER_THREAD_RATIO * _thread_count);
+        } else {
+          // If auto shutdown is on, enforce MAX_RECORDER_PER_THREAD threshold to prevent OOM
+          if (MemRecorder::_instance_count >= _thread_count * MAX_RECORDER_PER_THREAD) {
+            shutdown(NMT_out_of_memory);
+          }
         }
 
         // check _worker_thread with lock to avoid racing condition
--- a/hotspot/src/share/vm/trace/traceDataTypes.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/trace/traceDataTypes.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -63,5 +63,7 @@
 typedef u8 methodid;
 typedef u8 fieldid;
 
+class TraceUnicodeString;
+
 #endif // SHARE_VM_TRACE_TRACEDATATYPES_HPP
 
--- a/hotspot/src/share/vm/trace/tracetypes.xml	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/trace/tracetypes.xml	Fri Jul 26 14:01:00 2013 -0700
@@ -55,18 +55,6 @@
               type="u8" sizeop="sizeof(u1)"/>
 
 Now we can use the content + data type in declaring event fields.
-Remember however, that for us to be able to resolve the value later we must also add
-creating the constant pool data in  VM_JFRCheckpoint::write_checkpoint
-
-   ...
-   //CGMODE
-   w->be_uint(CONTENT_TYPE_GCMODE);
-   w->be_uint(MM_GC_MODE_UNINITIALIZED);
-   for (i = 0; i < MM_GC_MODE_UNINITIALIZED; i++) {
-      w->uchar(i);
-      w->write_utf8(gcModeGetName(i));
-   }
-
  -->
 
  <types>
@@ -81,10 +69,6 @@
       <value type="OSTHREAD" field="thread" label="VM Thread"/>
     </content_type>
 
-    <!-- The first argument ("JavaThread") is misleading, it's really a
-         java.lang.Thread id (long), but Mission Control depends on the name
-         being "JavaThread" so it shouldn't be changed.
-    -->
     <content_type id="JavaThread" hr_name="Java thread"
                   type="U8" builtin_type="JAVALANGTHREAD">
       <value type="OSTHREAD" field="thread" label="OS Thread ID"/>
@@ -285,6 +269,10 @@
     <primary_type symbol="UTF8" datatype="UTF8" contenttype="NONE"
                   type="const char *" sizeop="sizeof_utf(%)"/>
 
+    <!-- UTF-16 encoded (Unicode) string, max length maxjuint -->
+    <primary_type symbol="STRING" datatype="STRING" contenttype="NONE"
+                  type="TraceUnicodeString*" sizeop="sizeof_unicode(%)"/>
+
     <!-- Symbol* constant. Note that this may currently ONLY be used by
           classes, methods fields.  This restriction might be lifted. -->
     <primary_type symbol="SYMBOL" datatype="U8" contenttype="SYMBOL"
--- a/hotspot/src/share/vm/trace/xinclude.mod	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/trace/xinclude.mod	Fri Jul 26 14:01:00 2013 -0700
@@ -22,30 +22,6 @@
  questions.
   
 -->
-
-<!--
- 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.
-  
--->
 <!ELEMENT xi:include (xi:fallback?) >
 <!ATTLIST xi:include
     xmlns:xi   CDATA       #FIXED    "http://www.w3.org/2001/XInclude"
--- a/hotspot/src/share/vm/utilities/globalDefinitions.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/utilities/globalDefinitions.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -381,12 +381,12 @@
 #endif
 
 /*
- * If a platform does not support NMT_detail
+ * If a platform does not support native stack walking
  * the platform specific globalDefinitions (above)
- * can set PLATFORM_NMT_DETAIL_SUPPORTED to false
+ * can set PLATFORM_NATIVE_STACK_WALKING_SUPPORTED to 0
  */
-#ifndef PLATFORM_NMT_DETAIL_SUPPORTED
-#define PLATFORM_NMT_DETAIL_SUPPORTED true
+#ifndef PLATFORM_NATIVE_STACK_WALKING_SUPPORTED
+#define PLATFORM_NATIVE_STACK_WALKING_SUPPORTED 1
 #endif
 
 // The byte alignment to be used by Arena::Amalloc.  See bugid 4169348.
--- a/hotspot/src/share/vm/utilities/ostream.cpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/utilities/ostream.cpp	Fri Jul 26 14:01:00 2013 -0700
@@ -296,6 +296,7 @@
   buffer        = NEW_RESOURCE_ARRAY(char, buffer_length);
   buffer_pos    = 0;
   buffer_fixed  = false;
+  DEBUG_ONLY(rm = Thread::current()->current_resource_mark();)
 }
 
 // useful for output to fixed chunks of memory, such as performance counters
@@ -321,6 +322,8 @@
         end = buffer_length * 2;
       }
       char* oldbuf = buffer;
+      assert(rm == NULL || Thread::current()->current_resource_mark() == rm,
+             "stringStream is re-allocated with a different ResourceMark");
       buffer = NEW_RESOURCE_ARRAY(char, end);
       strncpy(buffer, oldbuf, buffer_pos);
       buffer_length = end;
--- a/hotspot/src/share/vm/utilities/ostream.hpp	Thu Jul 25 13:02:37 2013 -0700
+++ b/hotspot/src/share/vm/utilities/ostream.hpp	Fri Jul 26 14:01:00 2013 -0700
@@ -28,6 +28,8 @@
 #include "memory/allocation.hpp"
 #include "runtime/timer.hpp"
 
+DEBUG_ONLY(class ResourceMark;)
+
 // Output streams for printing
 //
 // Printing guidelines:
@@ -177,6 +179,7 @@
   size_t buffer_pos;
   size_t buffer_length;
   bool   buffer_fixed;
+  DEBUG_ONLY(ResourceMark* rm;)
  public:
   stringStream(size_t initial_bufsize = 256);
   stringStream(char* fixed_buffer, size_t fixed_buffer_size);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/EscapeAnalysis/Test8020215.java	Fri Jul 26 14:01:00 2013 -0700
@@ -0,0 +1,82 @@
+/*
+ * 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 8020215
+ * @summary Different execution plan when using JIT vs interpreter
+ * @run main Test8020215
+ */
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Test8020215 {
+    public static class NamedObject {
+        public int id;
+        public String name;
+        public NamedObject(int id, String name) {
+            this.id = id;
+            this.name = name;
+        }
+    }
+
+    public static class NamedObjectList {
+        public List<NamedObject> namedObjectList = new ArrayList<NamedObject>();
+
+        public NamedObject getBest(int id) {
+            NamedObject bestObject = null;
+            for (NamedObject o : namedObjectList) {
+                bestObject = id==o.id ? getBetter(bestObject, o) : bestObject;
+            }
+            return (bestObject != null) ? bestObject : null;
+        }
+
+        private static NamedObject getBetter(NamedObject p1, NamedObject p2) {
+            return (p1 == null) ? p2 : (p2 == null) ? p1 : (p2.name.compareTo(p1.name) >= 0) ? p2 : p1;
+        }
+    }
+
+    static void test(NamedObjectList b, int i) {
+        NamedObject x = b.getBest(2);
+        // test
+        if (x == null) {
+            throw new RuntimeException("x should never be null here! (i=" + i + ")");
+        }
+    }
+
+    public static void main(String[] args) {
+        // setup
+        NamedObjectList b = new NamedObjectList();
+        for (int i = 0; i < 10000; i++) {
+            b.namedObjectList.add(new NamedObject(1, "2012-12-31"));
+        }
+        b.namedObjectList.add(new NamedObject(2, "2013-12-31"));
+
+        // execution
+        for (int i = 0; i < 12000; i++) {
+            test(b, i);
+        }
+        System.out.println("PASSED");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/cpuflags/RestoreMXCSR.java	Fri Jul 26 14:01:00 2013 -0700
@@ -0,0 +1,42 @@
+/*
+ * 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 8020433
+ * @summary Crash when using -XX:+RestoreMXCSROnJNICalls
+ * @library /testlibrary
+ *
+ */
+import com.oracle.java.testlibrary.*;
+
+public class RestoreMXCSR {
+  public static void main(String[] args) throws Exception {
+    ProcessBuilder pb;
+    OutputAnalyzer out;
+
+    pb = ProcessTools.createJavaProcessBuilder("-XX:+RestoreMXCSROnJNICalls", "-version");
+    out = new OutputAnalyzer(pb.start());
+    out.shouldHaveExitValue(0);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/membars/DekkerTest.java	Fri Jul 26 14:01:00 2013 -0700
@@ -0,0 +1,163 @@
+/*
+ * Copyright 2013 SAP AG.  All Rights Reserved.
+ * 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 8007898
+ * @summary Incorrect optimization of Memory Barriers in Matcher::post_store_load_barrier().
+ * @run main/othervm -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:CICompilerCount=1 -XX:+StressGCM -XX:+StressLCM DekkerTest
+ * @run main/othervm -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:CICompilerCount=1 -XX:+StressGCM -XX:+StressLCM DekkerTest
+ * @run main/othervm -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:CICompilerCount=1 -XX:+StressGCM -XX:+StressLCM DekkerTest
+ * @author Martin Doerr martin DOT doerr AT sap DOT com
+ *
+ * Run 3 times since the failure is intermittent.
+ */
+
+public class DekkerTest {
+
+    /*
+      Read After Write Test (basically a simple Dekker test with volatile variables)
+      Derived from the original jcstress test, available at:
+        http://hg.openjdk.java.net/code-tools/jcstress/file/6c339a5aa00d/
+        tests-custom/src/main/java/org/openjdk/jcstress/tests/volatiles/DekkerTest.java
+     */
+
+    static final int ITERATIONS = 1000000;
+
+    static class TestData {
+        public volatile int a;
+        public volatile int b;
+    }
+
+    static class ResultData {
+        public int a;
+        public int b;
+    }
+
+    TestData[]   testDataArray;
+    ResultData[] results;
+
+    volatile boolean start;
+
+    public DekkerTest() {
+        testDataArray = new TestData[ITERATIONS];
+        results = new ResultData[ITERATIONS];
+        for (int i = 0; i < ITERATIONS; ++i) {
+            testDataArray[i] = new TestData();
+            results[i] = new ResultData();
+        }
+        start = false;
+    }
+
+    public void reset() {
+        for (int i = 0; i < ITERATIONS; ++i) {
+            testDataArray[i].a = 0;
+            testDataArray[i].b = 0;
+            results[i].a = 0;
+            results[i].b = 0;
+        }
+        start = false;
+    }
+
+    int actor1(TestData t) {
+        t.a = 1;
+        return t.b;
+    }
+
+    int actor2(TestData t) {
+        t.b = 1;
+        return t.a;
+    }
+
+    class Runner1 extends Thread {
+        public void run() {
+            do {} while (!start);
+            for (int i = 0; i < ITERATIONS; ++i) {
+                results[i].a = actor1(testDataArray[i]);
+            }
+        }
+    }
+
+    class Runner2 extends Thread {
+        public void run() {
+            do {} while (!start);
+            for (int i = 0; i < ITERATIONS; ++i) {
+                results[i].b = actor2(testDataArray[i]);
+            }
+        }
+    }
+
+    void testRunner() {
+        Thread thread1 = new Runner1();
+        Thread thread2 = new Runner2();
+        thread1.start();
+        thread2.start();
+        do {} while (!thread1.isAlive());
+        do {} while (!thread2.isAlive());
+        start = true;
+        Thread.yield();
+        try {
+            thread1.join();
+            thread2.join();
+        } catch (InterruptedException e) {
+            System.out.println("interrupted!");
+            System.exit(1);
+        }
+    }
+
+    boolean printResult() {
+        int[] count = new int[4];
+        for (int i = 0; i < ITERATIONS; ++i) {
+            int event_kind = (results[i].a << 1) + results[i].b;
+            ++count[event_kind];
+        }
+        if (count[0] == 0 && count[3] == 0) {
+            System.out.println("[not interesting]");
+            return false; // not interesting
+        }
+        String error = (count[0] == 0) ? " ok" : " disallowed!";
+        System.out.println("[0,0] " + count[0] + error);
+        System.out.println("[0,1] " + count[1]);
+        System.out.println("[1,0] " + count[2]);
+        System.out.println("[1,1] " + count[3]);
+        return (count[0] != 0);
+    }
+
+    public static void main(String args[]) {
+        DekkerTest test = new DekkerTest();
+        final int runs = 30;
+        int failed = 0;
+        for (int c = 0; c < runs; ++c) {
+            test.testRunner();
+            if (test.printResult()) {
+                failed++;
+            }
+            test.reset();
+        }
+        if (failed > 0) {
+            throw new InternalError("FAILED. Got " + failed + " failed ITERATIONS");
+        }
+        System.out.println("PASSED.");
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/jsig/Test8017498.sh	Fri Jul 26 14:01:00 2013 -0700
@@ -0,0 +1,92 @@
+#!/bin/sh
+
+#
+#  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 Test8017498.sh
+## @bug 8017498
+## @bug 8020791
+## @summary sigaction(sig) results in process hang/timed-out if sig is much greater than SIGRTMAX
+## @run shell/timeout=30 Test8017498.sh
+##
+
+if [ "${TESTSRC}" = "" ]
+then
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
+fi
+echo "TESTSRC=${TESTSRC}"
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
+
+# set platform-dependent variables
+OS=`uname -s`
+case "$OS" in
+  Linux)
+    echo "Testing on Linux"
+    if [ "$VM_BITS" = "64" ]
+    then
+        MY_LD_PRELOAD=${TESTJAVA}${FS}jre${FS}lib${FS}amd64${FS}libjsig.so
+    else
+        MY_LD_PRELOAD=${TESTJAVA}${FS}jre${FS}lib${FS}i386${FS}libjsig.so
+    fi
+    echo MY_LD_PRELOAD = ${MY_LD_PRELOAD}
+    ;;
+  *)
+    echo "Test passed; only valid for Linux"
+    exit 0;
+    ;;
+esac
+
+THIS_DIR=.
+
+cp ${TESTSRC}${FS}*.java ${THIS_DIR}
+${TESTJAVA}${FS}bin${FS}javac *.java
+
+gcc -DLINUX -fPIC -shared \
+    -o ${TESTSRC}${FS}libTestJNI.so \
+    -I${TESTJAVA}${FS}include \
+    -I${TESTJAVA}${FS}include${FS}linux \
+    ${TESTSRC}${FS}TestJNI.c
+if [ $? != 0 ]
+then
+    echo "WARNING: the gcc command failed." 2>&1
+fi
+
+# run the java test in the background
+cmd="LD_PRELOAD=$MY_LD_PRELOAD \
+    ${TESTJAVA}${FS}bin${FS}java \
+    -Djava.library.path=${TESTSRC}${FS} -server TestJNI 100"
+echo "$cmd > test.out 2>&1"
+eval $cmd > test.out 2>&1
+
+grep "old handler" test.out > ${NULL}
+if [ $? = 0 ]
+then
+    echo "Test Passed"
+    exit 0
+fi
+
+echo "Test Failed"
+exit 1
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/jsig/TestJNI.c	Fri Jul 26 14:01:00 2013 -0700
@@ -0,0 +1,59 @@
+/*
+ * 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.
+ */
+
+#define _GNU_SOURCE // for the definition of REG_RIP in ucontext.h
+#include <stdio.h>
+#include <jni.h>
+#include <signal.h>
+#include <sys/ucontext.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void sig_handler(int sig, siginfo_t *info, ucontext_t *context) {
+    int thrNum;
+
+    printf( " HANDLER (1) " );
+    // Move forward RIP to skip failing instruction
+    context->uc_mcontext.gregs[REG_RIP] += 6;
+}
+
+JNIEXPORT void JNICALL Java_TestJNI_doSomething(JNIEnv *env, jclass klass, jint val) {
+    struct sigaction act;
+    struct sigaction oact;
+
+    act.sa_flags = SA_ONSTACK|SA_RESTART|SA_SIGINFO;
+    sigfillset(&act.sa_mask);
+    act.sa_handler = SIG_DFL;
+    act.sa_sigaction = (void (*)())sig_handler;
+    sigaction(0x20+val, &act, &oact);
+
+    printf( " doSomething(%d) " , val);
+    printf( " old handler = %p " , oact.sa_handler);
+}
+
+#ifdef __cplusplus
+}
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/jsig/TestJNI.java	Fri Jul 26 14:01:00 2013 -0700
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+
+public class TestJNI {
+    static {
+        System.loadLibrary("TestJNI");
+    }
+    public static native void doSomething(int val);
+    public static void main(String[] args) {
+        int intArg = 43;
+        if (args.length > 0) {
+            try {
+                intArg = Integer.parseInt(args[0]);
+            } catch (NumberFormatException e) {
+                System.err.println("arg " + args[0] + " must be an integer");
+                System.exit(1);
+            }
+        }
+        TestJNI.doSomething(intArg);
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/serviceability/attach/AttachWithStalePidFile.java	Fri Jul 26 14:01:00 2013 -0700
@@ -0,0 +1,139 @@
+/*
+ * 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 7162400
+ * @key regression
+ * @summary Regression test for attach issue where stale pid files in /tmp lead to connection issues
+ * @library /testlibrary
+ * @compile AttachWithStalePidFileTarget.java
+ * @run main AttachWithStalePidFile
+ */
+
+import com.oracle.java.testlibrary.*;
+import com.sun.tools.attach.VirtualMachine;
+import sun.tools.attach.HotSpotVirtualMachine;
+import java.lang.reflect.Field;
+import java.nio.file.*;
+import java.nio.file.attribute.*;
+import java.io.*;
+
+public class AttachWithStalePidFile {
+  public static void main(String... args) throws Exception {
+
+    // this test is only valid on non-Windows platforms
+    if(Platform.isWindows()) {
+      System.out.println("This test is only valid on non-Windows platforms.");
+      return;
+    }
+
+    // Since there might be stale pid-files owned by different
+    // users on the system we may need to retry the test in case we
+    // are unable to remove the existing file.
+    int retries = 5;
+    while(!runTest() && --retries > 0);
+
+    if(retries == 0) {
+      throw new RuntimeException("Test failed after 5 retries. " +
+        "Remove any /tmp/.java_pid* files and retry.");
+    }
+  }
+
+  public static boolean runTest() throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+      "-XX:+UnlockDiagnosticVMOptions", "-XX:+PauseAtStartup", "AttachWithStalePidFileTarget");
+    Process target = pb.start();
+    Path pidFile = null;
+
+    try {
+      int pid = getUnixProcessId(target);
+
+      // create the stale .java_pid file. use hard-coded /tmp path as in th VM
+      pidFile = createJavaPidFile(pid);
+      if(pidFile == null) {
+        return false;
+      }
+
+      // wait for vm.paused file to be created and delete it once we find it.
+      waitForAndResumeVM(pid);
+
+      // unfortunately there's no reliable way to know the VM is ready to receive the
+      // attach request so we have to do an arbitrary sleep.
+      Thread.sleep(5000);
+
+      HotSpotVirtualMachine vm = (HotSpotVirtualMachine)VirtualMachine.attach(((Integer)pid).toString());
+      BufferedReader remoteDataReader = new BufferedReader(new InputStreamReader(vm.remoteDataDump()));
+      String line = null;
+      while((line = remoteDataReader.readLine()) != null);
+
+      vm.detach();
+      return true;
+    }
+    finally {
+      target.destroy();
+      target.waitFor();
+
+      if(pidFile != null && Files.exists(pidFile)) {
+        Files.delete(pidFile);
+      }
+    }
+  }
+
+  private static Path createJavaPidFile(int pid) throws Exception {
+    Path pidFile = Paths.get("/tmp/.java_pid" + pid);
+    if(Files.exists(pidFile)) {
+      try {
+        Files.delete(pidFile);
+      }
+      catch(FileSystemException e) {
+        if(e.getReason().equals("Operation not permitted")) {
+          System.out.println("Unable to remove exisiting stale PID file" + pidFile);
+          return null;
+        }
+        throw e;
+      }
+    }
+    return Files.createFile(pidFile,
+      PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
+  }
+
+  private static void waitForAndResumeVM(int pid) throws Exception {
+    Path pauseFile = Paths.get("vm.paused." + pid);
+    int retries = 60;
+    while(!Files.exists(pauseFile) && --retries > 0) {
+      Thread.sleep(1000);
+    }
+    if(retries == 0) {
+      throw new RuntimeException("Timeout waiting for VM to start. " +
+        "vm.paused file not created within 60 seconds.");
+    }
+    Files.delete(pauseFile);
+  }
+
+  private static int getUnixProcessId(Process unixProcess) throws Exception {
+    Field pidField = unixProcess.getClass().getDeclaredField("pid");
+    pidField.setAccessible(true);
+    return (Integer)pidField.get(unixProcess);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/serviceability/attach/AttachWithStalePidFileTarget.java	Fri Jul 26 14:01:00 2013 -0700
@@ -0,0 +1,27 @@
+/*
+ * 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.
+ */
+public class AttachWithStalePidFileTarget {
+  public static void main(String... args) throws Exception {
+    Thread.sleep(2*60*1000);
+  }
+}
--- a/jaxp/.hgtags	Thu Jul 25 13:02:37 2013 -0700
+++ b/jaxp/.hgtags	Fri Jul 26 14:01:00 2013 -0700
@@ -220,3 +220,5 @@
 6121efd299235b057f3de94b0a4158c388c2907c jdk8-b96
 6c830db28d21108f32af990ecf4d80a75887980d jdk8-b97
 15e5bb51bc0cd89304dc2f7f29b4c8002e632353 jdk8-b98
+adf49c3ef83c160d53ece623049b2cdccaf78fc7 jdk8-b99
+5d1974c1d7b9a86431bc253dc5a6a52d4586622e jdk8-b100
--- a/jaxws/.hgtags	Thu Jul 25 13:02:37 2013 -0700
+++ b/jaxws/.hgtags	Fri Jul 26 14:01:00 2013 -0700
@@ -220,3 +220,5 @@
 690d34b326bc78a6f5f225522695b41c7f7f70e8 jdk8-b96
 dcde7f049111353ad23175f54985a4f6bfea720c jdk8-b97
 b1fb4612a2caea52b5661b87509e560fa044b194 jdk8-b98
+8ef83d4b23c933935e28f59b282cea920b1b1f5f jdk8-b99
+4fd722afae5c02f00bbd44c3a34425ee474afb1c jdk8-b100
--- a/jdk/.hgtags	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/.hgtags	Fri Jul 26 14:01:00 2013 -0700
@@ -220,3 +220,5 @@
 4a5d3cf2b3af1660db0237e8da324c140e534fa4 jdk8-b96
 978a95239044f26dcc8a6d59246be07ad6ca6be2 jdk8-b97
 c4908732fef5235f1b98cafe0ce507771ef7892c jdk8-b98
+6a099a36589bd933957272ba63e5263bede29971 jdk8-b99
+5be9c5bfcfe9b2a40412b4fb364377d49de014eb jdk8-b100
--- a/jdk/make/sun/security/pkcs11/mapfile-vers	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/make/sun/security/pkcs11/mapfile-vers	Fri Jul 26 14:01:00 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/jdk/makefiles/mapfiles/libj2pkcs11/mapfile-vers	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/makefiles/mapfiles/libj2pkcs11/mapfile-vers	Fri Jul 26 14:01:00 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/jdk/src/macosx/classes/com/apple/eawt/FullScreenHandler.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/macosx/classes/com/apple/eawt/FullScreenHandler.java	Fri Jul 26 14:01:00 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/jdk/src/macosx/classes/com/apple/eawt/_AppEventHandler.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/macosx/classes/com/apple/eawt/_AppEventHandler.java	Fri Jul 26 14:01:00 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/jdk/src/macosx/classes/com/apple/eawt/event/GestureHandler.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/macosx/classes/com/apple/eawt/event/GestureHandler.java	Fri Jul 26 14:01:00 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/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java	Fri Jul 26 14:01:00 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/jdk/src/macosx/classes/sun/lwawt/macosx/CCheckboxMenuItem.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CCheckboxMenuItem.java	Fri Jul 26 14:01:00 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/jdk/src/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java	Fri Jul 26 14:01:00 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/jdk/src/macosx/classes/sun/lwawt/macosx/CDropTarget.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CDropTarget.java	Fri Jul 26 14:01:00 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/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Fri Jul 26 14:01:00 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/jdk/src/macosx/classes/sun/lwawt/macosx/CViewEmbeddedFrame.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CViewEmbeddedFrame.java	Fri Jul 26 14:01:00 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/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java	Fri Jul 26 14:01:00 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/jdk/src/macosx/native/sun/awt/CMenuItem.m	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/macosx/native/sun/awt/CMenuItem.m	Fri Jul 26 14:01:00 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/jdk/src/macosx/native/sun/awt/CWrapper.m	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/macosx/native/sun/awt/CWrapper.m	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility.properties	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility.properties	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_de.properties	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_de.properties	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_es.properties	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_es.properties	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_fr.properties	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_fr.properties	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_it.properties	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_it.properties	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ja.properties	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ja.properties	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ko.properties	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ko.properties	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_pt_BR.properties	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_pt_BR.properties	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_sv.properties	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_sv.properties	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_zh_CN.properties	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_zh_CN.properties	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_zh_TW.properties	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_zh_TW.properties	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/crypto/provider/DESKeyFactory.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/crypto/provider/DESKeyFactory.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/crypto/provider/DESedeKeyFactory.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/crypto/provider/DESedeKeyFactory.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/crypto/provider/DHKeyFactory.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/crypto/provider/DHKeyFactory.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/crypto/provider/DHPrivateKey.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/crypto/provider/DHPrivateKey.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/crypto/provider/DHPublicKey.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/crypto/provider/DHPublicKey.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties	Thu Jul 25 13:02:37 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java	Thu Jul 25 13:02:37 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java	Thu Jul 25 13:02:37 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java	Thu Jul 25 13:02:37 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathFactory.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathAPI.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java	Thu Jul 25 13:02:37 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathFactory.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/awt/GraphicsDevice.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/awt/GraphicsDevice.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/beans/Introspector.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/beans/Introspector.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/io/BufferedReader.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/io/BufferedReader.java	Fri Jul 26 14:01:00 2013 -0700
@@ -587,6 +587,6 @@
                 }
             }
         };
-        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iter, Spliterator.ORDERED));
+        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iter, Spliterator.ORDERED), false);
     }
 }
--- a/jdk/src/share/classes/java/io/DataInput.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/io/DataInput.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/io/File.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/io/File.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/io/FileInputStream.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/io/FileInputStream.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/io/FileOutputStream.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/io/FileOutputStream.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/io/InputStreamReader.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/io/InputStreamReader.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/io/OutputStreamWriter.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/io/OutputStreamWriter.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/io/PipedInputStream.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/io/PipedInputStream.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/io/RandomAccessFile.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/io/RandomAccessFile.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/CharSequence.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/CharSequence.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/Character.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/Character.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/Class.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/Class.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/ClassLoader.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/ClassLoader.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/Double.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/Double.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/Float.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/Float.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/Iterable.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/Iterable.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/ProcessBuilder.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/ProcessBuilder.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/Runtime.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/Runtime.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/SecurityManager.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/SecurityManager.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/System.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/System.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/Thread.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/Thread.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/ThreadLocal.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/ThreadLocal.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/invoke/MethodHandles.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/management/LockInfo.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/management/LockInfo.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/management/ManagementFactory.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/management/ManagementFactory.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/management/MemoryMXBean.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/management/MemoryMXBean.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/management/MemoryNotificationInfo.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/management/MemoryNotificationInfo.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/management/MemoryPoolMXBean.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/management/MemoryPoolMXBean.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/management/MemoryUsage.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/management/MemoryUsage.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/management/MonitorInfo.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/management/MonitorInfo.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/management/RuntimeMXBean.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/management/RuntimeMXBean.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/management/ThreadInfo.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/management/ThreadInfo.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/management/ThreadMXBean.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/management/ThreadMXBean.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/ref/Reference.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/ref/Reference.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/reflect/AnnotatedElement.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/reflect/AnnotatedElement.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/reflect/Executable.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/reflect/Executable.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/reflect/Member.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/reflect/Member.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/lang/reflect/Parameter.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/lang/reflect/Parameter.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/math/BigDecimal.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/math/BigDecimal.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/net/CookieStore.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/net/CookieStore.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/net/HttpURLPermission.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/net/HttpURLPermission.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/net/Inet4Address.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/net/Inet4Address.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/net/Inet6Address.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/net/Inet6Address.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/net/InetAddress.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/net/InetAddress.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/net/ProtocolFamily.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/net/ProtocolFamily.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/net/SocketOption.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/net/SocketOption.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/net/URI.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/net/URI.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/nio/X-Buffer.java.template	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/nio/X-Buffer.java.template	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/nio/file/Files.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/nio/file/Files.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/security/AuthProvider.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/security/AuthProvider.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/AbstractMap.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/AbstractMap.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/ArrayList.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/ArrayList.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/Arrays.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/Arrays.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/Base64.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/Base64.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/BitSet.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/BitSet.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/Calendar.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/Calendar.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/Collection.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/Collection.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/Collections.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/Collections.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/ConcurrentModificationException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/ConcurrentModificationException.java	Fri Jul 26 14:01:00 2013 -0700
@@ -57,6 +57,7 @@
  * @author  Josh Bloch
  * @see     Collection
  * @see     Iterator
+ * @see     Spliterator
  * @see     ListIterator
  * @see     Vector
  * @see     LinkedList
--- a/jdk/src/share/classes/java/util/EnumSet.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/EnumSet.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/Formattable.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/Formattable.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/Formatter.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/Formatter.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/GregorianCalendar.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/GregorianCalendar.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/HashMap.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/HashMap.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/LinkedList.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/LinkedList.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/Locale.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/Locale.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/NavigableSet.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/NavigableSet.java	Fri Jul 26 14:01:00 2013 -0700
@@ -303,7 +303,7 @@
      * @throws ClassCastException       {@inheritDoc}
      * @throws NullPointerException     {@inheritDoc}
      * @throws IllegalArgumentException {@inheritDoc}
-na     */
+     */
     SortedSet<E> headSet(E toElement);
 
     /**
--- a/jdk/src/share/classes/java/util/Optional.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/Optional.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/OptionalDouble.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/OptionalDouble.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/OptionalInt.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/OptionalInt.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/OptionalLong.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/OptionalLong.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/ResourceBundle.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/ResourceBundle.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/ServiceLoader.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/ServiceLoader.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/Spliterator.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/Spliterator.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/Spliterators.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/Spliterators.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/StringJoiner.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/StringJoiner.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/AbstractExecutorService.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/AbstractExecutorService.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/ArrayBlockingQueue.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/ArrayBlockingQueue.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/BlockingDeque.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/BlockingDeque.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/BlockingQueue.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/BlockingQueue.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/BrokenBarrierException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/BrokenBarrierException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/Callable.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/Callable.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/CancellationException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/CancellationException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/CompletableFuture.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/CompletableFuture.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/CompletionService.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/CompletionService.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/ConcurrentHashMap.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentHashMap.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/ConcurrentMap.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentMap.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/ConcurrentNavigableMap.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentNavigableMap.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListMap.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListMap.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/CopyOnWriteArrayList.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/CopyOnWriteArrayList.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/CopyOnWriteArraySet.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/CopyOnWriteArraySet.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/CountDownLatch.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/CountDownLatch.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/CountedCompleter.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/CountedCompleter.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/CyclicBarrier.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/CyclicBarrier.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/DelayQueue.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/DelayQueue.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/Delayed.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/Delayed.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/Exchanger.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/Exchanger.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/ExecutionException.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/ExecutionException.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/Executor.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/Executor.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/ExecutorService.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/ExecutorService.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/Executors.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/Executors.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/ForkJoinPool.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/ForkJoinPool.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/ForkJoinTask.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/ForkJoinTask.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/ForkJoinWorkerThread.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/ForkJoinWorkerThread.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/Future.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/Future.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/FutureTask.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/FutureTask.java	Fri Jul 26 14:01:00 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/jdk/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java	Thu Jul 25 13:02:37 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java	Fri Jul 26 14:01:00 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();
+                    }