From ef69ce852cb50f7844a2bc0b18d696665146d866 Mon Sep 17 00:00:00 2001 From: Goetz Lindenmaier Date: Thu, 20 Jun 2013 15:02:05 +0200 Subject: [PATCH 001/123] 8016697: Use stubs to implement safefetch Implement Safefetch as stub routines. This reduces compiler and os dependencies. Reviewed-by: twisti, kvn --- .../src/cpu/sparc/vm/stubGenerator_sparc.cpp | 53 +++++++++++++++++++ .../src/cpu/x86/vm/stubGenerator_x86_32.cpp | 41 ++++++++++++++ .../src/cpu/x86/vm/stubGenerator_x86_64.cpp | 46 ++++++++++++++++ hotspot/src/os/windows/vm/os_windows.cpp | 5 ++ hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_32.s | 18 ------- hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_64.s | 22 -------- hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp | 19 ++----- .../src/os_cpu/linux_sparc/vm/linux_sparc.s | 36 ------------- .../os_cpu/linux_sparc/vm/os_linux_sparc.cpp | 13 +---- .../src/os_cpu/linux_x86/vm/linux_x86_32.s | 18 ------- .../src/os_cpu/linux_x86/vm/linux_x86_64.s | 22 -------- .../src/os_cpu/linux_x86/vm/os_linux_x86.cpp | 19 ++----- .../solaris_sparc/vm/os_solaris_sparc.cpp | 20 ++----- .../os_cpu/solaris_sparc/vm/solaris_sparc.s | 41 -------------- .../os_cpu/solaris_x86/vm/os_solaris_x86.cpp | 20 ++----- .../os_cpu/solaris_x86/vm/solaris_x86_32.s | 14 ----- .../os_cpu/solaris_x86/vm/solaris_x86_64.s | 52 ++++++------------ .../os_cpu/windows_x86/vm/os_windows_x86.cpp | 18 ------- hotspot/src/share/vm/runtime/os.hpp | 4 +- hotspot/src/share/vm/runtime/stubRoutines.cpp | 7 +++ hotspot/src/share/vm/runtime/stubRoutines.hpp | 47 ++++++++++++++++ 21 files changed, 231 insertions(+), 304 deletions(-) diff --git a/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp b/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp index 494c1bc405a..214940cdbfb 100644 --- a/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp @@ -410,6 +410,51 @@ class StubGenerator: public StubCodeGenerator { 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 @@ class StubGenerator: public StubCodeGenerator { // 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); } diff --git a/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp b/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp index 82e4183ef47..a8abfea6bcd 100644 --- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp +++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp @@ -2766,6 +2766,39 @@ class StubGenerator: public StubCodeGenerator { 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 @@ class StubGenerator: public StubCodeGenerator { 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; } diff --git a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp index 2d94642f828..c80f1807936 100644 --- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp +++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp @@ -3357,7 +3357,45 @@ class StubGenerator: public StubCodeGenerator { 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 @@ -3833,6 +3871,14 @@ class StubGenerator: public StubCodeGenerator { 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: diff --git a/hotspot/src/os/windows/vm/os_windows.cpp b/hotspot/src/os/windows/vm/os_windows.cpp index cc43934d423..d875e875e45 100644 --- a/hotspot/src/os/windows/vm/os_windows.cpp +++ b/hotspot/src/os/windows/vm/os_windows.cpp @@ -2317,6 +2317,11 @@ LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) { #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; diff --git a/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_32.s b/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_32.s index 402c8da11a6..3275996f0c7 100644 --- a/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_32.s +++ b/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_32.s @@ -63,24 +63,6 @@ SYMBOL(fixcw): 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 diff --git a/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_64.s b/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_64.s index 65d2db45f70..2f70fce77a3 100644 --- a/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_64.s +++ b/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_64.s @@ -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) diff --git a/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp b/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp index aa36599ea2a..55ef24b899d 100644 --- a/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp +++ b/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp @@ -385,13 +385,6 @@ enum { 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, @@ -454,16 +447,10 @@ JVM_handle_bsd_signal(int sig, 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) { diff --git a/hotspot/src/os_cpu/linux_sparc/vm/linux_sparc.s b/hotspot/src/os_cpu/linux_sparc/vm/linux_sparc.s index e04f871f49e..d7c2ce87414 100644 --- a/hotspot/src/os_cpu/linux_sparc/vm/linux_sparc.s +++ b/hotspot/src/os_cpu/linux_sparc/vm/linux_sparc.s @@ -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) diff --git a/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp b/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp index d97f0e041bf..2367e2a0604 100644 --- a/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp +++ b/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp @@ -366,18 +366,9 @@ intptr_t* os::Linux::ucontext_get_fp(ucontext_t *uc) { // 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; diff --git a/hotspot/src/os_cpu/linux_x86/vm/linux_x86_32.s b/hotspot/src/os_cpu/linux_x86/vm/linux_x86_32.s index d29d31df464..7936cbf52bd 100644 --- a/hotspot/src/os_cpu/linux_x86/vm/linux_x86_32.s +++ b/hotspot/src/os_cpu/linux_x86/vm/linux_x86_32.s @@ -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 diff --git a/hotspot/src/os_cpu/linux_x86/vm/linux_x86_64.s b/hotspot/src/os_cpu/linux_x86/vm/linux_x86_64.s index 8be68610e80..fb688e7a7b6 100644 --- a/hotspot/src/os_cpu/linux_x86/vm/linux_x86_64.s +++ b/hotspot/src/os_cpu/linux_x86/vm/linux_x86_64.s @@ -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 diff --git a/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp b/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp index 4fc3b76d228..f7a57773fe9 100644 --- a/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp +++ b/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp @@ -209,13 +209,6 @@ enum { 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, @@ -278,16 +271,10 @@ JVM_handle_linux_signal(int sig, 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 diff --git a/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp b/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp index 939def32fec..4257f4e460b 100644 --- a/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp +++ b/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp @@ -303,11 +303,6 @@ bool os::is_allocatable(size_t bytes) { #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) { @@ -379,17 +374,10 @@ JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid, 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 diff --git a/hotspot/src/os_cpu/solaris_sparc/vm/solaris_sparc.s b/hotspot/src/os_cpu/solaris_sparc/vm/solaris_sparc.s index aa526a09d08..39aaa77f664 100644 --- a/hotspot/src/os_cpu/solaris_sparc/vm/solaris_sparc.s +++ b/hotspot/src/os_cpu/solaris_sparc/vm/solaris_sparc.s @@ -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) diff --git a/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp b/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp index 4ed094db734..f479ffbb193 100644 --- a/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp +++ b/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp @@ -352,13 +352,6 @@ bool os::is_allocatable(size_t bytes) { } -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) { @@ -436,17 +429,10 @@ JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid, // 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) { diff --git a/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_32.s b/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_32.s index 1fac3b25f11..19e790b6013 100644 --- a/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_32.s +++ b/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_32.s @@ -54,20 +54,6 @@ fixcw: 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: diff --git a/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_64.s b/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_64.s index 95050af24f0..487b569e58c 100644 --- a/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_64.s +++ b/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_64.s @@ -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 @@ SpinPause: nop movq $1, %rax ret - + / Support for void Copy::arrayof_conjoint_bytes(void* from, / void* to, @@ -340,7 +320,7 @@ aci_CopyLeft: addq $4,%rdx jg 1b ret - + / Support for void Copy::arrayof_conjoint_jlongs(jlong* from, / jlong* to, / size_t count) diff --git a/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp b/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp index 1ef29f99a55..a0f2a7680be 100644 --- a/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp +++ b/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp @@ -518,24 +518,6 @@ void os::print_register_info(outputStream *st, void *context) { 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 ; diff --git a/hotspot/src/share/vm/runtime/os.hpp b/hotspot/src/share/vm/runtime/os.hpp index e1866919df4..aeade2bbd11 100644 --- a/hotspot/src/share/vm/runtime/os.hpp +++ b/hotspot/src/share/vm/runtime/os.hpp @@ -915,8 +915,6 @@ class os: AllStatic { // 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 diff --git a/hotspot/src/share/vm/runtime/stubRoutines.cpp b/hotspot/src/share/vm/runtime/stubRoutines.cpp index a1179acd543..ff12ca65163 100644 --- a/hotspot/src/share/vm/runtime/stubRoutines.cpp +++ b/hotspot/src/share/vm/runtime/stubRoutines.cpp @@ -136,6 +136,13 @@ double (* StubRoutines::_intrinsic_sin )(double) = NULL; 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. diff --git a/hotspot/src/share/vm/runtime/stubRoutines.hpp b/hotspot/src/share/vm/runtime/stubRoutines.hpp index b8d61ea0cbf..e43e3ab0e7b 100644 --- a/hotspot/src/share/vm/runtime/stubRoutines.hpp +++ b/hotspot/src/share/vm/runtime/stubRoutines.hpp @@ -221,6 +221,14 @@ class StubRoutines: AllStatic { 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 @@ -381,6 +389,34 @@ class StubRoutines: AllStatic { return _intrinsic_tan(d); } + // + // 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 @@ class StubRoutines: AllStatic { 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 From 22b6014ba6b633b5bf588b6fc7c352181a0a24cb Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Wed, 3 Jul 2013 00:08:45 +0530 Subject: [PATCH 002/123] 8019629: void operator should always evaluate to undefined Reviewed-by: jlaskey --- .../jdk/nashorn/internal/codegen/Attr.java | 5 +-- .../internal/codegen/CodeGenerator.java | 8 ++++ .../jdk/nashorn/internal/ir/RuntimeNode.java | 2 - .../internal/runtime/ScriptRuntime.java | 17 -------- nashorn/test/script/basic/JDK-8019629.js | 42 +++++++++++++++++++ 5 files changed, 51 insertions(+), 23 deletions(-) create mode 100644 nashorn/test/script/basic/JDK-8019629.js diff --git a/nashorn/src/jdk/nashorn/internal/codegen/Attr.java b/nashorn/src/jdk/nashorn/internal/codegen/Attr.java index 3a442a7d8f2..d4b3405fb26 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/Attr.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/Attr.java @@ -1009,10 +1009,7 @@ final class Attr extends NodeOperatorVisitor { @Override public Node leaveVOID(final UnaryNode unaryNode) { - final RuntimeNode runtimeNode = (RuntimeNode)new RuntimeNode(unaryNode, Request.VOID).accept(this); - assert runtimeNode.getSymbol().getSymbolType().isObject(); - end(unaryNode); - return runtimeNode; + return end(ensureSymbol(Type.OBJECT, unaryNode)); } /** diff --git a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java index 414d1bb8bc3..d0bf7cd563e 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java @@ -2335,6 +2335,14 @@ final class CodeGenerator extends NodeOperatorVisitor { NEW, /** Typeof operator */ TYPEOF, - /** void type */ - VOID, /** Reference error type */ REFERENCE_ERROR, /** Delete operator */ diff --git a/nashorn/src/jdk/nashorn/internal/runtime/ScriptRuntime.java b/nashorn/src/jdk/nashorn/internal/runtime/ScriptRuntime.java index 15c915cf0e4..1144c57d76d 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptRuntime.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptRuntime.java @@ -600,23 +600,6 @@ public final class ScriptRuntime { return JSType.of(obj).typeName(); } - /** - * ECMA 11.4.2 - void operator - * - * @param object object to evaluate - * - * @return Undefined as the object type - */ - public static Object VOID(final Object object) { - if (object instanceof Number) { - if (Double.isNaN(((Number)object).doubleValue())) { - return Double.NaN; - } - } - - return UNDEFINED; - } - /** * Throw ReferenceError when LHS of assignment or increment/decrement * operator is not an assignable node (say a literal) diff --git a/nashorn/test/script/basic/JDK-8019629.js b/nashorn/test/script/basic/JDK-8019629.js new file mode 100644 index 00000000000..2d284d05150 --- /dev/null +++ b/nashorn/test/script/basic/JDK-8019629.js @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * 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. + */ + +/** + * JDK-8019629: void operator should always evaluate to undefined + * + * @test + * @run + */ + +function check(str) { + var val = eval(str); + if (typeof val !== 'undefined') { + print("FAILED: " + str + " does not evaluate to 'undefined'"); + } +} + +check("void +this"); +check("void +(void 0)"); +check("(function f(){return void +(void 0)})()"); +check("void function() {}"); + From 5a360a7579c6a46f7a0ed76e861fff704f2f62d8 Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Tue, 2 Jul 2013 15:58:09 -0700 Subject: [PATCH 003/123] 8007035: deprecate public void SecurityManager.checkMemberAccess(Class clazz, int which) Reviewed-by: jrose, alanb, dfuchs --- jdk/src/share/classes/java/lang/Class.java | 598 ++++++++---------- .../classes/java/lang/SecurityManager.java | 8 + .../java/lang/invoke/MethodHandles.java | 76 +-- .../classes/java/lang/reflect/Member.java | 2 - .../lang/invoke/InvokeDynamicPrintArgs.java | 48 +- .../java/lang/invoke/TestPrivateMember.java | 57 ++ 6 files changed, 359 insertions(+), 430 deletions(-) create mode 100644 jdk/test/java/lang/invoke/TestPrivateMember.java diff --git a/jdk/src/share/classes/java/lang/Class.java b/jdk/src/share/classes/java/lang/Class.java index df4d457367d..05cfa88cad1 100644 --- a/jdk/src/share/classes/java/lang/Class.java +++ b/jdk/src/share/classes/java/lang/Class.java @@ -360,36 +360,24 @@ public final class Class implements java.io.Serializable, * 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, s, is present and any of the - * following conditions is met: - * - *
    - * - *
  • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * creation of new instances of this class - * - *
  • 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 - * - *
- * + * @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, s, 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 @@ public final class Class implements java.io.Serializable, * * @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, s, is present and any of the - * following conditions is met: * - *
    + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *
  • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(enclosingClass, Member.DECLARED)} denies - * access to the methods within the enclosing class + *
      * - *
    • 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 + *
    • 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 * - *
    + *
  • 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 + * + *
* @since 1.5 */ @CallerSensitive @@ -1025,11 +1016,6 @@ public final class Class implements java.io.Serializable, // 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 @@ public final class Class implements java.io.Serializable, * * @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, s, is present and any of the - * following conditions is met: + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *
    + *
      * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(enclosingClass, Member.DECLARED)} denies - * access to the constructors within the enclosing class + *
    • 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 * - *
    • 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 + *
    • 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 * - *
    + *
* @since 1.5 */ @CallerSensitive @@ -1180,11 +1168,6 @@ public final class Class implements java.io.Serializable, // 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 @@ public final class Class implements java.io.Serializable, * class, or void. * * @return the array of {@code Class} objects representing the public - * members of this class - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *
    - * - *
  • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} method - * denies access to the classes within this class - * - *
  • 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 - * - *
+ * members of this class + * @throws SecurityException + * If a security manager, s, 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 @@ public final class Class implements java.io.Serializable, *

See The Java Language Specification, sections 8.2 and 8.3. * * @return the array of {@code Field} objects representing the - * public fields - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *

    - * - *
  • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the fields within this class - * - *
  • 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 - * - *
+ * public fields + * @throws SecurityException + * If a security manager, s, 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 @@ public final class Class implements java.io.Serializable, *

See The Java Language Specification, 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, s, is present and any of the - * following conditions is met: - * - *

    - * - *
  • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the methods within this class - * - *
  • 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 - * - *
+ * public methods of this class + * @throws SecurityException + * If a security manager, s, 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 @@ public final class Class implements java.io.Serializable, * {@code Constructor[]}. * * @return the array of {@code Constructor} objects representing the - * public constructors of this class - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *
    - * - *
  • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the constructors within this class - * - *
  • 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 - * - *
+ * public constructors of this class + * @throws SecurityException + * If a security manager, s, 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 @@ public final class Class implements java.io.Serializable, *

See The Java Language Specification, 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, s, is present and any of the - * following conditions is met: - * - *

    - * - *
  • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the field - * - *
  • 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 - * - *
+ * @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, s, 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 @@ public final class Class implements java.io.Serializable, * @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 "<init>"or "<clinit>". - * @exception NullPointerException if {@code name} is {@code null} - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *
    - * - *
  • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the method - * - *
  • 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 - * - *
+ * {@code name} and {@code parameterTypes} + * @throws NoSuchMethodException if a matching method is not found + * or if the name is "<init>"or "<clinit>". + * @throws NullPointerException if {@code name} is {@code null} + * @throws SecurityException + * If a security manager, s, 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 @@ public final class Class implements java.io.Serializable, * * @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, s, is present and any of the - * following conditions is met: - * - *
    - * - *
  • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the constructor - * - *
  • 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 - * - *
+ * matches the specified {@code parameterTypes} + * @throws NoSuchMethodException if a matching method is not found. + * @throws SecurityException + * If a security manager, s, 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 @@ public final class Class implements java.io.Serializable, * 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, s, is present and any of the - * following conditions is met: + * declared members of this class + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *
    + *
      * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared classes within this class + *
    • 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 * - *
    • 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 + *
    • 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 */ @@ -1899,26 +1807,28 @@ public final class Class implements java.io.Serializable, * *

See The Java Language Specification, 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, s, 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, s, is present and any of the + * following conditions is met: * - *

    + *
      * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared fields within this class + *
    • 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 * - *
    • 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 + *
    • 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 */ @@ -1945,26 +1855,28 @@ public final class Class implements java.io.Serializable, * *

See The Java Language Specification, section 8.2. * - * @return the array of {@code Method} objects representing all the - * declared methods of this class - * @exception SecurityException - * If a security manager, s, 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, s, is present and any of the + * following conditions is met: * - *

    + *
      * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared methods within this class + *
    • 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 * - *
    • 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 + *
    • 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 */ @@ -1988,26 +1900,28 @@ public final class Class implements java.io.Serializable, * *

See The Java Language Specification, section 8.2. * - * @return the array of {@code Constructor} objects representing all the - * declared constructors of this class - * @exception SecurityException - * If a security manager, s, 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, s, is present and any of the + * following conditions is met: * - *

    + *
      * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared constructors within this class + *
    • 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 * - *
    • 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 + *
    • 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 */ @@ -2026,29 +1940,31 @@ public final class Class implements java.io.Serializable, * 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, s, 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, s, is present and any of the + * following conditions is met: * - *
    + *
      * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared field + *
    • 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 * - *
    • 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 + *
    • 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 */ @@ -2080,28 +1996,30 @@ public final class Class implements java.io.Serializable, * * @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, s, 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, s, is present and any of the + * following conditions is met: * - *
    + *
      * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared method + *
    • 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 * - *
    • 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 + *
    • 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 */ @@ -2129,27 +2047,29 @@ public final class Class implements java.io.Serializable, * 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, s, 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, s, is present and any of the + * following conditions is met: * - *
    + *
      * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared constructor + *
    • 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 * - *
    • 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 + *
    • 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 */ @@ -2306,14 +2226,6 @@ public final class Class implements java.io.Serializable, */ 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 @@ public final class Class implements java.io.Serializable, 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); } diff --git a/jdk/src/share/classes/java/lang/SecurityManager.java b/jdk/src/share/classes/java/lang/SecurityManager.java index ca187630528..34be905bd02 100644 --- a/jdk/src/share/classes/java/lang/SecurityManager.java +++ b/jdk/src/share/classes/java/lang/SecurityManager.java @@ -1675,10 +1675,18 @@ class SecurityManager { * permission to access members. * @exception NullPointerException if the clazz argument is * null. + * + * @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) { diff --git a/jdk/src/share/classes/java/lang/invoke/MethodHandles.java b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java index 3bf24bc8503..78b01215636 100644 --- a/jdk/src/share/classes/java/lang/invoke/MethodHandles.java +++ b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java @@ -41,6 +41,7 @@ import sun.reflect.misc.ReflectUtil; 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 @@ public class MethodHandles { * * 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 not present + * 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: *
    - *
  • In all cases, {@link SecurityManager#checkMemberAccess - * smgr.checkMemberAccess(refc, Member.PUBLIC)} is called. - *
  • If the class loader of the lookup class is not + *
  • 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}. + *
  • 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. *
  • 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. - *
  • 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}. @@ -1053,22 +1048,6 @@ return mh1; return (allowedModes & PRIVATE) != 0; } - /** - * Determine whether a security manager has an overridden - * SecurityManager.checkMemberAccess method. - */ - private boolean isCheckMemberAccessOverridden(SecurityManager sm) { - final Class 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 access checks. * Determines a trustable caller class to compare with refc, the symbolic reference class. @@ -1079,45 +1058,22 @@ return mh1; 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); } diff --git a/jdk/src/share/classes/java/lang/reflect/Member.java b/jdk/src/share/classes/java/lang/reflect/Member.java index 5d3ab3dd8b3..a539cb54614 100644 --- a/jdk/src/share/classes/java/lang/reflect/Member.java +++ b/jdk/src/share/classes/java/lang/reflect/Member.java @@ -42,14 +42,12 @@ interface Member { /** * 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; diff --git a/jdk/test/java/lang/invoke/InvokeDynamicPrintArgs.java b/jdk/test/java/lang/invoke/InvokeDynamicPrintArgs.java index a318676ac29..a3f3cd2b69a 100644 --- a/jdk/test/java/lang/invoke/InvokeDynamicPrintArgs.java +++ b/jdk/test/java/lang/invoke/InvokeDynamicPrintArgs.java @@ -22,6 +22,7 @@ */ /* @test + * @bug 7050328 8007035 * @summary smoke test for invokedynamic instructions * @build indify.Indify * @compile InvokeDynamicPrintArgs.java @@ -42,6 +43,7 @@ import java.util.*; import java.io.*; import java.lang.invoke.*; +import java.security.*; import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; @@ -62,17 +64,10 @@ public class InvokeDynamicPrintArgs { } private static void checkConstantRefs() throws Throwable { - // check some constant references: + // check some constant references to its self class assertEquals(MT_bsm(), MH_bsm().type()); assertEquals(MT_bsm2(), MH_bsm2().type()); - try { - assertEquals(MT_bsm(), non_MH_bsm().type()); - // if SM is installed, must throw before this point - assertEquals(false, System.getSecurityManager() != null); - } catch (SecurityException ex) { - // if SM is installed, must throw to this point - assertEquals(true, System.getSecurityManager() != null); - } + assertEquals(MT_bsm(), non_MH_bsm().type()); } private static void assertEquals(Object exp, Object act) { if (exp == act || (exp != null && exp.equals(act))) return; @@ -80,21 +75,8 @@ public class InvokeDynamicPrintArgs { } private static void setSM() { - // Test for severe security manager interactions (7050328). - class SM extends SecurityManager { - public void checkPackageAccess(String pkg) { - if (pkg.startsWith("test.")) - throw new SecurityException("checkPackageAccess "+pkg); - } - public void checkMemberAccess(Class clazz, int which) { - if (clazz == InvokeDynamicPrintArgs.class) - throw new SecurityException("checkMemberAccess "+clazz.getName()+" #"+which); - } - // allow these others: - public void checkPermission(java.security.Permission perm) { - } - } - System.setSecurityManager(new SM()); + Policy.setPolicy(new TestPolicy()); + System.setSecurityManager(new SecurityManager()); } private static PrintStream oldOut; @@ -250,4 +232,22 @@ public class InvokeDynamicPrintArgs { if (System.getProperty("InvokeDynamicPrintArgs.allow-untransformed") != null) return; throw new AssertionError("this code should be statically transformed away by Indify"); } + + static class TestPolicy extends Policy { + final PermissionCollection permissions = new Permissions(); + TestPolicy() { + permissions.add(new java.io.FilePermission("<>", "read")); + } + public PermissionCollection getPermissions(ProtectionDomain domain) { + return permissions; + } + + public PermissionCollection getPermissions(CodeSource codesource) { + return permissions; + } + + public boolean implies(ProtectionDomain domain, Permission perm) { + return permissions.implies(perm); + } + } } diff --git a/jdk/test/java/lang/invoke/TestPrivateMember.java b/jdk/test/java/lang/invoke/TestPrivateMember.java new file mode 100644 index 00000000000..f2c0bc160d7 --- /dev/null +++ b/jdk/test/java/lang/invoke/TestPrivateMember.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; + +/** + * @test + * @bug 8007035 + * @summary Test MethodHandle of a private member + * + * @run main TestPrivateMember + */ + +public class TestPrivateMember { + public static void main(String... args) throws Throwable { + System.setSecurityManager(new SecurityManager()); + TestPrivateMember t = new TestPrivateMember(); + t.test(); + } + + public TestPrivateMember() { + } + + public void test() throws Throwable { + MethodHandles.Lookup lookup = MethodHandles.lookup(); + MethodType mt = MethodType.methodType(void.class); + try { + MethodHandle mh = lookup.findStatic(Class.class, "checkInitted", mt); + throw new RuntimeException("IllegalAccessException not thrown"); + } catch (IllegalAccessException e) { + // okay + System.out.println("Expected exception: " + e.getMessage()); + } + } +} From 118272d2e9a8345e2f402d6d50fe1e4615514bb3 Mon Sep 17 00:00:00 2001 From: Vinnie Ryan Date: Tue, 2 Jul 2013 16:38:09 -0700 Subject: [PATCH 004/123] 7165807: Non optimized initialization of NSS crypto library leads to scalability issues Reviewed-by: mullan, valeriep --- jdk/make/sun/security/pkcs11/mapfile-vers | 2 +- .../mapfiles/libj2pkcs11/mapfile-vers | 4 +- .../classes/sun/security/pkcs11/Config.java | 10 +++ .../classes/sun/security/pkcs11/Secmod.java | 15 +++-- .../sun/security/pkcs11/SunPKCS11.java | 5 +- .../native/sun/security/pkcs11/j2secmod.c | 65 +++++++++++++++---- .../native/sun/security/pkcs11/j2secmod_md.h | 11 +++- .../native/sun/security/pkcs11/j2secmod_md.h | 11 +++- 8 files changed, 97 insertions(+), 26 deletions(-) diff --git a/jdk/make/sun/security/pkcs11/mapfile-vers b/jdk/make/sun/security/pkcs11/mapfile-vers index 7301c11417d..dfd2e34e74a 100644 --- a/jdk/make/sun/security/pkcs11/mapfile-vers +++ b/jdk/make/sun/security/pkcs11/mapfile-vers @@ -102,7 +102,7 @@ SUNWprivate_1.1 { 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: diff --git a/jdk/makefiles/mapfiles/libj2pkcs11/mapfile-vers b/jdk/makefiles/mapfiles/libj2pkcs11/mapfile-vers index 7301c11417d..6ca76c07047 100644 --- a/jdk/makefiles/mapfiles/libj2pkcs11/mapfile-vers +++ b/jdk/makefiles/mapfiles/libj2pkcs11/mapfile-vers @@ -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 @@ SUNWprivate_1.1 { 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: diff --git a/jdk/src/share/classes/sun/security/pkcs11/Config.java b/jdk/src/share/classes/sun/security/pkcs11/Config.java index 4613719c9d1..f4bcc589131 100644 --- a/jdk/src/share/classes/sun/security/pkcs11/Config.java +++ b/jdk/src/share/classes/sun/security/pkcs11/Config.java @@ -197,6 +197,10 @@ final class Config { // (false). private boolean useEcX963Encoding = false; + // Flag to indicate whether NSS should favour performance (false) or + // memory footprint (true). + private boolean nssOptimizeSpace = false; + private Config(String filename, InputStream in) throws IOException { if (in == null) { if (filename.startsWith("--")) { @@ -329,6 +333,10 @@ final class Config { return useEcX963Encoding; } + boolean getNssOptimizeSpace() { + return nssOptimizeSpace; + } + private static String expand(final String s) throws IOException { try { return PropertyExpander.expand(s); @@ -451,6 +459,8 @@ final class Config { nssUseSecmodTrust = parseBooleanEntry(word); } else if (word.equals("useEcX963Encoding")) { useEcX963Encoding = parseBooleanEntry(word); + } else if (word.equals("nssOptimizeSpace")) { + nssOptimizeSpace = parseBooleanEntry(word); } else { throw new ConfigurationException ("Unknown keyword '" + word + "', line " + st.lineno()); diff --git a/jdk/src/share/classes/sun/security/pkcs11/Secmod.java b/jdk/src/share/classes/sun/security/pkcs11/Secmod.java index 07651fe39ca..927a32ae761 100644 --- a/jdk/src/share/classes/sun/security/pkcs11/Secmod.java +++ b/jdk/src/share/classes/sun/security/pkcs11/Secmod.java @@ -158,11 +158,17 @@ public final class Secmod { */ public void initialize(String configDir, String nssLibDir) throws IOException { - initialize(DbMode.READ_WRITE, configDir, nssLibDir); + initialize(DbMode.READ_WRITE, configDir, nssLibDir, false); } - public synchronized void initialize(DbMode dbMode, String configDir, String nssLibDir) + public void initialize(DbMode dbMode, String configDir, String nssLibDir) throws IOException { + initialize(dbMode, configDir, nssLibDir, false); + } + + public synchronized void initialize(DbMode dbMode, String configDir, + String nssLibDir, boolean nssOptimizeSpace) throws IOException { + if (isInitialized()) { throw new IOException("NSS is already initialized"); } @@ -211,7 +217,8 @@ public final class Secmod { } if (DEBUG) System.out.println("dir: " + configDir); - boolean initok = nssInit(dbMode.functionName, nssHandle, configDir); + boolean initok = nssInitialize(dbMode.functionName, nssHandle, + configDir, nssOptimizeSpace); if (DEBUG) System.out.println("init: " + initok); if (initok == false) { throw new IOException("NSS initialization failed"); @@ -764,7 +771,7 @@ public final class Secmod { private static native boolean nssVersionCheck(long handle, String minVersion); - private static native boolean nssInit(String functionName, long handle, String configDir); + private static native boolean nssInitialize(String functionName, long handle, String configDir, boolean nssOptimizeSpace); private static native Object nssGetModuleList(long handle, String libDir); diff --git a/jdk/src/share/classes/sun/security/pkcs11/SunPKCS11.java b/jdk/src/share/classes/sun/security/pkcs11/SunPKCS11.java index d138d675a48..ee9169b59d8 100644 --- a/jdk/src/share/classes/sun/security/pkcs11/SunPKCS11.java +++ b/jdk/src/share/classes/sun/security/pkcs11/SunPKCS11.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -167,6 +167,7 @@ public final class SunPKCS11 extends AuthProvider { try { String nssLibraryDirectory = config.getNssLibraryDirectory(); String nssSecmodDirectory = config.getNssSecmodDirectory(); + boolean nssOptimizeSpace = config.getNssOptimizeSpace(); if (secmod.isInitialized()) { if (nssSecmodDirectory != null) { @@ -204,7 +205,7 @@ public final class SunPKCS11 extends AuthProvider { } } secmod.initialize(nssDbMode, nssSecmodDirectory, - nssLibraryDirectory); + nssLibraryDirectory, nssOptimizeSpace); } } catch (IOException e) { // XXX which exception to throw diff --git a/jdk/src/share/native/sun/security/pkcs11/j2secmod.c b/jdk/src/share/native/sun/security/pkcs11/j2secmod.c index 79ad8709e12..9c648fa09e6 100644 --- a/jdk/src/share/native/sun/security/pkcs11/j2secmod.c +++ b/jdk/src/share/native/sun/security/pkcs11/j2secmod.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,20 +51,63 @@ JNIEXPORT jboolean JNICALL Java_sun_security_pkcs11_Secmod_nssVersionCheck return (res == 0) ? JNI_FALSE : JNI_TRUE; } -JNIEXPORT jboolean JNICALL Java_sun_security_pkcs11_Secmod_nssInit - (JNIEnv *env, jclass thisClass, jstring jFunctionName, jlong jHandle, jstring jConfigDir) +/* + * Initializes NSS. + * The NSS_INIT_OPTIMIZESPACE flag is supplied by the caller. + * The NSS_Init* functions are mapped to the NSS_Initialize function. + */ +JNIEXPORT jboolean JNICALL Java_sun_security_pkcs11_Secmod_nssInitialize + (JNIEnv *env, jclass thisClass, jstring jFunctionName, jlong jHandle, jstring jConfigDir, jboolean jNssOptimizeSpace) { - const char *functionName = (*env)->GetStringUTFChars(env, jFunctionName, NULL); - const char *configDir = (jConfigDir == NULL) ? NULL : (*env)->GetStringUTFChars(env, jConfigDir, NULL); - FPTR_Init init = (FPTR_Init)findFunction(env, jHandle, functionName); - int res; + const char *functionName = + (*env)->GetStringUTFChars(env, jFunctionName, NULL); + const char *configDir = (jConfigDir == NULL) + ? NULL : (*env)->GetStringUTFChars(env, jConfigDir, NULL); + FPTR_Initialize initialize = + (FPTR_Initialize)findFunction(env, jHandle, "NSS_Initialize"); + int res = 0; + unsigned int flags = 0x00; - (*env)->ReleaseStringUTFChars(env, jFunctionName, functionName); - if (init == NULL) { - return JNI_FALSE; + if (jNssOptimizeSpace == JNI_TRUE) { + flags = 0x20; // NSS_INIT_OPTIMIZESPACE flag } - res = init(configDir); + if (initialize != NULL) { + /* + * If the NSS_Init function is requested then call NSS_Initialize to + * open the Cert, Key and Security Module databases, read only. + */ + if (strcmp("NSS_Init", functionName) == 0) { + flags = flags | 0x01; // NSS_INIT_READONLY flag + res = initialize(configDir, "", "", "secmod.db", flags); + + /* + * If the NSS_InitReadWrite function is requested then call + * NSS_Initialize to open the Cert, Key and Security Module databases, + * read/write. + */ + } else if (strcmp("NSS_InitReadWrite", functionName) == 0) { + res = initialize(configDir, "", "", "secmod.db", flags); + + /* + * If the NSS_NoDB_Init function is requested then call + * NSS_Initialize without creating Cert, Key or Security Module + * databases. + */ + } else if (strcmp("NSS_NoDB_Init", functionName) == 0) { + flags = flags | 0x02 // NSS_INIT_NOCERTDB flag + | 0x04 // NSS_INIT_NOMODDB flag + | 0x08 // NSS_INIT_FORCEOPEN flag + | 0x10; // NSS_INIT_NOROOTINIT flag + res = initialize("", "", "", "", flags); + + } else { + res = 2; + } + } else { + res = 1; + } + (*env)->ReleaseStringUTFChars(env, jFunctionName, functionName); if (configDir != NULL) { (*env)->ReleaseStringUTFChars(env, jConfigDir, configDir); } diff --git a/jdk/src/solaris/native/sun/security/pkcs11/j2secmod_md.h b/jdk/src/solaris/native/sun/security/pkcs11/j2secmod_md.h index 61a7734bf96..8595a1700b8 100644 --- a/jdk/src/solaris/native/sun/security/pkcs11/j2secmod_md.h +++ b/jdk/src/solaris/native/sun/security/pkcs11/j2secmod_md.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,9 +25,14 @@ // in nss.h: // extern PRBool NSS_VersionCheck(const char *importedVersion); -// extern SECStatus NSS_Init(const char *configdir); +// extern SECStatus NSS_Initialize(const char *configdir, +// const char *certPrefix, const char *keyPrefix, +// const char *secmodName, PRUint32 flags); + typedef int (*FPTR_VersionCheck)(const char *importedVersion); -typedef int (*FPTR_Init)(const char *configdir); +typedef int (*FPTR_Initialize)(const char *configdir, + const char *certPrefix, const char *keyPrefix, + const char *secmodName, unsigned int flags); // in secmod.h //extern SECMODModule *SECMOD_LoadModule(char *moduleSpec,SECMODModule *parent, diff --git a/jdk/src/windows/native/sun/security/pkcs11/j2secmod_md.h b/jdk/src/windows/native/sun/security/pkcs11/j2secmod_md.h index 454dbee395c..b6dedd00dda 100644 --- a/jdk/src/windows/native/sun/security/pkcs11/j2secmod_md.h +++ b/jdk/src/windows/native/sun/security/pkcs11/j2secmod_md.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,9 +27,14 @@ // in nss.h: // extern PRBool NSS_VersionCheck(const char *importedVersion); -// extern SECStatus NSS_Init(const char *configdir); +// extern SECStatus NSS_Initialize(const char *configdir, +// const char *certPrefix, const char *keyPrefix, +// const char *secmodName, PRUint32 flags); + typedef int __declspec(dllimport) (*FPTR_VersionCheck)(const char *importedVersion); -typedef int __declspec(dllimport) (*FPTR_Init)(const char *configdir); +typedef int __declspec(dllimport) (*FPTR_Initialize)(const char *configdir, + const char *certPrefix, const char *keyPrefix, + const char *secmodName, unsigned int flags); // in secmod.h //extern SECMODModule *SECMOD_LoadModule(char *moduleSpec,SECMODModule *parent, From 5ccee02c35e76a4aeb54e3155d1b8c188a6bf609 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Wed, 3 Jul 2013 13:13:17 +0530 Subject: [PATCH 005/123] 8019783: typeof does not work properly for java methods and foreign objects Reviewed-by: hannesw --- .../jdk/nashorn/internal/runtime/JSType.java | 10 ++++ .../internal/runtime/ScriptRuntime.java | 2 + nashorn/test/script/basic/JDK-8019783.js | 55 +++++++++++++++++++ .../test/script/basic/JDK-8019783.js.EXPECTED | 9 +++ .../test/script/basic/NASHORN-759.js.EXPECTED | 2 +- 5 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 nashorn/test/script/basic/JDK-8019783.js create mode 100644 nashorn/test/script/basic/JDK-8019783.js.EXPECTED diff --git a/nashorn/src/jdk/nashorn/internal/runtime/JSType.java b/nashorn/src/jdk/nashorn/internal/runtime/JSType.java index 9507f0d3205..4d1d825c852 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/JSType.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/JSType.java @@ -29,7 +29,9 @@ import static jdk.nashorn.internal.codegen.CompilerConstants.staticCall; import static jdk.nashorn.internal.runtime.ECMAErrors.typeError; import java.util.Locale; +import jdk.internal.dynalink.beans.BeansLinker; import jdk.internal.dynalink.beans.StaticClass; +import jdk.nashorn.api.scripting.ScriptObjectMirror; import jdk.nashorn.internal.codegen.CompilerConstants.Call; import jdk.nashorn.internal.parser.Lexer; @@ -151,6 +153,14 @@ public enum JSType { return JSType.FUNCTION; } + if (BeansLinker.isDynamicMethod(obj)) { + return JSType.FUNCTION; + } + + if (obj instanceof ScriptObjectMirror) { + return ((ScriptObjectMirror)obj).isFunction()? JSType.FUNCTION : JSType.OBJECT; + } + return JSType.OBJECT; } diff --git a/nashorn/src/jdk/nashorn/internal/runtime/ScriptRuntime.java b/nashorn/src/jdk/nashorn/internal/runtime/ScriptRuntime.java index 1144c57d76d..f0b68c52ddf 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptRuntime.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptRuntime.java @@ -592,6 +592,8 @@ public final class ScriptRuntime { throw typeError("cant.get.property", safeToString(property), "null"); } else if (JSType.isPrimitive(obj)) { obj = ((ScriptObject)JSType.toScriptObject(obj)).get(property); + } else if (obj instanceof ScriptObjectMirror) { + obj = ((ScriptObjectMirror)obj).getMember(property.toString()); } else { obj = UNDEFINED; } diff --git a/nashorn/test/script/basic/JDK-8019783.js b/nashorn/test/script/basic/JDK-8019783.js new file mode 100644 index 00000000000..27afcaf2a85 --- /dev/null +++ b/nashorn/test/script/basic/JDK-8019783.js @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * 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. + */ + +/** + * JDK-8019783: typeof does not work properly for java methods and foreign objects + * + * @test + * @run + */ + +function printTypeof(str) { + print("typeof(" + str + ") = " + eval('typeof ' + str)); +} + +// Java methods +printTypeof("java.lang.System.exit"); +printTypeof("java.lang.System['exit']"); +// full signature +printTypeof("java.lang.System['exit(int)']"); +// overloaded method +printTypeof("java.security.AccessController.doPrivileged"); +printTypeof("java.security.AccessController['doPrivileged']"); + +// foreign objects +var global = loadWithNewGlobal({ name: "t", script: "this" }); +print("typeof(global.Object) = " + (typeof global.Object)); +print("typeof(new global.Object()) = " + (typeof (new global.Object()))); + +// foreign engine objects +var m = new javax.script.ScriptEngineManager(); +var engine = m.getEngineByName("nashorn"); +var engineGlobal = engine.eval("this"); + +print("typeof(engineGlobal.Object) = " + (typeof engineGlobal.Object)); +print("typeof(new engineGlobal.Object()) = " + (typeof (new engineGlobal.Object()))); diff --git a/nashorn/test/script/basic/JDK-8019783.js.EXPECTED b/nashorn/test/script/basic/JDK-8019783.js.EXPECTED new file mode 100644 index 00000000000..f2a5588bea6 --- /dev/null +++ b/nashorn/test/script/basic/JDK-8019783.js.EXPECTED @@ -0,0 +1,9 @@ +typeof(java.lang.System.exit) = function +typeof(java.lang.System['exit']) = function +typeof(java.lang.System['exit(int)']) = function +typeof(java.security.AccessController.doPrivileged) = function +typeof(java.security.AccessController['doPrivileged']) = function +typeof(global.Object) = function +typeof(new global.Object()) = object +typeof(engineGlobal.Object) = function +typeof(new engineGlobal.Object()) = object diff --git a/nashorn/test/script/basic/NASHORN-759.js.EXPECTED b/nashorn/test/script/basic/NASHORN-759.js.EXPECTED index ccb88e0f00e..5d0001ef327 100644 --- a/nashorn/test/script/basic/NASHORN-759.js.EXPECTED +++ b/nashorn/test/script/basic/NASHORN-759.js.EXPECTED @@ -11,7 +11,7 @@ number true object -object +function false T,h,e, ,q,u,i,c,k, ,g,r,a,y, ,n,a,s,h,o,r,n, ,j,u,m,p,s, ,o,v,e,r, ,t,h,e, ,l,a,z,y, ,z,e,b,r,a,. From 6dfb638284f1dc7d5f4e5770f592ac3a0d0a789d Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Wed, 3 Jul 2013 14:08:00 +0530 Subject: [PATCH 006/123] 8019791: ~ is a unary operator Reviewed-by: hannesw --- .../nashorn/internal/parser/TokenType.java | 2 +- nashorn/test/script/basic/JDK-8019791.js | 50 +++++++++++++++++++ .../test/script/basic/JDK-8019791.js.EXPECTED | 6 +++ 3 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 nashorn/test/script/basic/JDK-8019791.js create mode 100644 nashorn/test/script/basic/JDK-8019791.js.EXPECTED diff --git a/nashorn/src/jdk/nashorn/internal/parser/TokenType.java b/nashorn/src/jdk/nashorn/internal/parser/TokenType.java index 92f3ad745be..c92b9e98284 100644 --- a/nashorn/src/jdk/nashorn/internal/parser/TokenType.java +++ b/nashorn/src/jdk/nashorn/internal/parser/TokenType.java @@ -93,7 +93,7 @@ public enum TokenType { ASSIGN_BIT_OR (BINARY, "|=", 2, false), OR (BINARY, "||", 4, true), RBRACE (BRACKET, "}"), - BIT_NOT (BINARY, "~", 14, false), + BIT_NOT (UNARY, "~", 14, false), // ECMA 7.6.1.1 Keywords, 7.6.1.2 Future Reserved Words. // All other Java keywords are commented out. diff --git a/nashorn/test/script/basic/JDK-8019791.js b/nashorn/test/script/basic/JDK-8019791.js new file mode 100644 index 00000000000..75e92819d89 --- /dev/null +++ b/nashorn/test/script/basic/JDK-8019791.js @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * 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. + */ + +/** + * JDK-8019791: ~ is a unary operator + * + * @test + * @run + */ + +// Used to crash instead of SyntaxError +try { + eval('"" ~ ""'); + print("FAILED: SyntaxError expected for: \"\" ~ \"\""); +} catch (e) { + print(e.toString().replace(/\\/g, '/')); +} + +// Used to crash instead of SyntaxError +try { + eval("function() { if (1~0) return 0; return 1 }"); + print("FAILED: SyntaxError expected for: if (1~0) "); +} catch (e) { + print(e.toString().replace(/\\/g, '/')); +} + +// The following are valid, but used to crash +Function("0 \n ~ 2 \n ~ 1")(); + +Function("~ ~ 0 \n ~ ~ 1")(); diff --git a/nashorn/test/script/basic/JDK-8019791.js.EXPECTED b/nashorn/test/script/basic/JDK-8019791.js.EXPECTED new file mode 100644 index 00000000000..5aec5909ada --- /dev/null +++ b/nashorn/test/script/basic/JDK-8019791.js.EXPECTED @@ -0,0 +1,6 @@ +SyntaxError: test/script/basic/JDK-8019791.js#33:1:3 Expected ; but found ~ +"" ~ "" + ^ +SyntaxError: test/script/basic/JDK-8019791.js#41:1:18 Expected ) but found ~ +function() { if (1~0) return 0; return 1 } + ^ From efb561f6322b6d539d2bd8374ca53e3498b3968e Mon Sep 17 00:00:00 2001 From: Doug Lea Date: Wed, 3 Jul 2013 11:58:09 +0200 Subject: [PATCH 007/123] 8011427: java.util.concurrent collection Spliterator implementations Reviewed-by: martin --- .../util/concurrent/ArrayBlockingQueue.java | 955 ++++++++-- .../java/util/concurrent/BlockingDeque.java | 119 +- .../java/util/concurrent/BlockingQueue.java | 99 +- .../concurrent/ConcurrentLinkedDeque.java | 120 +- .../concurrent/ConcurrentLinkedQueue.java | 97 +- .../concurrent/ConcurrentSkipListMap.java | 1670 +++++++++++------ .../concurrent/ConcurrentSkipListSet.java | 98 +- .../util/concurrent/CopyOnWriteArrayList.java | 664 ++++--- .../util/concurrent/CopyOnWriteArraySet.java | 95 +- .../java/util/concurrent/DelayQueue.java | 139 +- .../classes/java/util/concurrent/Delayed.java | 4 +- .../util/concurrent/LinkedBlockingDeque.java | 141 +- .../util/concurrent/LinkedBlockingQueue.java | 130 +- .../util/concurrent/LinkedTransferQueue.java | 114 +- .../concurrent/PriorityBlockingQueue.java | 77 +- .../util/concurrent/SynchronousQueue.java | 98 +- 16 files changed, 3243 insertions(+), 1377 deletions(-) diff --git a/jdk/src/share/classes/java/util/concurrent/ArrayBlockingQueue.java b/jdk/src/share/classes/java/util/concurrent/ArrayBlockingQueue.java index 74f1e985523..fe91686627d 100644 --- a/jdk/src/share/classes/java/util/concurrent/ArrayBlockingQueue.java +++ b/jdk/src/share/classes/java/util/concurrent/ArrayBlockingQueue.java @@ -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 @@ public class ArrayBlockingQueue extends AbstractQueue /** 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 - /** - * Circularly increment i. + * Shared state for currently active iterators, or null if there + * are known not to be any. Allows queue operations to update + * iterator state. */ - final int inc(int i) { - return (++i == items.length) ? 0 : i; - } + transient Itrs itrs = null; + + // Internal helper methods /** * Circularly decrement i. @@ -123,11 +132,6 @@ public class ArrayBlockingQueue extends AbstractQueue return ((i == 0) ? items.length : i) - 1; } - @SuppressWarnings("unchecked") - static E cast(Object item) { - return (E) item; - } - /** * Returns item at index i. */ @@ -150,10 +154,14 @@ public class ArrayBlockingQueue extends AbstractQueue * 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 @@ public class ArrayBlockingQueue extends AbstractQueue * 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 @@ public class ArrayBlockingQueue extends AbstractQueue if (count == items.length) return false; else { - insert(e); + enqueue(e); return true; } } finally { @@ -324,7 +351,7 @@ public class ArrayBlockingQueue extends AbstractQueue try { while (count == items.length) notFull.await(); - insert(e); + enqueue(e); } finally { lock.unlock(); } @@ -351,7 +378,7 @@ public class ArrayBlockingQueue extends AbstractQueue return false; nanos = notFull.awaitNanos(nanos); } - insert(e); + enqueue(e); return true; } finally { lock.unlock(); @@ -362,7 +389,7 @@ public class ArrayBlockingQueue extends AbstractQueue 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 @@ public class ArrayBlockingQueue extends AbstractQueue try { while (count == 0) notEmpty.await(); - return extract(); + return dequeue(); } finally { lock.unlock(); } @@ -390,7 +417,7 @@ public class ArrayBlockingQueue extends AbstractQueue return null; nanos = notEmpty.awaitNanos(nanos); } - return extract(); + return dequeue(); } finally { lock.unlock(); } @@ -400,7 +427,7 @@ public class ArrayBlockingQueue extends AbstractQueue 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 @@ public class ArrayBlockingQueue extends AbstractQueue 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 @@ public class ArrayBlockingQueue extends AbstractQueue 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 @@ public class ArrayBlockingQueue extends AbstractQueue * @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 @@ public class ArrayBlockingQueue extends AbstractQueue * The following code can be used to dump the queue into a newly * allocated array of {@code String}: * - *
    -     *     String[] y = x.toArray(new String[0]);
    + *
     {@code String[] y = x.toArray(new String[0]);}
    * * Note that {@code toArray(new Object[0])} is identical in function to * {@code toArray()}. @@ -579,14 +623,19 @@ public class ArrayBlockingQueue extends AbstractQueue 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 @@ public class ArrayBlockingQueue extends AbstractQueue 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 @@ public class ArrayBlockingQueue extends AbstractQueue 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 @@ public class ArrayBlockingQueue extends AbstractQueue * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection 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 @@ public class ArrayBlockingQueue extends AbstractQueue 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 @@ public class ArrayBlockingQueue extends AbstractQueue * 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). * - *

    The returned {@code Iterator} is a "weakly consistent" iterator that + *

    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 @@ public class ArrayBlockingQueue extends AbstractQueue } /** - * 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. */ - private class Itr implements Iterator { - 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 + class Itrs { - Itr() { - final ReentrantLock lock = ArrayBlockingQueue.this.lock; - lock.lock(); - try { - lastRet = -1; - if ((remaining = count) > 0) - nextItem = itemAt(nextIndex = takeIndex); - } finally { - lock.unlock(); + /** + * Node in a linked list of weak iterator references. + */ + private class Node extends WeakReference { + Node next; + + Node(Itr iterator, Node next) { + super(iterator); + this.next = next; } } - public boolean hasNext() { - return remaining > 0; + /** 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); } - public E next() { - 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 + /** + * 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; } - else - lastItem = x; - while (--remaining > 0 && // skip over nulls - (nextItem = itemAt(nextIndex = inc(nextIndex))) == null) - ; - return x; - } finally { - lock.unlock(); + 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; } - public void remove() { - 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); + /** + * 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; } - } finally { - lock.unlock(); + 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 { + /** 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 { + 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(); + } + } + + 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; + } + + /** + * 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 { + // 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(); + } + } + // assert isDetached(); + // assert lastRet < 0 ^ lastItem != null; + } finally { + lock.unlock(); + } + } + + 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 { + 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 spliterator() { + return Spliterators.spliterator + (this, Spliterator.ORDERED | Spliterator.NONNULL | + Spliterator.CONCURRENT); + } } diff --git a/jdk/src/share/classes/java/util/concurrent/BlockingDeque.java b/jdk/src/share/classes/java/util/concurrent/BlockingDeque.java index 7f37f7e66ea..d98586a95b5 100644 --- a/jdk/src/share/classes/java/util/concurrent/BlockingDeque.java +++ b/jdk/src/share/classes/java/util/concurrent/BlockingDeque.java @@ -41,17 +41,18 @@ import java.util.*; * 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. * - *

    BlockingDeque methods come in four forms, with different ways + *

    {@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 - * null or false, 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: * *

    * + * * * * @@ -116,20 +117,21 @@ import java.util.*; * *
    Summary of BlockingDeque methods
    First Element (Head)
    * - *

    Like any {@link BlockingQueue}, a BlockingDeque is thread safe, + *

    Like any {@link BlockingQueue}, a {@code BlockingDeque} is thread safe, * does not permit null elements, and may (or may not) be * capacity-constrained. * - *

    A BlockingDeque implementation may be used directly as a FIFO - * BlockingQueue. The methods inherited from the - * BlockingQueue interface are precisely equivalent to - * BlockingDeque methods as indicated in the following table: + *

    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: * *

    * + * * - * - * + * + * * * * @@ -208,7 +210,7 @@ public interface BlockingDeque extends BlockingQueue, Deque { /** * Inserts the specified element at the front of this deque if it is * possible to do so immediately without violating capacity restrictions, - * throwing an IllegalStateException 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 @@ public interface BlockingDeque extends BlockingQueue, Deque { /** * Inserts the specified element at the end of this deque if it is * possible to do so immediately without violating capacity restrictions, - * throwing an IllegalStateException 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 @@ public interface BlockingDeque extends BlockingQueue, Deque { /** * Inserts the specified element at the front of this deque if it is * possible to do so immediately without violating capacity restrictions, - * returning true upon success and false 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 @@ public interface BlockingDeque extends BlockingQueue, Deque { /** * Inserts the specified element at the end of this deque if it is * possible to do so immediately without violating capacity restrictions, - * returning true upon success and false 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 @@ public interface BlockingDeque extends BlockingQueue, Deque { * * @param e the element to add * @param timeout how long to wait before giving up, in units of - * unit - * @param unit a TimeUnit determining how to interpret the - * timeout parameter - * @return true if successful, or false 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 @@ public interface BlockingDeque extends BlockingQueue, Deque { * * @param e the element to add * @param timeout how long to wait before giving up, in units of - * unit - * @param unit a TimeUnit determining how to interpret the - * timeout parameter - * @return true if successful, or false 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 @@ public interface BlockingDeque extends BlockingQueue, Deque { * become available. * * @param timeout how long to wait before giving up, in units of - * unit - * @param unit a TimeUnit determining how to interpret the - * timeout parameter - * @return the head of this deque, or null 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 @@ public interface BlockingDeque extends BlockingQueue, Deque { * become available. * * @param timeout how long to wait before giving up, in units of - * unit - * @param unit a TimeUnit determining how to interpret the - * timeout parameter - * @return the tail of this deque, or null 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 @@ public interface BlockingDeque extends BlockingQueue, Deque { /** * 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 e such that - * o.equals(e) (if such an element exists). - * Returns true 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 true 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 * (optional) @@ -410,13 +412,13 @@ public interface BlockingDeque extends BlockingQueue, Deque { /** * 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 e such that - * o.equals(e) (if such an element exists). - * Returns true 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 true 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 * (optional) @@ -431,8 +433,8 @@ public interface BlockingDeque extends BlockingQueue, Deque { * 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 - * true upon success and throwing an - * IllegalStateException 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 @@ public interface BlockingDeque extends BlockingQueue, Deque { * 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 - * true upon success and false 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 @@ public interface BlockingDeque extends BlockingQueue, Deque { * {@link #offerLast(Object,long,TimeUnit) offerLast}. * * @param e the element to add - * @return true if the element was added to this deque, else - * false + * @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 @@ public interface BlockingDeque extends BlockingQueue, Deque { /** * Retrieves and removes the head of the queue represented by this deque * (in other words, the first element of this deque), or returns - * null if this deque is empty. + * {@code null} if this deque is empty. * *

    This method is equivalent to {@link #pollFirst()}. * - * @return the head of this deque, or null 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 @@ public interface BlockingDeque extends BlockingQueue, Deque { *

    This method is equivalent to * {@link #pollFirst(long,TimeUnit) pollFirst}. * - * @return the head of this deque, or null 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 @@ public interface BlockingDeque extends BlockingQueue, Deque { /** * 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 null if this deque is empty. + * returns {@code null} if this deque is empty. * *

    This method is equivalent to {@link #peekFirst() peekFirst}. * - * @return the head of this deque, or null 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 e such that - * o.equals(e) (if such an element exists). - * Returns true 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). * *

    This method is equivalent to * {@link #removeFirstOccurrence(Object) removeFirstOccurrence}. * * @param o element to be removed from this deque, if present - * @return true 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 * (optional) @@ -603,12 +605,12 @@ public interface BlockingDeque extends BlockingQueue, Deque { boolean remove(Object o); /** - * Returns true if this deque contains the specified element. - * More formally, returns true if and only if this deque contains - * at least one element e such that o.equals(e). + * 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 true 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 * (optional) @@ -635,9 +637,10 @@ public interface BlockingDeque extends BlockingQueue, Deque { // *** 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. * *

    This method is equivalent to {@link #addFirst(Object) addFirst}. * diff --git a/jdk/src/share/classes/java/util/concurrent/BlockingQueue.java b/jdk/src/share/classes/java/util/concurrent/BlockingQueue.java index bb5eb603324..8eb3ce2c984 100644 --- a/jdk/src/share/classes/java/util/concurrent/BlockingQueue.java +++ b/jdk/src/share/classes/java/util/concurrent/BlockingQueue.java @@ -44,17 +44,18 @@ import java.util.Queue; * element, and wait for space to become available in the queue when * storing an element. * - *

    BlockingQueue methods come in four forms, with different ways + *

    {@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 - * null or false, 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: * *

    *

    Comparison of BlockingQueue and BlockingDeque methods
    BlockingQueue Method Equivalent BlockingDeque Method {@code BlockingQueue} Method Equivalent {@code BlockingDeque} Method
    Insert
    + * * * * @@ -85,37 +86,37 @@ import java.util.Queue; * *
    Summary of BlockingQueue methods
    Throws exception
    * - *

    A BlockingQueue does not accept null elements. - * Implementations throw NullPointerException on attempts - * to add, put or offer a null. A - * null is used as a sentinel value to indicate failure of - * poll operations. + *

    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. * - *

    A BlockingQueue may be capacity bounded. At any given - * time it may have a remainingCapacity beyond which no - * additional elements can be put without blocking. - * A BlockingQueue without any intrinsic capacity constraints always - * reports a remaining capacity of Integer.MAX_VALUE. + *

    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}. * - *

    BlockingQueue implementations are designed to be used + *

    {@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 - * remove(x). However, such operations are in general + * {@code remove(x)}. However, such operations are in general * not performed very efficiently, and are intended for only * occasional use, such as when a queued message is cancelled. * - *

    BlockingQueue implementations are thread-safe. All + *

    {@code BlockingQueue} implementations are thread-safe. All * queuing methods achieve their effects atomically using internal * locks or other forms of concurrency control. However, the - * bulk Collection operations addAll, - * containsAll, retainAll and removeAll are + * bulk Collection operations {@code addAll}, + * {@code containsAll}, {@code retainAll} and {@code removeAll} are * not necessarily performed atomically unless specified * otherwise in an implementation. So it is possible, for example, for - * addAll(c) to fail (throwing an exception) after adding - * only some of the elements in c. + * {@code addAll(c)} to fail (throwing an exception) after adding + * only some of the elements in {@code c}. * - *

    A BlockingQueue does not intrinsically support + *

    A {@code BlockingQueue} does not intrinsically support * any kind of "close" or "shutdown" 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 @@ import java.util.Queue; * *

    * Usage example, based on a typical producer-consumer scenario. - * Note that a BlockingQueue can safely be used with multiple + * Note that a {@code BlockingQueue} can safely be used with multiple * producers and multiple consumers. *

     {@code
      * class Producer implements Runnable {
    @@ -181,13 +182,13 @@ public interface BlockingQueue extends Queue {
         /**
          * Inserts the specified element into this queue if it is possible to do
          * so immediately without violating capacity restrictions, returning
    -     * true upon success and throwing an
    -     * IllegalStateException 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 true (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 @@ public interface BlockingQueue extends Queue {
         /**
          * Inserts the specified element into this queue if it is possible to do
          * so immediately without violating capacity restrictions, returning
    -     * true upon success and false 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 true if the element was added to this queue, else
    -     *         false
    +     * @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 @@ public interface BlockingQueue extends Queue {
          *
          * @param e the element to add
          * @param timeout how long to wait before giving up, in units of
    -     *        unit
    -     * @param unit a TimeUnit determining how to interpret the
    -     *        timeout parameter
    -     * @return true if successful, or false 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 @@ public interface BlockingQueue extends Queue {
          * specified wait time if necessary for an element to become available.
          *
          * @param timeout how long to wait before giving up, in units of
    -     *        unit
    -     * @param unit a TimeUnit determining how to interpret the
    -     *        timeout parameter
    -     * @return the head of this queue, or null 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 @@ public interface BlockingQueue extends Queue {
         /**
          * Returns the number of additional elements that this queue can ideally
          * (in the absence of memory or resource constraints) accept without
    -     * blocking, or Integer.MAX_VALUE if there is no intrinsic
    +     * blocking, or {@code Integer.MAX_VALUE} if there is no intrinsic
          * limit.
          *
          * 

    Note that you cannot always tell if an attempt to insert - * an element will succeed by inspecting remainingCapacity + * 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 @@ public interface BlockingQueue extends Queue { /** * Removes a single instance of the specified element from this queue, - * if it is present. More formally, removes an element e such - * that o.equals(e), 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 true 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 true 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 * (optional) @@ -310,12 +311,12 @@ public interface BlockingQueue extends Queue { boolean remove(Object o); /** - * Returns true if this queue contains the specified element. - * More formally, returns true if and only if this queue contains - * at least one element e such that o.equals(e). + * 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 true 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 * (optional) @@ -329,10 +330,10 @@ public interface BlockingQueue extends Queue { * 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 c 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 - * IllegalArgumentException. 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 @@ public interface BlockingQueue extends Queue { * 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 c 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 - * IllegalArgumentException. 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. * diff --git a/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java b/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java index 146934af475..6bb62f0f98c 100644 --- a/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java +++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java @@ -42,6 +42,9 @@ import java.util.Deque; 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 @@ public class ConcurrentLinkedDeque * Creates an array list and fills it with elements of this list. * Used by toArray. * - * @return the arrayList + * @return the array list */ private ArrayList toArrayList() { ArrayList list = new ArrayList(); @@ -1024,12 +1027,28 @@ public class ConcurrentLinkedDeque } public E poll() { return pollFirst(); } - public E remove() { return removeFirst(); } public E peek() { return peekFirst(); } - public E element() { return getFirst(); } - public void push(E e) { addFirst(e); } + + /** + * @throws NoSuchElementException {@inheritDoc} + */ + public E remove() { return removeFirst(); } + + /** + * @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); } + /** * Removes the first element {@code e} such that * {@code o.equals(e)}, if such an element exists in this deque. @@ -1385,6 +1404,99 @@ public class ConcurrentLinkedDeque Node nextNode(Node p) { return pred(p); } } + /** A customized variant of Spliterators.IteratorSpliterator */ + static final class CLDSpliterator implements Spliterator { + static final int MAX_BATCH = 1 << 25; // max batch array size; + final ConcurrentLinkedDeque queue; + Node current; // current node; null until initialized + int batch; // batch size for splits + boolean exhausted; // true when no more nodes + CLDSpliterator(ConcurrentLinkedDeque queue) { + this.queue = queue; + } + + public Spliterator trySplit() { + Node p; + final ConcurrentLinkedDeque 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 action) { + Node p; + if (action == null) throw new NullPointerException(); + final ConcurrentLinkedDeque 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 action) { + Node p; + if (action == null) throw new NullPointerException(); + final ConcurrentLinkedDeque 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 spliterator() { + return new CLDSpliterator(this); + } + /** * Saves this deque to a stream (that is, serializes it). * diff --git a/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java b/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java index abf12c59760..0b562bc217d 100644 --- a/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java +++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java @@ -41,6 +41,9 @@ import java.util.Collection; 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 @@ import java.util.Queue; * Like most other concurrent collection implementations, this class * does not permit the use of {@code null} elements. * - *

    This implementation employs an efficient "wait-free" + *

    This implementation employs an efficient non-blocking * algorithm based on one described in Simple, * Fast, and Practical Non-Blocking and Blocking Concurrent Queue @@ -295,7 +298,7 @@ public class ConcurrentLinkedQueue extends AbstractQueue } /** - * 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 h, Node p) { @@ -792,6 +795,96 @@ public class ConcurrentLinkedQueue extends AbstractQueue tail = t; } + /** A customized variant of Spliterators.IteratorSpliterator */ + static final class CLQSpliterator implements Spliterator { + static final int MAX_BATCH = 1 << 25; // max batch array size; + final ConcurrentLinkedQueue queue; + Node current; // current node; null until initialized + int batch; // batch size for splits + boolean exhausted; // true when no more nodes + CLQSpliterator(ConcurrentLinkedQueue queue) { + this.queue = queue; + } + + public Spliterator trySplit() { + Node p; + final ConcurrentLinkedQueue 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 action) { + Node p; + if (action == null) throw new NullPointerException(); + final ConcurrentLinkedQueue 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 action) { + Node p; + if (action == null) throw new NullPointerException(); + final ConcurrentLinkedQueue 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 spliterator() { + return new CLQSpliterator(this); + } + /** * Throws NullPointerException if argument is null. * diff --git a/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListMap.java b/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListMap.java index cd93e211890..99faf166834 100644 --- a/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListMap.java +++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListMap.java @@ -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 @@ import java.util.*; *

    This class implements a concurrent variant of SkipLists * providing expected average log(n) time cost for the - * containsKey, get, put and - * remove 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 weakly consistent, returning * elements reflecting the state of the map at some point at or since * the creation of the iterator. They do not 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. * - *

    All Map.Entry pairs returned by methods in this class + *

    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 not support the Entry.setValue + * produced. They do not support the {@code Entry.setValue} * method. (Note however that it is possible to change mappings in the - * associated map using put, putIfAbsent, or - * replace, depending on exactly which effect you need.) + * associated map using {@code put}, {@code putIfAbsent}, or + * {@code replace}, depending on exactly which effect you need.) * - *

    Beware that, unlike in most collections, the size + *

    Beware that, unlike in most collections, the {@code size} * method is not 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 putAll, equals, - * toArray, containsValue, and clear are + * Additionally, the bulk operations {@code putAll}, {@code equals}, + * {@code toArray}, {@code containsValue}, and {@code clear} are * not guaranteed to be performed atomically. For example, an - * iterator operating concurrently with a putAll operation + * iterator operating concurrently with a {@code putAll} operation * might view only some of the added elements. * *

    This class and its views and iterators implement all of the * optional methods of the {@link Map} and {@link Iterator} * interfaces. Like most other concurrent collections, this class does - * not permit the use of null keys or values because some + * not 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 @@ import java.util.*; * @param the type of mapped values * @since 1.6 */ -@SuppressWarnings("unchecked") public class ConcurrentSkipListMap extends AbstractMap implements ConcurrentNavigableMap, Cloneable, @@ -257,7 +274,7 @@ public class ConcurrentSkipListMap extends AbstractMap * * 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 @@ public class ConcurrentSkipListMap extends AbstractMap * 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 @@ -322,12 +353,6 @@ public class ConcurrentSkipListMap extends AbstractMap 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 */ @@ -339,17 +364,12 @@ public class ConcurrentSkipListMap extends AbstractMap private transient volatile HeadIndex 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 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 comparator; /** Lazily initialized key set */ private transient KeySet keySet; @@ -365,12 +385,11 @@ public class ConcurrentSkipListMap extends AbstractMap * 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(new Node(null, BASE_HEADER, null), null, null, 1); } @@ -438,7 +457,7 @@ public class ConcurrentSkipListMap extends AbstractMap * 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 @@ public class ConcurrentSkipListMap extends AbstractMap */ if (f == next && this == b.next) { if (f == null || f.value != f) // not already marked - appendMarker(f); + casNext(f, new Node(f)); else b.casNext(this, f.next); } @@ -487,13 +506,14 @@ public class ConcurrentSkipListMap extends AbstractMap * 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 @@ public class ConcurrentSkipListMap extends AbstractMap * @return new entry or null */ AbstractMap.SimpleImmutableEntry createSnapshot() { - V v = getValidValue(); - if (v == null) + Object v = value; + if (v == null || v == this || v == BASE_HEADER) return null; - return new AbstractMap.SimpleImmutableEntry(key, v); + @SuppressWarnings("unchecked") V vv = (V)v; + return new AbstractMap.SimpleImmutableEntry(key, vv); } // UNSAFE mechanics @@ -588,7 +609,7 @@ public class ConcurrentSkipListMap extends AbstractMap * @return true if successful */ final boolean unlink(Index succ) { - return !indexesDeletedNode() && casRight(succ, succ.right); + return node.value != null && casRight(succ, succ.right); } // Unsafe mechanics @@ -622,80 +643,12 @@ public class ConcurrentSkipListMap extends AbstractMap /* ---------------- 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. + * Compares using comparator or natural ordering if null. + * Called only by methods that have performed required type checks. */ - static final class ComparableUsingComparator implements Comparable { - final K actualKey; - final Comparator cmp; - ComparableUsingComparator(K key, Comparator 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. - */ - private Comparable comparable(Object key) - throws ClassCastException { - if (key == null) - throw new NullPointerException(); - if (comparator != null) - return new ComparableUsingComparator((K)key, comparator); - else - return (Comparable)key; - } - - /** - * Compares using comparator or natural ordering. Used when the - * ComparableUsingComparator approach doesn't apply. - */ - int compare(K k1, K k2) throws ClassCastException { - Comparator cmp = comparator; - if (cmp != null) - return cmp.compare(k1, k2); - else - return ((Comparable)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 @@ public class ConcurrentSkipListMap extends AbstractMap * @param key the key * @return a predecessor of key */ - private Node findPredecessor(Comparable key) { + private Node findPredecessor(Object key, Comparator cmp) { if (key == null) throw new NullPointerException(); // don't postpone errors for (;;) { - Index q = head; - Index r = q.right; - for (;;) { + for (Index q = head, r = q.right, d;;) { if (r != null) { Node n = r.node; K k = n.key; @@ -724,18 +675,16 @@ public class ConcurrentSkipListMap extends AbstractMap r = q.right; // reread r continue; } - if (key.compareTo(k) > 0) { + if (cpr(cmp, key, k) > 0) { q = r; r = r.right; continue; } } - Index 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 @@ public class ConcurrentSkipListMap extends AbstractMap * @param key the key * @return node holding key, or null if no such */ - private Node findNode(Comparable key) { - for (;;) { - Node b = findPredecessor(key); - Node n = b.next; - for (;;) { + private Node findNode(Object key) { + if (key == null) + throw new NullPointerException(); // don't postpone errors + Comparator cmp = comparator; + outer: for (;;) { + for (Node b = findPredecessor(key, cmp), n = b.next;;) { + Object v; int c; if (n == null) - return null; + break outer; Node 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 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 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 cmp = comparator; + outer: for (;;) { + for (Node b = findPredecessor(key, cmp), n = b.next;;) { + Object v; int c; + if (n == null) + break outer; + Node 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 @@ public class ConcurrentSkipListMap extends AbstractMap /** * 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 key = comparable(kkey); - for (;;) { - Node b = findPredecessor(key); - Node n = b.next; - for (;;) { + private V doPut(K key, V value, boolean onlyIfAbsent) { + Node z; // added node + if (key == null) + throw new NullPointerException(); + Comparator cmp = comparator; + outer: for (;;) { + for (Node b = findPredecessor(key, cmp), n = b.next;;) { if (n != null) { + Object v; int c; Node 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 z = new Node(kkey, value, n); + z = new Node(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 z, int level) { - HeadIndex 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 idx = null; - for (int i = 1; i <= level; ++i) - idx = new Index(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[] idxs = (Index[])new Index[level+1]; - Index idx = null; - for (int i = 1; i <= level; ++i) - idxs[i] = idx = new Index(z, idx, null); - - HeadIndex oldh; - int k; - for (;;) { - oldh = head; - int oldLevel = oldh.level; - if (level <= oldLevel) { // lost race to add level - k = level; - break; - } - HeadIndex newh = oldh; - Node oldbase = oldh.node; - for (int j = oldLevel+1; j <= level; ++j) - newh = new HeadIndex(oldbase, newh, idxs[j], j); - if (casHead(oldh, newh)) { - k = oldLevel; - break; + HeadIndex h = head; + if (level <= (max = h.level)) { + for (int i = 1; i <= level; ++i) + idx = new Index(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[] idxs = + (Index[])new Index[level+1]; + for (int i = 1; i <= level; ++i) + idxs[i] = idx = new Index(z, idx, null); + for (;;) { + h = head; + int oldLevel = h.level; + if (level <= oldLevel) // lost race to add level + break; + HeadIndex newh = h; + Node oldbase = h.node; + for (int j = oldLevel+1; j <= level; ++j) + newh = new HeadIndex(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 idx, HeadIndex h, int indexLevel) { - // Track next level to insert in case of retries - int insertionLevel = indexLevel; - Comparable key = comparable(idx.node.key); - if (key == null) throw new NullPointerException(); - - // Similar to findPredecessor, but adding index nodes along - // path to key. - for (;;) { - int j = h.level; - Index q = h; - Index r = q.right; - Index t = idx; - for (;;) { - if (r != null) { - Node 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; + // find insertion points and splice in + splice: for (int insertionLevel = level;;) { + int j = h.level; + for (Index q = h, r = q.right, t = idx;;) { + if (q == null || t == null) + break splice; + if (r != null) { + Node 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; + } } - if (c > 0) { - q = r; - r = r.right; - continue; - } - } - 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()) + if (j == insertionLevel) { + if (!q.link(r, t)) + break; // restart + if (t.node.value == null) { findNode(key); - return; + break splice; + } + if (--insertionLevel == 0) + break splice; } - } - if (--j >= insertionLevel && j < indexLevel) - t = t.down; - q = q.down; - r = q.right; + if (--j >= insertionLevel && j < level) + t = t.down; + q = q.down; + r = q.right; + } } } + return null; } /* ---------------- Deletion -------------- */ @@ -1038,51 +943,52 @@ public class ConcurrentSkipListMap extends AbstractMap * 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 key = comparable(okey); - for (;;) { - Node b = findPredecessor(key); - Node n = b.next; - for (;;) { + final V doRemove(Object key, Object value) { + if (key == null) + throw new NullPointerException(); + Comparator cmp = comparator; + outer: for (;;) { + for (Node b = findPredecessor(key, cmp), n = b.next;;) { + Object v; int c; if (n == null) - return null; + break outer; Node 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 @@ public class ConcurrentSkipListMap extends AbstractMap * Specialized variant of findNode to get first valid node. * @return first node or null if empty */ - Node findFirst() { - for (;;) { - Node b = head.node; - Node n = b.next; - if (n == null) + final Node findFirst() { + for (Node b, n;;) { + if ((n = (b = head.node).next) == null) return null; if (n.value != null) return n; @@ -1142,11 +1046,9 @@ public class ConcurrentSkipListMap extends AbstractMap * Removes first entry; returns its snapshot. * @return null if empty, else snapshot of first entry */ - Map.Entry doRemoveFirstEntry() { - for (;;) { - Node b = head.node; - Node n = b.next; - if (n == null) + private Map.Entry doRemoveFirstEntry() { + for (Node b, n;;) { + if ((n = (b = head.node).next) == null) return null; Node f = n.next; if (n != b.next) @@ -1161,7 +1063,8 @@ public class ConcurrentSkipListMap extends AbstractMap if (!n.appendMarker(f) || !b.casNext(n, f)) findFirst(); // retry clearIndexToFirst(); - return new AbstractMap.SimpleImmutableEntry(n.key, (V)v); + @SuppressWarnings("unchecked") V vv = (V)v; + return new AbstractMap.SimpleImmutableEntry(n.key, vv); } } @@ -1170,8 +1073,7 @@ public class ConcurrentSkipListMap extends AbstractMap */ private void clearIndexToFirst() { for (;;) { - Index q = head; - for (;;) { + for (Index q = head;;) { Index r = q.right; if (r != null && r.indexesDeletedNode() && !q.unlink(r)) break; @@ -1184,6 +1086,52 @@ public class ConcurrentSkipListMap extends AbstractMap } } + /** + * Removes last entry; returns its snapshot. + * Specialized variant of doRemove. + * @return null if empty, else snapshot of last entry + */ + private Map.Entry doRemoveLastEntry() { + for (;;) { + Node b = findPredecessorOfLast(); + Node n = b.next; + if (n == null) { + if (b.isBaseHeader()) // empty + return null; + else + continue; // all b's successors are deleted; retry + } + for (;;) { + Node 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(key, vv); + } + } + } /* ---------------- Finding and removing last element -------------- */ @@ -1191,7 +1139,7 @@ public class ConcurrentSkipListMap extends AbstractMap * Specialized version of find to get last valid node. * @return last node or null if empty */ - Node findLast() { + final Node findLast() { /* * findPredecessor can't be used to traverse index level * because this doesn't use comparisons. So traversals of @@ -1210,9 +1158,7 @@ public class ConcurrentSkipListMap extends AbstractMap } else if ((d = q.down) != null) { q = d; } else { - Node b = q.node; - Node n = b.next; - for (;;) { + for (Node b = q.node, n = b.next;;) { if (n == null) return b.isBaseHeader() ? null : b; Node f = n.next; // inconsistent read @@ -1223,7 +1169,7 @@ public class ConcurrentSkipListMap extends AbstractMap 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 @@ public class ConcurrentSkipListMap extends AbstractMap */ private Node findPredecessorOfLast() { for (;;) { - Index q = head; - for (;;) { + for (Index q = head;;) { Index d, r; if ((r = q.right) != null) { if (r.indexesDeletedNode()) { @@ -1264,53 +1209,6 @@ public class ConcurrentSkipListMap extends AbstractMap } } - /** - * Removes last entry; returns its snapshot. - * Specialized variant of doRemove. - * @return null if empty, else snapshot of last entry - */ - Map.Entry doRemoveLastEntry() { - for (;;) { - Node b = findPredecessorOfLast(); - Node n = b.next; - if (n == null) { - if (b.isBaseHeader()) // empty - return null; - else - continue; // all b's successors are deleted; retry - } - for (;;) { - Node 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 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(key, (V)v); - } - } - } - /* ---------------- Relational operations -------------- */ // Control values OR'ed as arguments to findNear @@ -1321,29 +1219,28 @@ public class ConcurrentSkipListMap extends AbstractMap /** * 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 findNear(K kkey, int rel) { - Comparable key = comparable(kkey); + final Node findNear(K key, int rel, Comparator cmp) { + if (key == null) + throw new NullPointerException(); for (;;) { - Node b = findPredecessor(key); - Node n = b.next; - for (;;) { + for (Node b = findPredecessor(key, cmp), n = b.next;;) { + Object v; if (n == null) return ((rel & LT) == 0 || b.isBaseHeader()) ? null : b; Node 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 @@ public class ConcurrentSkipListMap extends AbstractMap * @param rel the relation -- OR'ed combination of EQ, LT, GT * @return Entry fitting relation, or null if no such */ - AbstractMap.SimpleImmutableEntry getNear(K key, int rel) { + final AbstractMap.SimpleImmutableEntry getNear(K key, int rel) { + Comparator cmp = comparator; for (;;) { - Node n = findNear(key, rel); + Node n = findNear(key, rel, cmp); if (n == null) return null; AbstractMap.SimpleImmutableEntry e = n.createSnapshot(); @@ -1372,7 +1270,6 @@ public class ConcurrentSkipListMap extends AbstractMap } } - /* ---------------- Constructors -------------- */ /** @@ -1389,7 +1286,7 @@ public class ConcurrentSkipListMap extends AbstractMap * comparator. * * @param comparator the comparator that will be used to order this map. - * If null, the {@linkplain Comparable natural + * If {@code null}, the {@linkplain Comparable natural * ordering} of the keys will be used. */ public ConcurrentSkipListMap(Comparator comparator) { @@ -1403,7 +1300,7 @@ public class ConcurrentSkipListMap extends AbstractMap * the keys. * * @param m the map whose mappings are to be placed in this map - * @throws ClassCastException if the keys in m 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 @@ public class ConcurrentSkipListMap extends AbstractMap } /** - * Returns a shallow copy of this ConcurrentSkipListMap + * 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 @@ public class ConcurrentSkipListMap extends AbstractMap map.entrySet().iterator(); while (it.hasNext()) { Map.Entry 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 @@ public class ConcurrentSkipListMap extends AbstractMap * * @serialData The key (Object) and value (Object) for each * key-value mapping represented by the map, followed by - * null. 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 @@ public class ConcurrentSkipListMap extends AbstractMap /** * 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 @@ public class ConcurrentSkipListMap extends AbstractMap 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 z = new Node(key, val, null); basepred.next = z; basepred = z; @@ -1595,11 +1505,11 @@ public class ConcurrentSkipListMap extends AbstractMap /* ------ Map API methods ------ */ /** - * Returns true 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 true 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 @@ -1626,6 +1536,22 @@ public class ConcurrentSkipListMap extends AbstractMap return doGet(key); } + /** + * 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 @@ -1634,7 +1560,7 @@ public class ConcurrentSkipListMap extends AbstractMap * @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 - * null 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 @@ public class ConcurrentSkipListMap extends AbstractMap * * @param key key for which mapping should be removed * @return the previous value associated with the specified key, or - * null 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 @@ public class ConcurrentSkipListMap extends AbstractMap } /** - * Returns true 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 true if a mapping to value exists; - * false 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 @@ public class ConcurrentSkipListMap extends AbstractMap /** * Returns the number of key-value mappings in this map. If this map - * contains more than Integer.MAX_VALUE elements, it - * returns Integer.MAX_VALUE. + * contains more than {@code Integer.MAX_VALUE} elements, it + * returns {@code Integer.MAX_VALUE}. * *

    Beware that, unlike in most collections, this method is * NOT a constant-time operation. Because of the @@ -1708,8 +1634,8 @@ public class ConcurrentSkipListMap extends AbstractMap } /** - * Returns true if this map contains no key-value mappings. - * @return true 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 @@ public class ConcurrentSkipListMap extends AbstractMap 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 NOT 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 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 NOT 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 remappingFunction) { + if (key == null || remappingFunction == null) + throw new NullPointerException(); + Node 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 NOT 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 remappingFunction) { + if (key == null || remappingFunction == null) + throw new NullPointerException(); + for (;;) { + Node 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 NOT + * 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 remappingFunction) { + if (key == null || value == null || remappingFunction == null) + throw new NullPointerException(); + for (;;) { + Node 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 @@ public class ConcurrentSkipListMap extends AbstractMap * operations. It does not support the {@code add} or {@code addAll} * operations. * - *

    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. + *

    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. * *

    This method is equivalent to method {@code navigableKeySet}. * @@ -1771,16 +1831,16 @@ public class ConcurrentSkipListMap extends AbstractMap * 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 Iterator.remove, - * Collection.remove, removeAll, - * retainAll and clear operations. It does not - * support the add or addAll 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. * - *

    The view's 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. + *

    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 values() { Values vs = values; @@ -1793,20 +1853,20 @@ public class ConcurrentSkipListMap extends AbstractMap * 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 Iterator.remove, Set.remove, - * removeAll, retainAll and clear - * operations. It does not support the add or - * addAll 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. * - *

    The view's 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. + *

    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. * - *

    The Map.Entry elements returned by - * iterator.next() do not support the - * setValue operation. + *

    The {@code Map.Entry} elements returned by + * {@code iterator.next()} do not 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 @@ public class ConcurrentSkipListMap extends AbstractMap /** * Compares the specified object with this map for equality. - * Returns true 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 - * m1 and m2 represent the same mappings if - * m1.entrySet().equals(m2.entrySet()). 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 true 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 @@ public class ConcurrentSkipListMap extends AbstractMap * {@inheritDoc} * * @return the previous value associated with the specified key, - * or null 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 class ConcurrentSkipListMap extends AbstractMap 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 @@ public class ConcurrentSkipListMap extends AbstractMap * @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 k = comparable(key); for (;;) { - Node n = findNode(k); - if (n == null) + Node 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 @@ public class ConcurrentSkipListMap extends AbstractMap * {@inheritDoc} * * @return the previous value associated with the specified key, - * or null 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 k = comparable(key); for (;;) { - Node n = findNode(k); - if (n == null) + Node 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 @@ public class ConcurrentSkipListMap extends AbstractMap /** * Returns a key-value mapping associated with the greatest key - * strictly less than the given key, or null if there is + * strictly less than the given key, or {@code null} if there is * no such key. The returned entry does not support the - * Entry.setValue method. + * {@code Entry.setValue} method. * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null @@ -2058,15 +2114,15 @@ public class ConcurrentSkipListMap extends AbstractMap * @throws NullPointerException if the specified key is null */ public K lowerKey(K key) { - Node n = findNear(key, LT); + Node 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 null if there + * less than or equal to the given key, or {@code null} if there * is no such key. The returned entry does not support - * the Entry.setValue method. + * the {@code Entry.setValue} method. * * @param key the key * @throws ClassCastException {@inheritDoc} @@ -2082,15 +2138,15 @@ public class ConcurrentSkipListMap extends AbstractMap * @throws NullPointerException if the specified key is null */ public K floorKey(K key) { - Node n = findNear(key, LT|EQ); + Node 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 null if + * greater than or equal to the given key, or {@code null} if * there is no such entry. The returned entry does not - * support the Entry.setValue method. + * support the {@code Entry.setValue} method. * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null @@ -2104,15 +2160,15 @@ public class ConcurrentSkipListMap extends AbstractMap * @throws NullPointerException if the specified key is null */ public K ceilingKey(K key) { - Node n = findNear(key, GT|EQ); + Node 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 null if there + * strictly greater than the given key, or {@code null} if there * is no such key. The returned entry does not support - * the Entry.setValue method. + * the {@code Entry.setValue} method. * * @param key the key * @throws ClassCastException {@inheritDoc} @@ -2128,15 +2184,15 @@ public class ConcurrentSkipListMap extends AbstractMap * @throws NullPointerException if the specified key is null */ public K higherKey(K key) { - Node n = findNear(key, GT); + Node 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 null if the map is empty. + * key in this map, or {@code null} if the map is empty. * The returned entry does not support - * the Entry.setValue method. + * the {@code Entry.setValue} method. */ public Map.Entry firstEntry() { for (;;) { @@ -2151,9 +2207,9 @@ public class ConcurrentSkipListMap extends AbstractMap /** * Returns a key-value mapping associated with the greatest - * key in this map, or null if the map is empty. + * key in this map, or {@code null} if the map is empty. * The returned entry does not support - * the Entry.setValue method. + * the {@code Entry.setValue} method. */ public Map.Entry lastEntry() { for (;;) { @@ -2168,9 +2224,9 @@ public class ConcurrentSkipListMap extends AbstractMap /** * Removes and returns a key-value mapping associated with - * the least key in this map, or null if the map is empty. + * the least key in this map, or {@code null} if the map is empty. * The returned entry does not support - * the Entry.setValue method. + * the {@code Entry.setValue} method. */ public Map.Entry pollFirstEntry() { return doRemoveFirstEntry(); @@ -2178,9 +2234,9 @@ public class ConcurrentSkipListMap extends AbstractMap /** * Removes and returns a key-value mapping associated with - * the greatest key in this map, or null if the map is empty. + * the greatest key in this map, or {@code null} if the map is empty. * The returned entry does not support - * the Entry.setValue method. + * the {@code Entry.setValue} method. */ public Map.Entry pollLastEntry() { return doRemoveLastEntry(); @@ -2202,13 +2258,11 @@ public class ConcurrentSkipListMap extends AbstractMap /** 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 @@ public class ConcurrentSkipListMap extends AbstractMap 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 @@ public class ConcurrentSkipListMap extends AbstractMap static final List toList(Collection c) { // Using size() here would be a pessimization. - List list = new ArrayList(); + ArrayList list = new ArrayList(); for (E e : c) list.add(e); return list; @@ -2304,7 +2356,7 @@ public class ConcurrentSkipListMap extends AbstractMap static final class KeySet extends AbstractSet implements NavigableSet { - private final ConcurrentNavigableMap m; + final ConcurrentNavigableMap m; KeySet(ConcurrentNavigableMap map) { m = map; } public int size() { return m.size(); } public boolean isEmpty() { return m.isEmpty(); } @@ -2326,6 +2378,7 @@ public class ConcurrentSkipListMap extends AbstractMap Map.Entry e = m.pollLastEntry(); return (e == null) ? null : e.getKey(); } + @SuppressWarnings("unchecked") public Iterator iterator() { if (m instanceof ConcurrentSkipListMap) return ((ConcurrentSkipListMap)m).keyIterator(); @@ -2376,13 +2429,21 @@ public class ConcurrentSkipListMap extends AbstractMap public NavigableSet descendingSet() { return new KeySet(m.descendingMap()); } + @SuppressWarnings("unchecked") + public Spliterator spliterator() { + if (m instanceof ConcurrentSkipListMap) + return ((ConcurrentSkipListMap)m).keySpliterator(); + else + return (Spliterator)((SubMap)m).keyIterator(); + } } static final class Values extends AbstractCollection { - private final ConcurrentNavigableMap m; + final ConcurrentNavigableMap m; Values(ConcurrentNavigableMap map) { m = map; } + @SuppressWarnings("unchecked") public Iterator iterator() { if (m instanceof ConcurrentSkipListMap) return ((ConcurrentSkipListMap)m).valueIterator(); @@ -2403,14 +2464,21 @@ public class ConcurrentSkipListMap extends AbstractMap } public Object[] toArray() { return toList(this).toArray(); } public T[] toArray(T[] a) { return toList(this).toArray(a); } + @SuppressWarnings("unchecked") + public Spliterator spliterator() { + if (m instanceof ConcurrentSkipListMap) + return ((ConcurrentSkipListMap)m).valueSpliterator(); + else + return (Spliterator)((SubMap)m).valueIterator(); + } } static final class EntrySet extends AbstractSet> { - private final ConcurrentNavigableMap m; + final ConcurrentNavigableMap m; EntrySet(ConcurrentNavigableMap map) { m = map; } - + @SuppressWarnings("unchecked") public Iterator> iterator() { if (m instanceof ConcurrentSkipListMap) return ((ConcurrentSkipListMap)m).entryIterator(); @@ -2457,6 +2525,14 @@ public class ConcurrentSkipListMap extends AbstractMap } public Object[] toArray() { return toList(this).toArray(); } public T[] toArray(T[] a) { return toList(this).toArray(a); } + @SuppressWarnings("unchecked") + public Spliterator> spliterator() { + if (m instanceof ConcurrentSkipListMap) + return ((ConcurrentSkipListMap)m).entrySpliterator(); + else + return (Spliterator>) + ((SubMap)m).entryIterator(); + } } /** @@ -2466,8 +2542,8 @@ public class ConcurrentSkipListMap extends AbstractMap * 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 subMap, headMap, and - * tailMap 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 @@ public class ConcurrentSkipListMap extends AbstractMap private transient Collection valuesView; /** - * Creates a new submap, initializing all fields + * Creates a new submap, initializing all fields. */ SubMap(ConcurrentSkipListMap map, K fromKey, boolean fromInclusive, K toKey, boolean toInclusive, boolean isDescending) { + Comparator 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 @@ public class ConcurrentSkipListMap extends AbstractMap /* ---------------- 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 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 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 cmp) { + return !tooLow(key, cmp) && !tooHigh(key, cmp); } - private void checkKeyBounds(K key) throws IllegalArgumentException { + void checkKeyBounds(K key, Comparator 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 n) { + boolean isBeforeEnd(ConcurrentSkipListMap.Node n, + Comparator cmp) { if (n == null) return false; if (hi == null) @@ -2554,7 +2626,7 @@ public class ConcurrentSkipListMap extends AbstractMap 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 @@ public class ConcurrentSkipListMap extends AbstractMap /** * 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 loNode() { + ConcurrentSkipListMap.Node loNode(Comparator 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 hiNode() { + ConcurrentSkipListMap.Node hiNode(Comparator 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 n = loNode(); - if (isBeforeEnd(n)) + K lowestKey() { + Comparator cmp = m.comparator; + ConcurrentSkipListMap.Node 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 n = hiNode(); + K highestKey() { + Comparator cmp = m.comparator; + ConcurrentSkipListMap.Node 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 lowestEntry() { + Map.Entry lowestEntry() { + Comparator cmp = m.comparator; for (;;) { - ConcurrentSkipListMap.Node n = loNode(); - if (!isBeforeEnd(n)) + ConcurrentSkipListMap.Node n = loNode(cmp); + if (!isBeforeEnd(n, cmp)) return null; Map.Entry e = n.createSnapshot(); if (e != null) @@ -2621,10 +2696,11 @@ public class ConcurrentSkipListMap extends AbstractMap } } - private Map.Entry highestEntry() { + Map.Entry highestEntry() { + Comparator cmp = m.comparator; for (;;) { - ConcurrentSkipListMap.Node n = hiNode(); - if (n == null || !inBounds(n.key)) + ConcurrentSkipListMap.Node n = hiNode(cmp); + if (n == null || !inBounds(n.key, cmp)) return null; Map.Entry e = n.createSnapshot(); if (e != null) @@ -2632,13 +2708,14 @@ public class ConcurrentSkipListMap extends AbstractMap } } - private Map.Entry removeLowest() { + Map.Entry removeLowest() { + Comparator cmp = m.comparator; for (;;) { - Node n = loNode(); + Node 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 @@ public class ConcurrentSkipListMap extends AbstractMap } } - private Map.Entry removeHighest() { + Map.Entry removeHighest() { + Comparator cmp = m.comparator; for (;;) { - Node n = hiNode(); + Node 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 @@ public class ConcurrentSkipListMap extends AbstractMap /** * Submap version of ConcurrentSkipListMap.getNearEntry */ - private Map.Entry getNearEntry(K key, int rel) { + Map.Entry getNearEntry(K key, int rel) { + Comparator 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 n = m.findNear(key, rel); - if (n == null || !inBounds(n.key)) + Node 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 @@ public class ConcurrentSkipListMap extends AbstractMap } // Almost the same as getNearEntry, except for keys - private K getNearKey(K key, int rel) { + K getNearKey(K key, int rel) { + Comparator 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 n = loNode(); - if (isBeforeEnd(n)) + ConcurrentSkipListMap.Node 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 n = hiNode(); + ConcurrentSkipListMap.Node n = hiNode(cmp); if (n != null) { K last = n.key; - if (inBounds(last)) + if (inBounds(last, cmp)) return last; } } return null; } for (;;) { - Node n = m.findNear(key, rel); - if (n == null || !inBounds(n.key)) + Node 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 class ConcurrentSkipListMap extends AbstractMap 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 cmp = m.comparator; long count = 0; - for (ConcurrentSkipListMap.Node n = loNode(); - isBeforeEnd(n); + for (ConcurrentSkipListMap.Node n = loNode(cmp); + isBeforeEnd(n, cmp); n = n.next) { if (n.getValidValue() != null) ++count; @@ -2759,14 +2837,16 @@ public class ConcurrentSkipListMap extends AbstractMap } public boolean isEmpty() { - return !isBeforeEnd(loNode()); + Comparator cmp = m.comparator; + return !isBeforeEnd(loNode(cmp), cmp); } public boolean containsValue(Object value) { if (value == null) throw new NullPointerException(); - for (ConcurrentSkipListMap.Node n = loNode(); - isBeforeEnd(n); + Comparator cmp = m.comparator; + for (ConcurrentSkipListMap.Node n = loNode(cmp); + isBeforeEnd(n, cmp); n = n.next) { V v = n.getValidValue(); if (v != null && value.equals(v)) @@ -2776,8 +2856,9 @@ public class ConcurrentSkipListMap extends AbstractMap } public void clear() { - for (ConcurrentSkipListMap.Node n = loNode(); - isBeforeEnd(n); + Comparator cmp = m.comparator; + for (ConcurrentSkipListMap.Node n = loNode(cmp); + isBeforeEnd(n, cmp); n = n.next) { if (n.getValidValue() != null) m.remove(n.key); @@ -2787,22 +2868,21 @@ public class ConcurrentSkipListMap extends AbstractMap /* ---------------- 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 @@ public class ConcurrentSkipListMap extends AbstractMap * Utility to create submaps, where given bounds override * unbounded(null) ones and/or are checked against bounded ones. */ - private SubMap newSubMap(K fromKey, - boolean fromInclusive, - K toKey, - boolean toInclusive) { + SubMap newSubMap(K fromKey, boolean fromInclusive, + K toKey, boolean toInclusive) { + Comparator cmp = m.comparator; if (isDescending) { // flip senses K tk = fromKey; fromKey = toKey; @@ -2838,7 +2917,7 @@ public class ConcurrentSkipListMap extends AbstractMap 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 @@ public class ConcurrentSkipListMap extends AbstractMap 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 @@ public class ConcurrentSkipListMap extends AbstractMap toKey, toInclusive, isDescending); } - public SubMap subMap(K fromKey, - boolean fromInclusive, - K toKey, - boolean toInclusive) { + public SubMap 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 headMap(K toKey, - boolean inclusive) { + public SubMap headMap(K toKey, boolean inclusive) { if (toKey == null) throw new NullPointerException(); return newSubMap(null, false, toKey, inclusive); } - public SubMap tailMap(K fromKey, - boolean inclusive) { + public SubMap tailMap(K fromKey, boolean inclusive) { if (fromKey == null) throw new NullPointerException(); return newSubMap(fromKey, inclusive, null, false); @@ -2996,8 +3071,9 @@ public class ConcurrentSkipListMap extends AbstractMap /** * Variant of main Iter class to traverse through submaps. + * Also serves as back-up Spliterator for views */ - abstract class SubMapIter implements Iterator { + abstract class SubMapIter implements Iterator, Spliterator { /** the last node returned by next() */ Node lastReturned; /** the next node to return from next(); */ @@ -3006,16 +3082,19 @@ public class ConcurrentSkipListMap extends AbstractMap V nextValue; SubMapIter() { + Comparator 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 @@ public class ConcurrentSkipListMap extends AbstractMap } private void ascend() { + Comparator 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 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 @@ public class ConcurrentSkipListMap extends AbstractMap lastReturned = null; } + public Spliterator trySplit() { + return null; + } + + public boolean tryAdvance(Consumer action) { + if (hasNext()) { + action.accept(next()); + return true; + } + return false; + } + + public void forEachRemaining(Consumer action) { + while (hasNext()) + action.accept(next()); + } + + public long estimateSize() { + return Long.MAX_VALUE; + } } final class SubMapValueIterator extends SubMapIter { @@ -3083,6 +3188,9 @@ public class ConcurrentSkipListMap extends AbstractMap advance(); return v; } + public int characteristics() { + return 0; + } } final class SubMapKeyIterator extends SubMapIter { @@ -3091,6 +3199,13 @@ public class ConcurrentSkipListMap extends AbstractMap advance(); return n.key; } + public int characteristics() { + return Spliterator.DISTINCT | Spliterator.ORDERED | + Spliterator.SORTED; + } + public final Comparator getComparator() { + return SubMap.this.comparator(); + } } final class SubMapEntryIterator extends SubMapIter> { @@ -3100,18 +3215,351 @@ public class ConcurrentSkipListMap extends AbstractMap advance(); return new AbstractMap.SimpleImmutableEntry(n.key, v); } + public int characteristics() { + return Spliterator.DISTINCT; + } + } + } + + // default Map method overrides + + public void forEach(BiConsumer action) { + if (action == null) throw new NullPointerException(); + V v; + for (Node n = findFirst(); n != null; n = n.next) { + if ((v = n.getValidValue()) != null) + action.accept(n.key, v); + } + } + + public void replaceAll(BiFunction function) { + if (function == null) throw new NullPointerException(); + V v; + for (Node 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 { + final Comparator comparator; + final K fence; // exclusive upper bound for keys, or null if to end + Index row; // the level to split out + Node current; // current traversal node; initialize at origin + int est; // pseudo-size estimate + CSLMSpliterator(Comparator comparator, Index row, + Node 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 extends CSLMSpliterator + implements Spliterator { + KeySpliterator(Comparator comparator, Index row, + Node origin, K fence, int est) { + super(comparator, row, origin, fence, est); + } + + public Spliterator trySplit() { + Node e; K ek; + Comparator cmp = comparator; + K f = fence; + if ((e = current) != null && (ek = e.key) != null) { + for (Index q = row; q != null; q = row = q.down) { + Index s; Node 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 r = q.down; + row = (s.right != null) ? s : s.down; + est -= est >>> 2; + return new KeySpliterator(cmp, r, e, sk, est); + } + } + } + return null; + } + + public void forEachRemaining(Consumer action) { + if (action == null) throw new NullPointerException(); + Comparator cmp = comparator; + K f = fence; + Node 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 action) { + if (action == null) throw new NullPointerException(); + Comparator cmp = comparator; + K f = fence; + Node 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 getComparator() { + return comparator; + } + } + // factory method for KeySpliterator + final KeySpliterator keySpliterator() { + Comparator cmp = comparator; + for (;;) { // ensure h corresponds to origin p + HeadIndex h; Node p; + Node b = (h = head).node; + if ((p = b.next) == null || p.value != null) + return new KeySpliterator(cmp, h, p, null, (p == null) ? + 0 : Integer.MAX_VALUE); + p.helpDelete(b, p.next); + } + } + + static final class ValueSpliterator extends CSLMSpliterator + implements Spliterator { + ValueSpliterator(Comparator comparator, Index row, + Node origin, K fence, int est) { + super(comparator, row, origin, fence, est); + } + + public Spliterator trySplit() { + Node e; K ek; + Comparator cmp = comparator; + K f = fence; + if ((e = current) != null && (ek = e.key) != null) { + for (Index q = row; q != null; q = row = q.down) { + Index s; Node 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 r = q.down; + row = (s.right != null) ? s : s.down; + est -= est >>> 2; + return new ValueSpliterator(cmp, r, e, sk, est); + } + } + } + return null; + } + + public void forEachRemaining(Consumer action) { + if (action == null) throw new NullPointerException(); + Comparator cmp = comparator; + K f = fence; + Node 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 action) { + if (action == null) throw new NullPointerException(); + Comparator cmp = comparator; + K f = fence; + Node 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 valueSpliterator() { + Comparator cmp = comparator; + for (;;) { + HeadIndex h; Node p; + Node b = (h = head).node; + if ((p = b.next) == null || p.value != null) + return new ValueSpliterator(cmp, h, p, null, (p == null) ? + 0 : Integer.MAX_VALUE); + p.helpDelete(b, p.next); + } + } + + static final class EntrySpliterator extends CSLMSpliterator + implements Spliterator> { + EntrySpliterator(Comparator comparator, Index row, + Node origin, K fence, int est) { + super(comparator, row, origin, fence, est); + } + + public Spliterator> trySplit() { + Node e; K ek; + Comparator cmp = comparator; + K f = fence; + if ((e = current) != null && (ek = e.key) != null) { + for (Index q = row; q != null; q = row = q.down) { + Index s; Node 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 r = q.down; + row = (s.right != null) ? s : s.down; + est -= est >>> 2; + return new EntrySpliterator(cmp, r, e, sk, est); + } + } + } + return null; + } + + public void forEachRemaining(Consumer> action) { + if (action == null) throw new NullPointerException(); + Comparator cmp = comparator; + K f = fence; + Node 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, vv)); + } + } + } + + public boolean tryAdvance(Consumer> action) { + if (action == null) throw new NullPointerException(); + Comparator cmp = comparator; + K f = fence; + Node 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, vv)); + return true; + } + } + current = e; + return false; + } + + public int characteristics() { + return Spliterator.DISTINCT | Spliterator.SORTED | + Spliterator.ORDERED | Spliterator.CONCURRENT | + Spliterator.NONNULL; + } + + public final Comparator> getComparator() { + return comparator == null ? null : + Map.Entry.comparingByKey(comparator); + } + } + + // Almost the same as keySpliterator() + final EntrySpliterator entrySpliterator() { + Comparator cmp = comparator; + for (;;) { // almost same as key version + HeadIndex h; Node p; + Node b = (h = head).node; + if ((p = b.next) == null || p.value != null) + return new EntrySpliterator(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); } diff --git a/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java b/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java index 8214b37c4fd..4c41e388c8b 100644 --- a/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java +++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java @@ -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 @@ import java.util.*; * on which constructor is used. * *

    This implementation provides expected average log(n) time - * cost for the contains, add, and remove + * 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 weakly consistent, returning elements * reflecting the state of the set at some point at or since the * creation of the iterator. They do not 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. * - *

    Beware that, unlike in most collections, the size + *

    Beware that, unlike in most collections, the {@code size} * method is not 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 addAll, - * removeAll, retainAll, containsAll, - * equals, and toArray are not guaranteed + * Additionally, the bulk operations {@code addAll}, + * {@code removeAll}, {@code retainAll}, {@code containsAll}, + * {@code equals}, and {@code toArray} are not guaranteed * to be performed atomically. For example, an iterator operating - * concurrently with an addAll operation might view only some + * concurrently with an {@code addAll} operation might view only some * of the added elements. * *

    This class and its iterators implement all of the * optional methods of the {@link Set} and {@link Iterator} * interfaces. Like most other concurrent collection implementations, - * this class does not permit the use of null elements, - * because null 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. * *

    This class is a member of the @@ -90,7 +100,7 @@ public class ConcurrentSkipListSet /** * 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 m; @@ -107,7 +117,7 @@ public class ConcurrentSkipListSet * the specified comparator. * * @param comparator the comparator that will be used to order this set. - * If null, the {@linkplain Comparable natural + * If {@code null}, the {@linkplain Comparable natural * ordering} of the elements will be used. */ public ConcurrentSkipListSet(Comparator comparator) { @@ -120,7 +130,7 @@ public class ConcurrentSkipListSet * {@linkplain Comparable natural ordering}. * * @param c The elements that will comprise the new set - * @throws ClassCastException if the elements in c 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 @@ public class ConcurrentSkipListSet } /** - * Returns a shallow copy of this ConcurrentSkipListSet + * 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 @@ public class ConcurrentSkipListSet /** * Returns the number of elements in this set. If this set - * contains more than Integer.MAX_VALUE elements, it - * returns Integer.MAX_VALUE. + * contains more than {@code Integer.MAX_VALUE} elements, it + * returns {@code Integer.MAX_VALUE}. * *

    Beware that, unlike in most collections, this method is * NOT a constant-time operation. Because of the @@ -191,20 +201,20 @@ public class ConcurrentSkipListSet } /** - * Returns true if this set contains no elements. - * @return true 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 true if this set contains the specified element. - * More formally, returns true if and only if this set - * contains an element e such that o.equals(e). + * 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 true 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 @@ public class ConcurrentSkipListSet /** * Adds the specified element to this set if it is not already present. - * More formally, adds the specified element e to this set if - * the set contains no element e2 such that e.equals(e2). + * 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 false. + * unchanged and returns {@code false}. * * @param e element to be added to this set - * @return true if this set did not already contain the + * @return {@code true} if this set did not already contain the * specified element - * @throws ClassCastException if e 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 @@ public class ConcurrentSkipListSet /** * Removes the specified element from this set if it is present. - * More formally, removes an element e such that - * o.equals(e), if this set contains such an element. - * Returns true 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 true if this set contained the specified element - * @throws ClassCastException if o 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 @@ public class ConcurrentSkipListSet /** * Compares the specified object with this set for equality. Returns - * true 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 @@ public class ConcurrentSkipListSet * set interface. * * @param o the object to be compared for equality with this set - * @return true 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 @@ public class ConcurrentSkipListSet * value is the asymmetric set difference of the two sets. * * @param c collection containing elements to be removed from this set - * @return true 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 @@ public class ConcurrentSkipListSet } /** - * @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 @@ public class ConcurrentSkipListSet * reflected in the descending set, and vice-versa. * *

    The returned set has an ordering equivalent to - * {@link Collections#reverseOrder(Comparator) Collections.reverseOrder}(comparator()). + * {@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 @@ public class ConcurrentSkipListSet return new ConcurrentSkipListSet(m.descendingMap()); } + @SuppressWarnings("unchecked") + public Spliterator spliterator() { + if (m instanceof ConcurrentSkipListMap) + return ((ConcurrentSkipListMap)m).keySpliterator(); + else + return (Spliterator)((ConcurrentSkipListMap.SubMap)m).keyIterator(); + } + // Support for resetting map in clone private void setMap(ConcurrentNavigableMap map) { UNSAFE.putObjectVolatile(this, mapOffset, map); diff --git a/jdk/src/share/classes/java/util/concurrent/CopyOnWriteArrayList.java b/jdk/src/share/classes/java/util/concurrent/CopyOnWriteArrayList.java index 67e21313f68..2ea321100c3 100644 --- a/jdk/src/share/classes/java/util/concurrent/CopyOnWriteArrayList.java +++ b/jdk/src/share/classes/java/util/concurrent/CopyOnWriteArrayList.java @@ -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 @@ import java.util.function.UnaryOperator; /** * A thread-safe variant of {@link java.util.ArrayList} in which all mutative - * operations (add, set, 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. * - *

    This is ordinarily too costly, but may be more efficient + *

    This is ordinarily too costly, but may be more 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 @@ import java.util.function.UnaryOperator; * 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 ConcurrentModificationException. + * 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 (remove, set, and - * add) are not supported. These methods throw - * UnsupportedOperationException. + * operations on iterators themselves ({@code remove}, {@code set}, and + * {@code add}) are not supported. These methods throw + * {@code UnsupportedOperationException}. * - *

    All elements are permitted, including null. + *

    All elements are permitted, including {@code null}. * *

    Memory consistency effects: As with other concurrent * collections, actions in a thread prior to placing an object into a @@ -82,10 +93,10 @@ public class CopyOnWriteArrayList 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 @@ public class CopyOnWriteArrayList * @throws NullPointerException if the specified collection is null */ public CopyOnWriteArrayList(Collection 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 @@ public class CopyOnWriteArrayList } /** - * Returns true if this list contains no elements. + * Returns {@code true} if this list contains no elements. * - * @return true 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 @@ public class CopyOnWriteArrayList * 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 @@ public class CopyOnWriteArrayList } /** - * Returns true if this list contains the specified element. - * More formally, returns true if and only if this list contains - * at least one element e 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 * (o==null ? e==null : o.equals(e)). * * @param o element whose presence in this list is to be tested - * @return true 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 @@ public class CopyOnWriteArrayList /** * Returns the index of the first occurrence of the specified element in - * this list, searching forwards from index, 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 i such that + * More formally, returns the lowest index {@code i} such that * (i >= index && (e==null ? get(i)==null : e.equals(get(i)))), * 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 index or later in the list; - * -1 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 @@ public class CopyOnWriteArrayList /** * Returns the index of the last occurrence of the specified element in - * this list, searching backwards from index, 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 i such that + * More formally, returns the highest index {@code i} such that * (i <= index && (e==null ? get(i)==null : e.equals(get(i)))), * 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 index 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 @@ public class CopyOnWriteArrayList *

    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 - * null. (This is useful in determining the length of this + * {@code null}. (This is useful in determining the length of this * list only if the caller knows that this list does not contain * any null elements.) * @@ -332,14 +348,14 @@ public class CopyOnWriteArrayList * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * - *

    Suppose x is a list known to contain only strings. + *

    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 String: + * allocated array of {@code String}: * *

     {@code String[] y = x.toArray(new String[0]);}
    * - * Note that toArray(new Object[0]) is identical in function to - * toArray(). + * 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 @@ public class CopyOnWriteArrayList * Appends the specified element to the end of this list. * * @param e element to be appended to this list - * @return true (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 @@ public class CopyOnWriteArrayList * 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 - * i such that + * {@code i} such that * (o==null ? get(i)==null : o.equals(get(i))) - * (if such an element exists). Returns true 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 true 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]; - } - - // special handling for last cell - if (eq(o, elements[newlen])) { - setArray(newElements); - return true; + 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; + } } + 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 @@ public class CopyOnWriteArrayList /** * Removes from this list all of the elements whose index is between - * fromIndex, inclusive, and toIndex, exclusive. + * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. * Shifts any succeeding elements to the left (reduces their index). - * This call shortens the list by (toIndex - fromIndex) elements. - * (If toIndex==fromIndex, 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 @@ public class CopyOnWriteArrayList * Appends the element, if not present. * * @param e element to be added to this list, if absent - * @return true 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 @@ public class CopyOnWriteArrayList } /** - * Returns true 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 true 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 @@ public class CopyOnWriteArrayList * in this class because of the need for an internal temporary array. * * @param c collection containing elements to be removed from this list - * @return true 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 * (optional) @@ -675,7 +711,7 @@ public class CopyOnWriteArrayList * its elements that are not contained in the specified collection. * * @param c collection containing elements to be retained in this list - * @return true 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 * (optional) @@ -727,22 +763,22 @@ public class CopyOnWriteArrayList 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 @@ public class CopyOnWriteArrayList * collection's iterator. * * @param c collection containing elements to be added to this list - * @return true 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 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 @@ public class CopyOnWriteArrayList 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 @@ public class CopyOnWriteArrayList * @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 true 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 class CopyOnWriteArrayList } } + public void forEach(Consumer 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 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 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 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 @@ public class CopyOnWriteArrayList * 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 ("[]"). Adjacent elements are separated by - * the characters ", " (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 @@ public class CopyOnWriteArrayList *

    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 NOT support the - * remove method. + * {@code remove} method. * * @return an iterator over the elements in this list in proper sequence */ @@ -967,7 +1076,7 @@ public class CopyOnWriteArrayList *

    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 NOT support the - * remove, set or add methods. + * {@code remove}, {@code set} or {@code add} methods. */ public ListIterator listIterator() { return new COWIterator(getArray(), 0); @@ -979,7 +1088,7 @@ public class CopyOnWriteArrayList *

    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 NOT support the - * remove, set or add methods. + * {@code remove}, {@code set} or {@code add} methods. * * @throws IndexOutOfBoundsException {@inheritDoc} */ @@ -992,7 +1101,12 @@ public class CopyOnWriteArrayList return new COWIterator(elements, index); } - private static class COWIterator implements ListIterator { + public Spliterator spliterator() { + return Spliterators.spliterator + (getArray(), Spliterator.IMMUTABLE | Spliterator.ORDERED); + } + + static final class COWIterator implements ListIterator { /** Snapshot of the array */ private final Object[] snapshot; /** Index of element to be returned by subsequent call to next. */ @@ -1035,7 +1149,7 @@ public class CopyOnWriteArrayList /** * Not supported. Always throws UnsupportedOperationException. - * @throws UnsupportedOperationException always; remove + * @throws UnsupportedOperationException always; {@code remove} * is not supported by this iterator. */ public void remove() { @@ -1044,7 +1158,7 @@ public class CopyOnWriteArrayList /** * Not supported. Always throws UnsupportedOperationException. - * @throws UnsupportedOperationException always; set + * @throws UnsupportedOperationException always; {@code set} * is not supported by this iterator. */ public void set(E e) { @@ -1053,7 +1167,7 @@ public class CopyOnWriteArrayList /** * Not supported. Always throws UnsupportedOperationException. - * @throws UnsupportedOperationException always; add + * @throws UnsupportedOperationException always; {@code add} * is not supported by this iterator. */ public void add(E e) { @@ -1061,12 +1175,13 @@ public class CopyOnWriteArrayList } @Override - @SuppressWarnings("unchecked") public void forEachRemaining(Consumer 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 @@ public class CopyOnWriteArrayList /** * Returns a view of the portion of this list between - * fromIndex, inclusive, and toIndex, 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 @@ public class CopyOnWriteArrayList } } - @Override public void forEach(Consumer 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); + } + } + + public void replaceAll(UnaryOperator 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(); + } } - @Override public void sort(Comparator 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 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 { + 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 removeIf(Predicate filter) { - Objects.requireNonNull(filter); + if (filter == 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) { + @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; } - @Override - public void replaceAll(UnaryOperator operator) { - final ReentrantLock lock = l.lock; - lock.lock(); - try { - checkForComodification(); - l.replaceAll(operator, offset, offset + size); - expectedArray = l.getArray(); - } finally { - lock.unlock(); - } + public Spliterator 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 @@ public class CopyOnWriteArrayList } @Override - @SuppressWarnings("unchecked") public void forEachRemaining(Consumer action) { Objects.requireNonNull(action); - while (nextIndex() < size) { - action.accept(it.next()); + int s = size; + ListIterator i = it; + while (nextIndex() < s) { + action.accept(i.next()); } } } @@ -1405,139 +1662,4 @@ public class CopyOnWriteArrayList throw new Error(e); } } - - @Override - @SuppressWarnings("unchecked") - public void forEach(Consumer action) { - forEach(action, (E[]) getArray(), 0, size()); - } - - private void forEach(Consumer 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 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 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 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 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 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 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); - } } diff --git a/jdk/src/share/classes/java/util/concurrent/CopyOnWriteArraySet.java b/jdk/src/share/classes/java/util/concurrent/CopyOnWriteArraySet.java index da3c9856332..ffb9668647c 100644 --- a/jdk/src/share/classes/java/util/concurrent/CopyOnWriteArraySet.java +++ b/jdk/src/share/classes/java/util/concurrent/CopyOnWriteArraySet.java @@ -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 @@ import java.util.*; * vastly outnumber mutative operations, and you need * to prevent interference among threads during traversal. *

  • It is thread-safe. - *
  • Mutative operations (add, set, remove, etc.) + *
  • Mutative operations ({@code add}, {@code set}, {@code remove}, etc.) * are expensive since they usually entail copying the entire underlying * array. - *
  • Iterators do not support the mutative remove operation. + *
  • Iterators do not support the mutative {@code remove} operation. *
  • 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. *
* - *

Sample Usage. The following code sketch uses a + *

Sample Usage. 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 @@ import java.util.*; * public void update() { * changeState(); * for (Handler handler : handlers) - * handler.handle(); + * handler.handle(); * } * }} * @@ -107,8 +114,15 @@ public class CopyOnWriteArraySet extends AbstractSet * @throws NullPointerException if the specified collection is null */ public CopyOnWriteArraySet(Collection c) { - al = new CopyOnWriteArrayList(); - al.addAllAbsent(c); + if (c.getClass() == CopyOnWriteArraySet.class) { + @SuppressWarnings("unchecked") CopyOnWriteArraySet cc = + (CopyOnWriteArraySet)c; + al = new CopyOnWriteArrayList(cc.al); + } + else { + al = new CopyOnWriteArrayList(); + al.addAllAbsent(c); + } } /** @@ -121,22 +135,22 @@ public class CopyOnWriteArraySet extends AbstractSet } /** - * Returns true if this set contains no elements. + * Returns {@code true} if this set contains no elements. * - * @return true if this set contains no elements + * @return {@code true} if this set contains no elements */ public boolean isEmpty() { return al.isEmpty(); } /** - * Returns true if this set contains the specified element. - * More formally, returns true if and only if this set - * contains an element e 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 * (o==null ? e==null : o.equals(e)). * * @param o element whose presence in this set is to be tested - * @return true 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 @@ public class CopyOnWriteArraySet extends AbstractSet *

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 - * null. (This is useful in determining the length of this + * {@code null}. (This is useful in determining the length of this * set only if the caller knows that this set does not contain * any null elements.) * @@ -185,14 +199,14 @@ public class CopyOnWriteArraySet extends AbstractSet * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * - *

Suppose x is a set known to contain only strings. + *

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 String: + * array of {@code String}: * *

 {@code String[] y = x.toArray(new String[0]);}
* - * Note that toArray(new Object[0]) is identical in function to - * toArray(). + * 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 @@ public class CopyOnWriteArraySet extends AbstractSet /** * Removes the specified element from this set if it is present. - * More formally, removes an element e such that + * More formally, removes an element {@code e} such that * (o==null ? e==null : o.equals(e)), - * if this set contains such an element. Returns true 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 true 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 @@ public class CopyOnWriteArraySet extends AbstractSet /** * Adds the specified element to this set if it is not already present. - * More formally, adds the specified element e to this set if - * the set contains no element e2 such that + * More formally, adds the specified element {@code e} to this set if + * the set contains no element {@code e2} such that * (e==null ? e2==null : e.equals(e2)). * If this set already contains the element, the call leaves the set - * unchanged and returns false. + * unchanged and returns {@code false}. * * @param e element to be added to this set - * @return true 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 @@ public class CopyOnWriteArraySet extends AbstractSet } /** - * Returns true 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 true if it is a subset of this set. + * method returns {@code true} if it is a subset of this set. * * @param c collection to be checked for containment in this set - * @return true 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 @@ public class CopyOnWriteArraySet extends AbstractSet /** * 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 addAll operation effectively modifies this set so + * set, the {@code addAll} operation effectively modifies this set so * that its value is the union 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 true 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 @@ public class CopyOnWriteArraySet extends AbstractSet * asymmetric set difference of the two sets. * * @param c collection containing elements to be removed from this set - * @return true 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 @@ public class CopyOnWriteArraySet extends AbstractSet * two sets. * * @param c collection containing elements to be retained in this set - * @return true 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 @@ public class CopyOnWriteArraySet extends AbstractSet *

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 NOT support the - * remove method. + * {@code remove} method. * * @return an iterator over the elements in this set */ @@ -338,7 +352,7 @@ public class CopyOnWriteArraySet extends AbstractSet * 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 @@ public class CopyOnWriteArraySet extends AbstractSet return k == len; } + public boolean removeIf(Predicate filter) { + return al.removeIf(filter); + } + + public void forEach(Consumer action) { + al.forEach(action); + } + + public Spliterator spliterator() { + return Spliterators.spliterator + (al.getArray(), Spliterator.IMMUTABLE | Spliterator.DISTINCT); + } + /** * Tests for equality, coping with nulls. */ diff --git a/jdk/src/share/classes/java/util/concurrent/DelayQueue.java b/jdk/src/share/classes/java/util/concurrent/DelayQueue.java index aa68b749d7b..610fb717ac8 100644 --- a/jdk/src/share/classes/java/util/concurrent/DelayQueue.java +++ b/jdk/src/share/classes/java/util/concurrent/DelayQueue.java @@ -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 - * Delayed 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 head of the queue is that - * Delayed element whose delay expired furthest in the - * past. If no delay has expired there is no head and poll - * will return null. Expiration occurs when an element's - * getDelay(TimeUnit.NANOSECONDS) 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 take or poll, they are otherwise - * treated as normal elements. For example, the size 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. * *

This class and its iterator implement all of the * optional methods of the {@link Collection} and {@link - * Iterator} interfaces. + * Iterator} interfaces. The Iterator provided in method {@link + * #iterator()} is not guaranteed to traverse the elements of + * the DelayQueue in any particular order. * *

This class is a member of the * @@ -64,11 +67,10 @@ import java.util.*; * @author Doug Lea * @param the type of elements held in this collection */ - public class DelayQueue extends AbstractQueue implements BlockingQueue { - private transient final ReentrantLock lock = new ReentrantLock(); + private final transient ReentrantLock lock = new ReentrantLock(); private final PriorityQueue q = new PriorityQueue(); /** @@ -97,12 +99,12 @@ public class DelayQueue extends AbstractQueue private final Condition available = lock.newCondition(); /** - * Creates a new DelayQueue that is initially empty. + * Creates a new {@code DelayQueue} that is initially empty. */ public DelayQueue() {} /** - * Creates a DelayQueue 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 @@ public class DelayQueue extends AbstractQueue * Inserts the specified element into this delay queue. * * @param e the element to add - * @return true (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 @@ public class DelayQueue extends AbstractQueue * Inserts the specified element into this delay queue. * * @param e the element to add - * @return true + * @return {@code true} * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { @@ -164,7 +166,7 @@ public class DelayQueue extends AbstractQueue * @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 true + * @return {@code true} * @throws NullPointerException {@inheritDoc} */ public boolean offer(E e, long timeout, TimeUnit unit) { @@ -172,10 +174,10 @@ public class DelayQueue extends AbstractQueue } /** - * Retrieves and removes the head of this queue, or returns null + * 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 null 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 @@ public class DelayQueue extends AbstractQueue 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 @@ public class DelayQueue extends AbstractQueue 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 @@ public class DelayQueue extends AbstractQueue * 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 null 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 @@ public class DelayQueue extends AbstractQueue 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 @@ public class DelayQueue extends AbstractQueue /** * Retrieves, but does not remove, the head of this queue, or - * returns null if this queue is empty. Unlike - * poll, 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 null 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; @@ -312,6 +316,17 @@ public class DelayQueue extends AbstractQueue } } + /** + * 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} @@ -327,11 +342,9 @@ public class DelayQueue extends AbstractQueue 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 @@ public class DelayQueue extends AbstractQueue 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 @@ public class DelayQueue extends AbstractQueue } /** - * Always returns Integer.MAX_VALUE because - * a DelayQueue is not capacity constrained. + * Always returns {@code Integer.MAX_VALUE} because + * a {@code DelayQueue} is not capacity constrained. * - * @return Integer.MAX_VALUE + * @return {@code Integer.MAX_VALUE} */ public int remainingCapacity() { return Integer.MAX_VALUE; @@ -430,7 +441,7 @@ public class DelayQueue extends AbstractQueue *

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 - * null. + * {@code null}. * *

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 @@ public class DelayQueue extends AbstractQueue * under certain circumstances, be used to save allocation costs. * *

The following code can be used to dump a delay queue into a newly - * allocated array of Delayed: + * allocated array of {@code Delayed}: * - *

-     *     Delayed[] a = q.toArray(new Delayed[0]);
+ *
 {@code Delayed[] a = q.toArray(new Delayed[0]);}
* - * Note that toArray(new Object[0]) is identical in function to - * toArray(). + * 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 @@ -479,6 +489,24 @@ public class DelayQueue extends AbstractQueue } } + /** + * Identity-based version for use in Itr.remove + */ + void removeEQ(Object o) { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + for (Iterator 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 @@ -502,7 +530,7 @@ public class DelayQueue extends AbstractQueue */ private class Itr implements Iterator { 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 class DelayQueue extends AbstractQueue 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 it = q.iterator(); it.hasNext(); ) { - if (it.next() == x) { - it.remove(); - return; - } - } - } finally { - lock.unlock(); - } } } diff --git a/jdk/src/share/classes/java/util/concurrent/Delayed.java b/jdk/src/share/classes/java/util/concurrent/Delayed.java index 8b185e1d79c..5da1ec8d94c 100644 --- a/jdk/src/share/classes/java/util/concurrent/Delayed.java +++ b/jdk/src/share/classes/java/util/concurrent/Delayed.java @@ -40,8 +40,8 @@ package java.util.concurrent; * acted upon after a given delay. * *

An implementation of this interface must define a - * compareTo method that provides an ordering consistent with - * its getDelay method. + * {@code compareTo} method that provides an ordering consistent with + * its {@code getDelay} method. * * @since 1.5 * @author Doug Lea diff --git a/jdk/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java b/jdk/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java index b79bc9444e3..df688a57b06 100644 --- a/jdk/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java +++ b/jdk/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java @@ -41,12 +41,15 @@ import java.util.Iterator; 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. * - *

The optional capacity bound constructor argument serves as a + *

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 @@ public class LinkedBlockingDeque // 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 @@ public class LinkedBlockingDeque } /** - * @throws IllegalStateException {@inheritDoc} + * @throws IllegalStateException if this deque is full * @throws NullPointerException {@inheritDoc} */ public void addLast(E e) { @@ -623,8 +626,7 @@ public class LinkedBlockingDeque * *

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 @@ public class LinkedBlockingDeque // 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 @@ public class LinkedBlockingDeque // * @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 c) { @@ -1151,6 +1153,127 @@ public class LinkedBlockingDeque Node nextNode(Node n) { return n.prev; } } + /** A customized variant of Spliterators.IteratorSpliterator */ + static final class LBDSpliterator implements Spliterator { + static final int MAX_BATCH = 1 << 25; // max batch array size; + final LinkedBlockingDeque queue; + Node 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 queue) { + this.queue = queue; + this.est = queue.size(); + } + + public long estimateSize() { return est; } + + public Spliterator trySplit() { + Node h; + final LinkedBlockingDeque 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 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 action) { + if (action == null) throw new NullPointerException(); + final LinkedBlockingDeque q = this.queue; + final ReentrantLock lock = q.lock; + if (!exhausted) { + exhausted = true; + Node p = current; + do { + E e = null; + lock.lock(); + try { + if (p == null) + p = q.first; + while (p != null) { + e = p.item; + p = p.next; + if (e != null) + break; + } + } finally { + lock.unlock(); + } + if (e != null) + action.accept(e); + } while (p != null); + } + } + + public boolean tryAdvance(Consumer action) { + if (action == null) throw new NullPointerException(); + final LinkedBlockingDeque q = this.queue; + final ReentrantLock lock = q.lock; + if (!exhausted) { + E e = null; + lock.lock(); + try { + if (current == null) + current = q.first; + while (current != null) { + e = current.item; + current = current.next; + if (e != null) + break; + } + } finally { + lock.unlock(); + } + if (current == null) + exhausted = true; + if (e != null) { + action.accept(e); + return true; + } + } + return false; + } + + public int characteristics() { + return Spliterator.ORDERED | Spliterator.NONNULL | + Spliterator.CONCURRENT; + } + } + + public Spliterator spliterator() { + return new LBDSpliterator(this); + } + /** * Saves this deque to a stream (that is, serializes it). * diff --git a/jdk/src/share/classes/java/util/concurrent/LinkedBlockingQueue.java b/jdk/src/share/classes/java/util/concurrent/LinkedBlockingQueue.java index e95e0a32af8..05bf7cc22de 100644 --- a/jdk/src/share/classes/java/util/concurrent/LinkedBlockingQueue.java +++ b/jdk/src/share/classes/java/util/concurrent/LinkedBlockingQueue.java @@ -42,6 +42,9 @@ import java.util.AbstractQueue; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; +import java.util.Spliterator; +import java.util.Spliterators; +import java.util.function.Consumer; /** * An optionally-bounded {@linkplain BlockingQueue blocking queue} based on @@ -56,7 +59,7 @@ import java.util.NoSuchElementException; * Linked queues typically have higher throughput than array-based queues but * less predictable performance in most concurrent applications. * - *

The optional capacity bound constructor argument serves as a + *

The optional capacity bound constructor argument serves as a * way to prevent excessive queue expansion. The capacity, if unspecified, * is equal to {@link Integer#MAX_VALUE}. Linked nodes are * dynamically created upon each insertion unless this would bring the @@ -216,7 +219,7 @@ public class LinkedBlockingQueue extends AbstractQueue } /** - * Lock to prevent both puts and takes. + * Locks to prevent both puts and takes. */ void fullyLock() { putLock.lock(); @@ -224,7 +227,7 @@ public class LinkedBlockingQueue extends AbstractQueue } /** - * Unlock to allow both puts and takes. + * Unlocks to allow both puts and takes. */ void fullyUnlock() { takeLock.unlock(); @@ -362,7 +365,7 @@ public class LinkedBlockingQueue extends AbstractQueue * necessary up to the specified wait time for space to become available. * * @return {@code true} if successful, or {@code false} if - * the specified waiting time elapses before space is available. + * the specified waiting time elapses before space is available * @throws InterruptedException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ @@ -782,6 +785,7 @@ public class LinkedBlockingQueue extends AbstractQueue * item to hand out so that if hasNext() reports true, we will * still have it to return even if lost race with a take etc. */ + private Node current; private Node lastRet; private E currentElement; @@ -855,6 +859,124 @@ public class LinkedBlockingQueue extends AbstractQueue } } + /** A customized variant of Spliterators.IteratorSpliterator */ + static final class LBQSpliterator implements Spliterator { + static final int MAX_BATCH = 1 << 25; // max batch array size; + final LinkedBlockingQueue queue; + Node current; // current node; null until initialized + int batch; // batch size for splits + boolean exhausted; // true when no more nodes + long est; // size estimate + LBQSpliterator(LinkedBlockingQueue queue) { + this.queue = queue; + this.est = queue.size(); + } + + public long estimateSize() { return est; } + + public Spliterator trySplit() { + Node h; + final LinkedBlockingQueue q = this.queue; + int b = batch; + int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1; + if (!exhausted && + ((h = current) != null || (h = q.head.next) != null) && + h.next != null) { + Object[] a = new Object[n]; + int i = 0; + Node p = current; + q.fullyLock(); + try { + if (p != null || (p = q.head.next) != null) { + do { + if ((a[i] = p.item) != null) + ++i; + } while ((p = p.next) != null && i < n); + } + } finally { + q.fullyUnlock(); + } + if ((current = p) == null) { + est = 0L; + exhausted = true; + } + else if ((est -= i) < 0L) + est = 0L; + if (i > 0) { + batch = i; + return Spliterators.spliterator + (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL | + Spliterator.CONCURRENT); + } + } + return null; + } + + public void forEachRemaining(Consumer action) { + if (action == null) throw new NullPointerException(); + final LinkedBlockingQueue q = this.queue; + if (!exhausted) { + exhausted = true; + Node p = current; + do { + E e = null; + q.fullyLock(); + try { + if (p == null) + p = q.head.next; + while (p != null) { + e = p.item; + p = p.next; + if (e != null) + break; + } + } finally { + q.fullyUnlock(); + } + if (e != null) + action.accept(e); + } while (p != null); + } + } + + public boolean tryAdvance(Consumer action) { + if (action == null) throw new NullPointerException(); + final LinkedBlockingQueue q = this.queue; + if (!exhausted) { + E e = null; + q.fullyLock(); + try { + if (current == null) + current = q.head.next; + while (current != null) { + e = current.item; + current = current.next; + if (e != null) + break; + } + } finally { + q.fullyUnlock(); + } + if (current == null) + exhausted = true; + if (e != null) { + action.accept(e); + return true; + } + } + return false; + } + + public int characteristics() { + return Spliterator.ORDERED | Spliterator.NONNULL | + Spliterator.CONCURRENT; + } + } + + public Spliterator spliterator() { + return new LBQSpliterator(this); + } + /** * Saves this queue to a stream (that is, serializes it). * diff --git a/jdk/src/share/classes/java/util/concurrent/LinkedTransferQueue.java b/jdk/src/share/classes/java/util/concurrent/LinkedTransferQueue.java index 6b6e46a9264..7dbb368cc52 100644 --- a/jdk/src/share/classes/java/util/concurrent/LinkedTransferQueue.java +++ b/jdk/src/share/classes/java/util/concurrent/LinkedTransferQueue.java @@ -40,8 +40,10 @@ import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Queue; -import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; +import java.util.Spliterator; +import java.util.Spliterators; +import java.util.function.Consumer; /** * An unbounded {@link TransferQueue} based on linked nodes. @@ -776,6 +778,24 @@ public class LinkedTransferQueue extends AbstractQueue return null; } + /** + * Version of firstOfMode used by Spliterator + */ + final Node firstDataNode() { + for (Node p = head; p != null;) { + Object item = p.item; + if (p.isData) { + if (item != null && item != p) + return p; + } + else if (item == null) + break; + if (p == (p = p.next)) + p = head; + } + return null; + } + /** * Returns the item in the first unmatched node with isData; or * null if none. Used by peek. @@ -910,6 +930,98 @@ public class LinkedTransferQueue extends AbstractQueue } } + /** A customized variant of Spliterators.IteratorSpliterator */ + static final class LTQSpliterator implements Spliterator { + static final int MAX_BATCH = 1 << 25; // max batch array size; + final LinkedTransferQueue queue; + Node current; // current node; null until initialized + int batch; // batch size for splits + boolean exhausted; // true when no more nodes + LTQSpliterator(LinkedTransferQueue queue) { + this.queue = queue; + } + + public Spliterator trySplit() { + Node p; + final LinkedTransferQueue q = this.queue; + int b = batch; + int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1; + if (!exhausted && + ((p = current) != null || (p = q.firstDataNode()) != null) && + p.next != null) { + Object[] a = new Object[n]; + int i = 0; + do { + if ((a[i] = p.item) != null) + ++i; + if (p == (p = p.next)) + p = q.firstDataNode(); + } while (p != null && i < n); + if ((current = p) == null) + exhausted = true; + if (i > 0) { + batch = i; + return Spliterators.spliterator + (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL | + Spliterator.CONCURRENT); + } + } + return null; + } + + @SuppressWarnings("unchecked") + public void forEachRemaining(Consumer action) { + Node p; + if (action == null) throw new NullPointerException(); + final LinkedTransferQueue q = this.queue; + if (!exhausted && + ((p = current) != null || (p = q.firstDataNode()) != null)) { + exhausted = true; + do { + Object e = p.item; + if (p == (p = p.next)) + p = q.firstDataNode(); + if (e != null) + action.accept((E)e); + } while (p != null); + } + } + + @SuppressWarnings("unchecked") + public boolean tryAdvance(Consumer action) { + Node p; + if (action == null) throw new NullPointerException(); + final LinkedTransferQueue q = this.queue; + if (!exhausted && + ((p = current) != null || (p = q.firstDataNode()) != null)) { + Object e; + do { + e = p.item; + if (p == (p = p.next)) + p = q.firstDataNode(); + } while (e == null && p != null); + if ((current = p) == null) + exhausted = true; + if (e != null) { + action.accept((E)e); + return true; + } + } + return false; + } + + public long estimateSize() { return Long.MAX_VALUE; } + + public int characteristics() { + return Spliterator.ORDERED | Spliterator.NONNULL | + Spliterator.CONCURRENT; + } + } + + public Spliterator spliterator() { + return new LTQSpliterator(this); + } + /* -------------- Removal methods -------------- */ /** diff --git a/jdk/src/share/classes/java/util/concurrent/PriorityBlockingQueue.java b/jdk/src/share/classes/java/util/concurrent/PriorityBlockingQueue.java index d78cf205525..fdf9c71af93 100644 --- a/jdk/src/share/classes/java/util/concurrent/PriorityBlockingQueue.java +++ b/jdk/src/share/classes/java/util/concurrent/PriorityBlockingQueue.java @@ -37,7 +37,17 @@ package java.util.concurrent; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; -import java.util.*; +import java.util.AbstractQueue; +import java.util.Arrays; +import java.util.Collection; +import java.util.Comparator; +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.PriorityQueue; +import java.util.Queue; +import java.util.SortedSet; +import java.util.Spliterator; +import java.util.function.Consumer; /** * An unbounded {@linkplain BlockingQueue blocking queue} that uses @@ -342,7 +352,6 @@ public class PriorityBlockingQueue extends AbstractQueue * @param k the position to fill * @param x the item to insert * @param array the heap array - * @param n heap size */ private static void siftUpComparable(int k, T x, Object[] array) { Comparable key = (Comparable) x; @@ -936,6 +945,70 @@ public class PriorityBlockingQueue extends AbstractQueue } } + // Similar to Collections.ArraySnapshotSpliterator but avoids + // commitment to toArray until needed + static final class PBQSpliterator implements Spliterator { + final PriorityBlockingQueue queue; + Object[] array; + int index; + int fence; + + PBQSpliterator(PriorityBlockingQueue queue, Object[] array, + int index, int fence) { + this.queue = queue; + this.array = array; + this.index = index; + this.fence = fence; + } + + final int getFence() { + int hi; + if ((hi = fence) < 0) + hi = fence = (array = queue.toArray()).length; + return hi; + } + + public Spliterator trySplit() { + int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; + return (lo >= mid) ? null : + new PBQSpliterator(queue, array, lo, index = mid); + } + + @SuppressWarnings("unchecked") + public void forEachRemaining(Consumer action) { + Object[] a; int i, hi; // hoist accesses and checks from loop + if (action == null) + throw new NullPointerException(); + if ((a = array) == null) + fence = (a = queue.toArray()).length; + if ((hi = fence) <= a.length && + (i = index) >= 0 && i < (index = hi)) { + do { action.accept((E)a[i]); } while (++i < hi); + } + } + + public boolean tryAdvance(Consumer action) { + if (action == null) + throw new NullPointerException(); + if (getFence() > index && index >= 0) { + @SuppressWarnings("unchecked") E e = (E) array[index++]; + action.accept(e); + return true; + } + return false; + } + + public long estimateSize() { return (long)(getFence() - index); } + + public int characteristics() { + return Spliterator.NONNULL | Spliterator.SIZED | Spliterator.SUBSIZED; + } + } + + public Spliterator spliterator() { + return new PBQSpliterator(this, null, 0, -1); + } + // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long allocationSpinLockOffset; diff --git a/jdk/src/share/classes/java/util/concurrent/SynchronousQueue.java b/jdk/src/share/classes/java/util/concurrent/SynchronousQueue.java index ee9b1218854..97b53049716 100644 --- a/jdk/src/share/classes/java/util/concurrent/SynchronousQueue.java +++ b/jdk/src/share/classes/java/util/concurrent/SynchronousQueue.java @@ -44,17 +44,17 @@ import java.util.*; * operation must wait for a corresponding remove operation by another * thread, and vice versa. A synchronous queue does not have any * internal capacity, not even a capacity of one. You cannot - * peek at a synchronous queue because an element is only + * {@code peek} at a synchronous queue because an element is only * present when you try to remove it; you cannot insert an element * (using any method) unless another thread is trying to remove it; * you cannot iterate as there is nothing to iterate. The * head of the queue is the element that the first queued * inserting thread is trying to add to the queue; if there is no such * queued thread then no element is available for removal and - * poll() will return null. For purposes of other - * Collection methods (for example contains), a - * SynchronousQueue acts as an empty collection. This queue - * does not permit null elements. + * {@code poll()} will return {@code null}. For purposes of other + * {@code Collection} methods (for example {@code contains}), a + * {@code SynchronousQueue} acts as an empty collection. This queue + * does not permit {@code null} elements. * *

Synchronous queues are similar to rendezvous channels used in * CSP and Ada. They are well suited for handoff designs, in which an @@ -62,10 +62,10 @@ import java.util.*; * in another thread in order to hand it some information, event, or * task. * - *

This class supports an optional fairness policy for ordering + *

This class supports an optional fairness policy for ordering * waiting producer and consumer threads. By default, this ordering * is not guaranteed. However, a queue constructed with fairness set - * to true grants threads access in FIFO order. + * to {@code true} grants threads access in FIFO order. * *

This class and its iterator implement all of the * optional methods of the {@link Collection} and {@link @@ -599,7 +599,7 @@ public class SynchronousQueue extends AbstractQueue /** * Reference to a cancelled node that might not yet have been * unlinked from queue because it was the last inserted node - * when it cancelled. + * when it was cancelled. */ transient volatile QNode cleanMe; @@ -847,14 +847,14 @@ public class SynchronousQueue extends AbstractQueue private transient volatile Transferer transferer; /** - * Creates a SynchronousQueue with nonfair access policy. + * Creates a {@code SynchronousQueue} with nonfair access policy. */ public SynchronousQueue() { this(false); } /** - * Creates a SynchronousQueue with the specified fairness policy. + * Creates a {@code SynchronousQueue} with the specified fairness policy. * * @param fair if true, waiting threads contend in FIFO order for * access; otherwise the order is unspecified. @@ -882,8 +882,8 @@ public class SynchronousQueue extends AbstractQueue * Inserts the specified element into this queue, waiting if necessary * up to the specified wait time for another thread to receive it. * - * @return true if successful, or false if the - * specified waiting time elapses before a consumer appears. + * @return {@code true} if successful, or {@code false} if the + * specified waiting time elapses before a consumer appears * @throws InterruptedException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ @@ -902,8 +902,8 @@ public class SynchronousQueue extends AbstractQueue * waiting to receive it. * * @param e the element to add - * @return true if the element was added to this queue, else - * false + * @return {@code true} if the element was added to this queue, else + * {@code false} * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { @@ -931,8 +931,8 @@ public class SynchronousQueue extends AbstractQueue * if necessary up to the specified wait time, for another thread * to insert it. * - * @return the head of this queue, or null if the - * specified waiting time elapses before an element is present. + * @return the head of this queue, or {@code null} if the + * specified waiting time elapses before an element is present * @throws InterruptedException {@inheritDoc} */ public E poll(long timeout, TimeUnit unit) throws InterruptedException { @@ -946,18 +946,18 @@ public class SynchronousQueue extends AbstractQueue * Retrieves and removes the head of this queue, if another thread * is currently making an element available. * - * @return the head of this queue, or null if no - * element is available. + * @return the head of this queue, or {@code null} if no + * element is available */ public E poll() { return transferer.transfer(null, true, 0); } /** - * Always returns true. - * A SynchronousQueue has no internal capacity. + * Always returns {@code true}. + * A {@code SynchronousQueue} has no internal capacity. * - * @return true + * @return {@code true} */ public boolean isEmpty() { return true; @@ -965,9 +965,9 @@ public class SynchronousQueue extends AbstractQueue /** * Always returns zero. - * A SynchronousQueue has no internal capacity. + * A {@code SynchronousQueue} has no internal capacity. * - * @return zero. + * @return zero */ public int size() { return 0; @@ -975,9 +975,9 @@ public class SynchronousQueue extends AbstractQueue /** * Always returns zero. - * A SynchronousQueue has no internal capacity. + * A {@code SynchronousQueue} has no internal capacity. * - * @return zero. + * @return zero */ public int remainingCapacity() { return 0; @@ -985,80 +985,80 @@ public class SynchronousQueue extends AbstractQueue /** * Does nothing. - * A SynchronousQueue has no internal capacity. + * A {@code SynchronousQueue} has no internal capacity. */ public void clear() { } /** - * Always returns false. - * A SynchronousQueue has no internal capacity. + * Always returns {@code false}. + * A {@code SynchronousQueue} has no internal capacity. * * @param o the element - * @return false + * @return {@code false} */ public boolean contains(Object o) { return false; } /** - * Always returns false. - * A SynchronousQueue has no internal capacity. + * Always returns {@code false}. + * A {@code SynchronousQueue} has no internal capacity. * * @param o the element to remove - * @return false + * @return {@code false} */ public boolean remove(Object o) { return false; } /** - * Returns false unless the given collection is empty. - * A SynchronousQueue has no internal capacity. + * Returns {@code false} unless the given collection is empty. + * A {@code SynchronousQueue} has no internal capacity. * * @param c the collection - * @return false unless given collection is empty + * @return {@code false} unless given collection is empty */ public boolean containsAll(Collection c) { return c.isEmpty(); } /** - * Always returns false. - * A SynchronousQueue has no internal capacity. + * Always returns {@code false}. + * A {@code SynchronousQueue} has no internal capacity. * * @param c the collection - * @return false + * @return {@code false} */ public boolean removeAll(Collection c) { return false; } /** - * Always returns false. - * A SynchronousQueue has no internal capacity. + * Always returns {@code false}. + * A {@code SynchronousQueue} has no internal capacity. * * @param c the collection - * @return false + * @return {@code false} */ public boolean retainAll(Collection c) { return false; } /** - * Always returns null. - * A SynchronousQueue does not return elements + * Always returns {@code null}. + * A {@code SynchronousQueue} does not return elements * unless actively waited on. * - * @return null + * @return {@code null} */ public E peek() { return null; } /** - * Returns an empty iterator in which hasNext always returns - * false. + * Returns an empty iterator in which {@code hasNext} always returns + * {@code false}. * * @return an empty iterator */ @@ -1077,6 +1077,10 @@ public class SynchronousQueue extends AbstractQueue public void remove() { throw new IllegalStateException(); } } + public Spliterator spliterator() { + return Spliterators.emptySpliterator(); + } + /** * Returns a zero-length array. * @return a zero-length array @@ -1086,7 +1090,7 @@ public class SynchronousQueue extends AbstractQueue } /** - * Sets the zeroeth element of the specified array to null + * Sets the zeroeth element of the specified array to {@code null} * (if the array has non-zero length) and returns it. * * @param a the array From 1001452ba9338d90bf279e38d2dd0a8a1e65f31a Mon Sep 17 00:00:00 2001 From: Doug Lea Date: Wed, 3 Jul 2013 11:58:10 +0200 Subject: [PATCH 008/123] 8019481: Sync misc j.u.c classes from 166 to tl Reviewed-by: martin --- .../concurrent/BrokenBarrierException.java | 4 +- .../java/util/concurrent/CountDownLatch.java | 26 +- .../java/util/concurrent/CyclicBarrier.java | 59 +- .../java/util/concurrent/Exchanger.java | 867 +++++++++--------- .../classes/java/util/concurrent/Phaser.java | 143 +-- .../java/util/concurrent/TimeUnit.java | 93 +- .../util/concurrent/TimeoutException.java | 6 +- .../java/util/concurrent/package-info.java | 14 +- 8 files changed, 600 insertions(+), 612 deletions(-) diff --git a/jdk/src/share/classes/java/util/concurrent/BrokenBarrierException.java b/jdk/src/share/classes/java/util/concurrent/BrokenBarrierException.java index 2c8f7e3396d..11f126e015a 100644 --- a/jdk/src/share/classes/java/util/concurrent/BrokenBarrierException.java +++ b/jdk/src/share/classes/java/util/concurrent/BrokenBarrierException.java @@ -49,13 +49,13 @@ public class BrokenBarrierException extends Exception { private static final long serialVersionUID = 7117394618823254244L; /** - * Constructs a BrokenBarrierException with no specified detail + * Constructs a {@code BrokenBarrierException} with no specified detail * message. */ public BrokenBarrierException() {} /** - * Constructs a BrokenBarrierException with the specified + * Constructs a {@code BrokenBarrierException} with the specified * detail message. * * @param message the detail message diff --git a/jdk/src/share/classes/java/util/concurrent/CountDownLatch.java b/jdk/src/share/classes/java/util/concurrent/CountDownLatch.java index 055eb113727..a8b50ca3907 100644 --- a/jdk/src/share/classes/java/util/concurrent/CountDownLatch.java +++ b/jdk/src/share/classes/java/util/concurrent/CountDownLatch.java @@ -92,15 +92,15 @@ import java.util.concurrent.locks.AbstractQueuedSynchronizer; * 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 @@ import java.util.concurrent.locks.AbstractQueuedSynchronizer; * 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() { ... } diff --git a/jdk/src/share/classes/java/util/concurrent/CyclicBarrier.java b/jdk/src/share/classes/java/util/concurrent/CyclicBarrier.java index eb25879dbcf..d1186d8eb4f 100644 --- a/jdk/src/share/classes/java/util/concurrent/CyclicBarrier.java +++ b/jdk/src/share/classes/java/util/concurrent/CyclicBarrier.java @@ -45,14 +45,14 @@ import java.util.concurrent.locks.ReentrantLock; * cyclic because it can be re-used after the waiting threads * are released. * - *

A CyclicBarrier supports an optional {@link Runnable} command + *

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 barrier action is useful * for updating shared-state before any of the parties continue. * - *

Sample usage: Here is an example of - * using a barrier in a parallel decomposition design: + *

Sample usage: Here is an example of using a barrier in a + * parallel decomposition design: * *

 {@code
  * class Solver {
@@ -81,16 +81,20 @@ import java.util.concurrent.locks.ReentrantLock;
  *   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 threads = new ArrayList(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();
  *   }
  * }}
* @@ -98,8 +102,8 @@ import java.util.concurrent.locks.ReentrantLock; * 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 done() will return - * true and each worker will terminate. + * determines that a solution has been found then {@code done()} will return + * {@code true} and each worker will terminate. * *

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 @@ import java.util.concurrent.locks.ReentrantLock; * // log the completion of this iteration * }} * - *

The CyclicBarrier uses an all-or-none breakage model + *

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 @@ public class CyclicBarrier { * 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 count 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 @@ public class CyclicBarrier { } /** - * Creates a new CyclicBarrier 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 @@ public class CyclicBarrier { } /** - * Creates a new CyclicBarrier 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 @@ public class CyclicBarrier { /** * Waits until all {@linkplain #getParties parties} have invoked - * await on this barrier. + * {@code await} on this barrier. * *

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 @@ public class CyclicBarrier { * *

If the barrier is {@link #reset} while any thread is waiting, * or if the barrier {@linkplain #isBroken is broken} when - * await is invoked, or while any thread is waiting, then + * {@code await} is invoked, or while any thread is waiting, then * {@link BrokenBarrierException} is thrown. * *

If any thread is {@linkplain Thread#interrupt interrupted} while waiting, @@ -343,7 +347,7 @@ public class CyclicBarrier { * the broken state. * * @return the arrival index of the current thread, where index - * {@link #getParties()} - 1 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 @@ public class CyclicBarrier { * 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 @@ public class CyclicBarrier { /** * Waits until all {@linkplain #getParties parties} have invoked - * await on this barrier, or the specified waiting time elapses. + * {@code await} on this barrier, or the specified waiting time elapses. * *

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 @@ public class CyclicBarrier { * *

If the barrier is {@link #reset} while any thread is waiting, * or if the barrier {@linkplain #isBroken is broken} when - * await is invoked, or while any thread is waiting, then + * {@code await} is invoked, or while any thread is waiting, then * {@link BrokenBarrierException} is thrown. * *

If any thread is {@linkplain Thread#interrupt interrupted} while @@ -412,16 +416,17 @@ public class CyclicBarrier { * @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 - * {@link #getParties()} - 1 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 another 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, diff --git a/jdk/src/share/classes/java/util/concurrent/Exchanger.java b/jdk/src/share/classes/java/util/concurrent/Exchanger.java index 5accdb1ce58..980b0e187a4 100644 --- a/jdk/src/share/classes/java/util/concurrent/Exchanger.java +++ b/jdk/src/share/classes/java/util/concurrent/Exchanger.java @@ -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 @@ import java.util.concurrent.locks.LockSupport; * 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. - *

{@code
+ *  
 {@code
  * class FillAndEmpty {
  *   Exchanger exchanger = new Exchanger();
  *   DataBuffer initialEmptyBuffer = ... a made-up type
@@ -88,8 +89,7 @@ import java.util.concurrent.locks.LockSupport;
  *     new Thread(new FillingLoop()).start();
  *     new Thread(new EmptyingLoop()).start();
  *   }
- * }
- * }
+ * }}
* *

Memory consistency effects: For each pair of threads that * successfully exchange objects via an {@code Exchanger}, actions @@ -103,486 +103,425 @@ import java.util.concurrent.locks.LockSupport; * @param The type of objects that may be exchanged */ public class Exchanger { + /* - * 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 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 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 * - * 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. + * 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.) * - * 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. + * 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. * - * 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. + * 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). * - * 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. + * 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. * - * 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. + * 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. * - * 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 + * 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. + * + * 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.) + * + * 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; + static final int FULL = (NCPU >= (MMASK << 1)) ? MMASK : NCPU >>> 1; /** - * 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. + * 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 FULL = - Math.max(0, Math.min(CAPACITY, NCPU / 2) - 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. - */ - 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 { - /** 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; + /** + * 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 + } - /** - * Creates node with given item and empty hole. - * @param item the item - */ - public Node(Object item) { - this.item = item; - } + /** The corresponding thread local class */ + static final class Participant extends ThreadLocal { + public Node initialValue() { return new Node(); } } /** - * 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. + * Per-thread state */ - @SuppressWarnings("serial") - private static final class Slot extends AtomicReference { - // 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; - } + private final Participant participant; /** - * Slot array. Elements are lazily initialized when needed. - * Declared volatile to enable double-checked lazy construction. + * Elimination array; null until enabled (within slotExchange). + * Element accesses use emulation of volatile gets and CAS. */ - private volatile Slot[] arena = new Slot[CAPACITY]; + 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 - } - 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 (++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 - } - } - } - - /** - * 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. - * - *

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. - * - * @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 - */ - 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) + 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 (spins > 0) - --spins; - else - tryCancel(node, slot); - } - } - - /** - * 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); } - 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 (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 (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; } } - return CANCEL; + } + + /** + * Exchange function used until arenas enabled. See above for explanation. + * + * @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 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; + + 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 (arena != null) + return null; // caller must reroute to arenaExchange + else { + p.item = item; + if (U.compareAndSwapObject(this, SLOT, null, p)) + break; + p.item = null; + } + } + + // 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 @@ public class Exchanger { */ @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 @@ public class Exchanger { * * @param x the object to exchange * @param timeout the maximum time to wait - * @param unit the time unit of the timeout 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 @@ public class Exchanger { @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(); - } - throw new InterruptedException(); + 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); + } + if ((s & (s-1)) != 0 || s > (1 << ASHIFT)) + throw new Error("Unsupported array scale"); + } + } diff --git a/jdk/src/share/classes/java/util/concurrent/Phaser.java b/jdk/src/share/classes/java/util/concurrent/Phaser.java index c8afecc3c00..394f62bccf3 100644 --- a/jdk/src/share/classes/java/util/concurrent/Phaser.java +++ b/jdk/src/share/classes/java/util/concurrent/Phaser.java @@ -46,7 +46,7 @@ import java.util.concurrent.locks.LockSupport; * {@link java.util.concurrent.CountDownLatch CountDownLatch} * but supporting more flexible usage. * - *

Registration. Unlike the case for other barriers, the + *

Registration. Unlike the case for other barriers, the * number of parties registered to synchronize on a phaser * may vary over time. Tasks may be registered at any time (using * methods {@link #register}, {@link #bulkRegister}, or forms of @@ -59,7 +59,7 @@ import java.util.concurrent.locks.LockSupport; * (However, you can introduce such bookkeeping by subclassing this * class.) * - *

Synchronization. Like a {@code CyclicBarrier}, a {@code + *

Synchronization. Like a {@code CyclicBarrier}, a {@code * Phaser} may be repeatedly awaited. Method {@link * #arriveAndAwaitAdvance} has effect analogous to {@link * java.util.concurrent.CyclicBarrier#await CyclicBarrier.await}. Each @@ -103,7 +103,7 @@ import java.util.concurrent.locks.LockSupport; * * * - *

Termination. A phaser may enter a termination + *

Termination. A phaser may enter a termination * state, that may be checked using method {@link #isTerminated}. Upon * termination, all synchronization methods immediately return without * waiting for advance, as indicated by a negative return value. @@ -118,7 +118,7 @@ import java.util.concurrent.locks.LockSupport; * also available to abruptly release waiting threads and allow them * to terminate. * - *

Tiering. Phasers may be tiered (i.e., + *

Tiering. Phasers may be tiered (i.e., * constructed in tree structures) to reduce contention. Phasers with * large numbers of parties that would otherwise experience heavy * synchronization contention costs may instead be set up so that @@ -300,18 +300,20 @@ public class Phaser { private static final int PHASE_SHIFT = 32; private static final int UNARRIVED_MASK = 0xffff; // to mask ints private static final long PARTIES_MASK = 0xffff0000L; // to mask longs + private static final long COUNTS_MASK = 0xffffffffL; private static final long TERMINATION_BIT = 1L << 63; // some special values private static final int ONE_ARRIVAL = 1; private static final int ONE_PARTY = 1 << PARTIES_SHIFT; + private static final int ONE_DEREGISTER = ONE_ARRIVAL|ONE_PARTY; private static final int EMPTY = 1; // The following unpacking methods are usually manually inlined private static int unarrivedOf(long s) { int counts = (int)s; - return (counts == EMPTY) ? 0 : counts & UNARRIVED_MASK; + return (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK); } private static int partiesOf(long s) { @@ -372,37 +374,44 @@ public class Phaser { * Manually tuned to speed up and minimize race windows for the * common case of just decrementing unarrived field. * - * @param deregister false for arrive, true for arriveAndDeregister + * @param adjust value to subtract from state; + * ONE_ARRIVAL for arrive, + * ONE_DEREGISTER for arriveAndDeregister */ - private int doArrive(boolean deregister) { - int adj = deregister ? ONE_ARRIVAL|ONE_PARTY : ONE_ARRIVAL; + private int doArrive(int adjust) { final Phaser root = this.root; for (;;) { long s = (root == this) ? state : reconcileState(); int phase = (int)(s >>> PHASE_SHIFT); - int counts = (int)s; - int unarrived = (counts & UNARRIVED_MASK) - 1; if (phase < 0) return phase; - else if (counts == EMPTY || unarrived < 0) { - if (root == this || reconcileState() == s) - throw new IllegalStateException(badArrive(s)); - } - else if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s-=adj)) { - if (unarrived == 0) { + int counts = (int)s; + int unarrived = (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK); + if (unarrived <= 0) + throw new IllegalStateException(badArrive(s)); + if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s-=adjust)) { + if (unarrived == 1) { long n = s & PARTIES_MASK; // base of next state int nextUnarrived = (int)n >>> PARTIES_SHIFT; - if (root != this) - return parent.doArrive(nextUnarrived == 0); - if (onAdvance(phase, nextUnarrived)) - n |= TERMINATION_BIT; - else if (nextUnarrived == 0) - n |= EMPTY; + if (root == this) { + if (onAdvance(phase, nextUnarrived)) + n |= TERMINATION_BIT; + else if (nextUnarrived == 0) + n |= EMPTY; + else + n |= nextUnarrived; + int nextPhase = (phase + 1) & MAX_PHASE; + n |= (long)nextPhase << PHASE_SHIFT; + UNSAFE.compareAndSwapLong(this, stateOffset, s, n); + releaseWaiters(phase); + } + else if (nextUnarrived == 0) { // propagate deregistration + phase = parent.doArrive(ONE_DEREGISTER); + UNSAFE.compareAndSwapLong(this, stateOffset, + s, s | EMPTY); + } else - n |= nextUnarrived; - n |= (long)((phase + 1) & MAX_PHASE) << PHASE_SHIFT; - UNSAFE.compareAndSwapLong(this, stateOffset, s, n); - releaseWaiters(phase); + phase = parent.doArrive(ONE_ARRIVAL); } return phase; } @@ -417,42 +426,49 @@ public class Phaser { */ private int doRegister(int registrations) { // adjustment to state - long adj = ((long)registrations << PARTIES_SHIFT) | registrations; + long adjust = ((long)registrations << PARTIES_SHIFT) | registrations; final Phaser parent = this.parent; int phase; for (;;) { - long s = state; + long s = (parent == null) ? state : reconcileState(); int counts = (int)s; int parties = counts >>> PARTIES_SHIFT; int unarrived = counts & UNARRIVED_MASK; if (registrations > MAX_PARTIES - parties) throw new IllegalStateException(badRegister(s)); - else if ((phase = (int)(s >>> PHASE_SHIFT)) < 0) + phase = (int)(s >>> PHASE_SHIFT); + if (phase < 0) break; - else if (counts != EMPTY) { // not 1st registration + if (counts != EMPTY) { // not 1st registration if (parent == null || reconcileState() == s) { if (unarrived == 0) // wait out advance root.internalAwaitAdvance(phase, null); else if (UNSAFE.compareAndSwapLong(this, stateOffset, - s, s + adj)) + s, s + adjust)) break; } } else if (parent == null) { // 1st root registration - long next = ((long)phase << PHASE_SHIFT) | adj; + long next = ((long)phase << PHASE_SHIFT) | adjust; if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next)) break; } else { synchronized (this) { // 1st sub registration if (state == s) { // recheck under lock - parent.doRegister(1); - do { // force current phase + phase = parent.doRegister(1); + if (phase < 0) + break; + // finish registration whenever parent registration + // succeeded, even when racing with termination, + // since these are part of the same "transaction". + while (!UNSAFE.compareAndSwapLong + (this, stateOffset, s, + ((long)phase << PHASE_SHIFT) | adjust)) { + s = state; phase = (int)(root.state >>> PHASE_SHIFT); - // assert phase < 0 || (int)state == EMPTY; - } while (!UNSAFE.compareAndSwapLong - (this, stateOffset, state, - ((long)phase << PHASE_SHIFT) | adj)); + // assert (int)s == EMPTY; + } break; } } @@ -467,10 +483,6 @@ public class Phaser { * subphasers have not yet done so, in which case they must finish * their own advance by setting unarrived to parties (or if * parties is zero, resetting to unregistered EMPTY state). - * However, this method may also be called when "floating" - * subphasers with possibly some unarrived parties are merely - * catching up to current phase, in which case counts are - * unaffected. * * @return reconciled state */ @@ -478,16 +490,16 @@ public class Phaser { final Phaser root = this.root; long s = state; if (root != this) { - int phase, u, p; - // CAS root phase with current parties; possibly trip unarrived + int phase, p; + // CAS to root phase with current parties, tripping unarrived while ((phase = (int)(root.state >>> PHASE_SHIFT)) != (int)(s >>> PHASE_SHIFT) && !UNSAFE.compareAndSwapLong (this, stateOffset, s, s = (((long)phase << PHASE_SHIFT) | - (s & PARTIES_MASK) | - ((p = (int)s >>> PARTIES_SHIFT) == 0 ? EMPTY : - (u = (int)s & UNARRIVED_MASK) == 0 ? p : u)))) + ((phase < 0) ? (s & COUNTS_MASK) : + (((p = (int)s >>> PARTIES_SHIFT) == 0) ? EMPTY : + ((s & PARTIES_MASK) | p)))))) s = state; } return s; @@ -619,7 +631,7 @@ public class Phaser { * of unarrived parties would become negative */ public int arrive() { - return doArrive(false); + return doArrive(ONE_ARRIVAL); } /** @@ -639,7 +651,7 @@ public class Phaser { * of registered or unarrived parties would become negative */ public int arriveAndDeregister() { - return doArrive(true); + return doArrive(ONE_DEREGISTER); } /** @@ -666,17 +678,15 @@ public class Phaser { for (;;) { long s = (root == this) ? state : reconcileState(); int phase = (int)(s >>> PHASE_SHIFT); - int counts = (int)s; - int unarrived = (counts & UNARRIVED_MASK) - 1; if (phase < 0) return phase; - else if (counts == EMPTY || unarrived < 0) { - if (reconcileState() == s) - throw new IllegalStateException(badArrive(s)); - } - else if (UNSAFE.compareAndSwapLong(this, stateOffset, s, - s -= ONE_ARRIVAL)) { - if (unarrived != 0) + int counts = (int)s; + int unarrived = (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK); + if (unarrived <= 0) + throw new IllegalStateException(badArrive(s)); + if (UNSAFE.compareAndSwapLong(this, stateOffset, s, + s -= ONE_ARRIVAL)) { + if (unarrived > 1) return root.internalAwaitAdvance(phase, null); if (root != this) return parent.arriveAndAwaitAdvance(); @@ -809,8 +819,8 @@ public class Phaser { if (UNSAFE.compareAndSwapLong(root, stateOffset, s, s | TERMINATION_BIT)) { // signal all threads - releaseWaiters(0); - releaseWaiters(1); + releaseWaiters(0); // Waiters on evenQ + releaseWaiters(1); // Waiters on oddQ return; } } @@ -1016,7 +1026,7 @@ public class Phaser { /** * Possibly blocks and waits for phase to advance unless aborted. - * Call only from root node. + * Call only on root phaser. * * @param phase current phase * @param node if non-null, the wait node to track interrupt and timeout; @@ -1024,6 +1034,7 @@ public class Phaser { * @return current phase */ private int internalAwaitAdvance(int phase, QNode node) { + // assert root == this; releaseWaiters(phase-1); // ensure old queue clean boolean queued = false; // true when node is enqueued int lastUnarrived = 0; // to increase spins upon change @@ -1082,7 +1093,7 @@ public class Phaser { final boolean timed; boolean wasInterrupted; long nanos; - long lastTime; + final long deadline; volatile Thread thread; // nulled to cancel wait QNode next; @@ -1093,7 +1104,7 @@ public class Phaser { this.interruptible = interruptible; this.nanos = nanos; this.timed = timed; - this.lastTime = timed ? System.nanoTime() : 0L; + this.deadline = timed ? System.nanoTime() + nanos : 0L; thread = Thread.currentThread(); } @@ -1112,9 +1123,7 @@ public class Phaser { } if (timed) { if (nanos > 0L) { - long now = System.nanoTime(); - nanos -= now - lastTime; - lastTime = now; + nanos = deadline - System.nanoTime(); } if (nanos <= 0L) { thread = null; @@ -1129,7 +1138,7 @@ public class Phaser { return true; else if (!timed) LockSupport.park(this); - else if (nanos > 0) + else if (nanos > 0L) LockSupport.parkNanos(this, nanos); return isReleasable(); } diff --git a/jdk/src/share/classes/java/util/concurrent/TimeUnit.java b/jdk/src/share/classes/java/util/concurrent/TimeUnit.java index ab3aa854f35..bd56b4835a7 100644 --- a/jdk/src/share/classes/java/util/concurrent/TimeUnit.java +++ b/jdk/src/share/classes/java/util/concurrent/TimeUnit.java @@ -36,10 +36,10 @@ package java.util.concurrent; /** - * A TimeUnit represents time durations at a given unit of + * A {@code TimeUnit} represents time durations at a given unit of * granularity and provides utility methods to convert across units, * and to perform timing and delay operations in these units. A - * TimeUnit does not maintain time information, but only + * {@code TimeUnit} does not maintain time information, but only * helps organize and use time representations that may be maintained * separately across various contexts. A nanosecond is defined as one * thousandth of a microsecond, a microsecond as one thousandth of a @@ -47,7 +47,7 @@ package java.util.concurrent; * as sixty seconds, an hour as sixty minutes, and a day as twenty four * hours. * - *

A TimeUnit is mainly used to inform time-based methods + *

A {@code TimeUnit} is mainly used to inform time-based methods * how a given timing parameter should be interpreted. For example, * the following code will timeout in 50 milliseconds if the {@link * java.util.concurrent.locks.Lock lock} is not available: @@ -63,7 +63,7 @@ package java.util.concurrent; * * Note however, that there is no guarantee that a particular timeout * implementation will be able to notice the passage of time at the - * same granularity as the given TimeUnit. + * same granularity as the given {@code TimeUnit}. * * @since 1.5 * @author Doug Lea @@ -174,83 +174,82 @@ public enum TimeUnit { // etc. are not declared abstract but otherwise act as abstract methods. /** - * Convert the given time duration in the given unit to this - * unit. Conversions from finer to coarser granularities - * truncate, so lose precision. For example converting - * 999 milliseconds to seconds results in - * 0. Conversions from coarser to finer granularities - * with arguments that would numerically overflow saturate to - * Long.MIN_VALUE if negative or Long.MAX_VALUE - * if positive. + * Converts the given time duration in the given unit to this unit. + * Conversions from finer to coarser granularities truncate, so + * lose precision. For example, converting {@code 999} milliseconds + * to seconds results in {@code 0}. Conversions from coarser to + * finer granularities with arguments that would numerically + * overflow saturate to {@code Long.MIN_VALUE} if negative or + * {@code Long.MAX_VALUE} if positive. * *

For example, to convert 10 minutes to milliseconds, use: - * TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES) + * {@code TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES)} * - * @param sourceDuration the time duration in the given sourceUnit - * @param sourceUnit the unit of the sourceDuration argument + * @param sourceDuration the time duration in the given {@code sourceUnit} + * @param sourceUnit the unit of the {@code sourceDuration} argument * @return the converted duration in this unit, - * or Long.MIN_VALUE if conversion would negatively - * overflow, or Long.MAX_VALUE if it would positively overflow. + * or {@code Long.MIN_VALUE} if conversion would negatively + * overflow, or {@code Long.MAX_VALUE} if it would positively overflow. */ public long convert(long sourceDuration, TimeUnit sourceUnit) { throw new AbstractMethodError(); } /** - * Equivalent to NANOSECONDS.convert(duration, this). + * Equivalent to + * {@link #convert(long, TimeUnit) NANOSECONDS.convert(duration, this)}. * @param duration the duration * @return the converted duration, - * or Long.MIN_VALUE if conversion would negatively - * overflow, or Long.MAX_VALUE if it would positively overflow. - * @see #convert + * or {@code Long.MIN_VALUE} if conversion would negatively + * overflow, or {@code Long.MAX_VALUE} if it would positively overflow. */ public long toNanos(long duration) { throw new AbstractMethodError(); } /** - * Equivalent to MICROSECONDS.convert(duration, this). + * Equivalent to + * {@link #convert(long, TimeUnit) MICROSECONDS.convert(duration, this)}. * @param duration the duration * @return the converted duration, - * or Long.MIN_VALUE if conversion would negatively - * overflow, or Long.MAX_VALUE if it would positively overflow. - * @see #convert + * or {@code Long.MIN_VALUE} if conversion would negatively + * overflow, or {@code Long.MAX_VALUE} if it would positively overflow. */ public long toMicros(long duration) { throw new AbstractMethodError(); } /** - * Equivalent to MILLISECONDS.convert(duration, this). + * Equivalent to + * {@link #convert(long, TimeUnit) MILLISECONDS.convert(duration, this)}. * @param duration the duration * @return the converted duration, - * or Long.MIN_VALUE if conversion would negatively - * overflow, or Long.MAX_VALUE if it would positively overflow. - * @see #convert + * or {@code Long.MIN_VALUE} if conversion would negatively + * overflow, or {@code Long.MAX_VALUE} if it would positively overflow. */ public long toMillis(long duration) { throw new AbstractMethodError(); } /** - * Equivalent to SECONDS.convert(duration, this). + * Equivalent to + * {@link #convert(long, TimeUnit) SECONDS.convert(duration, this)}. * @param duration the duration * @return the converted duration, - * or Long.MIN_VALUE if conversion would negatively - * overflow, or Long.MAX_VALUE if it would positively overflow. - * @see #convert + * or {@code Long.MIN_VALUE} if conversion would negatively + * overflow, or {@code Long.MAX_VALUE} if it would positively overflow. */ public long toSeconds(long duration) { throw new AbstractMethodError(); } /** - * Equivalent to MINUTES.convert(duration, this). + * Equivalent to + * {@link #convert(long, TimeUnit) MINUTES.convert(duration, this)}. * @param duration the duration * @return the converted duration, - * or Long.MIN_VALUE if conversion would negatively - * overflow, or Long.MAX_VALUE if it would positively overflow. - * @see #convert + * or {@code Long.MIN_VALUE} if conversion would negatively + * overflow, or {@code Long.MAX_VALUE} if it would positively overflow. * @since 1.6 */ public long toMinutes(long duration) { @@ -258,12 +257,12 @@ public enum TimeUnit { } /** - * Equivalent to HOURS.convert(duration, this). + * Equivalent to + * {@link #convert(long, TimeUnit) HOURS.convert(duration, this)}. * @param duration the duration * @return the converted duration, - * or Long.MIN_VALUE if conversion would negatively - * overflow, or Long.MAX_VALUE if it would positively overflow. - * @see #convert + * or {@code Long.MIN_VALUE} if conversion would negatively + * overflow, or {@code Long.MAX_VALUE} if it would positively overflow. * @since 1.6 */ public long toHours(long duration) { @@ -271,10 +270,10 @@ public enum TimeUnit { } /** - * Equivalent to DAYS.convert(duration, this). + * Equivalent to + * {@link #convert(long, TimeUnit) DAYS.convert(duration, this)}. * @param duration the duration * @return the converted duration - * @see #convert * @since 1.6 */ public long toDays(long duration) { @@ -294,9 +293,9 @@ public enum TimeUnit { * Performs a timed {@link Object#wait(long, int) Object.wait} * using this time unit. * This is a convenience method that converts timeout arguments - * into the form required by the Object.wait method. + * into the form required by the {@code Object.wait} method. * - *

For example, you could implement a blocking poll + *

For example, you could implement a blocking {@code poll} * method (see {@link BlockingQueue#poll BlockingQueue.poll}) * using: * @@ -327,7 +326,7 @@ public enum TimeUnit { * Performs a timed {@link Thread#join(long, int) Thread.join} * using this time unit. * This is a convenience method that converts time arguments into the - * form required by the Thread.join method. + * form required by the {@code Thread.join} method. * * @param thread the thread to wait for * @param timeout the maximum time to wait. If less than @@ -347,7 +346,7 @@ public enum TimeUnit { * Performs a {@link Thread#sleep(long, int) Thread.sleep} using * this time unit. * This is a convenience method that converts time arguments into the - * form required by the Thread.sleep method. + * form required by the {@code Thread.sleep} method. * * @param timeout the minimum time to sleep. If less than * or equal to zero, do not sleep at all. diff --git a/jdk/src/share/classes/java/util/concurrent/TimeoutException.java b/jdk/src/share/classes/java/util/concurrent/TimeoutException.java index ed08990c7d6..b54c52b21f4 100644 --- a/jdk/src/share/classes/java/util/concurrent/TimeoutException.java +++ b/jdk/src/share/classes/java/util/concurrent/TimeoutException.java @@ -40,7 +40,7 @@ package java.util.concurrent; * operations for which a timeout is specified need a means to * indicate that the timeout has occurred. For many such operations it * is possible to return a value that indicates timeout; when that is - * not possible or desirable then TimeoutException should be + * not possible or desirable then {@code TimeoutException} should be * declared and thrown. * * @since 1.5 @@ -50,13 +50,13 @@ public class TimeoutException extends Exception { private static final long serialVersionUID = 1900926677490660714L; /** - * Constructs a TimeoutException with no specified detail + * Constructs a {@code TimeoutException} with no specified detail * message. */ public TimeoutException() {} /** - * Constructs a TimeoutException with the specified detail + * Constructs a {@code TimeoutException} with the specified detail * message. * * @param message the detail message diff --git a/jdk/src/share/classes/java/util/concurrent/package-info.java b/jdk/src/share/classes/java/util/concurrent/package-info.java index 4c56e0390df..b236c290b10 100644 --- a/jdk/src/share/classes/java/util/concurrent/package-info.java +++ b/jdk/src/share/classes/java/util/concurrent/package-info.java @@ -48,7 +48,7 @@ * * {@link java.util.concurrent.Executor} is a simple standardized * interface for defining custom thread-like subsystems, including - * thread pools, asynchronous IO, and lightweight task frameworks. + * thread pools, asynchronous I/O, and lightweight task frameworks. * Depending on which concrete Executor class is being used, tasks may * execute in a newly created thread, an existing task-execution thread, * or the thread calling {@link java.util.concurrent.Executor#execute @@ -102,8 +102,10 @@ *

Queues

* * The {@link java.util.concurrent.ConcurrentLinkedQueue} class - * supplies an efficient scalable thread-safe non-blocking FIFO - * queue. + * supplies an efficient scalable thread-safe non-blocking FIFO queue. + * The {@link java.util.concurrent.ConcurrentLinkedDeque} class is + * similar, but additionally supports the {@link java.util.Deque} + * interface. * *

Five implementations in {@code java.util.concurrent} support * the extended {@link java.util.concurrent.BlockingQueue} @@ -117,7 +119,7 @@ * for producer-consumer, messaging, parallel tasking, and * related concurrent designs. * - *

Extended interface {@link java.util.concurrent.TransferQueue}, + *

Extended interface {@link java.util.concurrent.TransferQueue}, * and implementation {@link java.util.concurrent.LinkedTransferQueue} * introduce a synchronous {@code transfer} method (along with related * features) in which a producer may optionally block awaiting its @@ -216,9 +218,9 @@ * it may (or may not) reflect any updates since the iterator was * created. * - *

Memory Consistency Properties

+ *

Memory Consistency Properties

* - * + * * Chapter 17 of the Java Language Specification defines the * happens-before relation on memory operations such as reads and * writes of shared variables. The results of a write by one thread are From 92bcfea39aeb7cf2b8f010a99c4d20f1eeef846a Mon Sep 17 00:00:00 2001 From: Attila Szegedi Date: Wed, 3 Jul 2013 12:39:28 +0200 Subject: [PATCH 009/123] 8010946: AccessControl.doPrivileged is broken when called from js script Reviewed-by: jlaskey, sundar --- nashorn/make/build.xml | 55 ++-- .../dynalink/beans/AbstractJavaLinker.java | 232 +++++++++++----- .../beans/ApplicableOverloadedMethods.java | 27 +- .../beans/CallerSensitiveDetector.java | 148 ++++++++++ .../beans/CallerSensitiveDynamicMethod.java | 158 +++++++++++ .../internal/dynalink/beans/ClassString.java | 4 +- .../dynalink/beans/DynamicMethod.java | 38 +-- .../dynalink/beans/DynamicMethodLinker.java | 13 +- .../dynalink/beans/FacetIntrospector.java | 4 - .../dynalink/beans/MaximallySpecific.java | 68 ++++- .../beans/OverloadedDynamicMethod.java | 92 +++---- .../dynalink/beans/OverloadedMethod.java | 4 +- .../dynalink/beans/SimpleDynamicMethod.java | 144 ++-------- .../dynalink/beans/SingleDynamicMethod.java | 255 ++++++++++++++++++ .../beans/StaticClassIntrospector.java | 10 +- .../dynalink/beans/StaticClassLinker.java | 24 +- .../support/AbstractCallSiteDescriptor.java | 3 +- .../jdk/internal/dynalink/support/Lookup.java | 25 +- .../internal/runtime/linker/Bootstrap.java | 16 +- .../runtime/linker/JavaAdapterFactory.java | 11 +- .../runtime/linker/LinkerCallSite.java | 7 +- .../linker/NashornCallSiteDescriptor.java | 54 ++-- nashorn/test/script/basic/JDK-8010946-2.js | 38 +++ .../script/basic/JDK-8010946-2.js.EXPECTED | 3 + .../script/basic/JDK-8010946-privileged.js | 47 ++++ nashorn/test/script/basic/JDK-8010946.js | 51 ++++ .../test/script/basic/JDK-8010946.js.EXPECTED | 5 + 27 files changed, 1133 insertions(+), 403 deletions(-) create mode 100644 nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDetector.java create mode 100644 nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDynamicMethod.java create mode 100644 nashorn/src/jdk/internal/dynalink/beans/SingleDynamicMethod.java create mode 100644 nashorn/test/script/basic/JDK-8010946-2.js create mode 100644 nashorn/test/script/basic/JDK-8010946-2.js.EXPECTED create mode 100644 nashorn/test/script/basic/JDK-8010946-privileged.js create mode 100644 nashorn/test/script/basic/JDK-8010946.js create mode 100644 nashorn/test/script/basic/JDK-8010946.js.EXPECTED diff --git a/nashorn/make/build.xml b/nashorn/make/build.xml index 7e2d999d328..58a1d116be1 100644 --- a/nashorn/make/build.xml +++ b/nashorn/make/build.xml @@ -235,44 +235,31 @@ - + - - - - - - - +grant codeBase "file:/${basedir}/${nashorn.internal.tests.jar}" { + permission java.security.AllPermission; +}; - - - - - - - +grant codeBase "file:/${basedir}/${file.reference.testng.jar}" { + permission java.security.AllPermission; +}; - - - - - - - +grant codeBase "file:/${basedir}/test/script/trusted/*" { + permission java.security.AllPermission; +}; - - - - - - - - - - - - +grant codeBase "file:/${basedir}/test/script/basic/*" { + permission java.io.FilePermission "${basedir}/test/script/-", "read"; + permission java.io.FilePermission "$${user.dir}", "read"; + permission java.util.PropertyPermission "user.dir", "read"; + permission java.util.PropertyPermission "nashorn.test.*", "read"; +}; + +grant codeBase "file:/${basedir}/test/script/basic/JDK-8010946-privileged.js" { + permission java.util.PropertyPermission "java.security.policy", "read"; +}; + \/ /// diff --git a/nashorn/src/jdk/internal/dynalink/beans/AbstractJavaLinker.java b/nashorn/src/jdk/internal/dynalink/beans/AbstractJavaLinker.java index 702c1509fd4..f541fa65d2a 100644 --- a/nashorn/src/jdk/internal/dynalink/beans/AbstractJavaLinker.java +++ b/nashorn/src/jdk/internal/dynalink/beans/AbstractJavaLinker.java @@ -86,7 +86,10 @@ package jdk.internal.dynalink.beans; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Constructor; import java.lang.reflect.Field; +import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; @@ -109,10 +112,11 @@ import jdk.internal.dynalink.support.Lookup; * @author Attila Szegedi */ abstract class AbstractJavaLinker implements GuardingDynamicLinker { + final Class clazz; private final MethodHandle classGuard; private final MethodHandle assignableGuard; - private final Map propertyGetters = new HashMap<>(); + private final Map propertyGetters = new HashMap<>(); private final Map propertySetters = new HashMap<>(); private final Map methods = new HashMap<>(); @@ -129,22 +133,19 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker { // Add methods and properties for(Method method: introspector.getMethods()) { final String name = method.getName(); - final MethodHandle methodHandle = introspector.unreflect(method); // Add method - addMember(name, methodHandle, methods); + addMember(name, method, methods); // Add the method as a property getter and/or setter if(name.startsWith("get") && name.length() > 3 && method.getParameterTypes().length == 0) { // Property getter - setPropertyGetter(decapitalize(name.substring(3)), introspector.unreflect( - getMostGenericGetter(method)), ValidationType.INSTANCE_OF); + setPropertyGetter(method, 3); } else if(name.startsWith("is") && name.length() > 2 && method.getParameterTypes().length == 0 && method.getReturnType() == boolean.class) { // Boolean property getter - setPropertyGetter(decapitalize(name.substring(2)), introspector.unreflect( - getMostGenericGetter(method)), ValidationType.INSTANCE_OF); + setPropertyGetter(method, 2); } else if(name.startsWith("set") && name.length() > 3 && method.getParameterTypes().length == 1) { // Property setter - addMember(decapitalize(name.substring(3)), methodHandle, propertySetters); + addMember(decapitalize(name.substring(3)), method, propertySetters); } } @@ -156,7 +157,8 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker { setPropertyGetter(name, introspector.unreflectGetter(field), ValidationType.EXACT_CLASS); } if(!(Modifier.isFinal(field.getModifiers()) || propertySetters.containsKey(name))) { - addMember(name, introspector.unreflectSetter(field), propertySetters); + addMember(name, new SimpleDynamicMethod(introspector.unreflectSetter(field), clazz, name), + propertySetters); } } @@ -192,38 +194,119 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker { abstract FacetIntrospector createFacetIntrospector(); - void setPropertyGetter(String name, MethodHandle handle, ValidationType validationType) { - propertyGetters.put(name, new AnnotatedMethodHandle(handle, validationType)); + /** + * Sets the specified dynamic method to be the property getter for the specified property. Note that you can only + * use this when you're certain that the method handle does not belong to a caller-sensitive method. For properties + * that are caller-sensitive, you must use {@link #setPropertyGetter(String, SingleDynamicMethod, ValidationType)} + * instead. + * @param name name of the property + * @param handle the method handle that implements the property getter + * @param validationType the validation type for the property + */ + private void setPropertyGetter(String name, SingleDynamicMethod handle, ValidationType validationType) { + propertyGetters.put(name, new AnnotatedDynamicMethod(handle, validationType)); } - private void addMember(String name, MethodHandle mh, Map methodMap) { + /** + * Sets the specified reflective method to be the property getter for the specified property. + * @param getter the getter method + * @param prefixLen the getter prefix in the method name; should be 3 for getter names starting with "get" and 2 for + * names starting with "is". + */ + private void setPropertyGetter(Method getter, int prefixLen) { + setPropertyGetter(decapitalize(getter.getName().substring(prefixLen)), createDynamicMethod( + getMostGenericGetter(getter)), ValidationType.INSTANCE_OF); + } + + /** + * Sets the specified method handle to be the property getter for the specified property. Note that you can only + * use this when you're certain that the method handle does not belong to a caller-sensitive method. For properties + * that are caller-sensitive, you must use {@link #setPropertyGetter(String, SingleDynamicMethod, ValidationType)} + * instead. + * @param name name of the property + * @param handle the method handle that implements the property getter + * @param validationType the validation type for the property + */ + void setPropertyGetter(String name, MethodHandle handle, ValidationType validationType) { + setPropertyGetter(name, new SimpleDynamicMethod(handle, clazz, name), validationType); + } + + private void addMember(String name, AccessibleObject ao, Map methodMap) { + addMember(name, createDynamicMethod(ao), methodMap); + } + + private void addMember(String name, SingleDynamicMethod method, Map methodMap) { final DynamicMethod existingMethod = methodMap.get(name); - final DynamicMethod newMethod = addMember(mh, existingMethod, clazz, name); + final DynamicMethod newMethod = mergeMethods(method, existingMethod, clazz, name); if(newMethod != existingMethod) { methodMap.put(name, newMethod); } } - static DynamicMethod createDynamicMethod(Iterable methodHandles, Class clazz, String name) { + /** + * Given one or more reflective methods or constructors, creates a dynamic method that represents them all. The + * methods should represent all overloads of the same name (or all constructors of the class). + * @param members the reflective members + * @param clazz the class declaring the reflective members + * @param name the common name of the reflective members. + * @return a dynamic method representing all the specified reflective members. + */ + static DynamicMethod createDynamicMethod(Iterable members, Class clazz, String name) { DynamicMethod dynMethod = null; - for(MethodHandle methodHandle: methodHandles) { - dynMethod = addMember(methodHandle, dynMethod, clazz, name); + for(AccessibleObject method: members) { + dynMethod = mergeMethods(createDynamicMethod(method), dynMethod, clazz, name); } return dynMethod; } - private static DynamicMethod addMember(MethodHandle mh, DynamicMethod existing, Class clazz, String name) { + /** + * Given a reflective method or a constructor, creates a dynamic method that represents it. This method will + * distinguish between caller sensitive and ordinary methods/constructors, and create appropriate caller sensitive + * dynamic method when needed. + * @param m the reflective member + * @return the single dynamic method representing the reflective member + */ + private static SingleDynamicMethod createDynamicMethod(AccessibleObject m) { + if(CallerSensitiveDetector.isCallerSensitive(m)) { + return new CallerSensitiveDynamicMethod(m); + } + final Member member = (Member)m; + return new SimpleDynamicMethod(unreflectSafely(m), member.getDeclaringClass(), member.getName()); + } + + /** + * Unreflects a method handle from a Method or a Constructor using safe (zero-privilege) unreflection. Should be + * only used for methods and constructors that are not caller sensitive. If a caller sensitive method were + * unreflected through this mechanism, it would not be a security issue, but would be bound to the zero-privilege + * unreflector as its caller, and thus completely useless. + * @param m the method or constructor + * @return the method handle + */ + private static MethodHandle unreflectSafely(AccessibleObject m) { + if(m instanceof Method) { + final Method reflMethod = (Method)m; + final MethodHandle handle = SafeUnreflector.unreflect(reflMethod); + if(Modifier.isStatic(reflMethod.getModifiers())) { + return StaticClassIntrospector.editStaticMethodHandle(handle); + } + return handle; + } + return StaticClassIntrospector.editConstructorMethodHandle(SafeUnreflector.unreflectConstructor( + (Constructor)m)); + } + + private static DynamicMethod mergeMethods(SingleDynamicMethod method, DynamicMethod existing, Class clazz, String name) { if(existing == null) { - return new SimpleDynamicMethod(mh, clazz, name); - } else if(existing.contains(mh)) { + return method; + } else if(existing.contains(method)) { return existing; - } else if(existing instanceof SimpleDynamicMethod) { + } else if(existing instanceof SingleDynamicMethod) { final OverloadedDynamicMethod odm = new OverloadedDynamicMethod(clazz, name); - odm.addMethod(((SimpleDynamicMethod)existing)); - odm.addMethod(mh); + odm.addMethod(((SingleDynamicMethod)existing)); + odm.addMethod(method); return odm; } else if(existing instanceof OverloadedDynamicMethod) { - ((OverloadedDynamicMethod)existing).addMethod(mh); + ((OverloadedDynamicMethod)existing).addMethod(method); return existing; } throw new AssertionError(); @@ -296,7 +379,7 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker { private GuardedInvocation getCallPropWithThis(CallSiteDescriptor callSiteDescriptor, LinkerServices linkerServices) { switch(callSiteDescriptor.getNameTokenCount()) { case 3: { - return createGuardedDynamicMethodInvocation(callSiteDescriptor.getMethodType(), linkerServices, + return createGuardedDynamicMethodInvocation(callSiteDescriptor, linkerServices, callSiteDescriptor.getNameToken(CallSiteDescriptor.NAME_OPERAND), methods); } default: { @@ -305,16 +388,16 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker { } } - private GuardedInvocation createGuardedDynamicMethodInvocation(MethodType callSiteType, + private GuardedInvocation createGuardedDynamicMethodInvocation(CallSiteDescriptor callSiteDescriptor, LinkerServices linkerServices, String methodName, Map methodMap){ - final MethodHandle inv = getDynamicMethodInvocation(callSiteType, linkerServices, methodName, methodMap); - return inv == null ? null : new GuardedInvocation(inv, getClassGuard(callSiteType)); + final MethodHandle inv = getDynamicMethodInvocation(callSiteDescriptor, linkerServices, methodName, methodMap); + return inv == null ? null : new GuardedInvocation(inv, getClassGuard(callSiteDescriptor.getMethodType())); } - private static MethodHandle getDynamicMethodInvocation(MethodType callSiteType, LinkerServices linkerServices, - String methodName, Map methodMap) { + private static MethodHandle getDynamicMethodInvocation(CallSiteDescriptor callSiteDescriptor, + LinkerServices linkerServices, String methodName, Map methodMap) { final DynamicMethod dynaMethod = getDynamicMethod(methodName, methodMap); - return dynaMethod != null ? dynaMethod.getInvocation(callSiteType, linkerServices) : null; + return dynaMethod != null ? dynaMethod.getInvocation(callSiteDescriptor, linkerServices) : null; } private static DynamicMethod getDynamicMethod(String methodName, Map methodMap) { @@ -322,13 +405,13 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker { return dynaMethod != null ? dynaMethod : getExplicitSignatureDynamicMethod(methodName, methodMap); } - private static SimpleDynamicMethod getExplicitSignatureDynamicMethod(String methodName, + private static SingleDynamicMethod getExplicitSignatureDynamicMethod(String methodName, Map methodsMap) { // What's below is meant to support the "name(type, type, ...)" syntax that programmers can use in a method name // to manually pin down an exact overloaded variant. This is not usually required, as the overloaded method // resolution works correctly in almost every situation. However, in presence of many language-specific // conversions with a radically dynamic language, most overloaded methods will end up being constantly selected - // at invocation time, so a programmer knowledgable of the situation might choose to pin down an exact overload + // at invocation time, so a programmer knowledgeable of the situation might choose to pin down an exact overload // for performance reasons. // Is the method name lexically of the form "name(types)"? @@ -377,8 +460,8 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker { final MethodType setterType = type.dropParameterTypes(1, 2); // Bind property setter handle to the expected setter type and linker services. Type is // MethodHandle(Object, String, Object) - final MethodHandle boundGetter = MethodHandles.insertArguments(getPropertySetterHandle, 0, setterType, - linkerServices); + final MethodHandle boundGetter = MethodHandles.insertArguments(getPropertySetterHandle, 0, + CallSiteDescriptorFactory.dropParameterTypes(callSiteDescriptor, 1, 2), linkerServices); // Cast getter to MethodHandle(O, N, V) final MethodHandle typedGetter = linkerServices.asType(boundGetter, type.changeReturnType( @@ -415,9 +498,8 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker { case 3: { // Must have two arguments: target object and property value assertParameterCount(callSiteDescriptor, 2); - final GuardedInvocation gi = createGuardedDynamicMethodInvocation(callSiteDescriptor.getMethodType(), - linkerServices, callSiteDescriptor.getNameToken(CallSiteDescriptor.NAME_OPERAND), - propertySetters); + final GuardedInvocation gi = createGuardedDynamicMethodInvocation(callSiteDescriptor, linkerServices, + callSiteDescriptor.getNameToken(CallSiteDescriptor.NAME_OPERAND), propertySetters); // If we have a property setter with this name, this composite operation will always stop here if(gi != null) { return new GuardedInvocationComponent(gi, clazz, ValidationType.EXACT_CLASS); @@ -435,14 +517,13 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker { private static final Lookup privateLookup = new Lookup(MethodHandles.lookup()); - private static final MethodHandle IS_ANNOTATED_HANDLE_NOT_NULL = Guards.isNotNull().asType(MethodType.methodType( - boolean.class, AnnotatedMethodHandle.class)); - private static final MethodHandle CONSTANT_NULL_DROP_ANNOTATED_HANDLE = MethodHandles.dropArguments( - MethodHandles.constant(Object.class, null), 0, AnnotatedMethodHandle.class); - private static final MethodHandle GET_ANNOTATED_HANDLE = privateLookup.findGetter(AnnotatedMethodHandle.class, - "handle", MethodHandle.class); - private static final MethodHandle GENERIC_PROPERTY_GETTER_HANDLER_INVOKER = MethodHandles.filterArguments( - MethodHandles.invoker(MethodType.methodType(Object.class, Object.class)), 0, GET_ANNOTATED_HANDLE); + private static final MethodHandle IS_ANNOTATED_METHOD_NOT_NULL = Guards.isNotNull().asType(MethodType.methodType( + boolean.class, AnnotatedDynamicMethod.class)); + private static final MethodHandle CONSTANT_NULL_DROP_ANNOTATED_METHOD = MethodHandles.dropArguments( + MethodHandles.constant(Object.class, null), 0, AnnotatedDynamicMethod.class); + private static final MethodHandle GET_ANNOTATED_METHOD = privateLookup.findVirtual(AnnotatedDynamicMethod.class, + "getTarget", MethodType.methodType(MethodHandle.class, MethodHandles.Lookup.class)); + private static final MethodHandle GETTER_INVOKER = MethodHandles.invoker(MethodType.methodType(Object.class, Object.class)); private GuardedInvocationComponent getPropertyGetter(CallSiteDescriptor callSiteDescriptor, LinkerServices linkerServices, List ops) throws Exception { @@ -455,16 +536,20 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker { // What's below is basically: // foldArguments(guardWithTest(isNotNull, invoke(get_handle), null|nextComponent.invocation), get_getter_handle) // only with a bunch of method signature adjustments. Basically, retrieve method getter - // AnnotatedMethodHandle; if it is non-null, invoke its "handle" field, otherwise either return null, + // AnnotatedDynamicMethod; if it is non-null, invoke its "handle" field, otherwise either return null, // or delegate to next component's invocation. final MethodHandle typedGetter = linkerServices.asType(getPropertyGetterHandle, type.changeReturnType( - AnnotatedMethodHandle.class)); - // Object(AnnotatedMethodHandle, Object)->R(AnnotatedMethodHandle, T0) - final MethodHandle invokeHandleTyped = linkerServices.asType(GENERIC_PROPERTY_GETTER_HANDLER_INVOKER, - MethodType.methodType(type.returnType(), AnnotatedMethodHandle.class, type.parameterType(0))); + AnnotatedDynamicMethod.class)); + final MethodHandle callSiteBoundMethodGetter = MethodHandles.insertArguments( + GET_ANNOTATED_METHOD, 1, callSiteDescriptor.getLookup()); + final MethodHandle callSiteBoundInvoker = MethodHandles.filterArguments(GETTER_INVOKER, 0, + callSiteBoundMethodGetter); + // Object(AnnotatedDynamicMethod, Object)->R(AnnotatedDynamicMethod, T0) + final MethodHandle invokeHandleTyped = linkerServices.asType(callSiteBoundInvoker, + MethodType.methodType(type.returnType(), AnnotatedDynamicMethod.class, type.parameterType(0))); // Since it's in the target of a fold, drop the unnecessary second argument - // R(AnnotatedMethodHandle, T0)->R(AnnotatedMethodHandle, T0, T1) + // R(AnnotatedDynamicMethod, T0)->R(AnnotatedDynamicMethod, T0, T1) final MethodHandle invokeHandleFolded = MethodHandles.dropArguments(invokeHandleTyped, 2, type.parameterType(1)); final GuardedInvocationComponent nextComponent = getGuardedInvocationComponent(callSiteDescriptor, @@ -472,19 +557,19 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker { final MethodHandle fallbackFolded; if(nextComponent == null) { - // Object(AnnotatedMethodHandle)->R(AnnotatedMethodHandle, T0, T1); returns constant null - fallbackFolded = MethodHandles.dropArguments(CONSTANT_NULL_DROP_ANNOTATED_HANDLE, 1, - type.parameterList()).asType(type.insertParameterTypes(0, AnnotatedMethodHandle.class)); + // Object(AnnotatedDynamicMethod)->R(AnnotatedDynamicMethod, T0, T1); returns constant null + fallbackFolded = MethodHandles.dropArguments(CONSTANT_NULL_DROP_ANNOTATED_METHOD, 1, + type.parameterList()).asType(type.insertParameterTypes(0, AnnotatedDynamicMethod.class)); } else { - // R(T0, T1)->R(AnnotatedMethodHAndle, T0, T1); adapts the next component's invocation to drop the + // R(T0, T1)->R(AnnotatedDynamicMethod, T0, T1); adapts the next component's invocation to drop the // extra argument resulting from fold fallbackFolded = MethodHandles.dropArguments(nextComponent.getGuardedInvocation().getInvocation(), - 0, AnnotatedMethodHandle.class); + 0, AnnotatedDynamicMethod.class); } - // fold(R(AnnotatedMethodHandle, T0, T1), AnnotatedMethodHandle(T0, T1)) + // fold(R(AnnotatedDynamicMethod, T0, T1), AnnotatedDynamicMethod(T0, T1)) final MethodHandle compositeGetter = MethodHandles.foldArguments(MethodHandles.guardWithTest( - IS_ANNOTATED_HANDLE_NOT_NULL, invokeHandleFolded, fallbackFolded), typedGetter); + IS_ANNOTATED_METHOD_NOT_NULL, invokeHandleFolded, fallbackFolded), typedGetter); if(nextComponent == null) { return getClassGuardedInvocationComponent(compositeGetter, type); } @@ -494,13 +579,13 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker { // Must have exactly one argument: receiver assertParameterCount(callSiteDescriptor, 1); // Fixed name - final AnnotatedMethodHandle annGetter = propertyGetters.get(callSiteDescriptor.getNameToken( + final AnnotatedDynamicMethod annGetter = propertyGetters.get(callSiteDescriptor.getNameToken( CallSiteDescriptor.NAME_OPERAND)); if(annGetter == null) { // We have no such property, always delegate to the next component operation return getGuardedInvocationComponent(callSiteDescriptor, linkerServices, ops); } - final MethodHandle getter = annGetter.handle; + final MethodHandle getter = annGetter.getInvocation(callSiteDescriptor, linkerServices); // NOTE: since property getters (not field getters!) are no-arg, we don't have to worry about them being // overloaded in a subclass. Therefore, we can discover the most abstract superclass that has the // method, and use that as the guard with Guards.isInstance() for a more stably linked call site. If @@ -508,6 +593,7 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker { // NOTE: No delegation to the next component operation if we have a property with this name, even if its // value is null. final ValidationType validationType = annGetter.validationType; + // TODO: we aren't using the type that declares the most generic getter here! return new GuardedInvocationComponent(linkerServices.asType(getter, type), getGuard(validationType, type), clazz, validationType); } @@ -623,14 +709,15 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker { // args are dropped; this makes handles with first three args conform to "Object, String, Object" though, which is // a typical property setter with variable name signature (target, name, value). private static final MethodHandle GET_PROPERTY_SETTER_HANDLE = MethodHandles.dropArguments(MethodHandles.dropArguments( - privateLookup.findOwnSpecial("getPropertySetterHandle", MethodHandle.class, MethodType.class, + privateLookup.findOwnSpecial("getPropertySetterHandle", MethodHandle.class, CallSiteDescriptor.class, LinkerServices.class, Object.class), 3, Object.class), 5, Object.class); // Type is MethodHandle(MethodType, LinkerServices, Object, String, Object) private final MethodHandle getPropertySetterHandle = GET_PROPERTY_SETTER_HANDLE.bindTo(this); @SuppressWarnings("unused") - private MethodHandle getPropertySetterHandle(MethodType setterType, LinkerServices linkerServices, Object id) { - return getDynamicMethodInvocation(setterType, linkerServices, String.valueOf(id), propertySetters); + private MethodHandle getPropertySetterHandle(CallSiteDescriptor setterDescriptor, LinkerServices linkerServices, + Object id) { + return getDynamicMethodInvocation(setterDescriptor, linkerServices, String.valueOf(id), propertySetters); } private static MethodHandle GET_DYNAMIC_METHOD = MethodHandles.dropArguments(privateLookup.findOwnSpecial( @@ -689,13 +776,24 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker { return null; } - private static final class AnnotatedMethodHandle { - final MethodHandle handle; + private static final class AnnotatedDynamicMethod { + private final SingleDynamicMethod method; /*private*/ final ValidationType validationType; - AnnotatedMethodHandle(MethodHandle handle, ValidationType validationType) { - this.handle = handle; + AnnotatedDynamicMethod(SingleDynamicMethod method, ValidationType validationType) { + this.method = method; this.validationType = validationType; } + + MethodHandle getInvocation(CallSiteDescriptor callSiteDescriptor, LinkerServices linkerServices) { + return method.getInvocation(callSiteDescriptor, linkerServices); + } + + @SuppressWarnings("unused") + MethodHandle getTarget(MethodHandles.Lookup lookup) { + MethodHandle inv = method.getTarget(lookup); + assert inv != null; + return inv; + } } } diff --git a/nashorn/src/jdk/internal/dynalink/beans/ApplicableOverloadedMethods.java b/nashorn/src/jdk/internal/dynalink/beans/ApplicableOverloadedMethods.java index a232caf137a..39a03a8ef96 100644 --- a/nashorn/src/jdk/internal/dynalink/beans/ApplicableOverloadedMethods.java +++ b/nashorn/src/jdk/internal/dynalink/beans/ApplicableOverloadedMethods.java @@ -83,7 +83,6 @@ package jdk.internal.dynalink.beans; -import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodType; import java.util.LinkedList; import java.util.List; @@ -95,7 +94,7 @@ import jdk.internal.dynalink.support.TypeUtilities; * @author Attila Szegedi */ class ApplicableOverloadedMethods { - private final List methods; + private final List methods; private final boolean varArgs; /** @@ -106,10 +105,10 @@ class ApplicableOverloadedMethods { * @param test applicability test. One of {@link #APPLICABLE_BY_SUBTYPING}, * {@link #APPLICABLE_BY_METHOD_INVOCATION_CONVERSION}, or {@link #APPLICABLE_BY_VARIABLE_ARITY}. */ - ApplicableOverloadedMethods(final List methods, final MethodType callSiteType, + ApplicableOverloadedMethods(final List methods, final MethodType callSiteType, final ApplicabilityTest test) { this.methods = new LinkedList<>(); - for(MethodHandle m: methods) { + for(SingleDynamicMethod m: methods) { if(test.isApplicable(callSiteType, m)) { this.methods.add(m); } @@ -122,7 +121,7 @@ class ApplicableOverloadedMethods { * * @return list of all methods. */ - List getMethods() { + List getMethods() { return methods; } @@ -131,12 +130,12 @@ class ApplicableOverloadedMethods { * * @return a list of maximally specific methods. */ - List findMaximallySpecificMethods() { + List findMaximallySpecificMethods() { return MaximallySpecific.getMaximallySpecificMethods(methods, varArgs); } abstract static class ApplicabilityTest { - abstract boolean isApplicable(MethodType callSiteType, MethodHandle method); + abstract boolean isApplicable(MethodType callSiteType, SingleDynamicMethod method); } /** @@ -144,8 +143,8 @@ class ApplicableOverloadedMethods { */ static final ApplicabilityTest APPLICABLE_BY_SUBTYPING = new ApplicabilityTest() { @Override - boolean isApplicable(MethodType callSiteType, MethodHandle method) { - final MethodType methodType = method.type(); + boolean isApplicable(MethodType callSiteType, SingleDynamicMethod method) { + final MethodType methodType = method.getMethodType(); final int methodArity = methodType.parameterCount(); if(methodArity != callSiteType.parameterCount()) { return false; @@ -166,8 +165,8 @@ class ApplicableOverloadedMethods { */ static final ApplicabilityTest APPLICABLE_BY_METHOD_INVOCATION_CONVERSION = new ApplicabilityTest() { @Override - boolean isApplicable(MethodType callSiteType, MethodHandle method) { - final MethodType methodType = method.type(); + boolean isApplicable(MethodType callSiteType, SingleDynamicMethod method) { + final MethodType methodType = method.getMethodType(); final int methodArity = methodType.parameterCount(); if(methodArity != callSiteType.parameterCount()) { return false; @@ -189,11 +188,11 @@ class ApplicableOverloadedMethods { */ static final ApplicabilityTest APPLICABLE_BY_VARIABLE_ARITY = new ApplicabilityTest() { @Override - boolean isApplicable(MethodType callSiteType, MethodHandle method) { - if(!method.isVarargsCollector()) { + boolean isApplicable(MethodType callSiteType, SingleDynamicMethod method) { + if(!method.isVarArgs()) { return false; } - final MethodType methodType = method.type(); + final MethodType methodType = method.getMethodType(); final int methodArity = methodType.parameterCount(); final int fixArity = methodArity - 1; final int callSiteArity = callSiteType.parameterCount(); diff --git a/nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDetector.java b/nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDetector.java new file mode 100644 index 00000000000..466bafe65dc --- /dev/null +++ b/nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDetector.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * This file is available under and governed by the GNU General Public + * License version 2 only, as published by the Free Software Foundation. + * However, the following notice accompanied the original version of this + * file, and Oracle licenses the original version of this file under the BSD + * license: + */ +/* + Copyright 2009-2013 Attila Szegedi + + Licensed under both the Apache License, Version 2.0 (the "Apache License") + and the BSD License (the "BSD License"), with licensee being free to + choose either of the two at their discretion. + + You may not use this file except in compliance with either the Apache + License or the BSD License. + + If you choose to use this file in compliance with the Apache License, the + following notice applies to you: + + You may obtain a copy of the Apache 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. + + If you choose to use this file in compliance with the BSD License, the + following notice applies to you: + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the copyright holder nor the names of + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER + BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +package jdk.internal.dynalink.beans; + +import java.lang.annotation.Annotation; +import java.lang.reflect.AccessibleObject; +import sun.reflect.CallerSensitive; + +/** + * Utility class that determines if a method or constructor is caller sensitive. It actually encapsulates two different + * strategies for determining caller sensitivity; a more robust one that works if Dynalink runs as code with access + * to {@code sun.reflect} package, and an unprivileged one that is used when Dynalink doesn't have access to that + * package. Note that even the unprivileged strategy is ordinarily robust, but it relies on the {@code toString} method + * of the annotation. If an attacker were to use a different annotation to spoof the string representation of the + * {@code CallerSensitive} annotation, they could designate their own methods as caller sensitive. This however does not + * escalate privileges, only causes Dynalink to never cache method handles for such methods, so all it would do would + * decrease the performance in linking such methods. In the opposite case when an attacker could trick Dynalink into not + * recognizing genuine {@code CallerSensitive} annotations, Dynalink would treat caller sensitive methods as ordinary + * methods, and would cache them bound to a zero-privilege delegate as the caller (just what Dynalink did before it + * could handle caller-sensitive methods). That would practically render caller-sensitive methods exposed through + * Dynalink unusable, but again, can not lead to any privilege escalations. Therefore, even the less robust unprivileged + * strategy is safe; the worst thing a successful attack against it can achieve is slight reduction in Dynalink-exposed + * functionality or performance. + */ +public class CallerSensitiveDetector { + + private static final DetectionStrategy DETECTION_STRATEGY = getDetectionStrategy(); + + static boolean isCallerSensitive(AccessibleObject ao) { + return DETECTION_STRATEGY.isCallerSensitive(ao); + } + + private static DetectionStrategy getDetectionStrategy() { + try { + return new PrivilegedDetectionStrategy(); + } catch(Throwable t) { + return new UnprivilegedDetectionStrategy(); + } + } + + private abstract static class DetectionStrategy { + abstract boolean isCallerSensitive(AccessibleObject ao); + } + + private static class PrivilegedDetectionStrategy extends DetectionStrategy { + private static final Class CALLER_SENSITIVE_ANNOTATION_CLASS = CallerSensitive.class; + + @Override + boolean isCallerSensitive(AccessibleObject ao) { + return ao.getAnnotation(CALLER_SENSITIVE_ANNOTATION_CLASS) != null; + } + } + + private static class UnprivilegedDetectionStrategy extends DetectionStrategy { + private static final String CALLER_SENSITIVE_ANNOTATION_STRING = "@sun.reflect.CallerSensitive()"; + + @Override + boolean isCallerSensitive(AccessibleObject o) { + for(Annotation a: o.getAnnotations()) { + if(String.valueOf(a).equals(CALLER_SENSITIVE_ANNOTATION_STRING)) { + return true; + } + } + return false; + } + } +} diff --git a/nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDynamicMethod.java b/nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDynamicMethod.java new file mode 100644 index 00000000000..1e274d516e9 --- /dev/null +++ b/nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDynamicMethod.java @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * This file is available under and governed by the GNU General Public + * License version 2 only, as published by the Free Software Foundation. + * However, the following notice accompanied the original version of this + * file, and Oracle licenses the original version of this file under the BSD + * license: + */ +/* + Copyright 2009-2013 Attila Szegedi + + Licensed under both the Apache License, Version 2.0 (the "Apache License") + and the BSD License (the "BSD License"), with licensee being free to + choose either of the two at their discretion. + + You may not use this file except in compliance with either the Apache + License or the BSD License. + + If you choose to use this file in compliance with the Apache License, the + following notice applies to you: + + You may obtain a copy of the Apache 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. + + If you choose to use this file in compliance with the BSD License, the + following notice applies to you: + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the copyright holder nor the names of + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER + BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +package jdk.internal.dynalink.beans; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Constructor; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import jdk.internal.dynalink.support.Lookup; + +/** + * A dynamic method bound to exactly one Java method or constructor that is caller sensitive. Since the target method is + * caller sensitive, it doesn't cache a method handle but rather uses the passed lookup object in + * {@link #getTarget(java.lang.invoke.MethodHandles.Lookup)} to unreflect a method handle from the reflective member on + * every request. + * + * @author Attila Szegedi + */ +class CallerSensitiveDynamicMethod extends SingleDynamicMethod { + // Typed as "AccessibleObject" as it can be either a method or a constructor. + // If we were Java8-only, we could use java.lang.reflect.Executable + private final AccessibleObject target; + private final MethodType type; + + public CallerSensitiveDynamicMethod(AccessibleObject target) { + super(getName(target)); + this.target = target; + this.type = getMethodType(target); + } + + private static String getName(AccessibleObject target) { + final Member m = (Member)target; + return getMethodNameWithSignature(getMethodType(target), getClassAndMethodName(m.getDeclaringClass(), + m.getName())); + } + + @Override + MethodType getMethodType() { + return type; + } + + private static MethodType getMethodType(AccessibleObject ao) { + final boolean isMethod = ao instanceof Method; + final Class rtype = isMethod ? ((Method)ao).getReturnType() : ((Constructor)ao).getDeclaringClass(); + final Class[] ptypes = isMethod ? ((Method)ao).getParameterTypes() : ((Constructor)ao).getParameterTypes(); + final MethodType type = MethodType.methodType(rtype, ptypes); + final Member m = (Member)ao; + return type.insertParameterTypes(0, + isMethod ? + Modifier.isStatic(m.getModifiers()) ? + Object.class : + m.getDeclaringClass() : + StaticClass.class); + } + + @Override + boolean isVarArgs() { + return target instanceof Method ? ((Method)target).isVarArgs() : ((Constructor)target).isVarArgs(); + } + + @Override + MethodHandle getTarget(MethodHandles.Lookup lookup) { + if(target instanceof Method) { + final MethodHandle mh = Lookup.unreflect(lookup, (Method)target); + if(Modifier.isStatic(((Member)target).getModifiers())) { + return StaticClassIntrospector.editStaticMethodHandle(mh); + } + return mh; + } + return StaticClassIntrospector.editConstructorMethodHandle(Lookup.unreflectConstructor(lookup, + (Constructor)target)); + } +} diff --git a/nashorn/src/jdk/internal/dynalink/beans/ClassString.java b/nashorn/src/jdk/internal/dynalink/beans/ClassString.java index dfcb378662f..8ab45727de6 100644 --- a/nashorn/src/jdk/internal/dynalink/beans/ClassString.java +++ b/nashorn/src/jdk/internal/dynalink/beans/ClassString.java @@ -155,8 +155,8 @@ final class ClassString { } List getMaximallySpecifics(List methods, LinkerServices linkerServices, boolean varArg) { - return MaximallySpecific.getMaximallySpecificMethods(getApplicables(methods, linkerServices, varArg), varArg, - classes, linkerServices); + return MaximallySpecific.getMaximallySpecificMethodHandles(getApplicables(methods, linkerServices, varArg), + varArg, classes, linkerServices); } /** diff --git a/nashorn/src/jdk/internal/dynalink/beans/DynamicMethod.java b/nashorn/src/jdk/internal/dynalink/beans/DynamicMethod.java index aee69ff722e..6beb92b12f7 100644 --- a/nashorn/src/jdk/internal/dynalink/beans/DynamicMethod.java +++ b/nashorn/src/jdk/internal/dynalink/beans/DynamicMethod.java @@ -84,8 +84,7 @@ package jdk.internal.dynalink.beans; import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodType; -import java.util.StringTokenizer; +import jdk.internal.dynalink.CallSiteDescriptor; import jdk.internal.dynalink.linker.LinkerServices; /** @@ -116,45 +115,28 @@ abstract class DynamicMethod { * is a variable arguments (vararg) method, it will pack the extra arguments in an array before the invocation of * the underlying method if it is not already done. * - * @param callSiteType the method type at a call site + * @param callSiteDescriptor the descriptor of the call site * @param linkerServices linker services. Used for language-specific type conversions. * @return an invocation suitable for calling the method from the specified call site. */ - abstract MethodHandle getInvocation(MethodType callSiteType, LinkerServices linkerServices); + abstract MethodHandle getInvocation(CallSiteDescriptor callSiteDescriptor, LinkerServices linkerServices); /** - * Returns a simple dynamic method representing a single underlying Java method (possibly selected among several + * Returns a single dynamic method representing a single underlying Java method (possibly selected among several * overloads) with formal parameter types exactly matching the passed signature. * @param paramTypes the comma-separated list of requested parameter type names. The names will match both * qualified and unqualified type names. - * @return a simple dynamic method representing a single underlying Java method, or null if none of the Java methods + * @return a single dynamic method representing a single underlying Java method, or null if none of the Java methods * behind this dynamic method exactly match the requested parameter types. */ - abstract SimpleDynamicMethod getMethodForExactParamTypes(String paramTypes); + abstract SingleDynamicMethod getMethodForExactParamTypes(String paramTypes); /** - * True if this dynamic method already contains a method handle with an identical signature as the passed in method - * handle. - * @param mh the method handle to check - * @return true if it already contains an equivalent method handle. + * True if this dynamic method already contains a method with an identical signature as the passed in method. + * @param method the method to check + * @return true if it already contains an equivalent method. */ - abstract boolean contains(MethodHandle mh); - - static boolean typeMatchesDescription(String paramTypes, MethodType type) { - final StringTokenizer tok = new StringTokenizer(paramTypes, ", "); - for(int i = 1; i < type.parameterCount(); ++i) { // i = 1 as we ignore the receiver - if(!(tok.hasMoreTokens() && typeNameMatches(tok.nextToken(), type.parameterType(i)))) { - return false; - } - } - return !tok.hasMoreTokens(); - } - - private static boolean typeNameMatches(String typeName, Class type) { - final int lastDot = typeName.lastIndexOf('.'); - final String fullTypeName = type.getCanonicalName(); - return lastDot != -1 && fullTypeName.endsWith(typeName.substring(lastDot)) || typeName.equals(fullTypeName); - } + abstract boolean contains(SingleDynamicMethod method); static String getClassAndMethodName(Class clazz, String name) { final String clazzName = clazz.getCanonicalName(); diff --git a/nashorn/src/jdk/internal/dynalink/beans/DynamicMethodLinker.java b/nashorn/src/jdk/internal/dynalink/beans/DynamicMethodLinker.java index d8ceeea0045..32942b9a423 100644 --- a/nashorn/src/jdk/internal/dynalink/beans/DynamicMethodLinker.java +++ b/nashorn/src/jdk/internal/dynalink/beans/DynamicMethodLinker.java @@ -85,12 +85,12 @@ package jdk.internal.dynalink.beans; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; import jdk.internal.dynalink.CallSiteDescriptor; import jdk.internal.dynalink.linker.GuardedInvocation; import jdk.internal.dynalink.linker.LinkRequest; import jdk.internal.dynalink.linker.LinkerServices; import jdk.internal.dynalink.linker.TypeBasedGuardingDynamicLinker; +import jdk.internal.dynalink.support.CallSiteDescriptorFactory; import jdk.internal.dynalink.support.Guards; /** @@ -110,19 +110,18 @@ class DynamicMethodLinker implements TypeBasedGuardingDynamicLinker { return null; } final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor(); - if(desc.getNameTokenCount() != 2 && desc.getNameToken(CallSiteDescriptor.SCHEME) != "dyn") { + if(desc.getNameTokenCount() != 2 && desc.getNameToken(CallSiteDescriptor.SCHEME) != "dyn") { return null; } final String operator = desc.getNameToken(CallSiteDescriptor.OPERATOR); if(operator == "call") { - final MethodType type = desc.getMethodType(); - final MethodHandle invocation = ((DynamicMethod)receiver).getInvocation(type.dropParameterTypes(0, 1), - linkerServices); + final MethodHandle invocation = ((DynamicMethod)receiver).getInvocation( + CallSiteDescriptorFactory.dropParameterTypes(desc, 0, 1), linkerServices); if(invocation == null) { return null; } - return new GuardedInvocation(MethodHandles.dropArguments(invocation, 0, type.parameterType(0)), - Guards.getIdentityGuard(receiver)); + return new GuardedInvocation(MethodHandles.dropArguments(invocation, 0, + desc.getMethodType().parameterType(0)), Guards.getIdentityGuard(receiver)); } return null; } diff --git a/nashorn/src/jdk/internal/dynalink/beans/FacetIntrospector.java b/nashorn/src/jdk/internal/dynalink/beans/FacetIntrospector.java index f4fbd8244f1..97e431ca24b 100644 --- a/nashorn/src/jdk/internal/dynalink/beans/FacetIntrospector.java +++ b/nashorn/src/jdk/internal/dynalink/beans/FacetIntrospector.java @@ -167,10 +167,6 @@ abstract class FacetIntrospector { return editMethodHandle(SafeUnreflector.unreflectSetter(field)); } - MethodHandle unreflect(Method method) { - return editMethodHandle(SafeUnreflector.unreflect(method)); - } - /** * Returns an edited method handle. A facet might need to edit an unreflected method handle before it is usable with * the facet. By default, returns the passed method handle unchanged. The class' static facet will introduce a diff --git a/nashorn/src/jdk/internal/dynalink/beans/MaximallySpecific.java b/nashorn/src/jdk/internal/dynalink/beans/MaximallySpecific.java index 182fd01695d..3ee8e41ab30 100644 --- a/nashorn/src/jdk/internal/dynalink/beans/MaximallySpecific.java +++ b/nashorn/src/jdk/internal/dynalink/beans/MaximallySpecific.java @@ -105,10 +105,58 @@ class MaximallySpecific { * @param varArgs whether to assume the methods are varargs * @return the list of maximally specific methods. */ - static List getMaximallySpecificMethods(List methods, boolean varArgs) { - return getMaximallySpecificMethods(methods, varArgs, null, null); + static List getMaximallySpecificMethods(List methods, boolean varArgs) { + return getMaximallySpecificSingleDynamicMethods(methods, varArgs, null, null); } + private abstract static class MethodTypeGetter { + abstract MethodType getMethodType(T t); + } + + private static final MethodTypeGetter METHOD_HANDLE_TYPE_GETTER = + new MethodTypeGetter() { + @Override + MethodType getMethodType(MethodHandle t) { + return t.type(); + } + }; + + private static final MethodTypeGetter DYNAMIC_METHOD_TYPE_GETTER = + new MethodTypeGetter() { + @Override + MethodType getMethodType(SingleDynamicMethod t) { + return t.getMethodType(); + } + }; + + /** + * Given a list of methods handles, returns a list of maximally specific methods, applying language-runtime + * specific conversion preferences. + * + * @param methods the list of method handles + * @param varArgs whether to assume the method handles are varargs + * @param argTypes concrete argument types for the invocation + * @return the list of maximally specific method handles. + */ + static List getMaximallySpecificMethodHandles(List methods, boolean varArgs, + Class[] argTypes, LinkerServices ls) { + return getMaximallySpecificMethods(methods, varArgs, argTypes, ls, METHOD_HANDLE_TYPE_GETTER); + } + + /** + * Given a list of methods, returns a list of maximally specific methods, applying language-runtime specific + * conversion preferences. + * + * @param methods the list of methods + * @param varArgs whether to assume the methods are varargs + * @param argTypes concrete argument types for the invocation + * @return the list of maximally specific methods. + */ + static List getMaximallySpecificSingleDynamicMethods(List methods, + boolean varArgs, Class[] argTypes, LinkerServices ls) { + return getMaximallySpecificMethods(methods, varArgs, argTypes, ls, DYNAMIC_METHOD_TYPE_GETTER); + } + /** * Given a list of methods, returns a list of maximally specific methods, applying language-runtime specific * conversion preferences. @@ -118,18 +166,18 @@ class MaximallySpecific { * @param argTypes concrete argument types for the invocation * @return the list of maximally specific methods. */ - static List getMaximallySpecificMethods(List methods, boolean varArgs, - Class[] argTypes, LinkerServices ls) { + private static List getMaximallySpecificMethods(List methods, boolean varArgs, + Class[] argTypes, LinkerServices ls, MethodTypeGetter methodTypeGetter) { if(methods.size() < 2) { return methods; } - final LinkedList maximals = new LinkedList<>(); - for(MethodHandle m: methods) { - final MethodType methodType = m.type(); + final LinkedList maximals = new LinkedList<>(); + for(T m: methods) { + final MethodType methodType = methodTypeGetter.getMethodType(m); boolean lessSpecific = false; - for(Iterator maximal = maximals.iterator(); maximal.hasNext();) { - final MethodHandle max = maximal.next(); - switch(isMoreSpecific(methodType, max.type(), varArgs, argTypes, ls)) { + for(Iterator maximal = maximals.iterator(); maximal.hasNext();) { + final T max = maximal.next(); + switch(isMoreSpecific(methodType, methodTypeGetter.getMethodType(max), varArgs, argTypes, ls)) { case TYPE_1_BETTER: { maximal.remove(); break; diff --git a/nashorn/src/jdk/internal/dynalink/beans/OverloadedDynamicMethod.java b/nashorn/src/jdk/internal/dynalink/beans/OverloadedDynamicMethod.java index 7873cf1520e..407d2b8310f 100644 --- a/nashorn/src/jdk/internal/dynalink/beans/OverloadedDynamicMethod.java +++ b/nashorn/src/jdk/internal/dynalink/beans/OverloadedDynamicMethod.java @@ -84,16 +84,21 @@ package jdk.internal.dynalink.beans; import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; +import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import jdk.internal.dynalink.CallSiteDescriptor; import jdk.internal.dynalink.beans.ApplicableOverloadedMethods.ApplicabilityTest; import jdk.internal.dynalink.linker.LinkerServices; import jdk.internal.dynalink.support.TypeUtilities; /** - * Represents an overloaded method. + * Represents a group of {@link SingleDynamicMethod} objects that represents all overloads of a particular name (or all + * constructors) for a particular class. Correctly handles overload resolution, variable arity methods, and caller + * sensitive methods within the overloads. * * @author Attila Szegedi */ @@ -101,7 +106,7 @@ class OverloadedDynamicMethod extends DynamicMethod { /** * Holds a list of all methods. */ - private final LinkedList methods; + private final LinkedList methods; private final ClassLoader classLoader; /** @@ -111,21 +116,22 @@ class OverloadedDynamicMethod extends DynamicMethod { * @param name the name of the method */ OverloadedDynamicMethod(Class clazz, String name) { - this(new LinkedList(), clazz.getClassLoader(), getClassAndMethodName(clazz, name)); + this(new LinkedList(), clazz.getClassLoader(), getClassAndMethodName(clazz, name)); } - private OverloadedDynamicMethod(LinkedList methods, ClassLoader classLoader, String name) { + private OverloadedDynamicMethod(LinkedList methods, ClassLoader classLoader, String name) { super(name); this.methods = methods; this.classLoader = classLoader; } @Override - SimpleDynamicMethod getMethodForExactParamTypes(String paramTypes) { - final LinkedList matchingMethods = new LinkedList<>(); - for(MethodHandle method: methods) { - if(typeMatchesDescription(paramTypes, method.type())) { - matchingMethods.add(method); + SingleDynamicMethod getMethodForExactParamTypes(String paramTypes) { + final LinkedList matchingMethods = new LinkedList<>(); + for(SingleDynamicMethod method: methods) { + final SingleDynamicMethod matchingMethod = method.getMethodForExactParamTypes(paramTypes); + if(matchingMethod != null) { + matchingMethods.add(matchingMethod); } } switch(matchingMethods.size()) { @@ -133,8 +139,7 @@ class OverloadedDynamicMethod extends DynamicMethod { return null; } case 1: { - final MethodHandle target = matchingMethods.get(0); - return new SimpleDynamicMethod(target, SimpleDynamicMethod.getMethodNameWithSignature(target, getName())); + return matchingMethods.getFirst(); } default: { throw new BootstrapMethodError("Can't choose among " + matchingMethods + " for argument types " @@ -144,7 +149,8 @@ class OverloadedDynamicMethod extends DynamicMethod { } @Override - public MethodHandle getInvocation(final MethodType callSiteType, final LinkerServices linkerServices) { + public MethodHandle getInvocation(final CallSiteDescriptor callSiteDescriptor, final LinkerServices linkerServices) { + final MethodType callSiteType = callSiteDescriptor.getMethodType(); // First, find all methods applicable to the call site by subtyping (JLS 15.12.2.2) final ApplicableOverloadedMethods subtypingApplicables = getApplicables(callSiteType, ApplicableOverloadedMethods.APPLICABLE_BY_SUBTYPING); @@ -156,7 +162,7 @@ class OverloadedDynamicMethod extends DynamicMethod { ApplicableOverloadedMethods.APPLICABLE_BY_VARIABLE_ARITY); // Find the methods that are maximally specific based on the call site signature - List maximallySpecifics = subtypingApplicables.findMaximallySpecificMethods(); + List maximallySpecifics = subtypingApplicables.findMaximallySpecificMethods(); if(maximallySpecifics.isEmpty()) { maximallySpecifics = methodInvocationApplicables.findMaximallySpecificMethods(); if(maximallySpecifics.isEmpty()) { @@ -171,12 +177,12 @@ class OverloadedDynamicMethod extends DynamicMethod { // (Object, Object), and we have a method whose parameter types are (String, int). None of the JLS applicability // rules will trigger, but we must consider the method, as it can be the right match for a concrete invocation. @SuppressWarnings({ "unchecked", "rawtypes" }) - final List invokables = (List)methods.clone(); + final List invokables = (List)methods.clone(); invokables.removeAll(subtypingApplicables.getMethods()); invokables.removeAll(methodInvocationApplicables.getMethods()); invokables.removeAll(variableArityApplicables.getMethods()); - for(final Iterator it = invokables.iterator(); it.hasNext();) { - final MethodHandle m = it.next(); + for(final Iterator it = invokables.iterator(); it.hasNext();) { + final SingleDynamicMethod m = it.next(); if(!isApplicableDynamically(linkerServices, callSiteType, m)) { it.remove(); } @@ -199,54 +205,45 @@ class OverloadedDynamicMethod extends DynamicMethod { } case 1: { // Very lucky, we ended up with a single candidate method handle based on the call site signature; we - // can link it very simply by delegating to a SimpleDynamicMethod. - final MethodHandle mh = invokables.iterator().next(); - return new SimpleDynamicMethod(mh).getInvocation(callSiteType, linkerServices); + // can link it very simply by delegating to the SingleDynamicMethod. + invokables.iterator().next().getInvocation(callSiteDescriptor, linkerServices); } default: { // We have more than one candidate. We have no choice but to link to a method that resolves overloads on // every invocation (alternatively, we could opportunistically link the one method that resolves for the // current arguments, but we'd need to install a fairly complex guard for that and when it'd fail, we'd - // go back all the way to candidate selection. - // TODO: cache per call site type - return new OverloadedMethod(invokables, this, callSiteType, linkerServices).getInvoker(); + // go back all the way to candidate selection. Note that we're resolving any potential caller sensitive + // methods here to their handles, as the OverloadedMethod instance is specific to a call site, so it + // has an already determined Lookup. + final List methodHandles = new ArrayList<>(invokables.size()); + final MethodHandles.Lookup lookup = callSiteDescriptor.getLookup(); + for(SingleDynamicMethod method: invokables) { + methodHandles.add(method.getTarget(lookup)); + } + return new OverloadedMethod(methodHandles, this, callSiteType, linkerServices).getInvoker(); } } } @Override - public boolean contains(MethodHandle mh) { - final MethodType type = mh.type(); - for(MethodHandle method: methods) { - if(typesEqualNoReceiver(type, method.type())) { + public boolean contains(SingleDynamicMethod m) { + for(SingleDynamicMethod method: methods) { + if(method.contains(m)) { return true; } } return false; } - private static boolean typesEqualNoReceiver(MethodType type1, MethodType type2) { - final int pc = type1.parameterCount(); - if(pc != type2.parameterCount()) { - return false; - } - for(int i = 1; i < pc; ++i) { // i = 1: ignore receiver - if(type1.parameterType(i) != type2.parameterType(i)) { - return false; - } - } - return true; - } - ClassLoader getClassLoader() { return classLoader; } private static boolean isApplicableDynamically(LinkerServices linkerServices, MethodType callSiteType, - MethodHandle m) { - final MethodType methodType = m.type(); - final boolean varArgs = m.isVarargsCollector(); + SingleDynamicMethod m) { + final MethodType methodType = m.getMethodType(); + final boolean varArgs = m.isVarArgs(); final int fixedArgLen = methodType.parameterCount() - (varArgs ? 1 : 0); final int callSiteArgLen = callSiteType.parameterCount(); @@ -300,21 +297,12 @@ class OverloadedDynamicMethod extends DynamicMethod { return new ApplicableOverloadedMethods(methods, callSiteType, test); } - /** - * Add a method identified by a {@link SimpleDynamicMethod} to this overloaded method's set. - * - * @param method the method to add. - */ - void addMethod(SimpleDynamicMethod method) { - addMethod(method.getTarget()); - } - /** * Add a method to this overloaded method's set. * * @param method a method to add */ - public void addMethod(MethodHandle method) { + public void addMethod(SingleDynamicMethod method) { methods.add(method); } } diff --git a/nashorn/src/jdk/internal/dynalink/beans/OverloadedMethod.java b/nashorn/src/jdk/internal/dynalink/beans/OverloadedMethod.java index 7093e757497..f711489b037 100644 --- a/nashorn/src/jdk/internal/dynalink/beans/OverloadedMethod.java +++ b/nashorn/src/jdk/internal/dynalink/beans/OverloadedMethod.java @@ -135,7 +135,7 @@ class OverloadedMethod { varArgMethods.trimToSize(); final MethodHandle bound = SELECT_METHOD.bindTo(this); - final MethodHandle collecting = SimpleDynamicMethod.collectArguments(bound, argNum).asType( + final MethodHandle collecting = SingleDynamicMethod.collectArguments(bound, argNum).asType( callSiteType.changeReturnType(MethodHandle.class)); invoker = MethodHandles.foldArguments(MethodHandles.exactInvoker(callSiteType), collecting); } @@ -167,7 +167,7 @@ class OverloadedMethod { break; } case 1: { - method = new SimpleDynamicMethod(methods.get(0)).getInvocation(callSiteType, linkerServices); + method = SingleDynamicMethod.getInvocation(methods.get(0), callSiteType, linkerServices); break; } default: { diff --git a/nashorn/src/jdk/internal/dynalink/beans/SimpleDynamicMethod.java b/nashorn/src/jdk/internal/dynalink/beans/SimpleDynamicMethod.java index 1fbf7dbb1a0..9d4d6961081 100644 --- a/nashorn/src/jdk/internal/dynalink/beans/SimpleDynamicMethod.java +++ b/nashorn/src/jdk/internal/dynalink/beans/SimpleDynamicMethod.java @@ -84,28 +84,21 @@ package jdk.internal.dynalink.beans; import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodHandles.Lookup; import java.lang.invoke.MethodType; -import java.lang.reflect.Array; -import jdk.internal.dynalink.linker.LinkerServices; -import jdk.internal.dynalink.support.Guards; /** - * A dynamic method bound to exactly one, non-overloaded Java method. Handles varargs. + * A dynamic method bound to exactly one Java method or constructor that is not caller sensitive. Since its target is + * not caller sensitive, this class pre-caches its method handle and always returns it from the call to + * {@link #getTarget(Lookup)}. Can be used in general to represents dynamic methods bound to a single method handle, + * even if that handle is not mapped to a Java method, i.e. as a wrapper around field getters/setters, array element + * getters/setters, etc. * * @author Attila Szegedi */ -class SimpleDynamicMethod extends DynamicMethod { +class SimpleDynamicMethod extends SingleDynamicMethod { private final MethodHandle target; - /** - * Creates a simple dynamic method with no name. - * @param target the target method handle - */ - SimpleDynamicMethod(MethodHandle target) { - this(target, null); - } - /** * Creates a new simple dynamic method, with a name constructed from the class name, method name, and handle * signature. @@ -115,125 +108,26 @@ class SimpleDynamicMethod extends DynamicMethod { * @param name the simple name of the method */ SimpleDynamicMethod(MethodHandle target, Class clazz, String name) { - this(target, getName(target, clazz, name)); - } - - SimpleDynamicMethod(MethodHandle target, String name) { - super(name); + super(getName(target, clazz, name)); this.target = target; } private static String getName(MethodHandle target, Class clazz, String name) { - return getMethodNameWithSignature(target, getClassAndMethodName(clazz, name)); + return getMethodNameWithSignature(target.type(), getClassAndMethodName(clazz, name)); } - static String getMethodNameWithSignature(MethodHandle target, String methodName) { - final String typeStr = target.type().toString(); - final int retTypeIndex = typeStr.lastIndexOf(')') + 1; - int secondParamIndex = typeStr.indexOf(',') + 1; - if(secondParamIndex == 0) { - secondParamIndex = retTypeIndex - 1; - } - return typeStr.substring(retTypeIndex) + " " + methodName + "(" + typeStr.substring(secondParamIndex, retTypeIndex); + @Override + boolean isVarArgs() { + return target.isVarargsCollector(); } - /** - * Returns the target of this dynamic method - * - * @return the target of this dynamic method - */ - MethodHandle getTarget() { + @Override + MethodType getMethodType() { + return target.type(); + } + + @Override + MethodHandle getTarget(Lookup lookup) { return target; } - - @Override - SimpleDynamicMethod getMethodForExactParamTypes(String paramTypes) { - return typeMatchesDescription(paramTypes, target.type()) ? this : null; - } - - @Override - MethodHandle getInvocation(MethodType callSiteType, LinkerServices linkerServices) { - final MethodType methodType = target.type(); - final int paramsLen = methodType.parameterCount(); - final boolean varArgs = target.isVarargsCollector(); - final MethodHandle fixTarget = varArgs ? target.asFixedArity() : target; - final int fixParamsLen = varArgs ? paramsLen - 1 : paramsLen; - final int argsLen = callSiteType.parameterCount(); - if(argsLen < fixParamsLen) { - // Less actual arguments than number of fixed declared arguments; can't invoke. - return null; - } - // Method handle has the same number of fixed arguments as the call site type - if(argsLen == fixParamsLen) { - // Method handle that matches the number of actual arguments as the number of fixed arguments - final MethodHandle matchedMethod; - if(varArgs) { - // If vararg, add a zero-length array of the expected type as the last argument to signify no variable - // arguments. - matchedMethod = MethodHandles.insertArguments(fixTarget, fixParamsLen, Array.newInstance( - methodType.parameterType(fixParamsLen).getComponentType(), 0)); - } else { - // Otherwise, just use the method - matchedMethod = fixTarget; - } - return createConvertingInvocation(matchedMethod, linkerServices, callSiteType); - } - - // What's below only works for varargs - if(!varArgs) { - return null; - } - - final Class varArgType = methodType.parameterType(fixParamsLen); - // Handle a somewhat sinister corner case: caller passes exactly one argument in the vararg position, and we - // must handle both a prepacked vararg array as well as a genuine 1-long vararg sequence. - if(argsLen == paramsLen) { - final Class callSiteLastArgType = callSiteType.parameterType(fixParamsLen); - if(varArgType.isAssignableFrom(callSiteLastArgType)) { - // Call site signature guarantees we'll always be passed a single compatible array; just link directly - // to the method. - return createConvertingInvocation(fixTarget, linkerServices, callSiteType); - } - if(!linkerServices.canConvert(callSiteLastArgType, varArgType)) { - // Call site signature guarantees the argument can definitely not be an array (i.e. it is primitive); - // link immediately to a vararg-packing method handle. - return createConvertingInvocation(collectArguments(fixTarget, argsLen), linkerServices, callSiteType); - } - // Call site signature makes no guarantees that the single argument in the vararg position will be - // compatible across all invocations. Need to insert an appropriate guard and fall back to generic vararg - // method when it is not. - return MethodHandles.guardWithTest(Guards.isInstance(varArgType, fixParamsLen, callSiteType), - createConvertingInvocation(fixTarget, linkerServices, callSiteType), - createConvertingInvocation(collectArguments(fixTarget, argsLen), linkerServices, callSiteType)); - } - - // Remaining case: more than one vararg. - return createConvertingInvocation(collectArguments(fixTarget, argsLen), linkerServices, callSiteType); - } - - @Override - public boolean contains(MethodHandle mh) { - return target.type().parameterList().equals(mh.type().parameterList()); - } - - /** - * Creates a method handle out of the original target that will collect the varargs for the exact component type of - * the varArg array. Note that this will nicely trigger language-specific type converters for exactly those varargs - * for which it is necessary when later passed to linkerServices.convertArguments(). - * - * @param target the original method handle - * @param parameterCount the total number of arguments in the new method handle - * @return a collecting method handle - */ - static MethodHandle collectArguments(MethodHandle target, final int parameterCount) { - final MethodType methodType = target.type(); - final int fixParamsLen = methodType.parameterCount() - 1; - final Class arrayType = methodType.parameterType(fixParamsLen); - return target.asCollector(arrayType, parameterCount - fixParamsLen); - } - - private static MethodHandle createConvertingInvocation(final MethodHandle sizedMethod, - final LinkerServices linkerServices, final MethodType callSiteType) { - return linkerServices.asType(sizedMethod, callSiteType); - } } diff --git a/nashorn/src/jdk/internal/dynalink/beans/SingleDynamicMethod.java b/nashorn/src/jdk/internal/dynalink/beans/SingleDynamicMethod.java new file mode 100644 index 00000000000..d15fab9966e --- /dev/null +++ b/nashorn/src/jdk/internal/dynalink/beans/SingleDynamicMethod.java @@ -0,0 +1,255 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * This file is available under and governed by the GNU General Public + * License version 2 only, as published by the Free Software Foundation. + * However, the following notice accompanied the original version of this + * file, and Oracle licenses the original version of this file under the BSD + * license: + */ +/* + Copyright 2009-2013 Attila Szegedi + + Licensed under both the Apache License, Version 2.0 (the "Apache License") + and the BSD License (the "BSD License"), with licensee being free to + choose either of the two at their discretion. + + You may not use this file except in compliance with either the Apache + License or the BSD License. + + If you choose to use this file in compliance with the Apache License, the + following notice applies to you: + + You may obtain a copy of the Apache 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. + + If you choose to use this file in compliance with the BSD License, the + following notice applies to you: + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the copyright holder nor the names of + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER + BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +package jdk.internal.dynalink.beans; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.lang.reflect.Array; +import java.util.StringTokenizer; +import jdk.internal.dynalink.CallSiteDescriptor; +import jdk.internal.dynalink.linker.LinkerServices; +import jdk.internal.dynalink.support.Guards; + +/** + * Base class for dynamic methods that dispatch to a single target Java method or constructor. Handles adaptation of the + * target method to a call site type (including mapping variable arity methods to a call site signature with different + * arity). + * @author Attila Szegedi + * @version $Id: $ + */ +abstract class SingleDynamicMethod extends DynamicMethod { + SingleDynamicMethod(String name) { + super(name); + } + + /** + * Returns true if this method is variable arity. + * @return true if this method is variable arity. + */ + abstract boolean isVarArgs(); + + /** + * Returns this method's native type. + * @return this method's native type. + */ + abstract MethodType getMethodType(); + + /** + * Given a specified lookup, returns a method handle to this method's target. + * @param lookup the lookup to use. + * @return the handle to this method's target method. + */ + abstract MethodHandle getTarget(MethodHandles.Lookup lookup); + + @Override + MethodHandle getInvocation(CallSiteDescriptor callSiteDescriptor, LinkerServices linkerServices) { + return getInvocation(getTarget(callSiteDescriptor.getLookup()), callSiteDescriptor.getMethodType(), + linkerServices); + } + + @Override + SingleDynamicMethod getMethodForExactParamTypes(String paramTypes) { + return typeMatchesDescription(paramTypes, getMethodType()) ? this : null; + } + + @Override + boolean contains(SingleDynamicMethod method) { + return getMethodType().parameterList().equals(method.getMethodType().parameterList()); + } + + static String getMethodNameWithSignature(MethodType type, String methodName) { + final String typeStr = type.toString(); + final int retTypeIndex = typeStr.lastIndexOf(')') + 1; + int secondParamIndex = typeStr.indexOf(',') + 1; + if(secondParamIndex == 0) { + secondParamIndex = retTypeIndex - 1; + } + return typeStr.substring(retTypeIndex) + " " + methodName + "(" + typeStr.substring(secondParamIndex, retTypeIndex); + } + + /** + * Given a method handle and a call site type, adapts the method handle to the call site type. Performs type + * conversions as needed using the specified linker services, and in case that the method handle is a vararg + * collector, matches it to the arity of the call site. + * @param target the method handle to adapt + * @param callSiteType the type of the call site + * @param linkerServices the linker services used for type conversions + * @return the adapted method handle. + */ + static MethodHandle getInvocation(MethodHandle target, MethodType callSiteType, LinkerServices linkerServices) { + final MethodType methodType = target.type(); + final int paramsLen = methodType.parameterCount(); + final boolean varArgs = target.isVarargsCollector(); + final MethodHandle fixTarget = varArgs ? target.asFixedArity() : target; + final int fixParamsLen = varArgs ? paramsLen - 1 : paramsLen; + final int argsLen = callSiteType.parameterCount(); + if(argsLen < fixParamsLen) { + // Less actual arguments than number of fixed declared arguments; can't invoke. + return null; + } + // Method handle has the same number of fixed arguments as the call site type + if(argsLen == fixParamsLen) { + // Method handle that matches the number of actual arguments as the number of fixed arguments + final MethodHandle matchedMethod; + if(varArgs) { + // If vararg, add a zero-length array of the expected type as the last argument to signify no variable + // arguments. + matchedMethod = MethodHandles.insertArguments(fixTarget, fixParamsLen, Array.newInstance( + methodType.parameterType(fixParamsLen).getComponentType(), 0)); + } else { + // Otherwise, just use the method + matchedMethod = fixTarget; + } + return createConvertingInvocation(matchedMethod, linkerServices, callSiteType); + } + + // What's below only works for varargs + if(!varArgs) { + return null; + } + + final Class varArgType = methodType.parameterType(fixParamsLen); + // Handle a somewhat sinister corner case: caller passes exactly one argument in the vararg position, and we + // must handle both a prepacked vararg array as well as a genuine 1-long vararg sequence. + if(argsLen == paramsLen) { + final Class callSiteLastArgType = callSiteType.parameterType(fixParamsLen); + if(varArgType.isAssignableFrom(callSiteLastArgType)) { + // Call site signature guarantees we'll always be passed a single compatible array; just link directly + // to the method, introducing necessary conversions. Also, preserve it being a variable arity method. + return createConvertingInvocation(target, linkerServices, callSiteType).asVarargsCollector( + callSiteLastArgType); + } + if(!linkerServices.canConvert(callSiteLastArgType, varArgType)) { + // Call site signature guarantees the argument can definitely not be an array (i.e. it is primitive); + // link immediately to a vararg-packing method handle. + return createConvertingInvocation(collectArguments(fixTarget, argsLen), linkerServices, callSiteType); + } + // Call site signature makes no guarantees that the single argument in the vararg position will be + // compatible across all invocations. Need to insert an appropriate guard and fall back to generic vararg + // method when it is not. + return MethodHandles.guardWithTest(Guards.isInstance(varArgType, fixParamsLen, callSiteType), + createConvertingInvocation(fixTarget, linkerServices, callSiteType), + createConvertingInvocation(collectArguments(fixTarget, argsLen), linkerServices, callSiteType)); + } + + // Remaining case: more than one vararg. + return createConvertingInvocation(collectArguments(fixTarget, argsLen), linkerServices, callSiteType); + } + + /** + * Creates a method handle out of the original target that will collect the varargs for the exact component type of + * the varArg array. Note that this will nicely trigger language-specific type converters for exactly those varargs + * for which it is necessary when later passed to linkerServices.convertArguments(). + * + * @param target the original method handle + * @param parameterCount the total number of arguments in the new method handle + * @return a collecting method handle + */ + static MethodHandle collectArguments(MethodHandle target, final int parameterCount) { + final MethodType methodType = target.type(); + final int fixParamsLen = methodType.parameterCount() - 1; + final Class arrayType = methodType.parameterType(fixParamsLen); + return target.asCollector(arrayType, parameterCount - fixParamsLen); + } + + private static MethodHandle createConvertingInvocation(final MethodHandle sizedMethod, + final LinkerServices linkerServices, final MethodType callSiteType) { + return linkerServices.asType(sizedMethod, callSiteType); + } + + private static boolean typeMatchesDescription(String paramTypes, MethodType type) { + final StringTokenizer tok = new StringTokenizer(paramTypes, ", "); + for(int i = 1; i < type.parameterCount(); ++i) { // i = 1 as we ignore the receiver + if(!(tok.hasMoreTokens() && typeNameMatches(tok.nextToken(), type.parameterType(i)))) { + return false; + } + } + return !tok.hasMoreTokens(); + } + + private static boolean typeNameMatches(String typeName, Class type) { + return typeName.equals(typeName.indexOf('.') == -1 ? type.getSimpleName() : type.getCanonicalName()); + } +} diff --git a/nashorn/src/jdk/internal/dynalink/beans/StaticClassIntrospector.java b/nashorn/src/jdk/internal/dynalink/beans/StaticClassIntrospector.java index 214152a41ec..62ce41a95a6 100644 --- a/nashorn/src/jdk/internal/dynalink/beans/StaticClassIntrospector.java +++ b/nashorn/src/jdk/internal/dynalink/beans/StaticClassIntrospector.java @@ -106,10 +106,18 @@ class StaticClassIntrospector extends FacetIntrospector { @Override MethodHandle editMethodHandle(MethodHandle mh) { + return editStaticMethodHandle(mh); + } + + static MethodHandle editStaticMethodHandle(MethodHandle mh) { return dropReceiver(mh, Object.class); } - static MethodHandle dropReceiver(final MethodHandle mh, final Class receiverClass) { + static MethodHandle editConstructorMethodHandle(MethodHandle cmh) { + return dropReceiver(cmh, StaticClass.class); + } + + private static MethodHandle dropReceiver(final MethodHandle mh, final Class receiverClass) { MethodHandle newHandle = MethodHandles.dropArguments(mh, 0, receiverClass); // NOTE: this is a workaround for the fact that dropArguments doesn't preserve vararg collector state. if(mh.isVarargsCollector() && !newHandle.isVarargsCollector()) { diff --git a/nashorn/src/jdk/internal/dynalink/beans/StaticClassLinker.java b/nashorn/src/jdk/internal/dynalink/beans/StaticClassLinker.java index d6096fe559b..8cd221f3df4 100644 --- a/nashorn/src/jdk/internal/dynalink/beans/StaticClassLinker.java +++ b/nashorn/src/jdk/internal/dynalink/beans/StaticClassLinker.java @@ -87,9 +87,7 @@ import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.reflect.Array; -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.List; +import java.util.Arrays; import jdk.internal.dynalink.CallSiteDescriptor; import jdk.internal.dynalink.beans.GuardedInvocationComponent.ValidationType; import jdk.internal.dynalink.linker.GuardedInvocation; @@ -131,20 +129,11 @@ class StaticClassLinker implements TypeBasedGuardingDynamicLinker { private static DynamicMethod createConstructorMethod(Class clazz) { if(clazz.isArray()) { final MethodHandle boundArrayCtor = ARRAY_CTOR.bindTo(clazz.getComponentType()); - return new SimpleDynamicMethod(drop(boundArrayCtor.asType(boundArrayCtor.type().changeReturnType( - clazz))), clazz, ""); + return new SimpleDynamicMethod(StaticClassIntrospector.editConstructorMethodHandle( + boundArrayCtor.asType(boundArrayCtor.type().changeReturnType(clazz))), clazz, ""); } - final Constructor[] ctrs = clazz.getConstructors(); - final List mhs = new ArrayList<>(ctrs.length); - for(int i = 0; i < ctrs.length; ++i) { - mhs.add(drop(SafeUnreflector.unreflectConstructor(ctrs[i]))); - } - return createDynamicMethod(mhs, clazz, ""); - } - - private static MethodHandle drop(MethodHandle mh) { - return StaticClassIntrospector.dropReceiver(mh, StaticClass.class); + return createDynamicMethod(Arrays.asList(clazz.getConstructors()), clazz, ""); } @Override @@ -161,11 +150,10 @@ class StaticClassLinker implements TypeBasedGuardingDynamicLinker { } final CallSiteDescriptor desc = request.getCallSiteDescriptor(); final String op = desc.getNameToken(CallSiteDescriptor.OPERATOR); - final MethodType methodType = desc.getMethodType(); if("new" == op && constructor != null) { - final MethodHandle ctorInvocation = constructor.getInvocation(methodType, linkerServices); + final MethodHandle ctorInvocation = constructor.getInvocation(desc, linkerServices); if(ctorInvocation != null) { - return new GuardedInvocation(ctorInvocation, getClassGuard(methodType)); + return new GuardedInvocation(ctorInvocation, getClassGuard(desc.getMethodType())); } } return null; diff --git a/nashorn/src/jdk/internal/dynalink/support/AbstractCallSiteDescriptor.java b/nashorn/src/jdk/internal/dynalink/support/AbstractCallSiteDescriptor.java index e51f6fe2f2a..3161cf50a76 100644 --- a/nashorn/src/jdk/internal/dynalink/support/AbstractCallSiteDescriptor.java +++ b/nashorn/src/jdk/internal/dynalink/support/AbstractCallSiteDescriptor.java @@ -139,8 +139,9 @@ public abstract class AbstractCallSiteDescriptor implements CallSiteDescriptor { @Override public int hashCode() { + final MethodHandles.Lookup lookup = getLookup(); + int h = lookup.lookupClass().hashCode() + 31 * lookup.lookupModes(); final int c = getNameTokenCount(); - int h = 0; for(int i = 0; i < c; ++i) { h = h * 31 + getNameToken(i).hashCode(); } diff --git a/nashorn/src/jdk/internal/dynalink/support/Lookup.java b/nashorn/src/jdk/internal/dynalink/support/Lookup.java index 52a610246a8..4b21e1c4af4 100644 --- a/nashorn/src/jdk/internal/dynalink/support/Lookup.java +++ b/nashorn/src/jdk/internal/dynalink/support/Lookup.java @@ -122,6 +122,18 @@ public class Lookup { * @return the unreflected method handle. */ public MethodHandle unreflect(Method m) { + return unreflect(lookup, m); + } + + /** + * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflect(Method)}, converting any encountered + * {@link IllegalAccessException} into an {@link IllegalAccessError}. + * + * @param lookup the lookup used to unreflect + * @param m the method to unreflect + * @return the unreflected method handle. + */ + public static MethodHandle unreflect(MethodHandles.Lookup lookup, Method m) { try { return lookup.unreflect(m); } catch(IllegalAccessException e) { @@ -131,7 +143,6 @@ public class Lookup { } } - /** * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter(Field)}, converting any encountered * {@link IllegalAccessException} into an {@link IllegalAccessError}. @@ -202,6 +213,18 @@ public class Lookup { * @return the unreflected constructor handle. */ public MethodHandle unreflectConstructor(Constructor c) { + return unreflectConstructor(lookup, c); + } + + /** + * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor(Constructor)}, converting any + * encountered {@link IllegalAccessException} into an {@link IllegalAccessError}. + * + * @param lookup the lookup used to unreflect + * @param c the constructor to unreflect + * @return the unreflected constructor handle. + */ + public static MethodHandle unreflectConstructor(MethodHandles.Lookup lookup, Constructor c) { try { return lookup.unreflectConstructor(c); } catch(IllegalAccessException e) { diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java index 6b55656ba17..3f3c2a5b8b3 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java @@ -78,7 +78,7 @@ public final class Bootstrap { * @return CallSite with MethodHandle to appropriate method or null if not found. */ public static CallSite bootstrap(final Lookup lookup, final String opDesc, final MethodType type, final int flags) { - return dynamicLinker.link(LinkerCallSite.newLinkerCallSite(opDesc, type, flags)); + return dynamicLinker.link(LinkerCallSite.newLinkerCallSite(lookup, opDesc, type, flags)); } /** @@ -94,12 +94,12 @@ public final class Bootstrap { return new RuntimeCallSite(type, initialName); } - /** - * Returns a dynamic invoker for a specified dynamic operation. You can use this method to create a method handle - * that when invoked acts completely as if it were a Nashorn-linked call site. An overview of available dynamic - * operations can be found in the Dynalink User Guide, - * but we'll show few examples here: + * Returns a dynamic invoker for a specified dynamic operation using the public lookup. You can use this method to + * create a method handle that when invoked acts completely as if it were a Nashorn-linked call site. An overview of + * available dynamic operations can be found in the + * Dynalink User Guide, but we'll show few + * examples here: *
    *
  • Get a named property with fixed name: *
    @@ -196,7 +196,7 @@ public final class Bootstrap {
         }
     
         /**
    -     * Returns a dynamic invoker for a specified dynamic operation. Similar to
    +     * Returns a dynamic invoker for a specified dynamic operation using the public lookup. Similar to
          * {@link #createDynamicInvoker(String, Class, Class...)} but with return and parameter types composed into a
          * method type in the signature. See the discussion of that method for details.
          * @param opDesc Dynalink dynamic operation descriptor.
    @@ -204,7 +204,7 @@ public final class Bootstrap {
          * @return MethodHandle for invoking the operation.
          */
         public static MethodHandle createDynamicInvoker(final String opDesc, final MethodType type) {
    -        return bootstrap(null, opDesc, type, 0).dynamicInvoker();
    +        return bootstrap(MethodHandles.publicLookup(), opDesc, type, 0).dynamicInvoker();
         }
     
         /**
    diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java
    index ecec63bcbad..f207d37cf66 100644
    --- a/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java
    +++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java
    @@ -28,6 +28,7 @@ package jdk.nashorn.internal.runtime.linker;
     import static jdk.nashorn.internal.lookup.Lookup.MH;
     
     import java.lang.invoke.MethodHandle;
    +import java.lang.invoke.MethodHandles;
     import java.lang.invoke.MethodType;
     import java.lang.reflect.Modifier;
     import java.security.AccessController;
    @@ -39,7 +40,6 @@ import java.util.Collections;
     import java.util.HashMap;
     import java.util.List;
     import java.util.Map;
    -
     import jdk.internal.dynalink.beans.StaticClass;
     import jdk.internal.dynalink.support.LinkRequestImpl;
     import jdk.nashorn.internal.objects.NativeJava;
    @@ -119,9 +119,12 @@ public final class JavaAdapterFactory {
             return AccessController.doPrivileged(new PrivilegedExceptionAction() {
                 @Override
                 public MethodHandle run() throws Exception {
    -                return  MH.bindTo(Bootstrap.getLinkerServices().getGuardedInvocation(new LinkRequestImpl(NashornCallSiteDescriptor.get(
    -                    "dyn:new", MethodType.methodType(targetType, StaticClass.class, sourceType), 0), false,
    -                    adapterClass, null)).getInvocation(), adapterClass);
    +                // NOTE: we use publicLookup(), but none of our adapter constructors are caller sensitive, so this is
    +                // okay, we won't artificially limit access.
    +                return  MH.bindTo(Bootstrap.getLinkerServices().getGuardedInvocation(new LinkRequestImpl(
    +                        NashornCallSiteDescriptor.get(MethodHandles.publicLookup(),  "dyn:new",
    +                                MethodType.methodType(targetType, StaticClass.class, sourceType), 0), false,
    +                                adapterClass, null)).getInvocation(), adapterClass);
                 }
             });
         }
    diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/LinkerCallSite.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/LinkerCallSite.java
    index 7457641e987..5665f02f3e4 100644
    --- a/nashorn/src/jdk/nashorn/internal/runtime/linker/LinkerCallSite.java
    +++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/LinkerCallSite.java
    @@ -25,7 +25,6 @@
     
     package jdk.nashorn.internal.runtime.linker;
     
    -import jdk.nashorn.internal.lookup.MethodHandleFactory;
     import static jdk.nashorn.internal.lookup.Lookup.MH;
     
     import java.io.FileNotFoundException;
    @@ -47,6 +46,7 @@ import java.util.concurrent.atomic.AtomicInteger;
     import jdk.internal.dynalink.ChainedCallSite;
     import jdk.internal.dynalink.DynamicLinker;
     import jdk.internal.dynalink.linker.GuardedInvocation;
    +import jdk.nashorn.internal.lookup.MethodHandleFactory;
     import jdk.nashorn.internal.runtime.Context;
     import jdk.nashorn.internal.runtime.Debug;
     import jdk.nashorn.internal.runtime.ScriptObject;
    @@ -79,8 +79,9 @@ public class LinkerCallSite extends ChainedCallSite {
          * @param flags    Call site specific flags.
          * @return New LinkerCallSite.
          */
    -    static LinkerCallSite newLinkerCallSite(final String name, final MethodType type, final int flags) {
    -        final NashornCallSiteDescriptor desc = NashornCallSiteDescriptor.get(name, type, flags);
    +    static LinkerCallSite newLinkerCallSite(final MethodHandles.Lookup lookup, final String name, final MethodType type,
    +            final int flags) {
    +        final NashornCallSiteDescriptor desc = NashornCallSiteDescriptor.get(lookup, name, type, flags);
     
             if (desc.isProfile()) {
                 return ProfilingLinkerCallSite.newProfilingLinkerCallSite(desc);
    diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornCallSiteDescriptor.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornCallSiteDescriptor.java
    index 8cb360c4fcf..58ef2703882 100644
    --- a/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornCallSiteDescriptor.java
    +++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornCallSiteDescriptor.java
    @@ -25,9 +25,12 @@
     
     package jdk.nashorn.internal.runtime.linker;
     
    +import java.lang.invoke.MethodHandles;
    +import java.lang.invoke.MethodHandles.Lookup;
     import java.lang.invoke.MethodType;
    -import java.lang.ref.WeakReference;
    -import java.util.WeakHashMap;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.ConcurrentMap;
     import jdk.internal.dynalink.CallSiteDescriptor;
     import jdk.internal.dynalink.support.AbstractCallSiteDescriptor;
     import jdk.internal.dynalink.support.CallSiteDescriptorFactory;
    @@ -70,9 +73,15 @@ public class NashornCallSiteDescriptor extends AbstractCallSiteDescriptor {
          * set. */
         public static final int CALLSITE_TRACE_SCOPE      = 0x200;
     
    -    private static final WeakHashMap> canonicals =
    -            new WeakHashMap<>();
    +    private static final ClassValue> canonicals =
    +            new ClassValue>() {
    +        @Override
    +        protected ConcurrentMap computeValue(Class type) {
    +            return new ConcurrentHashMap<>();
    +        }
    +    };
     
    +    private final MethodHandles.Lookup lookup;
         private final String operator;
         private final String operand;
         private final MethodType methodType;
    @@ -81,39 +90,35 @@ public class NashornCallSiteDescriptor extends AbstractCallSiteDescriptor {
         /**
          * Retrieves a Nashorn call site descriptor with the specified values. Since call site descriptors are immutable
          * this method is at liberty to retrieve canonicalized instances (although it is not guaranteed it will do so).
    +     * @param lookup the lookup describing the script
          * @param name the name at the call site, e.g. {@code "dyn:getProp|getElem|getMethod:color"}.
          * @param methodType the method type at the call site
          * @param flags Nashorn-specific call site flags
          * @return a call site descriptor with the specified values.
          */
    -    public static NashornCallSiteDescriptor get(final String name, final MethodType methodType, final int flags) {
    +    public static NashornCallSiteDescriptor get(final MethodHandles.Lookup lookup, final String name,
    +            final MethodType methodType, final int flags) {
             final String[] tokenizedName = CallSiteDescriptorFactory.tokenizeName(name);
             assert tokenizedName.length == 2 || tokenizedName.length == 3;
             assert "dyn".equals(tokenizedName[0]);
             assert tokenizedName[1] != null;
             // TODO: see if we can move mangling/unmangling into Dynalink
    -        return get(tokenizedName[1], tokenizedName.length == 3 ? tokenizedName[2].intern() : null,
    +        return get(lookup, tokenizedName[1], tokenizedName.length == 3 ? tokenizedName[2].intern() : null,
                     methodType, flags);
         }
     
    -    private static NashornCallSiteDescriptor get(final String operator, final String operand, final MethodType methodType, final int flags) {
    -        final NashornCallSiteDescriptor csd = new NashornCallSiteDescriptor(operator, operand, methodType, flags);
    +    private static NashornCallSiteDescriptor get(final MethodHandles.Lookup lookup, final String operator, final String operand, final MethodType methodType, final int flags) {
    +        final NashornCallSiteDescriptor csd = new NashornCallSiteDescriptor(lookup, operator, operand, methodType, flags);
             // Many of these call site descriptors are identical (e.g. every getter for a property color will be
    -        // "dyn:getProp:color(Object)Object", so it makes sense canonicalizing them in a weak map
    -        synchronized(canonicals) {
    -            final WeakReference ref = canonicals.get(csd);
    -            if(ref != null) {
    -                final NashornCallSiteDescriptor canonical = ref.get();
    -                if(canonical != null) {
    -                    return canonical;
    -                }
    -            }
    -            canonicals.put(csd, new WeakReference<>(csd));
    -        }
    -        return csd;
    +        // "dyn:getProp:color(Object)Object", so it makes sense canonicalizing them.
    +        final Map classCanonicals = canonicals.get(lookup.lookupClass());
    +        final NashornCallSiteDescriptor canonical = classCanonicals.putIfAbsent(csd, csd);
    +        return canonical != null ? canonical : csd;
         }
     
    -    private NashornCallSiteDescriptor(final String operator, final String operand, final MethodType methodType, final int flags) {
    +    private NashornCallSiteDescriptor(final MethodHandles.Lookup lookup, final String operator, final String operand,
    +            final MethodType methodType, final int flags) {
    +        this.lookup = lookup;
             this.operator = operator;
             this.operand = operand;
             this.methodType = methodType;
    @@ -141,6 +146,11 @@ public class NashornCallSiteDescriptor extends AbstractCallSiteDescriptor {
             throw new IndexOutOfBoundsException(String.valueOf(i));
         }
     
    +    @Override
    +    public Lookup getLookup() {
    +        return lookup;
    +    }
    +
         @Override
         public boolean equals(final CallSiteDescriptor csd) {
             return super.equals(csd) && flags == getFlags(csd);
    @@ -279,6 +289,6 @@ public class NashornCallSiteDescriptor extends AbstractCallSiteDescriptor {
     
         @Override
         public CallSiteDescriptor changeMethodType(final MethodType newMethodType) {
    -        return get(operator, operand, newMethodType, flags);
    +        return get(getLookup(), operator, operand, newMethodType, flags);
         }
     }
    diff --git a/nashorn/test/script/basic/JDK-8010946-2.js b/nashorn/test/script/basic/JDK-8010946-2.js
    new file mode 100644
    index 00000000000..c3dc2889a6c
    --- /dev/null
    +++ b/nashorn/test/script/basic/JDK-8010946-2.js
    @@ -0,0 +1,38 @@
    +/*
    + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * 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.
    + */
    +
    +/**
    + * JDK-8010946: AccessController.doPrivileged() doesn't work as expected.
    + * This is actually a broader issue of having Dynalink correctly handle
    + * caller-sensitive methods.
    + *
    + * @test
    + * @run
    + */
    +
    +// Ensure these are CallerSensitiveDynamicMethods
    +print(java.security.AccessController["doPrivileged(PrivilegedAction)"])
    +print(java.lang.Class["forName(String)"])
    +
    +// Ensure this is not
    +print(java.lang.String["valueOf(char)"])
    diff --git a/nashorn/test/script/basic/JDK-8010946-2.js.EXPECTED b/nashorn/test/script/basic/JDK-8010946-2.js.EXPECTED
    new file mode 100644
    index 00000000000..d573510c9de
    --- /dev/null
    +++ b/nashorn/test/script/basic/JDK-8010946-2.js.EXPECTED
    @@ -0,0 +1,3 @@
    +[jdk.internal.dynalink.beans.CallerSensitiveDynamicMethod Object java.security.AccessController.doPrivileged(PrivilegedAction)]
    +[jdk.internal.dynalink.beans.CallerSensitiveDynamicMethod Class java.lang.Class.forName(String)]
    +[jdk.internal.dynalink.beans.SimpleDynamicMethod String java.lang.String.valueOf(char)]
    diff --git a/nashorn/test/script/basic/JDK-8010946-privileged.js b/nashorn/test/script/basic/JDK-8010946-privileged.js
    new file mode 100644
    index 00000000000..fc409f97172
    --- /dev/null
    +++ b/nashorn/test/script/basic/JDK-8010946-privileged.js
    @@ -0,0 +1,47 @@
    +/*
    + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * 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.
    + */
    +
    +/**
    + * JDK-8010946: AccessController.doPrivileged() doesn't work as expected.
    + * This is actually a broader issue of having Dynalink correctly handle
    + * caller-sensitive methods.
    + * 
    + * NOTE: This is not a standalone test file, it is loaded by JDK-801946.js
    + * @subtest
    + */
    +
    +(function() {
    +    var getProperty = java.lang.System.getProperty
    +    var doPrivileged = java.security.AccessController["doPrivileged(PrivilegedAction)"]
    +
    +    this.executeUnprivileged = function() {
    +        var x = getProperty("java.security.policy")
    +        if(x != null) {
    +            print("Successfully retrieved restricted system property.")
    +        }
    +    }
    +
    +    this.executePrivileged = function() {
    +        doPrivileged(executeUnprivileged)
    +    }
    +})();
    diff --git a/nashorn/test/script/basic/JDK-8010946.js b/nashorn/test/script/basic/JDK-8010946.js
    new file mode 100644
    index 00000000000..4f0124273e0
    --- /dev/null
    +++ b/nashorn/test/script/basic/JDK-8010946.js
    @@ -0,0 +1,51 @@
    +/*
    + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * 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.
    + */
    +
    +/**
    + * JDK-8010946: AccessController.doPrivileged() doesn't work as expected.
    + * This is actually a broader issue of having Dynalink correctly handle
    + * caller-sensitive methods.
    + *
    + * @test
    + * @run
    + */
    +
    +// This is unprivileged code that loads privileged code.
    +load(__DIR__ + "JDK-8010946-privileged.js")
    +
    +try {
    +    // This should fail, even though the code itself resides in the 
    +    // privileged script, as we're invoking it without going through
    +    // doPrivileged()
    +    print("Attempting unprivileged execution...")
    +    executeUnprivileged()
    +    print("FAIL: Unprivileged execution succeeded!")
    +} catch(e) {
    +    print("Unprivileged execution failed with " + e)
    +}
    +
    +print()
    +
    +// This should succeed, as it's going through doPrivileged().
    +print("Attempting privileged execution...")
    +executePrivileged()
    diff --git a/nashorn/test/script/basic/JDK-8010946.js.EXPECTED b/nashorn/test/script/basic/JDK-8010946.js.EXPECTED
    new file mode 100644
    index 00000000000..f78956a884b
    --- /dev/null
    +++ b/nashorn/test/script/basic/JDK-8010946.js.EXPECTED
    @@ -0,0 +1,5 @@
    +Attempting unprivileged execution...
    +Unprivileged execution failed with java.security.AccessControlException: access denied ("java.util.PropertyPermission" "java.security.policy" "read")
    +
    +Attempting privileged execution...
    +Successfully retrieved restricted system property.
    
    From 62fb002570c159e70c4533eea2436200ece9ab27 Mon Sep 17 00:00:00 2001
    From: Marcus Lagergren 
    Date: Wed, 3 Jul 2013 13:03:36 +0200
    Subject: [PATCH 010/123] 8019585: Sometimes a var declaration using itself in
     its init wasn't declared as canBeUndefined, causing erroneous bytecode
    
    Reviewed-by: sundar, attila
    ---
     .../api/scripting/NashornException.java       |  4 +--
     .../jdk/nashorn/internal/codegen/Attr.java    | 19 ++++++++++-
     .../internal/codegen/CodeGenerator.java       |  2 +-
     .../internal/objects/ArrayBufferView.java     |  1 +
     .../jdk/nashorn/internal/objects/Global.java  |  1 +
     .../nashorn/internal/objects/NativeError.java |  5 +--
     .../internal/objects/NativeFloat32Array.java  |  1 +
     .../internal/objects/NativeFloat64Array.java  |  1 +
     .../internal/objects/NativeFunction.java      |  2 ++
     .../internal/objects/NativeInt16Array.java    |  1 +
     .../internal/objects/NativeInt32Array.java    |  1 +
     .../internal/objects/NativeInt8Array.java     |  1 +
     .../nashorn/internal/objects/NativeJava.java  |  2 ++
     .../internal/objects/NativeObject.java        |  2 +-
     .../internal/objects/NativeRegExp.java        |  1 +
     .../internal/objects/NativeUint16Array.java   |  1 +
     .../internal/objects/NativeUint32Array.java   |  1 +
     .../internal/objects/NativeUint8Array.java    |  1 +
     .../objects/NativeUint8ClampedArray.java      |  1 +
     .../internal/objects/ScriptFunctionImpl.java  |  9 ++---
     .../runtime/arrays/ObjectArrayData.java       |  2 +-
     nashorn/test/script/basic/JDK-8019585.js      | 34 +++++++++++++++++++
     22 files changed, 81 insertions(+), 12 deletions(-)
     create mode 100644 nashorn/test/script/basic/JDK-8019585.js
    
    diff --git a/nashorn/src/jdk/nashorn/api/scripting/NashornException.java b/nashorn/src/jdk/nashorn/api/scripting/NashornException.java
    index 3cd687cce08..d5ec5bb4a60 100644
    --- a/nashorn/src/jdk/nashorn/api/scripting/NashornException.java
    +++ b/nashorn/src/jdk/nashorn/api/scripting/NashornException.java
    @@ -146,7 +146,7 @@ public abstract class NashornException extends RuntimeException {
          * @return array of javascript stack frames
          */
         public static StackTraceElement[] getScriptFrames(final Throwable exception) {
    -        final StackTraceElement[] frames = ((Throwable)exception).getStackTrace();
    +        final StackTraceElement[] frames = exception.getStackTrace();
             final List filtered = new ArrayList<>();
             for (final StackTraceElement st : frames) {
                 if (ECMAErrors.isScriptFrame(st)) {
    @@ -170,7 +170,7 @@ public abstract class NashornException extends RuntimeException {
          */
         public static String getScriptStackString(final Throwable exception) {
             final StringBuilder buf = new StringBuilder();
    -        final StackTraceElement[] frames = getScriptFrames((Throwable)exception);
    +        final StackTraceElement[] frames = getScriptFrames(exception);
             for (final StackTraceElement st : frames) {
                 buf.append("\tat ");
                 buf.append(st.getMethodName());
    diff --git a/nashorn/src/jdk/nashorn/internal/codegen/Attr.java b/nashorn/src/jdk/nashorn/internal/codegen/Attr.java
    index d4b3405fb26..e9cc259fb3d 100644
    --- a/nashorn/src/jdk/nashorn/internal/codegen/Attr.java
    +++ b/nashorn/src/jdk/nashorn/internal/codegen/Attr.java
    @@ -54,6 +54,7 @@ import java.util.HashSet;
     import java.util.Iterator;
     import java.util.List;
     import java.util.Set;
    +
     import jdk.nashorn.internal.codegen.types.Type;
     import jdk.nashorn.internal.ir.AccessNode;
     import jdk.nashorn.internal.ir.BinaryNode;
    @@ -234,10 +235,25 @@ final class Attr extends NodeOperatorVisitor {
                 @Override
                 public boolean enterVarNode(final VarNode varNode) {
                     final String name = varNode.getName().getName();
    -                //if this is used the var node symbol needs to be tagged as can be undefined
    +                //if this is used before the var node, the var node symbol needs to be tagged as can be undefined
                     if (uses.contains(name)) {
                         canBeUndefined.add(name);
                     }
    +
    +                // all uses of the declared varnode inside the var node are potentially undefined
    +                // however this is a bit conservative as e.g. var x = 17; var x = 1 + x; does work
    +                if (!varNode.isFunctionDeclaration() && varNode.getInit() != null) {
    +                    varNode.getInit().accept(new NodeVisitor(new LexicalContext()) {
    +                       @Override
    +                       public boolean enterIdentNode(final IdentNode identNode) {
    +                           if (name.equals(identNode.getName())) {
    +                              canBeUndefined.add(name);
    +                           }
    +                           return false;
    +                       }
    +                    });
    +                }
    +
                     return true;
                 }
     
    @@ -257,6 +273,7 @@ final class Attr extends NodeOperatorVisitor {
                         }
                         return varNode.setName((IdentNode)ident.setSymbol(lc, symbol));
                     }
    +
                     return varNode;
                 }
             });
    diff --git a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java
    index d0bf7cd563e..6ea53a408fa 100644
    --- a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java
    +++ b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java
    @@ -1847,7 +1847,7 @@ final class CodeGenerator extends NodeOperatorVisitor exprClass = type.getTypeClass();
                     method.invoke(staticCallNoLookup(ScriptRuntime.class, "switchTagAsInt", int.class, exprClass.isPrimitive()? exprClass : Object.class, int.class));
                 }
     
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/ArrayBufferView.java b/nashorn/src/jdk/nashorn/internal/objects/ArrayBufferView.java
    index 312d521c65e..6e58c4cdbae 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/ArrayBufferView.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/ArrayBufferView.java
    @@ -40,6 +40,7 @@ import static jdk.nashorn.internal.runtime.ECMAErrors.rangeError;
     abstract class ArrayBufferView extends ScriptObject {
     
         // initialized by nasgen
    +    @SuppressWarnings("unused")
         private static PropertyMap $nasgenmap$;
     
         ArrayBufferView(final NativeArrayBuffer buffer, final int byteOffset, final int elementLength) {
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/Global.java b/nashorn/src/jdk/nashorn/internal/objects/Global.java
    index 5644c510642..f1b65e5cb02 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/Global.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/Global.java
    @@ -382,6 +382,7 @@ public final class Global extends ScriptObject implements GlobalObject, Scope {
         private final Context context;
     
         // initialized by nasgen
    +    @SuppressWarnings("unused")
         private static PropertyMap $nasgenmap$;
     
         /**
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeError.java b/nashorn/src/jdk/nashorn/internal/objects/NativeError.java
    index 07f5d65aa7b..b8f69c502e4 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/NativeError.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeError.java
    @@ -119,6 +119,7 @@ public final class NativeError extends ScriptObject {
          * Nashorn extension: Error.captureStackTrace. Capture stack trace at the point of call into the Error object provided.
          *
          * @param self self reference
    +     * @param errorObj the error object
          * @return undefined
          */
         @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
    @@ -286,9 +287,9 @@ public final class NativeError extends ScriptObject {
             final Object exception = ECMAException.getException(sobj);
             if (exception instanceof Throwable) {
                 return getScriptStackString(sobj, (Throwable)exception);
    -        } else {
    -            return "";
             }
    +
    +        return "";
         }
     
         /**
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeFloat32Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeFloat32Array.java
    index beb7d50e542..852f448dd1e 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/NativeFloat32Array.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeFloat32Array.java
    @@ -48,6 +48,7 @@ public final class NativeFloat32Array extends ArrayBufferView {
         public static final int BYTES_PER_ELEMENT = 4;
     
         // initialized by nasgen
    +    @SuppressWarnings("unused")
         private static PropertyMap $nasgenmap$;
     
         private static final Factory FACTORY = new Factory(BYTES_PER_ELEMENT) {
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeFloat64Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeFloat64Array.java
    index 3451e31527c..4ea52991243 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/NativeFloat64Array.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeFloat64Array.java
    @@ -48,6 +48,7 @@ public final class NativeFloat64Array extends ArrayBufferView {
         public static final int BYTES_PER_ELEMENT = 8;
     
         // initialized by nasgen
    +    @SuppressWarnings("unused")
         private static PropertyMap $nasgenmap$;
     
         private static final Factory FACTORY = new Factory(BYTES_PER_ELEMENT) {
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeFunction.java b/nashorn/src/jdk/nashorn/internal/objects/NativeFunction.java
    index 7df1b521027..5e5f42f0475 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/NativeFunction.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeFunction.java
    @@ -29,6 +29,7 @@ import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
     import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
     
     import java.util.List;
    +
     import jdk.nashorn.api.scripting.ScriptObjectMirror;
     import jdk.nashorn.internal.objects.annotations.Attribute;
     import jdk.nashorn.internal.objects.annotations.Constructor;
    @@ -55,6 +56,7 @@ import jdk.nashorn.internal.runtime.Source;
     public final class NativeFunction {
     
         // initialized by nasgen
    +    @SuppressWarnings("unused")
         private static PropertyMap $nasgenmap$;
     
         // do *not* create me!
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeInt16Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeInt16Array.java
    index d05c69d70a5..24b2383756c 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/NativeInt16Array.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeInt16Array.java
    @@ -42,6 +42,7 @@ import jdk.nashorn.internal.runtime.arrays.ArrayData;
     public final class NativeInt16Array extends ArrayBufferView {
     
         // initialized by nasgen
    +    @SuppressWarnings("unused")
         private static PropertyMap $nasgenmap$;
     
         /**
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeInt32Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeInt32Array.java
    index 596b935cb7d..a89d8350a50 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/NativeInt32Array.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeInt32Array.java
    @@ -47,6 +47,7 @@ public final class NativeInt32Array extends ArrayBufferView {
         public static final int BYTES_PER_ELEMENT = 4;
     
         // initialized by nasgen
    +    @SuppressWarnings("unused")
         private static PropertyMap $nasgenmap$;
     
         private static final Factory FACTORY = new Factory(BYTES_PER_ELEMENT) {
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeInt8Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeInt8Array.java
    index f1a9b7f7100..316fdab50d8 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/NativeInt8Array.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeInt8Array.java
    @@ -47,6 +47,7 @@ public final class NativeInt8Array extends ArrayBufferView {
         public static final int BYTES_PER_ELEMENT = 1;
     
         // initialized by nasgen
    +    @SuppressWarnings("unused")
         private static PropertyMap $nasgenmap$;
     
         private static final Factory FACTORY = new Factory(BYTES_PER_ELEMENT) {
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeJava.java b/nashorn/src/jdk/nashorn/internal/objects/NativeJava.java
    index 7a9ec38fe87..288770b45ef 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/NativeJava.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeJava.java
    @@ -32,6 +32,7 @@ import java.lang.reflect.Array;
     import java.util.Collection;
     import java.util.Deque;
     import java.util.List;
    +
     import jdk.internal.dynalink.beans.StaticClass;
     import jdk.internal.dynalink.support.TypeUtilities;
     import jdk.nashorn.internal.objects.annotations.Attribute;
    @@ -54,6 +55,7 @@ import jdk.nashorn.internal.runtime.linker.JavaAdapterFactory;
     public final class NativeJava {
     
         // initialized by nasgen
    +    @SuppressWarnings("unused")
         private static PropertyMap $nasgenmap$;
     
         private NativeJava() {
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java b/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java
    index 1034034506b..7112557e1d0 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java
    @@ -27,7 +27,6 @@ package jdk.nashorn.internal.objects;
     
     import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
     import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
    -
     import jdk.nashorn.api.scripting.ScriptObjectMirror;
     import jdk.nashorn.internal.objects.annotations.Attribute;
     import jdk.nashorn.internal.objects.annotations.Constructor;
    @@ -55,6 +54,7 @@ public final class NativeObject {
         private static final InvokeByName TO_STRING = new InvokeByName("toString", ScriptObject.class);
     
         // initialized by nasgen
    +    @SuppressWarnings("unused")
         private static PropertyMap $nasgenmap$;
     
         private NativeObject() {
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java b/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java
    index bec8b37db0a..1ba8b4df01b 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java
    @@ -68,6 +68,7 @@ public final class NativeRegExp extends ScriptObject {
         private Global globalObject;
     
         // initialized by nasgen
    +    @SuppressWarnings("unused")
         private static PropertyMap $nasgenmap$;
     
         NativeRegExp(final String input, final String flagString) {
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeUint16Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeUint16Array.java
    index 39c19131280..d19e787195d 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/NativeUint16Array.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeUint16Array.java
    @@ -47,6 +47,7 @@ public final class NativeUint16Array extends ArrayBufferView {
         public static final int BYTES_PER_ELEMENT = 2;
     
         // initialized by nasgen
    +    @SuppressWarnings("unused")
         private static PropertyMap $nasgenmap$;
     
         private static final Factory FACTORY = new Factory(BYTES_PER_ELEMENT) {
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeUint32Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeUint32Array.java
    index 37102bae590..87a383cb555 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/NativeUint32Array.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeUint32Array.java
    @@ -48,6 +48,7 @@ public final class NativeUint32Array extends ArrayBufferView {
         public static final int BYTES_PER_ELEMENT = 4;
     
         // initialized by nasgen
    +    @SuppressWarnings("unused")
         private static PropertyMap $nasgenmap$;
     
         private static final Factory FACTORY = new Factory(BYTES_PER_ELEMENT) {
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeUint8Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeUint8Array.java
    index aa6f89bec67..6ae786f3fda 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/NativeUint8Array.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeUint8Array.java
    @@ -47,6 +47,7 @@ public final class NativeUint8Array extends ArrayBufferView {
         public static final int BYTES_PER_ELEMENT = 1;
     
         // initialized by nasgen
    +    @SuppressWarnings("unused")
         private static PropertyMap $nasgenmap$;
     
         private static final Factory FACTORY = new Factory(BYTES_PER_ELEMENT) {
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeUint8ClampedArray.java b/nashorn/src/jdk/nashorn/internal/objects/NativeUint8ClampedArray.java
    index 4467c856f06..02b7a4edcd0 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/NativeUint8ClampedArray.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeUint8ClampedArray.java
    @@ -48,6 +48,7 @@ public final class NativeUint8ClampedArray extends ArrayBufferView {
         public static final int BYTES_PER_ELEMENT = 1;
     
         // initialized by nasgen
    +    @SuppressWarnings("unused")
         private static PropertyMap $nasgenmap$;
     
         private static final Factory FACTORY = new Factory(BYTES_PER_ELEMENT) {
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java b/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java
    index 6834ef4b701..d49f4d3331b 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java
    @@ -149,12 +149,13 @@ public class ScriptFunctionImpl extends ScriptFunction {
             return typeErrorThrower;
         }
     
    -    private static PropertyMap createStrictModeMap(PropertyMap map) {
    +    private static PropertyMap createStrictModeMap(final PropertyMap map) {
             final int flags = Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE;
    +        PropertyMap newMap = map;
             // Need to add properties directly to map since slots are assigned speculatively by newUserAccessors.
    -        map = map.addProperty(map.newUserAccessors("arguments", flags));
    -        map = map.addProperty(map.newUserAccessors("caller", flags));
    -        return map;
    +        newMap = newMap.addProperty(map.newUserAccessors("arguments", flags));
    +        newMap = newMap.addProperty(map.newUserAccessors("caller", flags));
    +        return newMap;
         }
     
         // Choose the map based on strict mode!
    diff --git a/nashorn/src/jdk/nashorn/internal/runtime/arrays/ObjectArrayData.java b/nashorn/src/jdk/nashorn/internal/runtime/arrays/ObjectArrayData.java
    index 4b1f58a430a..41c4d5ced30 100644
    --- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/ObjectArrayData.java
    +++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/ObjectArrayData.java
    @@ -146,7 +146,7 @@ final class ObjectArrayData extends ArrayData {
     
         @Override
         public ArrayData setEmpty(final long lo, final long hi) {
    -        Arrays.fill(array, (int)Math.max(lo, 0L), (int)Math.min(hi, (long)Integer.MAX_VALUE), ScriptRuntime.EMPTY);
    +        Arrays.fill(array, (int)Math.max(lo, 0L), (int)Math.min(hi, Integer.MAX_VALUE), ScriptRuntime.EMPTY);
             return this;
         }
     
    diff --git a/nashorn/test/script/basic/JDK-8019585.js b/nashorn/test/script/basic/JDK-8019585.js
    new file mode 100644
    index 00000000000..58d18f35a7f
    --- /dev/null
    +++ b/nashorn/test/script/basic/JDK-8019585.js
    @@ -0,0 +1,34 @@
    +/*
    + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + * 
    + * This code is free software; you can redistribute it and/or modify it
    + * 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.
    + */
    +
    +/**
    + * JDK-8019585 - use before def issues with vars using the declared var
    + * legal - but needs to set "a" as undefined
    + *
    + * @test
    + * @run
    + */
    +
    +function f() {
    +    var a = b == 17 && (a = toto(b)) && toto2(a); 
    +}
    
    From 72a7034a41cbce7843bc66442136a3b490b826a5 Mon Sep 17 00:00:00 2001
    From: Athijegannathan Sundararajan 
    Date: Wed, 3 Jul 2013 17:26:31 +0530
    Subject: [PATCH 011/123] 8019805: for each (init; test; modify) is invalid
    
    Reviewed-by: lagergren, jlaskey
    ---
     .../jdk/nashorn/internal/parser/Parser.java   |  6 ++++
     .../runtime/resources/Messages.properties     |  1 +
     nashorn/test/script/basic/JDK-8019805.js      | 36 +++++++++++++++++++
     .../test/script/basic/JDK-8019805.js.EXPECTED |  3 ++
     nashorn/test/script/basic/forin.js            |  5 ---
     nashorn/test/script/basic/forin.js.EXPECTED   | 10 ------
     6 files changed, 46 insertions(+), 15 deletions(-)
     create mode 100644 nashorn/test/script/basic/JDK-8019805.js
     create mode 100644 nashorn/test/script/basic/JDK-8019805.js.EXPECTED
    
    diff --git a/nashorn/src/jdk/nashorn/internal/parser/Parser.java b/nashorn/src/jdk/nashorn/internal/parser/Parser.java
    index 181dcf83dd4..efd6eda6435 100644
    --- a/nashorn/src/jdk/nashorn/internal/parser/Parser.java
    +++ b/nashorn/src/jdk/nashorn/internal/parser/Parser.java
    @@ -1084,6 +1084,12 @@ loop:
                 switch (type) {
                 case SEMICOLON:
                     // for (init; test; modify)
    +
    +                // for each (init; test; modify) is invalid
    +                if (forNode.isForEach()) {
    +                    throw error(AbstractParser.message("for.each.without.in"), token);
    +                }
    +
                     expect(SEMICOLON);
                     if (type != SEMICOLON) {
                         forNode = forNode.setTest(lc, expression());
    diff --git a/nashorn/src/jdk/nashorn/internal/runtime/resources/Messages.properties b/nashorn/src/jdk/nashorn/internal/runtime/resources/Messages.properties
    index 83c0a5abb00..8ec4f7e17f1 100644
    --- a/nashorn/src/jdk/nashorn/internal/runtime/resources/Messages.properties
    +++ b/nashorn/src/jdk/nashorn/internal/runtime/resources/Messages.properties
    @@ -50,6 +50,7 @@ parser.error.no.func.decl.here=Function declarations can only occur at program o
     parser.error.no.func.decl.here.warn=Function declarations should only occur at program or function body level. Function declaration in nested block was converted to a function expression.
     parser.error.property.redefinition=Property "{0}" already defined
     parser.error.unexpected.token=Unexpected token: {0}
    +parser.error.for.each.without.in=for each can only be used with for..in
     parser.error.many.vars.in.for.in.loop=Only one variable allowed in for..in loop
     parser.error.not.lvalue.for.in.loop=Invalid left side value of for..in loop
     parser.error.missing.catch.or.finally=Missing catch or finally after try
    diff --git a/nashorn/test/script/basic/JDK-8019805.js b/nashorn/test/script/basic/JDK-8019805.js
    new file mode 100644
    index 00000000000..70371fb85e0
    --- /dev/null
    +++ b/nashorn/test/script/basic/JDK-8019805.js
    @@ -0,0 +1,36 @@
    +/*
    + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + * 
    + * This code is free software; you can redistribute it and/or modify it
    + * 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.
    + */
    +
    +/**
    + * JDK-8019805: for each (init; test; modify) is invalid
    + *
    + * @test
    + * @run
    + */
    +
    +try {
    +    eval("for each(var v=0;false;);");
    +    print("FAILED: for each(var v=0; false;); should have thrown error");
    +} catch (e) {
    +    print(e.toString().replace(/\\/g, '/'));
    +}
    diff --git a/nashorn/test/script/basic/JDK-8019805.js.EXPECTED b/nashorn/test/script/basic/JDK-8019805.js.EXPECTED
    new file mode 100644
    index 00000000000..154c3326372
    --- /dev/null
    +++ b/nashorn/test/script/basic/JDK-8019805.js.EXPECTED
    @@ -0,0 +1,3 @@
    +SyntaxError: test/script/basic/JDK-8019805.js#32:1:16 for each can only be used with for..in
    +for each(var v=0;false;);
    +                ^
    diff --git a/nashorn/test/script/basic/forin.js b/nashorn/test/script/basic/forin.js
    index ee3fa89b64a..2a60a660c56 100644
    --- a/nashorn/test/script/basic/forin.js
    +++ b/nashorn/test/script/basic/forin.js
    @@ -49,8 +49,3 @@ for each (i in s) print(i);
     // 'each' is a contextual keyword. Ok to use as identifier elsewhere..
     var each = "This is each";
     print(each);
    -
    -// it is ok to use "each" is usual for loop. Ignored as noise word.
    -for each (var i = 0; i < 10; i++) {
    -    print(i);
    -}
    diff --git a/nashorn/test/script/basic/forin.js.EXPECTED b/nashorn/test/script/basic/forin.js.EXPECTED
    index 159e43ba843..f5b96f12ba7 100644
    --- a/nashorn/test/script/basic/forin.js.EXPECTED
    +++ b/nashorn/test/script/basic/forin.js.EXPECTED
    @@ -25,13 +25,3 @@ apple
     bear
     car
     This is each
    -0
    -1
    -2
    -3
    -4
    -5
    -6
    -7
    -8
    -9
    
    From 047d1b732f383ea4f65723ab99ec73ef2eccf3dc Mon Sep 17 00:00:00 2001
    From: Marcus Lagergren 
    Date: Wed, 3 Jul 2013 15:46:03 +0200
    Subject: [PATCH 012/123] 8019811: Static calls - self referential functions
     needed a return type conversion if they were specialized, as they can't use
     the same mechanism as indy calls
    
    Reviewed-by: sundar, jlaskey
    ---
     .../internal/codegen/CodeGenerator.java       | 20 ++++----
     nashorn/test/script/basic/JDK-8016667.js      | 20 ++++++++
     nashorn/test/script/basic/JDK-8019808.js      | 39 +++++++++++++++
     nashorn/test/script/basic/JDK-8019810.js      | 36 ++++++++++++++
     .../test/script/basic/JDK-8019810.js.EXPECTED |  1 +
     nashorn/test/script/basic/JDK-8019811.js      | 47 +++++++++++++++++++
     nashorn/test/script/basic/JDK-8019817.js      | 37 +++++++++++++++
     .../script/currently-failing/JDK-8019809.js   | 37 +++++++++++++++
     8 files changed, 228 insertions(+), 9 deletions(-)
     create mode 100644 nashorn/test/script/basic/JDK-8019808.js
     create mode 100644 nashorn/test/script/basic/JDK-8019810.js
     create mode 100644 nashorn/test/script/basic/JDK-8019810.js.EXPECTED
     create mode 100644 nashorn/test/script/basic/JDK-8019811.js
     create mode 100644 nashorn/test/script/basic/JDK-8019817.js
     create mode 100644 nashorn/test/script/currently-failing/JDK-8019809.js
    
    diff --git a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java
    index 6ea53a408fa..df6906c6bb7 100644
    --- a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java
    +++ b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java
    @@ -578,6 +578,7 @@ final class CodeGenerator extends NodeOperatorVisitor(new LexicalContext()) {
     
    @@ -593,7 +594,7 @@ final class CodeGenerator extends NodeOperatorVisitor> window;
    +}
    +
    +Function("L:if((function x ()3)() + arguments++) {return; } else if (new gc()) while(((x2.prop = functional)) && 0){ }"); 
    +
    +Function("var x = x -= '' "); 
    +
    +Function("switch((Math.pow ? x = 1.2e3 : 3)) { default: return; }") 
    +
    +Function("x = 0.1, x\ntrue\n~this");
    +
    +Function("with((function (x)x2)() ^ this){return; }");
    + 
    \ No newline at end of file
    diff --git a/nashorn/test/script/basic/JDK-8019817.js b/nashorn/test/script/basic/JDK-8019817.js
    new file mode 100644
    index 00000000000..6611e9b49e7
    --- /dev/null
    +++ b/nashorn/test/script/basic/JDK-8019817.js
    @@ -0,0 +1,37 @@
    +/*
    + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + * 
    + * This code is free software; you can redistribute it and/or modify it
    + * 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.
    + */
    +
    +/**
    + * JDK-8019817: More number coercion issues
    + *
    + * @test
    + * @run
    + */
    +var y = 17.17;
    +
    +Function("return y % function(q) { return q; }();"); 
    +
    +function f() {
    +    return y % function(q) { return q; }();
    +}
    +f();
    diff --git a/nashorn/test/script/currently-failing/JDK-8019809.js b/nashorn/test/script/currently-failing/JDK-8019809.js
    new file mode 100644
    index 00000000000..cc31bd86201
    --- /dev/null
    +++ b/nashorn/test/script/currently-failing/JDK-8019809.js
    @@ -0,0 +1,37 @@
    +/*
    + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + * 
    + * This code is free software; you can redistribute it and/or modify it
    + * 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.
    + */
    +
    +/**
    + * JDK-8019809: Break return combo that generates erroneous bytecode
    + *
    + * @test
    + * @run
    + */
    +
    +//Function("L: {break L;return; }"); 
    +
    +function f() {
    +    L: { break L; return; }
    +}
    +
    +f();
    
    From 1e6e9dc0c6f6815196453949fd4958ca07b94b88 Mon Sep 17 00:00:00 2001
    From: Athijegannathan Sundararajan 
    Date: Wed, 3 Jul 2013 19:20:29 +0530
    Subject: [PATCH 013/123] 8019814: Add regression test for passing cases
    
    Reviewed-by: jlaskey, lagergren
    ---
     .../nashorn/internal/runtime/ListAdapter.java | 25 +++++++
     nashorn/test/script/basic/JDK-8019814.js      | 73 +++++++++++++++++++
     .../test/script/basic/JDK-8019814.js.EXPECTED |  6 ++
     3 files changed, 104 insertions(+)
     create mode 100644 nashorn/test/script/basic/JDK-8019814.js
     create mode 100644 nashorn/test/script/basic/JDK-8019814.js.EXPECTED
    
    diff --git a/nashorn/src/jdk/nashorn/internal/runtime/ListAdapter.java b/nashorn/src/jdk/nashorn/internal/runtime/ListAdapter.java
    index 428cb555fb0..194bd132000 100644
    --- a/nashorn/src/jdk/nashorn/internal/runtime/ListAdapter.java
    +++ b/nashorn/src/jdk/nashorn/internal/runtime/ListAdapter.java
    @@ -1,3 +1,28 @@
    +/*
    + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.  Oracle designates this
    + * particular file as subject to the "Classpath" exception as provided
    + * by Oracle in the LICENSE file that accompanied this code.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
     package jdk.nashorn.internal.runtime;
     
     import java.util.AbstractList;
    diff --git a/nashorn/test/script/basic/JDK-8019814.js b/nashorn/test/script/basic/JDK-8019814.js
    new file mode 100644
    index 00000000000..24abf53b77e
    --- /dev/null
    +++ b/nashorn/test/script/basic/JDK-8019814.js
    @@ -0,0 +1,73 @@
    +/*
    + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + * 
    + * This code is free software; you can redistribute it and/or modify it
    + * 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.
    + */
    +
    +/**
    + * JDK-8019814: Add regression test for passing cases
    + *
    + * @test
    + * @run
    + */
    +
    +// java.lang.VerifyError: Bad type on operand stack
    +Function("switch([]) { case 7: }");
    +
    +// java.lang.AssertionError: expecting integer type or object for jump, but found double
    +Function("with(\nnull == (this % {}))( /x/g );");
    +
    +// java.lang.AssertionError: expecting equivalent types on stack but got double and int 
    +try {
    +    eval('Function("/*infloop*/while(((function ()4.)([z1,,], [,,]) - true++))switch(1e+81.x) { default: break; \u0009 }")');
    +} catch (e) {
    +    print(e.toString().replace(/\\/g, '/'));
    +}
    +
    +// java.lang.VerifyError: get long/double overflows locals
    +Function("var x = x -= '' ");
    +
    +// java.lang.AssertionError: object is not compatible with boolean
    +Function("return (null != [,,] <= this);");
    +
    +// java.lang.AssertionError: Only return value on stack allowed at return point
    +// - depth=2 stack = jdk.nashorn.internal.codegen.Label$Stack@4bd0d62f 
    +Function("x = 0.1, x\ntrue\n~this");
    +
    +// java.lang.AssertionError: node NaN ~ window class jdk.nashorn.internal.ir.BinaryNode
    +// has no symbol! [object] function _L1() 
    +Function("throw NaN\n~window;");
    +
    +// java.lang.AssertionError: array element type doesn't match array type
    +Function("if(([(this >>> 4.)].map(gc))) x;");
    +
    +try {
    +    eval('Function("if(--) y;")');
    +} catch (e) {
    +    print(e.toString().replace(/\\/g, '/'));
    +}
    +
    +// java.lang.AssertionError: stacks jdk.nashorn.internal.codegen.Label$Stack@4918f90f
    +// is not equivalent with jdk.nashorn.internal.codegen.Label$Stack@5f9b21a1 at join point 
    +Function("if((null ^ [1]) !== (this.yoyo(false))) {var NaN, x;x\n~[,,z1] }");
    +
    +// java.lang.AssertionError
    +//    at jdk.nashorn.internal.codegen.Attr.enterFunctionBody(Attr.java:276) 
    +Function("return (void ({ set each (x2)y }));"); 
    diff --git a/nashorn/test/script/basic/JDK-8019814.js.EXPECTED b/nashorn/test/script/basic/JDK-8019814.js.EXPECTED
    new file mode 100644
    index 00000000000..51db7b5e953
    --- /dev/null
    +++ b/nashorn/test/script/basic/JDK-8019814.js.EXPECTED
    @@ -0,0 +1,6 @@
    +ReferenceError: :1:50 Invalid left hand side for assignment
    +/*infloop*/while(((function ()4.)([z1,,], [,,]) - true++))switch(1e+81.x) { default: break; 	 }
    +                                                  ^
    +SyntaxError: :1:5 Expected l-value but found )
    +if(--) y;
    +     ^
    
    From 45d608aa5bd713a25f1a1819f2f2087096e20280 Mon Sep 17 00:00:00 2001
    From: Sergey Bylokhov 
    Date: Wed, 3 Jul 2013 19:00:10 +0400
    Subject: [PATCH 014/123] 8004859: Graphics.getClipBounds/getClip return
     difference nonequivalent bounds, depending from transform
    
    Reviewed-by: prr, flar
    ---
     .../classes/sun/java2d/SunGraphics2D.java     |  42 ++++----
     .../Graphics2D/Test8004859/Test8004859.java   | 102 ++++++++++++++++++
     2 files changed, 126 insertions(+), 18 deletions(-)
     create mode 100644 jdk/test/java/awt/Graphics2D/Test8004859/Test8004859.java
    
    diff --git a/jdk/src/share/classes/sun/java2d/SunGraphics2D.java b/jdk/src/share/classes/sun/java2d/SunGraphics2D.java
    index 3699b5d5174..3921bbcd2ac 100644
    --- a/jdk/src/share/classes/sun/java2d/SunGraphics2D.java
    +++ b/jdk/src/share/classes/sun/java2d/SunGraphics2D.java
    @@ -1795,20 +1795,10 @@ public final class SunGraphics2D
         }
     
         public Rectangle getClipBounds() {
    -        Rectangle r;
             if (clipState == CLIP_DEVICE) {
    -            r = null;
    -        } else if (transformState <= TRANSFORM_INT_TRANSLATE) {
    -            if (usrClip instanceof Rectangle) {
    -                r = new Rectangle((Rectangle) usrClip);
    -            } else {
    -                r = usrClip.getBounds();
    -            }
    -            r.translate(-transX, -transY);
    -        } else {
    -            r = getClip().getBounds();
    +            return null;
             }
    -        return r;
    +        return getClipBounds(new Rectangle());
         }
     
         public Rectangle getClipBounds(Rectangle r) {
    @@ -1817,11 +1807,11 @@ public final class SunGraphics2D
                     if (usrClip instanceof Rectangle) {
                         r.setBounds((Rectangle) usrClip);
                     } else {
    -                    r.setBounds(usrClip.getBounds());
    +                    r.setFrame(usrClip.getBounds2D());
                     }
                     r.translate(-transX, -transY);
                 } else {
    -                r.setBounds(getClip().getBounds());
    +                r.setFrame(getClip().getBounds2D());
                 }
             } else if (r == null) {
                 throw new NullPointerException("null rectangle parameter");
    @@ -1996,10 +1986,10 @@ public final class SunGraphics2D
                 matrix[2] = matrix[0] + rect.getWidth();
                 matrix[3] = matrix[1] + rect.getHeight();
                 tx.transform(matrix, 0, matrix, 0, 2);
    -            rect = new Rectangle2D.Float();
    -            rect.setFrameFromDiagonal(matrix[0], matrix[1],
    -                                      matrix[2], matrix[3]);
    -            return rect;
    +            fixRectangleOrientation(matrix, rect);
    +            return new Rectangle2D.Double(matrix[0], matrix[1],
    +                                          matrix[2] - matrix[0],
    +                                          matrix[3] - matrix[1]);
             }
     
             if (tx.isIdentity()) {
    @@ -2009,6 +1999,22 @@ public final class SunGraphics2D
             return tx.createTransformedShape(clip);
         }
     
    +    /**
    +     * Sets orientation of the rectangle according to the clip.
    +     */
    +    private static void fixRectangleOrientation(double[] m, Rectangle2D clip) {
    +        if (clip.getWidth() > 0 != (m[2] - m[0] > 0)) {
    +            double t = m[0];
    +            m[0] = m[2];
    +            m[2] = t;
    +        }
    +        if (clip.getHeight() > 0 != (m[3] - m[1] > 0)) {
    +            double t = m[1];
    +            m[1] = m[3];
    +            m[3] = t;
    +        }
    +    }
    +
         public void clipRect(int x, int y, int w, int h) {
             clip(new Rectangle(x, y, w, h));
         }
    diff --git a/jdk/test/java/awt/Graphics2D/Test8004859/Test8004859.java b/jdk/test/java/awt/Graphics2D/Test8004859/Test8004859.java
    new file mode 100644
    index 00000000000..73e0acaeace
    --- /dev/null
    +++ b/jdk/test/java/awt/Graphics2D/Test8004859/Test8004859.java
    @@ -0,0 +1,102 @@
    +/*
    + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +import java.awt.Graphics2D;
    +import java.awt.Rectangle;
    +import java.awt.Shape;
    +import java.awt.geom.NoninvertibleTransformException;
    +import java.awt.image.BufferedImage;
    +
    +import sun.java2d.SunGraphics2D;
    +
    +/**
    + * @test
    + * @bug 8004859
    + * @summary getClipBounds/getClip should return equivalent bounds.
    + * @author Sergey Bylokhov
    + */
    +public final class Test8004859 {
    +
    +    private static Shape[] clips = {new Rectangle(0, 0, 1, 1), new Rectangle(
    +            100, 100, -100, -100)};
    +
    +    private static boolean status = true;
    +
    +    public static void main(final String[] args)
    +            throws NoninvertibleTransformException {
    +        final BufferedImage bi = new BufferedImage(300, 300,
    +                                                   BufferedImage.TYPE_INT_RGB);
    +        final Graphics2D g = (Graphics2D) bi.getGraphics();
    +        test(g);
    +        g.translate(2.0, 2.0);
    +        test(g);
    +        g.translate(-4.0, -4.0);
    +        test(g);
    +        g.scale(2.0, 2.0);
    +        test(g);
    +        g.scale(-4.0, -4.0);
    +        test(g);
    +        g.rotate(Math.toRadians(90));
    +        test(g);
    +        g.rotate(Math.toRadians(90));
    +        test(g);
    +        g.rotate(Math.toRadians(90));
    +        test(g);
    +        g.rotate(Math.toRadians(90));
    +        test(g);
    +        g.dispose();
    +        if (!status) {
    +            throw new RuntimeException("Test failed");
    +        }
    +    }
    +
    +    private static void test(final Graphics2D g) {
    +        for (final Shape clip : clips) {
    +            g.setClip(clip);
    +            if (!g.getClip().equals(clip)) {
    +                System.err.println("Expected clip: " + clip);
    +                System.err.println("Actual clip: " + g.getClip());
    +                System.err.println("bounds="+g.getClip().getBounds2D());
    +                System.err.println("bounds="+g.getClip().getBounds());
    +                status = false;
    +            }
    +            final Rectangle bounds = g.getClipBounds();
    +            if (!clip.equals(bounds)) {
    +                System.err.println("Expected getClipBounds(): " + clip);
    +                System.err.println("Actual getClipBounds(): " + bounds);
    +                status = false;
    +            }
    +            g.getClipBounds(bounds);
    +            if (!clip.equals(bounds)) {
    +                System.err.println("Expected getClipBounds(r): " + clip);
    +                System.err.println("Actual getClipBounds(r): " + bounds);
    +                status = false;
    +            }
    +            if (!clip.getBounds2D().isEmpty() && ((SunGraphics2D) g).clipRegion
    +                    .isEmpty()) {
    +                System.err.println("clipRegion should not be empty");
    +                status = false;
    +            }
    +        }
    +    }
    +}
    
    From 75501c69930ef905a0ea2997e29a2c3a978b09c1 Mon Sep 17 00:00:00 2001
    From: Attila Szegedi 
    Date: Wed, 3 Jul 2013 18:10:12 +0200
    Subject: [PATCH 015/123] 8017768: allow dot as inner class name separator for
     Java.type
    
    Reviewed-by: jlaskey, sundar
    ---
     .../docs/JavaScriptingProgrammersGuide.html   |  9 +++-
     .../nashorn/internal/objects/NativeJava.java  | 45 +++++++++++++++++--
     nashorn/test/script/basic/JDK-8017768.js      | 35 +++++++++++++++
     .../test/script/basic/JDK-8017768.js.EXPECTED |  4 ++
     .../jdk/nashorn/test/models/OuterClass.java   |  4 ++
     5 files changed, 91 insertions(+), 6 deletions(-)
     create mode 100644 nashorn/test/script/basic/JDK-8017768.js
     create mode 100644 nashorn/test/script/basic/JDK-8017768.js.EXPECTED
    
    diff --git a/nashorn/docs/JavaScriptingProgrammersGuide.html b/nashorn/docs/JavaScriptingProgrammersGuide.html
    index 18ae823d82e..dd74d74903e 100644
    --- a/nashorn/docs/JavaScriptingProgrammersGuide.html
    +++ b/nashorn/docs/JavaScriptingProgrammersGuide.html
    @@ -501,14 +501,19 @@ or
      var anArrayListWithSize = new ArrayList(16)
     
    -In the special case of inner classes, you need to use the JVM fully qualified name, meaning using $ sign in the class name: +In the special case of inner classes, you can either use the JVM fully qualified name, meaning using the dollar sign in the class name, or you can use the dot:
    
      var ftype = Java.type("java.awt.geom.Arc2D$Float")
     
    +and + +
    
    + var ftype = Java.type("java.awt.geom.Arc2D.Float")
    +
    -However, once you retrieved the outer class, you can access the inner class as a property on it: +both work. Note however that using the dollar sign is faster, as Java.type first tries to resolve the class name as it is originally specified, and the internal JVM names for inner classes use the dollar sign. If you use the dot, Java.type will internally get a ClassNotFoundException and subsequently retry by changing the last dot to dollar sign. As a matter of fact, it'll keep replacing dots with dollar signs until it either successfully loads the class or runs out of all dots in the name. This way it can correctly resolve and load even multiply nested inner classes with the dot notation. Again, this will be slower than using the dollar signs in the name. An alternative way to access the inner class is as a property of the outer class:
    
      var arctype = Java.type("java.awt.geom.Arc2D")
    diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeJava.java b/nashorn/src/jdk/nashorn/internal/objects/NativeJava.java
    index 288770b45ef..8303c39367a 100644
    --- a/nashorn/src/jdk/nashorn/internal/objects/NativeJava.java
    +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeJava.java
    @@ -39,6 +39,7 @@ import jdk.nashorn.internal.objects.annotations.Attribute;
     import jdk.nashorn.internal.objects.annotations.Function;
     import jdk.nashorn.internal.objects.annotations.ScriptClass;
     import jdk.nashorn.internal.objects.annotations.Where;
    +import jdk.nashorn.internal.runtime.Context;
     import jdk.nashorn.internal.runtime.JSType;
     import jdk.nashorn.internal.runtime.ListAdapter;
     import jdk.nashorn.internal.runtime.PropertyMap;
    @@ -105,12 +106,22 @@ public final class NativeJava {
          * var anArrayList = new ArrayList
          * var anArrayListWithSize = new ArrayList(16)
          * 
    - * In the special case of inner classes, you need to use the JVM fully qualified name, meaning using {@code $} sign - * in the class name: + * In the special case of inner classes, you can either use the JVM fully qualified name, meaning using {@code $} + * sign in the class name, or you can use the dot: *
          * var ftype = Java.type("java.awt.geom.Arc2D$Float")
          * 
    - * However, once you retrieved the outer class, you can access the inner class as a property on it: + * and + *
    +     * var ftype = Java.type("java.awt.geom.Arc2D.Float")
    +     * 
    + * both work. Note however that using the dollar sign is faster, as Java.type first tries to resolve the class name + * as it is originally specified, and the internal JVM names for inner classes use the dollar sign. If you use the + * dot, Java.type will internally get a ClassNotFoundException and subsequently retry by changing the last dot to + * dollar sign. As a matter of fact, it'll keep replacing dots with dollar signs until it either successfully loads + * the class or runs out of all dots in the name. This way it can correctly resolve and load even multiply nested + * inner classes with the dot notation. Again, this will be slower than using the dollar signs in the name. An + * alternative way to access the inner class is as a property of the outer class: *
          * var arctype = Java.type("java.awt.geom.Arc2D")
          * var ftype = arctype.Float
    @@ -390,7 +401,33 @@ public final class NativeJava {
     
         private static Class simpleType(final String typeName) throws ClassNotFoundException {
             final Class primClass = TypeUtilities.getPrimitiveTypeByName(typeName);
    -        return primClass != null ? primClass : Global.getThisContext().findClass(typeName);
    +        if(primClass != null) {
    +            return primClass;
    +        }
    +        final Context ctx = Global.getThisContext();
    +        try {
    +            return ctx.findClass(typeName);
    +        } catch(ClassNotFoundException e) {
    +            // The logic below compensates for a frequent user error - when people use dot notation to separate inner
    +            // class names, i.e. "java.lang.Character.UnicodeBlock" vs."java.lang.Character$UnicodeBlock". The logic
    +            // below will try alternative class names, replacing dots at the end of the name with dollar signs.
    +            final StringBuilder nextName = new StringBuilder(typeName);
    +            int lastDot = nextName.length();
    +            for(;;) {
    +                lastDot = nextName.lastIndexOf(".", lastDot - 1);
    +                if(lastDot == -1) {
    +                    // Exhausted the search space, class not found - rethrow the original exception.
    +                    throw e;
    +                }
    +                nextName.setCharAt(lastDot, '$');
    +                try {
    +                    return ctx.findClass(nextName.toString());
    +                } catch(ClassNotFoundException cnfe) {
    +                    // Intentionally ignored, so the loop retries with the next name
    +                }
    +            }
    +        }
    +
         }
     
         private static Class arrayType(final String typeName) throws ClassNotFoundException {
    diff --git a/nashorn/test/script/basic/JDK-8017768.js b/nashorn/test/script/basic/JDK-8017768.js
    new file mode 100644
    index 00000000000..c91f6d1f74a
    --- /dev/null
    +++ b/nashorn/test/script/basic/JDK-8017768.js
    @@ -0,0 +1,35 @@
    +/*
    + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * 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.
    + */
    +
    +/**
    + * JDK-8017768: Allow use of dot notation for inner class names.
    + * 
    + * @test
    + * @run
    + */
    +
    +print(Java.type("java.awt.geom.Arc2D.Float") === Java.type("java.awt.geom.Arc2D$Float"))
    +var iisc = Java.type("jdk.nashorn.test.models.OuterClass$InnerStaticClass$InnerInnerStaticClass")
    +print(Java.type("jdk.nashorn.test.models.OuterClass.InnerStaticClass.InnerInnerStaticClass") === iisc)
    +print(Java.type("jdk.nashorn.test.models.OuterClass$InnerStaticClass.InnerInnerStaticClass") === iisc)
    +print(Java.type("jdk.nashorn.test.models.OuterClass.InnerStaticClass$InnerInnerStaticClass") === iisc)
    diff --git a/nashorn/test/script/basic/JDK-8017768.js.EXPECTED b/nashorn/test/script/basic/JDK-8017768.js.EXPECTED
    new file mode 100644
    index 00000000000..1140ff52e2b
    --- /dev/null
    +++ b/nashorn/test/script/basic/JDK-8017768.js.EXPECTED
    @@ -0,0 +1,4 @@
    +true
    +true
    +true
    +true
    diff --git a/nashorn/test/src/jdk/nashorn/test/models/OuterClass.java b/nashorn/test/src/jdk/nashorn/test/models/OuterClass.java
    index 5db86f28c1b..fc280f65734 100644
    --- a/nashorn/test/src/jdk/nashorn/test/models/OuterClass.java
    +++ b/nashorn/test/src/jdk/nashorn/test/models/OuterClass.java
    @@ -33,6 +33,10 @@ public class OuterClass {
         }
     
         public static class InnerStaticClass {
    +
    +        public static class InnerInnerStaticClass {
    +        }
    +
             private final String value;
     
             public InnerStaticClass(String value) {
    
    From 8ebb701354d6b1eca995cceba78eb0b36b17de5e Mon Sep 17 00:00:00 2001
    From: James Laskey 
    Date: Wed, 3 Jul 2013 13:41:18 -0300
    Subject: [PATCH 016/123] 8011629: Object.defineProperty performance issue
    
    Reviewed-by: sundar, attila
    ---
     .../internal/runtime/AccessorProperty.java    | 55 ++++++++++---------
     1 file changed, 30 insertions(+), 25 deletions(-)
    
    diff --git a/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java b/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java
    index bfdfa71995d..1144eb630bd 100644
    --- a/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java
    +++ b/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java
    @@ -75,6 +75,8 @@ public class AccessorProperty extends Property {
     
         private static final MethodType[] ACCESSOR_GETTER_TYPES = new MethodType[NOOF_TYPES];
         private static final MethodType[] ACCESSOR_SETTER_TYPES = new MethodType[NOOF_TYPES];
    +    private static final MethodType ACCESSOR_GETTER_PRIMITIVE_TYPE;
    +    private static final MethodType ACCESSOR_SETTER_PRIMITIVE_TYPE;
         private static final MethodHandle SPILL_ELEMENT_GETTER;
         private static final MethodHandle SPILL_ELEMENT_SETTER;
     
    @@ -82,13 +84,25 @@ public class AccessorProperty extends Property {
         private static final MethodHandle[] SPILL_ACCESSORS = new MethodHandle[SPILL_CACHE_SIZE * 2];
     
         static {
    +        MethodType getterPrimitiveType = null;
    +        MethodType setterPrimitiveType = null;
    +
             for (int i = 0; i < NOOF_TYPES; i++) {
                 final Type type = ACCESSOR_TYPES.get(i);
                 ACCESSOR_GETTER_TYPES[i] = MH.type(type.getTypeClass(), Object.class);
                 ACCESSOR_SETTER_TYPES[i] = MH.type(void.class, Object.class, type.getTypeClass());
    +
    +            if (type == PRIMITIVE_TYPE) {
    +                getterPrimitiveType = ACCESSOR_GETTER_TYPES[i];
    +                setterPrimitiveType = ACCESSOR_SETTER_TYPES[i];
    +            }
             }
     
    -        final MethodHandle spillGetter = MH.getter(MethodHandles.lookup(), ScriptObject.class, "spill", Object[].class);
    +        ACCESSOR_GETTER_PRIMITIVE_TYPE = getterPrimitiveType;
    +        ACCESSOR_SETTER_PRIMITIVE_TYPE = setterPrimitiveType;
    +
    +        final MethodType spillGetterType = MethodType.methodType(Object[].class, Object.class);
    +        final MethodHandle spillGetter = MH.asType(MH.getter(MethodHandles.lookup(), ScriptObject.class, "spill", Object[].class), spillGetterType);
             SPILL_ELEMENT_GETTER = MH.filterArguments(MH.arrayElementGetter(Object[].class), 0, spillGetter);
             SPILL_ELEMENT_SETTER = MH.filterArguments(MH.arrayElementSetter(Object[].class), 0, spillGetter);
         }
    @@ -177,9 +191,8 @@ public class AccessorProperty extends Property {
                         ACCESSOR_GETTER_TYPES[i]);
                 }
             } else {
    -            //this will work as the object setter and getter will be converted appropriately
    -            objectGetter = getter;
    -            objectSetter = setter;
    +            objectGetter = getter.type() != Lookup.GET_OBJECT_TYPE ? MH.asType(getter, Lookup.GET_OBJECT_TYPE) : getter;
    +            objectSetter = setter != null && setter.type() != Lookup.SET_OBJECT_TYPE ? MH.asType(setter, Lookup.SET_OBJECT_TYPE) : setter;
             }
     
             setCurrentType(getterType);
    @@ -195,8 +208,8 @@ public class AccessorProperty extends Property {
                 setters = new MethodHandle[fieldCount];
                 for(int i = 0; i < fieldCount; ++i) {
                     final String fieldName = ObjectClassGenerator.getFieldName(i, Type.OBJECT);
    -                getters[i] = MH.getter(lookup, structure, fieldName, Type.OBJECT.getTypeClass());
    -                setters[i] = MH.setter(lookup, structure, fieldName, Type.OBJECT.getTypeClass());
    +                getters[i] = MH.asType(MH.getter(lookup, structure, fieldName, Type.OBJECT.getTypeClass()), Lookup.GET_OBJECT_TYPE);
    +                setters[i] = MH.asType(MH.setter(lookup, structure, fieldName, Type.OBJECT.getTypeClass()), Lookup.SET_OBJECT_TYPE);
                 }
             }
         }
    @@ -224,17 +237,18 @@ public class AccessorProperty extends Property {
                 final MethodHandle arguments   = MH.getter(lookup, structure, "arguments", Object.class);
                 final MethodHandle argumentsSO = MH.asType(arguments, arguments.type().changeReturnType(ScriptObject.class));
     
    -            objectGetter = MH.insertArguments(MH.filterArguments(ScriptObject.GET_ARGUMENT.methodHandle(), 0, argumentsSO), 1, slot);
    -            objectSetter = MH.insertArguments(MH.filterArguments(ScriptObject.SET_ARGUMENT.methodHandle(), 0, argumentsSO), 1, slot);
    +            objectGetter = MH.asType(MH.insertArguments(MH.filterArguments(ScriptObject.GET_ARGUMENT.methodHandle(), 0, argumentsSO), 1, slot), Lookup.GET_OBJECT_TYPE);
    +            objectSetter = MH.asType(MH.insertArguments(MH.filterArguments(ScriptObject.SET_ARGUMENT.methodHandle(), 0, argumentsSO), 1, slot), Lookup.SET_OBJECT_TYPE);
             } else {
                 final GettersSetters gs = GETTERS_SETTERS.get(structure);
                 objectGetter = gs.getters[slot];
                 objectSetter = gs.setters[slot];
     
                 if (!OBJECT_FIELDS_ONLY) {
    -                final String fieldNamePrimitive = ObjectClassGenerator.getFieldName(slot, ObjectClassGenerator.PRIMITIVE_TYPE);
    -                primitiveGetter = MH.getter(lookup, structure, fieldNamePrimitive, PRIMITIVE_TYPE.getTypeClass());
    -                primitiveSetter = MH.setter(lookup, structure, fieldNamePrimitive, PRIMITIVE_TYPE.getTypeClass());
    +                final String fieldNamePrimitive = ObjectClassGenerator.getFieldName(slot, PRIMITIVE_TYPE);
    +                final Class typeClass = PRIMITIVE_TYPE.getTypeClass();
    +                primitiveGetter = MH.asType(MH.getter(lookup, structure, fieldNamePrimitive, typeClass), ACCESSOR_GETTER_PRIMITIVE_TYPE);
    +                primitiveSetter = MH.asType(MH.setter(lookup, structure, fieldNamePrimitive, typeClass), ACCESSOR_SETTER_PRIMITIVE_TYPE);
                 }
             }
     
    @@ -325,16 +339,8 @@ public class AccessorProperty extends Property {
             final int i = getAccessorTypeIndex(type);
             if (getters[i] == null) {
                 getters[i] = debug(
    -                MH.asType(
    -                    createGetter(
    -                        currentType,
    -                        type,
    -                        primitiveGetter,
    -                        objectGetter),
    -                    ACCESSOR_GETTER_TYPES[i]),
    -                currentType,
    -                type,
    -                "get");
    +                createGetter(currentType, type, primitiveGetter, objectGetter),
    +                currentType, type, "get");
             }
     
             return getters[i];
    @@ -370,7 +376,6 @@ public class AccessorProperty extends Property {
                 objectSetter = getSpillSetter();
             }
             MethodHandle mh = createSetter(forType, type, primitiveSetter, objectSetter);
    -        mh = MH.asType(mh, ACCESSOR_SETTER_TYPES[getAccessorTypeIndex(type)]); //has to be the case for invokeexact to work in ScriptObject
             mh = debug(mh, currentType, type, "set");
             return mh;
         }
    @@ -423,9 +428,9 @@ public class AccessorProperty extends Property {
             final int slot = getSlot();
             MethodHandle getter = slot < SPILL_CACHE_SIZE ? SPILL_ACCESSORS[slot * 2] : null;
             if (getter == null) {
    -            getter = MH.asType(MH.insertArguments(SPILL_ELEMENT_GETTER, 1, slot), Lookup.GET_OBJECT_TYPE);
    +            getter = MH.insertArguments(SPILL_ELEMENT_GETTER, 1, slot);
                 if (slot < SPILL_CACHE_SIZE) {
    -                SPILL_ACCESSORS[slot * 2] = getter;
    +                SPILL_ACCESSORS[slot * 2 + 0] = getter;
                 }
             }
             return getter;
    @@ -435,7 +440,7 @@ public class AccessorProperty extends Property {
             final int slot = getSlot();
             MethodHandle setter = slot < SPILL_CACHE_SIZE ? SPILL_ACCESSORS[slot * 2 + 1] : null;
             if (setter == null) {
    -            setter = MH.asType(MH.insertArguments(SPILL_ELEMENT_SETTER, 1, slot), Lookup.SET_OBJECT_TYPE);
    +            setter = MH.insertArguments(SPILL_ELEMENT_SETTER, 1, slot);
                 if (slot < SPILL_CACHE_SIZE) {
                     SPILL_ACCESSORS[slot * 2 + 1] = setter;
                 }
    
    From f530400e5c5e0e7bca681b99de63736d875ee0bb Mon Sep 17 00:00:00 2001
    From: Johnny Chen 
    Date: Wed, 3 Jul 2013 10:22:13 -0700
    Subject: [PATCH 017/123] 8014497: [parfait] Potential null pointer dereference
     in jdk/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c
    
    Reviewed-by: bae, prr
    ---
     jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c | 4 ++++
     1 file changed, 4 insertions(+)
    
    diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c
    index 7086109cecb..281f722f9f6 100644
    --- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c
    +++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c
    @@ -548,6 +548,10 @@ cmsBool FixWhiteMisalignment(cmsPipeline* Lut, cmsColorSpaceSignature EntryColor
             for (i=0; i < nOuts; i++) {
     
                 cmsToneCurve* InversePostLin = cmsReverseToneCurve(Curves[i]);
    +            if (InversePostLin == NULL) {
    +                WhiteOut[i] = 0;
    +                continue;
    +            }
                 WhiteOut[i] = cmsEvalToneCurve16(InversePostLin, WhitePointOut[i]);
                 cmsFreeToneCurve(InversePostLin);
             }
    
    From 22d32e76cea96048d94d103f039675a34bd24142 Mon Sep 17 00:00:00 2001
    From: Christian Thalinger 
    Date: Wed, 3 Jul 2013 11:35:06 -0700
    Subject: [PATCH 018/123] 8019184: MethodHandles.catchException() fails when
     methods have 8 args + varargs
    
    Reviewed-by: jrose
    ---
     .../java/lang/invoke/MethodHandleImpl.java    |  3 +-
     .../invoke/TestCatchExceptionWithVarargs.java | 97 +++++++++++++++++++
     2 files changed, 99 insertions(+), 1 deletion(-)
     create mode 100644 jdk/test/java/lang/invoke/TestCatchExceptionWithVarargs.java
    
    diff --git a/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java b/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java
    index 8efbda80614..04eda964966 100644
    --- a/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java
    +++ b/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java
    @@ -747,7 +747,8 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
                 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);
             }
         }
     
    diff --git a/jdk/test/java/lang/invoke/TestCatchExceptionWithVarargs.java b/jdk/test/java/lang/invoke/TestCatchExceptionWithVarargs.java
    new file mode 100644
    index 00000000000..a3df17c0f70
    --- /dev/null
    +++ b/jdk/test/java/lang/invoke/TestCatchExceptionWithVarargs.java
    @@ -0,0 +1,97 @@
    +/*
    + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.  Oracle designates this
    + * particular file as subject to the "Classpath" exception as provided
    + * by Oracle in the LICENSE file that accompanied this code.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +/*
    + * @test
    + * @bug 8019184
    + * @summary MethodHandles.catchException() fails when methods have 8 args + varargs
    + */
    +
    +import java.util.*;
    +import java.lang.invoke.*;
    +
    +public class TestCatchExceptionWithVarargs {
    +
    +    private static final Class CLASS = TestCatchExceptionWithVarargs.class;
    +    private static final int MAX_MH_ARITY = 254;
    +
    +    public static MethodHandle target;
    +    public static MethodHandle handler;
    +
    +    private static Object firstArg;
    +
    +    static class MyException extends Exception {
    +    }
    +
    +    public static Object target(Object... a) throws Exception {
    +        if (a[0] != firstArg) {
    +            throw new AssertionError("first argument different than expected: " + a[0] + " != " + firstArg);
    +        }
    +        throw new MyException();
    +    }
    +
    +    public static Object handler(Object... a) {
    +        if (a[0] != firstArg) {
    +            throw new AssertionError("first argument different than expected: " + a[0] + " != " + firstArg);
    +        }
    +        return a[0];
    +    }
    +
    +    static {
    +        try {
    +            MethodType mtype = MethodType.methodType(Object.class, Object[].class);
    +            target = MethodHandles.lookup().findStatic(CLASS, "target", mtype);
    +            handler = MethodHandles.lookup().findStatic(CLASS, "handler", mtype);
    +        } catch (Exception e) {
    +            throw new AssertionError(e);
    +        }
    +    }
    +
    +    public static void main(String[] args) throws Throwable {
    +        List> ptypes = new LinkedList<>();
    +        ptypes.add(Object[].class);
    +
    +        // We use MAX_MH_ARITY - 1 here to account for the Object[] argument.
    +        for (int i = 1; i < MAX_MH_ARITY - 1; i++) {
    +            ptypes.add(0, Object.class);
    +
    +            MethodHandle targetWithArgs = target.asType(MethodType.methodType(Object.class, ptypes));
    +            MethodHandle handlerWithArgs = handler.asType(MethodType.methodType(Object.class, ptypes));
    +            handlerWithArgs = MethodHandles.dropArguments(handlerWithArgs, 0, MyException.class);
    +
    +            MethodHandle gwc1 = MethodHandles.catchException(targetWithArgs, MyException.class, handlerWithArgs);
    +
    +            // The next line throws an IllegalArgumentException if there is a bug.
    +            MethodHandle gwc2 = MethodHandles.catchException(gwc1, MyException.class, handlerWithArgs);
    +
    +            // This is only to verify that the method handles can actually be invoked and do the right thing.
    +            firstArg = new Object();
    +            Object o = gwc2.asSpreader(Object[].class, ptypes.size() - 1).invoke(firstArg, new Object[i]);
    +            if (o != firstArg) {
    +                throw new AssertionError("return value different than expected: " + o + " != " + firstArg);
    +            }
    +        }
    +    }
    +}
    
    From 355205b8a5d1405e8d57a615ba0390163f3ffbb7 Mon Sep 17 00:00:00 2001
    From: Paul Sandoz 
    Date: Wed, 3 Jul 2013 21:19:25 +0200
    Subject: [PATCH 019/123] 8017329: 8b92-lambda regression: TreeSet("a",
     "b").stream().substream(1).parallel().iterator() is empty
    
    Reviewed-by: alanb
    ---
     .../classes/java/util/stream/SliceOps.java    |  6 +--
     .../tests/java/util/stream/SliceOpTest.java   | 50 +++++++++++++++++++
     2 files changed, 53 insertions(+), 3 deletions(-)
    
    diff --git a/jdk/src/share/classes/java/util/stream/SliceOps.java b/jdk/src/share/classes/java/util/stream/SliceOps.java
    index 78fd3d7f0d5..ac538f2d86c 100644
    --- a/jdk/src/share/classes/java/util/stream/SliceOps.java
    +++ b/jdk/src/share/classes/java/util/stream/SliceOps.java
    @@ -598,9 +598,9 @@ final class SliceOps {
                     final Node.Builder nb = op.makeNodeBuilder(sizeIfKnown, generator);
                     Sink opSink = op.opWrapSink(helper.getStreamAndOpFlags(), nb);
                     helper.copyIntoWithCancel(helper.wrapSink(opSink), spliterator);
    -                // It is necessary to truncate here since the result at the root
    -                // can only be set once
    -                return doTruncate(nb.build());
    +                // There is no need to truncate since the op performs the
    +                // skipping and limiting of elements
    +                return nb.build();
                 }
                 else {
                     Node node = helper.wrapAndCopyInto(helper.makeNodeBuilder(-1, generator),
    diff --git a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SliceOpTest.java b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SliceOpTest.java
    index 29086fa351d..afa1b012653 100644
    --- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SliceOpTest.java
    +++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SliceOpTest.java
    @@ -26,13 +26,16 @@ import org.testng.annotations.Test;
     
     import java.util.*;
     import java.util.concurrent.atomic.AtomicInteger;
    +import java.util.function.Consumer;
     import java.util.function.Function;
    +import java.util.stream.Collectors;
     import java.util.stream.DoubleStream;
     import java.util.stream.IntStream;
     import java.util.stream.LambdaTestHelpers;
     import java.util.stream.LongStream;
     import java.util.stream.OpTestCase;
     import java.util.stream.Stream;
    +import java.util.stream.StreamSupport;
     import java.util.stream.StreamTestDataProvider;
     import java.util.stream.TestData;
     
    @@ -192,6 +195,53 @@ public class SliceOpTest extends OpTestCase {
             }
         }
     
    +    public void testSkipLimitOpsWithNonSplittingSpliterator() {
    +        class NonSplittingNotSubsizedOrderedSpliterator implements Spliterator {
    +            Spliterator s;
    +
    +            NonSplittingNotSubsizedOrderedSpliterator(Spliterator s) {
    +                assert s.hasCharacteristics(Spliterator.ORDERED);
    +                this.s = s;
    +            }
    +
    +            @Override
    +            public boolean tryAdvance(Consumer action) {
    +                return s.tryAdvance(action);
    +            }
    +
    +            @Override
    +            public void forEachRemaining(Consumer action) {
    +                s.forEachRemaining(action);
    +            }
    +
    +            @Override
    +            public Spliterator trySplit() {
    +                return null;
    +            }
    +
    +            @Override
    +            public long estimateSize() {
    +                return s.estimateSize();
    +            }
    +
    +            @Override
    +            public int characteristics() {
    +                return s.characteristics() & ~(Spliterator.SUBSIZED);
    +            }
    +
    +            @Override
    +            public Comparator getComparator() {
    +                return s.getComparator();
    +            }
    +        }
    +        List list = IntStream.range(0, 100).boxed().collect(Collectors.toList());
    +        TestData.OfRef data = TestData.Factory.ofSupplier(
    +                "Non splitting, not SUBSIZED, ORDERED, stream",
    +                () -> StreamSupport.stream(new NonSplittingNotSubsizedOrderedSpliterator<>(list.spliterator())));
    +
    +        testSkipLimitOps("testSkipLimitOpsWithNonSplittingSpliterator", data);
    +    }
    +
         @Test(dataProvider = "StreamTestData", dataProviderClass = StreamTestDataProvider.class)
         public void testLimitOps(String name, TestData.OfRef data) {
             List limits = sizes(data.size());
    
    From d0f08f798729b89baf64d5c0ebd2fab5157f2d46 Mon Sep 17 00:00:00 2001
    From: Jason Uh 
    Date: Wed, 3 Jul 2013 12:51:45 -0700
    Subject: [PATCH 020/123] 8019772: Fix doclint issues in javax.crypto and
     javax.security subpackages
    
    Reviewed-by: darcy
    ---
     .../share/classes/javax/crypto/Cipher.java    |  6 ++--
     .../javax/crypto/CipherInputStream.java       |  2 +-
     .../javax/crypto/ExemptionMechanism.java      |  8 ++---
     .../classes/javax/crypto/KeyAgreement.java    | 12 +++----
     .../classes/javax/crypto/KeyGenerator.java    |  6 ++--
     .../classes/javax/crypto/NullCipher.java      |  5 ++-
     .../classes/javax/security/auth/Subject.java  | 20 ++++++++++-
     .../javax/security/cert/X509Certificate.java  | 35 +++++++++++--------
     8 files changed, 60 insertions(+), 34 deletions(-)
    
    diff --git a/jdk/src/share/classes/javax/crypto/Cipher.java b/jdk/src/share/classes/javax/crypto/Cipher.java
    index 70d8d346601..d16c579469c 100644
    --- a/jdk/src/share/classes/javax/crypto/Cipher.java
    +++ b/jdk/src/share/classes/javax/crypto/Cipher.java
    @@ -1135,7 +1135,7 @@ public class Cipher {
          *
          * 

    If this cipher (including its underlying feedback or padding scheme) * requires any random bytes (e.g., for parameter generation), it will get - * them using the {@link SecureRandom SecureRandom} + * them using the {@link java.security.SecureRandom} * implementation of the highest-priority * installed provider as the source of randomness. * (If none of the installed providers supply an implementation of @@ -1263,7 +1263,7 @@ public class Cipher { * *

    If this cipher (including its underlying feedback or padding scheme) * requires any random bytes (e.g., for parameter generation), it will get - * them using the {@link SecureRandom SecureRandom} + * them using the {@link java.security.SecureRandom} * implementation of the highest-priority * installed provider as the source of randomness. * (If none of the installed providers supply an implementation of @@ -1400,7 +1400,7 @@ public class Cipher { * *

    If this cipher (including its underlying feedback or padding scheme) * requires any random bytes (e.g., for parameter generation), it will get - * them using the {@link SecureRandom SecureRandom} + * them using the {@link java.security.SecureRandom} * implementation of the highest-priority * installed provider as the source of randomness. * (If none of the installed providers supply an implementation of diff --git a/jdk/src/share/classes/javax/crypto/CipherInputStream.java b/jdk/src/share/classes/javax/crypto/CipherInputStream.java index f062a1bc28e..a8b4152a5ae 100644 --- a/jdk/src/share/classes/javax/crypto/CipherInputStream.java +++ b/jdk/src/share/classes/javax/crypto/CipherInputStream.java @@ -245,7 +245,7 @@ public class CipherInputStream extends FilterInputStream { *

    Fewer bytes than requested might be skipped. * The actual number of bytes skipped is equal to n or * the result of a call to - * {@link #available() available}, + * {@link #available() available}, * whichever is smaller. * If n is less than zero, no bytes are skipped. * diff --git a/jdk/src/share/classes/javax/crypto/ExemptionMechanism.java b/jdk/src/share/classes/javax/crypto/ExemptionMechanism.java index 6a7cc90d389..72b0e75cfb1 100644 --- a/jdk/src/share/classes/javax/crypto/ExemptionMechanism.java +++ b/jdk/src/share/classes/javax/crypto/ExemptionMechanism.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -116,7 +116,7 @@ public class ExemptionMechanism { * mechanism. * See the ExemptionMechanism section in the * + * "{@docRoot}/../technotes/guides/security/StandardNames.html#Exemption"> * Java Cryptography Architecture Standard Algorithm Name Documentation * for information about standard exemption mechanism names. * @@ -155,7 +155,7 @@ public class ExemptionMechanism { * @param algorithm the standard name of the requested exemption mechanism. * See the ExemptionMechanism section in the * + * "{@docRoot}/../technotes/guides/security/StandardNames.html#Exemption"> * Java Cryptography Architecture Standard Algorithm Name Documentation * for information about standard exemption mechanism names. * @@ -199,7 +199,7 @@ public class ExemptionMechanism { * @param algorithm the standard name of the requested exemption mechanism. * See the ExemptionMechanism section in the * + * "{@docRoot}/../technotes/guides/security/StandardNames.html#Exemption"> * Java Cryptography Architecture Standard Algorithm Name Documentation * for information about standard exemption mechanism names. * diff --git a/jdk/src/share/classes/javax/crypto/KeyAgreement.java b/jdk/src/share/classes/javax/crypto/KeyAgreement.java index cb85cb57d31..70221aa0c6e 100644 --- a/jdk/src/share/classes/javax/crypto/KeyAgreement.java +++ b/jdk/src/share/classes/javax/crypto/KeyAgreement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -149,7 +149,7 @@ public class KeyAgreement { * algorithm. * See the KeyAgreement section in the - * Java Cryptography Architecture Standard Algorithm Name Documentation + * Java Cryptography Architecture Standard Algorithm Name Documentation * for information about standard algorithm names. * * @return the new KeyAgreement object. @@ -196,7 +196,7 @@ public class KeyAgreement { * algorithm. * See the KeyAgreement section in the - * Java Cryptography Architecture Standard Algorithm Name Documentation + * Java Cryptography Architecture Standard Algorithm Name Documentation * for information about standard algorithm names. * * @param provider the name of the provider. @@ -240,7 +240,7 @@ public class KeyAgreement { * algorithm. * See the KeyAgreement section in the - * Java Cryptography Architecture Standard Algorithm Name Documentation + * Java Cryptography Architecture Standard Algorithm Name Documentation * for information about standard algorithm names. * * @param provider the provider. @@ -418,7 +418,7 @@ public class KeyAgreement { * *

    If this key agreement requires any random bytes, it will get * them using the - * {@link SecureRandom SecureRandom} + * {@link java.security.SecureRandom} * implementation of the highest-priority * installed provider as the source of randomness. * (If none of the installed providers supply an implementation of @@ -476,7 +476,7 @@ public class KeyAgreement { * *

    If this key agreement requires any random bytes, it will get * them using the - * {@link SecureRandom SecureRandom} + * {@link java.security.SecureRandom} * implementation of the highest-priority * installed provider as the source of randomness. * (If none of the installed providers supply an implementation of diff --git a/jdk/src/share/classes/javax/crypto/KeyGenerator.java b/jdk/src/share/classes/javax/crypto/KeyGenerator.java index fee08392998..961f0ea9eb3 100644 --- a/jdk/src/share/classes/javax/crypto/KeyGenerator.java +++ b/jdk/src/share/classes/javax/crypto/KeyGenerator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -398,7 +398,7 @@ public class KeyGenerator { * *

    If this key generator requires any random bytes, it will get them * using the - * {@link SecureRandom SecureRandom} + * {@link java.security.SecureRandom} * implementation of the highest-priority installed * provider as the source of randomness. * (If none of the installed providers supply an implementation of @@ -463,7 +463,7 @@ public class KeyGenerator { * *

    If this key generator requires any random bytes, it will get them * using the - * {@link SecureRandom SecureRandom} + * {@link java.security.SecureRandom} * implementation of the highest-priority installed * provider as the source of randomness. * (If none of the installed providers supply an implementation of diff --git a/jdk/src/share/classes/javax/crypto/NullCipher.java b/jdk/src/share/classes/javax/crypto/NullCipher.java index 39afb2ac4a8..5c8d2f54735 100644 --- a/jdk/src/share/classes/javax/crypto/NullCipher.java +++ b/jdk/src/share/classes/javax/crypto/NullCipher.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,6 +38,9 @@ package javax.crypto; public class NullCipher extends Cipher { + /** + * Creates a NullCipher object. + */ public NullCipher() { super(new NullCipherSpi(), null); } diff --git a/jdk/src/share/classes/javax/security/auth/Subject.java b/jdk/src/share/classes/javax/security/auth/Subject.java index 1caaad400e2..c72734edab3 100644 --- a/jdk/src/share/classes/javax/security/auth/Subject.java +++ b/jdk/src/share/classes/javax/security/auth/Subject.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -325,6 +325,9 @@ public final class Subject implements java.io.Serializable { * action will run as. This parameter * may be null.

    * + * @param the type of the value returned by the PrivilegedAction's + * {@code run} method. + * * @param action the code to be run as the specified * Subject.

    * @@ -378,6 +381,9 @@ public final class Subject implements java.io.Serializable { * action will run as. This parameter * may be null.

    * + * @param the type of the value returned by the + * PrivilegedExceptionAction's {@code run} method. + * * @param action the code to be run as the specified * Subject.

    * @@ -434,6 +440,9 @@ public final class Subject implements java.io.Serializable { * action will run as. This parameter * may be null.

    * + * @param the type of the value returned by the PrivilegedAction's + * {@code run} method. + * * @param action the code to be run as the specified * Subject.

    * @@ -492,6 +501,9 @@ public final class Subject implements java.io.Serializable { * action will run as. This parameter * may be null.

    * + * @param the type of the value returned by the + * PrivilegedExceptionAction's {@code run} method. + * * @param action the code to be run as the specified * Subject.

    * @@ -590,6 +602,8 @@ public final class Subject implements java.io.Serializable { * *

    * + * @param the type of the class modeled by {@code c} + * * @param c the returned Set of Principals will all be * instances of this class. * @@ -684,6 +698,8 @@ public final class Subject implements java.io.Serializable { * *

    * + * @param the type of the class modeled by {@code c} + * * @param c the returned Set of public credentials will all be * instances of this class. * @@ -721,6 +737,8 @@ public final class Subject implements java.io.Serializable { * *

    * + * @param the type of the class modeled by {@code c} + * * @param c the returned Set of private credentials will all be * instances of this class. * diff --git a/jdk/src/share/classes/javax/security/cert/X509Certificate.java b/jdk/src/share/classes/javax/security/cert/X509Certificate.java index 1f5af7e2d23..16fb0149801 100644 --- a/jdk/src/share/classes/javax/security/cert/X509Certificate.java +++ b/jdk/src/share/classes/javax/security/cert/X509Certificate.java @@ -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 @@ -159,9 +159,9 @@ public abstract class X509Certificate extends Certificate { * certificate is expected to be in the input stream. * Also, all X509Certificate * subclasses must provide a constructor of the form: - *

    -     * public <subClass>(InputStream inStream) ...
    -     * 
    + *
    {@code
    +     * public (InputStream inStream) ...
    +     * }
    * * @param inStream an input stream with the data to be read to * initialize the certificate. @@ -184,9 +184,9 @@ public abstract class X509Certificate extends Certificate { * *

    Note: All X509Certificate * subclasses must provide a constructor of the form: - *

    -     * public <subClass>(InputStream inStream) ...
    -     * 
    + *
    {@code
    +     * public (InputStream inStream) ...
    +     * }
    * * @param certData a byte array containing the DER-encoded * certificate. @@ -255,10 +255,12 @@ public abstract class X509Certificate extends Certificate { * is valid. It is defined in * ASN.1 as: *
    -     * validity             Validity

    + * validity Validity + * * Validity ::= SEQUENCE { * notBefore CertificateValidityDate, - * notAfter CertificateValidityDate }

    + * notAfter CertificateValidityDate } + * * CertificateValidityDate ::= CHOICE { * utcTime UTCTime, * generalTime GeneralizedTime } @@ -291,7 +293,8 @@ public abstract class X509Certificate extends Certificate { * Gets the version (version number) value from the * certificate. The ASN.1 definition for this is: *

    -     * version         [0]  EXPLICIT Version DEFAULT v1

    + * version [0] EXPLICIT Version DEFAULT v1 + * * Version ::= INTEGER { v1(0), v2(1), v3(2) } *

    * @@ -307,7 +310,7 @@ public abstract class X509Certificate extends Certificate { * serial number identify a unique certificate). * The ASN.1 definition for this is: *
    -     * serialNumber     CertificateSerialNumber

    + * serialNumber CertificateSerialNumber * * CertificateSerialNumber ::= INTEGER *

    @@ -325,7 +328,7 @@ public abstract class X509Certificate extends Certificate { * X.500 distinguished name (DN). * The ASN.1 definition for this is: *
    -     * issuer    Name

    + * issuer Name * * Name ::= CHOICE { RDNSequence } * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName @@ -371,11 +374,12 @@ public abstract class X509Certificate extends Certificate { * the certificate. * The relevant ASN.1 definitions are: *

    -     * validity             Validity

    + * validity Validity * * Validity ::= SEQUENCE { * notBefore CertificateValidityDate, - * notAfter CertificateValidityDate }

    + * notAfter CertificateValidityDate } + * * CertificateValidityDate ::= CHOICE { * utcTime UTCTime, * generalTime GeneralizedTime } @@ -401,7 +405,8 @@ public abstract class X509Certificate extends Certificate { * signature algorithm. An example is the string "SHA-1/DSA". * The ASN.1 definition for this is: *

    -     * signatureAlgorithm   AlgorithmIdentifier

    + * signatureAlgorithm AlgorithmIdentifier + * * AlgorithmIdentifier ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, * parameters ANY DEFINED BY algorithm OPTIONAL } From c70d472774b0f03e40058cb35c3a75c0acce7459 Mon Sep 17 00:00:00 2001 From: Brian Burkhalter Date: Wed, 3 Jul 2013 13:30:46 -0700 Subject: [PATCH 021/123] 8019857: Fix doclint errors in java.util.Format* Fix doclint errors in java.util.Format*. Reviewed-by: darcy --- .../share/classes/java/util/Formattable.java | 8 +-- .../share/classes/java/util/Formatter.java | 49 ++++++++++++------- 2 files changed, 35 insertions(+), 22 deletions(-) diff --git a/jdk/src/share/classes/java/util/Formattable.java b/jdk/src/share/classes/java/util/Formattable.java index 28b788c340a..6f3fd1ab080 100644 --- a/jdk/src/share/classes/java/util/Formattable.java +++ b/jdk/src/share/classes/java/util/Formattable.java @@ -36,7 +36,7 @@ import java.io.IOException; * For example, the following class prints out different representations of a * stock's name depending on the flags and length constraints: * - *

    + * {@code
      *   import java.nio.CharBuffer;
      *   import java.util.Formatter;
      *   import java.util.Formattable;
    @@ -89,12 +89,12 @@ import java.io.IOException;
      *           return String.format("%s - %s", symbol, companyName);
      *       }
      *   }
    - * 
    + * } * *

    When used in conjunction with the {@link java.util.Formatter}, the above * class produces the following output for various format strings. * - *

    + * {@code
      *   Formatter fmt = new Formatter();
      *   StockName sn = new StockName("HUGE", "Huge Fruit, Inc.",
      *                                "Fruit Titanesque, Inc.");
    @@ -104,7 +104,7 @@ import java.io.IOException;
      *   fmt.format("%-10.8s", sn);              //   -> "HUGE      "
      *   fmt.format("%.12s", sn);                //   -> "Huge Fruit,*"
      *   fmt.format(Locale.FRANCE, "%25s", sn);  //   -> "   Fruit Titanesque, Inc."
    - * 
    + * } * *

    Formattables are not necessarily safe for multithreaded access. Thread * safety is optional and may be enforced by classes that extend and implement diff --git a/jdk/src/share/classes/java/util/Formatter.java b/jdk/src/share/classes/java/util/Formatter.java index 7906c763fe2..dae0b37f48b 100644 --- a/jdk/src/share/classes/java/util/Formatter.java +++ b/jdk/src/share/classes/java/util/Formatter.java @@ -841,7 +841,7 @@ import sun.misc.FormattedFloatingDecimal; * *

    Numeric types will be formatted according to the following algorithm: * - *

    Number Localization Algorithm + *

    Number Localization Algorithm * *

    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 @@ import sun.misc.FormattedFloatingDecimal; * substituted. * *

  • If the {@code ','} ('\u002c') - * flag is given, then the locale-specific {@linkplain + * flag 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 @@ import sun.misc.FormattedFloatingDecimal; * {@code 'd'} * '\u0054' * Formats the argument as a decimal integer. The localization algorithm is applied. + * href="#L10nAlgorithm">localization algorithm is applied. * *

    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 @@ import sun.misc.FormattedFloatingDecimal; * '\u002c' * Requires the output to include the locale-specific {@linkplain * java.text.DecimalFormatSymbols#getGroupingSeparator group separators} as - * described in the "group" section of the + * described in the "group" section of the * localization algorithm. * * {@code '('} @@ -1060,7 +1060,7 @@ import sun.misc.FormattedFloatingDecimal; * {@code 'd'} * '\u0054' * Requires the output to be formatted as a decimal integer. The localization algorithm is applied. + * href="#L10nAlgorithm">localization algorithm is applied. * *

    If the {@code '#'} flag is given {@link * FormatFlagsConversionMismatchException} will be thrown. @@ -1155,7 +1155,7 @@ import sun.misc.FormattedFloatingDecimal; * '\u0065' * Requires the output to be formatted using computerized scientific notation. The localization algorithm is applied. + * href="#L10nAlgorithm">localization algorithm is applied. * *

    The formatting of the magnitude m depends upon its value. * @@ -1168,7 +1168,7 @@ import sun.misc.FormattedFloatingDecimal; * *

    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 localization + * is described in the localization * algorithm. The formatting of the magnitude m depends upon its * value. * @@ -1207,7 +1207,7 @@ import sun.misc.FormattedFloatingDecimal; * {@code 'g'} * '\u0067' * Requires the output to be formatted in general scientific notation - * as described below. The localization + * as described below. The localization * algorithm is applied. * *

    After rounding for the precision, the formatting of the resulting @@ -1236,12 +1236,12 @@ import sun.misc.FormattedFloatingDecimal; * {@code 'f'} * '\u0066' * Requires the output to be formatted using decimal - * format. The localization algorithm is + * format. The localization algorithm is * applied. * *

    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 localization + * described in the localization * algorithm. The formatting of the magnitude m depends upon its * value. * @@ -1382,7 +1382,7 @@ import sun.misc.FormattedFloatingDecimal; * '\u0065' * Requires the output to be formatted using computerized scientific notation. The localization algorithm is applied. + * href="#L10nAlgorithm">localization algorithm is applied. * *

    The formatting of the magnitude m depends upon its value. * @@ -1391,7 +1391,7 @@ import sun.misc.FormattedFloatingDecimal; * *

    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 localization + * is described in the localization * algorithm. The formatting of the magnitude m depends upon its * value. * @@ -1428,7 +1428,7 @@ import sun.misc.FormattedFloatingDecimal; * {@code 'g'} * '\u0067' * Requires the output to be formatted in general scientific notation - * as described below. The localization + * as described below. The localization * algorithm is applied. * *

    After rounding for the precision, the formatting of the resulting @@ -1457,12 +1457,12 @@ import sun.misc.FormattedFloatingDecimal; * {@code 'f'} * '\u0066' * Requires the output to be formatted using decimal - * format. The localization algorithm is + * format. The localization algorithm is * applied. * *

    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 localization + * described in the localization * algorithm. The formatting of the magnitude m depends upon its * value. * @@ -1721,7 +1721,7 @@ import sun.misc.FormattedFloatingDecimal; * conversions applies. If the {@code '#'} flag is given, then a {@link * FormatFlagsConversionMismatchException} will be thrown. * - *

    The width is the minimum number of characters to + *

    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 * ('\u0020') until the total number of characters equals width. @@ -1741,7 +1741,7 @@ import sun.misc.FormattedFloatingDecimal; * {@code '%'} * The result is a literal {@code '%'} ('\u0025') * - *

    The width is the minimum number of characters to + *

    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 ('\u0020') until the total number of @@ -2590,7 +2590,20 @@ public final class Formatter implements Closeable, Flushable { 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; From a58f094d4003d60f3a75833a7ddbd577d8f2b0d3 Mon Sep 17 00:00:00 2001 From: Eric McCorkle Date: Wed, 3 Jul 2013 19:47:15 -0400 Subject: [PATCH 022/123] 8016285: Add java.lang.reflect.Parameter.isNamePresent() Add isNamePresent method to parameter reflection library, which indicates whether or real parameter data is available Reviewed-by: darcy --- .../classes/java/lang/reflect/Executable.java | 16 +++++++++++- .../classes/java/lang/reflect/Parameter.java | 25 ++++++++++++++++--- .../reflect/Parameter/WithParameters.java | 4 +++ .../reflect/Parameter/WithoutParameters.java | 1 + 4 files changed, 41 insertions(+), 5 deletions(-) diff --git a/jdk/src/share/classes/java/lang/reflect/Executable.java b/jdk/src/share/classes/java/lang/reflect/Executable.java index 2501fd68d5d..aa8820fd2d7 100644 --- a/jdk/src/share/classes/java/lang/reflect/Executable.java +++ b/jdk/src/share/classes/java/lang/reflect/Executable.java @@ -326,8 +326,12 @@ public abstract class Executable extends AccessibleObject 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 @@ public abstract class Executable extends AccessibleObject 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(); diff --git a/jdk/src/share/classes/java/lang/reflect/Parameter.java b/jdk/src/share/classes/java/lang/reflect/Parameter.java index 20969347255..f49c1daa436 100644 --- a/jdk/src/share/classes/java/lang/reflect/Parameter.java +++ b/jdk/src/share/classes/java/lang/reflect/Parameter.java @@ -94,6 +94,19 @@ public final class Parameter implements AnnotatedElement { return executable.hashCode() ^ index; } + /** + * 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 @@ -149,11 +162,15 @@ public final class Parameter implements AnnotatedElement { /** * 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. diff --git a/jdk/test/java/lang/reflect/Parameter/WithParameters.java b/jdk/test/java/lang/reflect/Parameter/WithParameters.java index bddebf1c782..47e9fae90ef 100644 --- a/jdk/test/java/lang/reflect/Parameter/WithParameters.java +++ b/jdk/test/java/lang/reflect/Parameter/WithParameters.java @@ -73,6 +73,10 @@ public class WithParameters { } for(int i = 0; i < parameters.length; i++) { Parameter p = parameters[i]; + if(!p.isNamePresent()) { + System.err.println(p + ".isNamePresent == false"); + error++; + } if(!parameters[i].getName().equals(qux_names[i])) { System.err.println("Wrong parameter name for " + parameters[i]); error++; diff --git a/jdk/test/java/lang/reflect/Parameter/WithoutParameters.java b/jdk/test/java/lang/reflect/Parameter/WithoutParameters.java index 50254fd9d6b..a42973d6a64 100644 --- a/jdk/test/java/lang/reflect/Parameter/WithoutParameters.java +++ b/jdk/test/java/lang/reflect/Parameter/WithoutParameters.java @@ -69,6 +69,7 @@ public class WithoutParameters { for(int i = 0; i < parameters.length; i++) { Parameter p = parameters[i]; + errorIfTrue(p.isNamePresent(), p + ".isNamePresent == true"); errorIfTrue(!p.getDeclaringExecutable().equals(e), p + ".getDeclaringExecutable != " + e); Objects.requireNonNull(p.getType(), "getType() should not be null"); Objects.requireNonNull(p.getParameterizedType(), "getParameterizedType() should not be null"); From 095614ee2c1634b899127edb9936825f5d3b986b Mon Sep 17 00:00:00 2001 From: Brian Burkhalter Date: Wed, 3 Jul 2013 17:08:14 -0700 Subject: [PATCH 023/123] 8019862: Fix doclint errors in java.lang.* Fix doclint errors in java.lang.* Reviewed-by: darcy --- .../share/classes/java/lang/CharSequence.java | 8 +-- .../share/classes/java/lang/Character.java | 8 ++- .../share/classes/java/lang/ClassLoader.java | 60 +++++++++---------- jdk/src/share/classes/java/lang/Double.java | 2 +- jdk/src/share/classes/java/lang/Float.java | 2 +- .../classes/java/lang/ProcessBuilder.java | 7 ++- jdk/src/share/classes/java/lang/Runtime.java | 2 +- jdk/src/share/classes/java/lang/Thread.java | 6 +- .../share/classes/java/lang/ThreadLocal.java | 3 +- 9 files changed, 53 insertions(+), 45 deletions(-) diff --git a/jdk/src/share/classes/java/lang/CharSequence.java b/jdk/src/share/classes/java/lang/CharSequence.java index 30a23590875..3ee0b9ac1dd 100644 --- a/jdk/src/share/classes/java/lang/CharSequence.java +++ b/jdk/src/share/classes/java/lang/CharSequence.java @@ -60,7 +60,7 @@ public interface CharSequence { /** * Returns the length of this character sequence. The length is the number - * of 16-bit chars in the sequence.

    + * of 16-bit chars in the sequence. * * @return the number of chars in this sequence */ @@ -70,7 +70,7 @@ public interface CharSequence { * Returns the char value at the specified index. An index ranges from zero * to length() - 1. The first char value of the sequence is at * index zero, the next at index one, and so on, as for array - * indexing.

    + * indexing. * *

    If the char value specified by the index is a * surrogate, the surrogate @@ -92,7 +92,7 @@ public interface CharSequence { * ends with the char value at index end - 1. The length * (in chars) of the * returned sequence is end - start, so if start == end - * then an empty sequence is returned.

    + * then an empty sequence is returned. * * @param start the start index, inclusive * @param end the end index, exclusive @@ -109,7 +109,7 @@ public interface CharSequence { /** * 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.

    + * this sequence. * * @return a string consisting of exactly this sequence of characters */ diff --git a/jdk/src/share/classes/java/lang/Character.java b/jdk/src/share/classes/java/lang/Character.java index e512e582612..41576cca8d8 100644 --- a/jdk/src/share/classes/java/lang/Character.java +++ b/jdk/src/share/classes/java/lang/Character.java @@ -54,7 +54,7 @@ import java.util.Locale; *
  • http://www.unicode.org *
* - *

Unicode Character Representations

+ *

Unicode Character Representations

* *

The {@code char} data type (and therefore the value that a * {@code Character} object encapsulates) are based on the @@ -68,7 +68,7 @@ import java.util.Locale; * definition of the U+n notation in the Unicode * Standard.) * - *

The set of characters from U+0000 to U+FFFF is + *

The set of characters from U+0000 to U+FFFF is * sometimes referred to as the Basic Multilingual Plane (BMP). * Characters whose code points are greater * than U+FFFF are called supplementary characters. The Java @@ -4599,6 +4599,7 @@ class Character implements java.io.Serializable, Comparable { * * @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 @@ class Character implements java.io.Serializable, Comparable { * Determines if the specified character is ISO-LATIN-1 white space. * This method returns {@code true} for the following five * characters only: - * + *
* * * @@ -7174,6 +7175,7 @@ class Character implements java.io.Serializable, Comparable { * Returns the value obtained by reversing the order of the bytes in the * specified char 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 char value. * @since 1.5 diff --git a/jdk/src/share/classes/java/lang/ClassLoader.java b/jdk/src/share/classes/java/lang/ClassLoader.java index f26eafd980a..c3f2aa20458 100644 --- a/jdk/src/share/classes/java/lang/ClassLoader.java +++ b/jdk/src/share/classes/java/lang/ClassLoader.java @@ -157,7 +157,7 @@ import sun.security.util.SecurityConstants; * } * * - *

Binary names

+ *

Binary names

* *

Any class name provided as a {@link String} parameter to methods in * ClassLoader must be a binary name as defined by @@ -342,7 +342,7 @@ public abstract class ClassLoader { * #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) loadClass(name, - * false)}.

+ * false)}. * * @param name * The binary name of the class @@ -441,7 +441,7 @@ public abstract class ClassLoader { * 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.

+ * ClassLoader object. * * @param className * The name of the to-be-loaded class @@ -506,7 +506,7 @@ public abstract class ClassLoader { * follow the delegation model for loading classes, and will be invoked by * the {@link #loadClass loadClass} method after checking the * parent class loader for the requested class. The default implementation - * throws a ClassNotFoundException.

+ * throws a ClassNotFoundException. * * @param name * The binary name of the class @@ -772,16 +772,16 @@ public abstract class ClassLoader { * bBuffer, pd) yields exactly the same * result as the statements * - *
+ *

* ...
- * byte[] temp = new byte[
bBuffer.{@link + * byte[] temp = new byte[bBuffer.{@link * java.nio.ByteBuffer#remaining remaining}()];
- *
bBuffer.{@link java.nio.ByteBuffer#get(byte[]) + * bBuffer.{@link java.nio.ByteBuffer#get(byte[]) * get}(temp);
* return {@link #defineClass(String, byte[], int, int, ProtectionDomain) - *
cl.defineClass}(name, temp, 0, - * temp.length, pd);
- *

+ * cl.defineClass}(name, temp, 0, + * temp.length, pd);
+ *

* * @param name * The expected binary name. of the class, or @@ -940,7 +940,6 @@ public abstract class ClassLoader { * already been linked, then this method simply returns. Otherwise, the * class is linked as described in the "Execution" chapter of * The Java™ Language Specification. - *

* * @param c * The class to link @@ -1012,7 +1011,7 @@ public abstract class ClassLoader { * Returns the class with the given binary name if this * loader has been recorded by the Java virtual machine as an initiating * loader of a class with that binary name. Otherwise - * null is returned.

+ * null is returned. * * @param name * The binary name of the class @@ -1032,7 +1031,7 @@ public abstract class ClassLoader { /** * Sets the signers of a class. This should be invoked after defining a - * class.

+ * class. * * @param c * The Class object @@ -1125,7 +1124,7 @@ public abstract class ClassLoader { /** * Finds the resource with the given name. Class loader implementations - * should override this method to specify where to find resources.

+ * should override this method to specify where to find resources. * * @param name * The resource name @@ -1143,7 +1142,7 @@ public abstract class ClassLoader { * Returns an enumeration of {@link java.net.URL URL} objects * representing all the resources with the given name. Class loader * implementations should override this method to specify where to load - * resources from.

+ * resources from. * * @param name * The resource name @@ -1161,14 +1160,16 @@ public abstract class ClassLoader { } /** - * Registers the caller as parallel capable.

+ * Registers the caller as parallel capable. * The registration succeeds if and only if all of the following - * conditions are met:
- * 1. no instance of the caller has been created

- * 2. all of the super classes (except class Object) of the caller are - * registered as parallel capable

- * Note that once a class loader is registered as parallel capable, there - * is no way to change it back.

+ * conditions are met: + *
    + *
  1. no instance of the caller has been created
  2. + *
  3. all of the super classes (except class Object) of the caller are + * registered as parallel capable
  4. + *
+ *

Note that once a class loader is registered as parallel capable, there + * is no way to change it back.

* * @return true if the caller is successfully registered as * parallel capable and false if otherwise. @@ -1185,7 +1186,7 @@ public abstract class ClassLoader { /** * 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()}).

+ * loader (see {@link #getSystemClassLoader()}). * * @param name * The resource name @@ -1292,7 +1293,7 @@ public abstract class ClassLoader { /** * 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()}).

+ * system class loader (see {@link #getSystemClassLoader()}). * * @param name * The resource name @@ -1515,7 +1516,7 @@ public abstract class ClassLoader { * 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.

+ * created. * * @param name * The package name @@ -1572,7 +1573,7 @@ public abstract class ClassLoader { /** * Returns a Package that has been defined by this class loader - * or any of its ancestors.

+ * or any of its ancestors. * * @param name * The package name @@ -1609,7 +1610,7 @@ public abstract class ClassLoader { /** * Returns all of the Packages defined by this class loader and - * its ancestors.

+ * its ancestors. * * @return The array of Package objects defined by this * ClassLoader @@ -1646,7 +1647,7 @@ public abstract class ClassLoader { * method to locate the native libraries that belong to classes loaded with * this class loader. If this method returns null, the VM * searches the library along the path specified as the - * "java.library.path" property.

+ * "java.library.path" property. * * @param libname * The library name @@ -1966,7 +1967,7 @@ public abstract class ClassLoader { * 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)}.

+ * #setClassAssertionStatus(String, boolean)}. * * @param enabled * true if classes loaded by this class loader will @@ -2068,7 +2069,6 @@ public abstract class ClassLoader { * 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." - *

* * @since 1.4 */ diff --git a/jdk/src/share/classes/java/lang/Double.java b/jdk/src/share/classes/java/lang/Double.java index 113cdf81a4c..1b1aece8122 100644 --- a/jdk/src/share/classes/java/lang/Double.java +++ b/jdk/src/share/classes/java/lang/Double.java @@ -256,7 +256,7 @@ public final class Double extends Number implements Comparable { * * *
{@code '\t'} {@code U+0009}{@code HORIZONTAL TABULATION}
{@code '\n'} {@code U+000A}
- * + * * * * diff --git a/jdk/src/share/classes/java/lang/Float.java b/jdk/src/share/classes/java/lang/Float.java index 2f2b6b22444..e130e92314e 100644 --- a/jdk/src/share/classes/java/lang/Float.java +++ b/jdk/src/share/classes/java/lang/Float.java @@ -258,7 +258,7 @@ public final class Float extends Number implements Comparable { * * *

Examples

Examples
Floating-point ValueHexadecimal String
{@code 1.0} {@code 0x1.0p0}
{@code -1.0} {@code -0x1.0p0}
- * + * * * * diff --git a/jdk/src/share/classes/java/lang/ProcessBuilder.java b/jdk/src/share/classes/java/lang/ProcessBuilder.java index b467f45c351..0cb7febe533 100644 --- a/jdk/src/share/classes/java/lang/ProcessBuilder.java +++ b/jdk/src/share/classes/java/lang/ProcessBuilder.java @@ -65,7 +65,7 @@ import java.util.Map; * working directory of the current process, usually the directory * named by the system property {@code user.dir}. * - *
  • a source of standard input. + *
  • a source of standard input. * 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 @@ import java.util.Map; * * *
  • a destination for standard output - * and standard error. By default, the subprocess writes standard + * and standard error. 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 @@ public final class ProcessBuilder * Redirect.from(file).type() == Redirect.Type.READ * } * + * @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 @@ public final class ProcessBuilder * Redirect.to(file).type() == Redirect.Type.WRITE * } * + * @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 @@ public final class ProcessBuilder * Redirect.appendTo(file).type() == Redirect.Type.APPEND * } * + * @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 */ diff --git a/jdk/src/share/classes/java/lang/Runtime.java b/jdk/src/share/classes/java/lang/Runtime.java index 5ff1aac0bce..9e53dc939ec 100644 --- a/jdk/src/share/classes/java/lang/Runtime.java +++ b/jdk/src/share/classes/java/lang/Runtime.java @@ -661,7 +661,7 @@ public class Runtime { /** * 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.

    + * 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 diff --git a/jdk/src/share/classes/java/lang/Thread.java b/jdk/src/share/classes/java/lang/Thread.java index eb89670d149..d8a9ee2a582 100644 --- a/jdk/src/share/classes/java/lang/Thread.java +++ b/jdk/src/share/classes/java/lang/Thread.java @@ -865,8 +865,8 @@ class Thread implements Runnable { * will receive an {@link InterruptedException}. * *

    If this thread is blocked in an I/O operation upon an {@link - * java.nio.channels.InterruptibleChannel interruptible - * channel} 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 @@ class Thread implements Runnable { * 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 @@ class Thread implements Runnable { * ThreadGroup object is returned, unless this thread * has terminated, in which case null is returned. * @since 1.5 + * @return the uncaught exception handler for this thread */ public UncaughtExceptionHandler getUncaughtExceptionHandler() { return uncaughtExceptionHandler != null ? diff --git a/jdk/src/share/classes/java/lang/ThreadLocal.java b/jdk/src/share/classes/java/lang/ThreadLocal.java index b337fc5f2e6..91d3df940d6 100644 --- a/jdk/src/share/classes/java/lang/ThreadLocal.java +++ b/jdk/src/share/classes/java/lang/ThreadLocal.java @@ -131,12 +131,13 @@ public class ThreadLocal { * Creates a thread local variable. The initial value of the variable is * determined by invoking the {@code get} method on the {@code Supplier}. * + * @param 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 ThreadLocal withInitial(Supplier supplier) { + public static ThreadLocal withInitial(Supplier supplier) { return new SuppliedThreadLocal<>(supplier); } From fac53ff2dc7a6002fd5193dde1bf81e4262aa74f Mon Sep 17 00:00:00 2001 From: Alan Bateman Date: Thu, 4 Jul 2013 14:38:44 +0100 Subject: [PATCH 024/123] 8019622: (sl) ServiceLoader.next incorrect when creation and usages are in different contexts Reviewed-by: mchung, ahgross, forax, psandoz --- .../classes/java/util/ServiceLoader.java | 40 ++++++++++++++++--- 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/jdk/src/share/classes/java/util/ServiceLoader.java b/jdk/src/share/classes/java/util/ServiceLoader.java index 01a5f440feb..962438022a7 100644 --- a/jdk/src/share/classes/java/util/ServiceLoader.java +++ b/jdk/src/share/classes/java/util/ServiceLoader.java @@ -30,6 +30,9 @@ import java.io.IOException; 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 @@ public final class ServiceLoader private static final String PREFIX = "META-INF/services/"; // The class or interface representing the service being loaded - private Class service; + private final Class 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 providers = new LinkedHashMap<>(); @@ -215,6 +221,7 @@ public final class ServiceLoader private ServiceLoader(Class 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 @@ public final class ServiceLoader this.loader = loader; } - public boolean hasNext() { + private boolean hasNextService() { if (nextName != null) { return true; } @@ -352,10 +359,9 @@ public final class ServiceLoader 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 @@ public final class ServiceLoader throw new Error(); // This cannot happen } + public boolean hasNext() { + if (acc == null) { + return hasNextService(); + } else { + PrivilegedAction action = new PrivilegedAction() { + public Boolean run() { return hasNextService(); } + }; + return AccessController.doPrivileged(action, acc); + } + } + + public S next() { + if (acc == null) { + return nextService(); + } else { + PrivilegedAction action = new PrivilegedAction() { + public S run() { return nextService(); } + }; + return AccessController.doPrivileged(action, acc); + } + } + public void remove() { throw new UnsupportedOperationException(); } From fd97f9873af2c2a4cff383dffb3951a77fe56de3 Mon Sep 17 00:00:00 2001 From: Brian Goetz Date: Thu, 4 Jul 2013 20:00:20 +0100 Subject: [PATCH 025/123] 8017231: Add StringJoiner.merge Co-authored-by: Henry Jen Reviewed-by: psandoz, alanb --- .../share/classes/java/util/StringJoiner.java | 37 +++++- .../java/util/StringJoiner/MergeTest.java | 124 ++++++++++++++++++ .../util/StringJoiner/StringJoinerTest.java | 22 +--- 3 files changed, 163 insertions(+), 20 deletions(-) create mode 100644 jdk/test/java/util/StringJoiner/MergeTest.java diff --git a/jdk/src/share/classes/java/util/StringJoiner.java b/jdk/src/share/classes/java/util/StringJoiner.java index 3157aa3a2db..d2734102c67 100644 --- a/jdk/src/share/classes/java/util/StringJoiner.java +++ b/jdk/src/share/classes/java/util/StringJoiner.java @@ -114,8 +114,9 @@ public final class StringJoiner { * @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 @@ public final class StringJoiner { } /** - * 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 @@ public final class StringJoiner { 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. + * + *

    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. + * + *

    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); diff --git a/jdk/test/java/util/StringJoiner/MergeTest.java b/jdk/test/java/util/StringJoiner/MergeTest.java new file mode 100644 index 00000000000..79654612db7 --- /dev/null +++ b/jdk/test/java/util/StringJoiner/MergeTest.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8017231 + * @summary test StringJoiner::merge + * @run testng MergeTest + */ + +import java.util.StringJoiner; +import java.util.stream.Stream; +import org.testng.annotations.Test; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.fail; + +@Test +public class MergeTest { + public void testNull() { + StringJoiner sj = new StringJoiner(",", "{", "}"); + try { + sj.merge(null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException npe) { + // expected + } + } + + public void testSimple() { + StringJoiner sj = new StringJoiner(",", "{", "}"); + StringJoiner other = new StringJoiner(",", "[", "]"); + Stream.of("a", "b", "c").forEachOrdered(sj::add); + Stream.of("d", "e", "f").forEachOrdered(other::add); + + sj.merge(other); + assertEquals(sj.toString(), "{a,b,c,d,e,f}"); + } + + public void testEmptyOther() { + StringJoiner sj = new StringJoiner(",", "{", "}"); + StringJoiner other = new StringJoiner(",", "[", "]"); + Stream.of("a", "b", "c").forEachOrdered(sj::add); + + sj.merge(other); + assertEquals(sj.toString(), "{a,b,c}"); + + other.setEmptyValue("EMPTY"); + sj.merge(other); + assertEquals(sj.toString(), "{a,b,c}"); + } + + public void testEmptyThis() { + StringJoiner sj = new StringJoiner(",", "{", "}"); + StringJoiner other = new StringJoiner(":", "[", "]"); + Stream.of("d", "e", "f").forEachOrdered(other::add); + + sj.merge(other); + assertEquals(sj.toString(), "{d:e:f}"); + + sj = new StringJoiner(",", "{", "}").setEmptyValue("EMPTY"); + assertEquals(sj.toString(), "EMPTY"); + sj.merge(other); + assertEquals(sj.toString(), "{d:e:f}"); + } + + public void testEmptyBoth() { + StringJoiner sj = new StringJoiner(",", "{", "}"); + StringJoiner other = new StringJoiner(":", "[", "]"); + + sj.merge(other); + assertEquals(sj.toString(), "{}"); + + other.setEmptyValue("NOTHING"); + sj.merge(other); + assertEquals(sj.toString(), "{}"); + + sj = new StringJoiner(",", "{", "}").setEmptyValue("EMPTY"); + assertEquals(sj.toString(), "EMPTY"); + sj.merge(other); + assertEquals(sj.toString(), "EMPTY"); + } + + public void testCascadeEmpty() { + StringJoiner sj = new StringJoiner(",", "{", "}"); + StringJoiner o1 = new StringJoiner(":", "[", "]").setEmptyValue("Empty1"); + StringJoiner o2 = new StringJoiner(",", "<", ">").setEmptyValue("Empty2"); + + o1.merge(o2); + assertEquals(o1.toString(), "Empty1"); + + sj.merge(o1); + assertEquals(sj.toString(), "{}"); + } + + public void testDelimiter() { + StringJoiner sj = new StringJoiner(",", "{", "}"); + StringJoiner other = new StringJoiner(":", "[", "]"); + Stream.of("a", "b", "c").forEachOrdered(sj::add); + Stream.of("d", "e", "f").forEachOrdered(other::add); + + sj.merge(other); + assertEquals(sj.toString(), "{a,b,c,d:e:f}"); + } +} \ No newline at end of file diff --git a/jdk/test/java/util/StringJoiner/StringJoinerTest.java b/jdk/test/java/util/StringJoiner/StringJoinerTest.java index 3dfdb358772..e1b6fd3f2bf 100644 --- a/jdk/test/java/util/StringJoiner/StringJoinerTest.java +++ b/jdk/test/java/util/StringJoiner/StringJoinerTest.java @@ -27,6 +27,7 @@ * @run testng StringJoinerTest * @author Jim Gish */ +import java.util.ArrayList; import java.util.StringJoiner; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; @@ -44,7 +45,6 @@ public class StringJoinerTest { private static final String FIVE = "Five"; private static final String DASH = "-"; - /* Uncomment when we have streams public void addAddAll() { StringJoiner sj = new StringJoiner(DASH, "{", "}"); sj.add(ONE); @@ -52,7 +52,7 @@ public class StringJoinerTest { ArrayList nextOne = new ArrayList<>(); nextOne.add(TWO); nextOne.add(THREE); - nextOne.stream().forEach(sj::add); + nextOne.stream().forEachOrdered(sj::add); String expected = "{"+ONE+DASH+TWO+DASH+THREE+"}"; assertEquals(sj.toString(), expected); @@ -64,7 +64,7 @@ public class StringJoinerTest { ArrayList firstOne = new ArrayList<>(); firstOne.add(ONE); firstOne.add(TWO); - firstOne.stream().forEach(sj::add); + firstOne.stream().forEachOrdered(sj::add); sj.add(THREE); @@ -79,29 +79,17 @@ public class StringJoinerTest { firstOne.add(ONE); firstOne.add(TWO); firstOne.add(THREE); - firstOne.stream().forEach(sj::add); + firstOne.stream().forEachOrdered(sj::add); ArrayList nextOne = new ArrayList<>(); nextOne.add(FOUR); nextOne.add(FIVE); - nextOne.stream().forEach(sj::add); + nextOne.stream().forEachOrdered(sj::add); String expected = "{"+ONE+DASH+TWO+DASH+THREE+DASH+FOUR+DASH+FIVE+"}"; assertEquals(sj.toString(), expected); } - public void testInto() { - ArrayList list = new ArrayList<>(); - list.add(ONE); - list.add(TWO); - list.add(THREE); - - StringJoiner target = new StringJoiner(",", "{", "}"); - assertEquals(target.toString(), "{" + ONE + "," + TWO + "," + THREE + - "}"); - } - */ - public void addCharSequence() { StringJoiner sj = new StringJoiner(","); CharSequence cs_one = ONE; From 2e28a006d8f7c02d6e8948c24b9dc16296be33c4 Mon Sep 17 00:00:00 2001 From: Shi Jun Zhang Date: Fri, 5 Jul 2013 10:51:54 +0800 Subject: [PATCH 026/123] 8019381: HashMap.isEmpty is non-final, potential issues for get/remove Reviewed-by: chegar, mduigou --- jdk/src/share/classes/java/util/HashMap.java | 14 ++-- .../java/util/HashMap/OverrideIsEmpty.java | 78 +++++++++++++++++++ 2 files changed, 85 insertions(+), 7 deletions(-) create mode 100644 jdk/test/java/util/HashMap/OverrideIsEmpty.java diff --git a/jdk/src/share/classes/java/util/HashMap.java b/jdk/src/share/classes/java/util/HashMap.java index eab47e3776d..c2aace9db8f 100644 --- a/jdk/src/share/classes/java/util/HashMap.java +++ b/jdk/src/share/classes/java/util/HashMap.java @@ -1013,7 +1013,7 @@ public class HashMap */ @SuppressWarnings("unchecked") final Entry getEntry(Object key) { - if (isEmpty()) { + if (size == 0) { return null; } if (key == null) { @@ -1468,7 +1468,7 @@ public class HashMap @Override public boolean remove(Object key, Object value) { - if (isEmpty()) { + if (size == 0) { return false; } if (key == null) { @@ -1531,7 +1531,7 @@ public class HashMap @Override public boolean replace(K key, V oldValue, V newValue) { - if (isEmpty()) { + if (size == 0) { return false; } if (key == null) { @@ -1574,7 +1574,7 @@ public class HashMap @Override public V replace(K key, V value) { - if (isEmpty()) { + if (size == 0) { return null; } if (key == null) { @@ -1694,7 +1694,7 @@ public class HashMap @Override public V computeIfPresent(K key, BiFunction remappingFunction) { - if (isEmpty()) { + if (size == 0) { return null; } if (key == null) { @@ -1980,7 +1980,7 @@ public class HashMap * TreeNode in a TreeBin. */ final Entry removeEntryForKey(Object key) { - if (isEmpty()) { + if (size == 0) { return null; } if (key == null) { @@ -2040,7 +2040,7 @@ public class HashMap * for matching. */ final Entry removeMapping(Object o) { - if (isEmpty() || !(o instanceof Map.Entry)) + if (size == 0 || !(o instanceof Map.Entry)) return null; Map.Entry entry = (Map.Entry) o; diff --git a/jdk/test/java/util/HashMap/OverrideIsEmpty.java b/jdk/test/java/util/HashMap/OverrideIsEmpty.java new file mode 100644 index 00000000000..1c1fd312312 --- /dev/null +++ b/jdk/test/java/util/HashMap/OverrideIsEmpty.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * Portions Copyright (c) 2013 IBM Corporation + */ + +/** + * @test + * @bug 8019381 + * @summary Verify that we do not get exception when we override isEmpty() + * in a subclass of HashMap + * @author zhangshj@linux.vnet.ibm.com + */ + +import java.util.function.BiFunction; +import java.util.HashMap; + +public class OverrideIsEmpty { + public static class NotEmptyHashMap extends HashMap { + private K alwaysExistingKey; + private V alwaysExistingValue; + + @Override + public V get(Object key) { + if (key == alwaysExistingKey) { + return alwaysExistingValue; + } + return super.get(key); + } + + @Override + public int size() { + return super.size() + 1; + } + + @Override + public boolean isEmpty() { + return size() == 0; + } + } + + public static void main(String[] args) { + NotEmptyHashMap map = new NotEmptyHashMap<>(); + Object key = new Object(); + Object value = new Object(); + map.get(key); + map.remove(key); + map.replace(key, value, null); + map.replace(key, value); + map.computeIfPresent(key, new BiFunction() { + public Object apply(Object key, Object oldValue) { + return oldValue; + } + }); + } +} + From e8695e26e428afd041d5eeed9d6ef8b4afeb420f Mon Sep 17 00:00:00 2001 From: Sean Mullan Date: Fri, 5 Jul 2013 15:54:42 -0400 Subject: [PATCH 027/123] 8011547: Update XML Signature implementation to Apache Santuario 1.5.4 Reviewed-by: xuelei --- .../security/algorithms/Algorithm.java | 112 +- .../security/algorithms/JCEMapper.java | 28 + .../algorithms/MessageDigestAlgorithm.java | 449 +- .../algorithms/SignatureAlgorithm.java | 23 +- .../algorithms/SignatureAlgorithmSpi.java | 288 +- .../implementations/IntegrityHmac.java | 946 ++-- .../implementations/SignatureBaseRSA.java | 131 +- .../implementations/SignatureDSA.java | 141 +- .../implementations/SignatureECDSA.java | 668 +-- .../c14n/CanonicalizationException.java | 128 +- .../internal/security/c14n/Canonicalizer.java | 10 + .../security/c14n/CanonicalizerSpi.java | 281 +- .../c14n/InvalidCanonicalizerException.java | 133 +- .../security/c14n/helper/AttrCompare.java | 53 +- .../security/c14n/helper/C14nHelper.java | 241 +- .../c14n/implementations/Canonicalizer11.java | 580 ++- .../Canonicalizer11_OmitComments.java | 28 +- .../Canonicalizer11_WithComments.java | 28 +- .../Canonicalizer20010315.java | 634 +-- .../Canonicalizer20010315Excl.java | 552 ++- ...Canonicalizer20010315ExclOmitComments.java | 64 +- ...Canonicalizer20010315ExclWithComments.java | 66 +- .../Canonicalizer20010315OmitComments.java | 62 +- .../Canonicalizer20010315WithComments.java | 58 +- .../implementations/CanonicalizerBase.java | 1571 +++---- .../CanonicalizerPhysical.java | 184 + .../implementations/NameSpaceSymbTable.java | 428 +- .../c14n/implementations/UtfHelpper.java | 279 +- .../encryption/AbstractSerializer.java | 249 + .../security/encryption/AgreementMethod.java | 41 +- .../security/encryption/CipherData.java | 46 +- .../security/encryption/CipherReference.java | 50 +- .../security/encryption/CipherValue.java | 41 +- .../encryption/DocumentSerializer.java | 114 + .../security/encryption/EncryptedData.java | 30 +- .../security/encryption/EncryptedKey.java | 35 +- .../security/encryption/EncryptedType.java | 40 +- .../security/encryption/EncryptionMethod.java | 55 +- .../encryption/EncryptionProperties.java | 36 +- .../encryption/EncryptionProperty.java | 36 +- .../security/encryption/Reference.java | 41 +- .../security/encryption/ReferenceList.java | 58 +- .../security/encryption/Serializer.java | 77 + .../security/encryption/Transforms.java | 67 +- .../security/encryption/XMLCipher.java | 4052 ++++++++--------- .../security/encryption/XMLCipherInput.java | 169 +- .../encryption/XMLCipherParameters.java | 87 +- .../encryption/XMLEncryptionException.java | 120 +- .../AlgorithmAlreadyRegisteredException.java | 136 +- .../exceptions/Base64DecodingException.java | 124 +- .../exceptions/XMLSecurityException.java | 317 +- .../XMLSecurityRuntimeException.java | 306 +- ...tentHandlerAlreadyRegisteredException.java | 136 +- .../xml/internal/security/keys/KeyInfo.java | 1935 ++++---- .../xml/internal/security/keys/KeyUtils.java | 102 +- .../keys/content/DEREncodedKeyValue.java | 158 + .../security/keys/content/KeyInfoContent.java | 36 +- .../keys/content/KeyInfoReference.java | 107 + .../security/keys/content/KeyName.java | 96 +- .../security/keys/content/KeyValue.java | 86 +- .../security/keys/content/MgmtData.java | 98 +- .../security/keys/content/PGPData.java | 59 +- .../keys/content/RetrievalMethod.java | 214 +- .../security/keys/content/SPKIData.java | 61 +- .../security/keys/content/X509Data.java | 857 ++-- .../keys/content/keyvalues/DSAKeyValue.java | 197 +- .../content/keyvalues/KeyValueContent.java | 54 +- .../keys/content/keyvalues/RSAKeyValue.java | 177 +- .../keys/content/x509/XMLX509CRL.java | 104 +- .../keys/content/x509/XMLX509Certificate.java | 240 +- .../keys/content/x509/XMLX509DataContent.java | 34 +- .../keys/content/x509/XMLX509Digest.java | 139 + .../content/x509/XMLX509IssuerSerial.java | 100 +- .../keys/content/x509/XMLX509SKI.java | 83 +- .../keys/content/x509/XMLX509SubjectName.java | 136 +- .../InvalidKeyResolverException.java | 132 +- .../keys/keyresolver/KeyResolver.java | 6 + .../keyresolver/KeyResolverException.java | 134 +- .../keys/keyresolver/KeyResolverSpi.java | 330 +- .../DEREncodedKeyValueResolver.java | 83 + .../implementations/DSAKeyValueResolver.java | 145 +- .../implementations/EncryptedKeyResolver.java | 176 +- .../KeyInfoReferenceResolver.java | 290 ++ .../implementations/PrivateKeyResolver.java | 353 ++ .../implementations/RSAKeyValueResolver.java | 132 +- .../RetrievalMethodResolver.java | 591 +-- .../implementations/SecretKeyResolver.java | 129 + .../implementations/SingleKeyResolver.java | 172 + .../X509CertificateResolver.java | 178 +- .../implementations/X509DigestResolver.java | 164 + .../X509IssuerSerialResolver.java | 214 +- .../implementations/X509SKIResolver.java | 245 +- .../X509SubjectNameResolver.java | 261 +- .../keys/storage/StorageResolver.java | 294 +- .../storage/StorageResolverException.java | 130 +- .../keys/storage/StorageResolverSpi.java | 48 +- .../CertsInFilesystemDirectoryResolver.java | 331 +- .../implementations/KeyStoreResolver.java | 235 +- .../SingleCertificateResolver.java | 137 +- .../xml/internal/security/resource/config.xml | 126 +- .../security/resource/log4j.properties | 36 - .../resource/xmlsecurity_de.properties | 7 + .../resource/xmlsecurity_en.properties | 257 +- .../InvalidDigestValueException.java | 130 +- .../InvalidSignatureValueException.java | 126 +- .../internal/security/signature/Manifest.java | 949 ++-- .../MissingResourceFailureException.java | 192 +- .../security/signature/NodeFilter.java | 74 +- .../security/signature/ObjectContainer.java | 213 +- .../security/signature/Reference.java | 1331 +++--- .../ReferenceNotInitializedException.java | 128 +- .../signature/SignatureProperties.java | 224 +- .../security/signature/SignatureProperty.java | 195 +- .../security/signature/SignedInfo.java | 461 +- .../security/signature/XMLSignature.java | 1329 +++--- .../signature/XMLSignatureException.java | 126 +- .../security/signature/XMLSignatureInput.java | 410 +- .../signature/XMLSignatureInputDebugger.java | 1224 +++-- .../signature/reference/ReferenceData.java | 34 + .../reference/ReferenceNodeSetData.java | 53 + .../reference/ReferenceOctetStreamData.java | 105 + .../reference/ReferenceSubTreeData.java | 181 + .../transforms/InvalidTransformException.java | 126 +- .../security/transforms/Transform.java | 6 +- .../security/transforms/TransformParam.java | 35 +- .../security/transforms/TransformSpi.java | 92 +- .../transforms/TransformationException.java | 127 +- .../security/transforms/Transforms.java | 148 +- .../transforms/implementations/FuncHere.java | 190 +- .../implementations/FuncHereContext.java | 143 - .../TransformBase64Decode.java | 221 +- .../implementations/TransformC14N.java | 83 +- .../implementations/TransformC14N11.java | 40 +- .../TransformC14N11_WithComments.java | 40 +- .../TransformC14NExclusive.java | 132 +- .../TransformC14NExclusiveWithComments.java | 121 +- .../TransformC14NWithComments.java | 76 +- .../TransformEnvelopedSignature.java | 200 +- .../implementations/TransformXPath.java | 202 +- .../TransformXPath2Filter.java | 465 +- .../implementations/TransformXPointer.java | 74 +- .../implementations/TransformXSLT.java | 227 +- .../params/InclusiveNamespaces.java | 259 +- .../params/XPath2FilterContainer.java | 479 +- .../params/XPath2FilterContainer04.java | 411 +- .../transforms/params/XPathContainer.java | 101 +- .../params/XPathFilterCHGPContainer.java | 515 ++- .../xml/internal/security/utils/Base64.java | 1407 +++--- .../security/utils/CachedXPathAPIHolder.java | 65 - .../utils/CachedXPathFuncHereAPI.java | 466 -- .../security/utils/ClassLoaderUtils.java | 277 ++ .../internal/security/utils/Constants.java | 439 +- .../security/utils/DOMNamespaceContext.java | 79 + .../security/utils/DigesterOutputStream.java | 44 +- .../security/utils/ElementChecker.java | 40 +- .../security/utils/ElementCheckerImpl.java | 118 +- .../internal/security/utils/ElementProxy.java | 98 +- .../security/utils/EncryptionConstants.java | 363 +- .../utils/EncryptionElementProxy.java | 78 +- .../security/utils/HelperNodeList.java | 140 +- .../internal/security/utils/IdResolver.java | 270 +- .../security/utils/IgnoreAllErrorHandler.java | 104 +- .../internal/security/utils/JDKXPathAPI.java | 132 + .../security/utils/JDKXPathFactory.java | 37 + .../internal/security/utils/JavaUtils.java | 85 +- .../security/utils/RFC2253Parser.java | 870 ++-- .../utils/Signature11ElementProxy.java | 70 + .../security/utils/SignatureElementProxy.java | 95 +- .../security/utils/SignerOutputStream.java | 53 +- .../utils/UnsyncBufferedOutputStream.java | 144 +- .../utils/UnsyncByteArrayOutputStream.java | 51 +- .../xml/internal/security/utils/XMLUtils.java | 1119 +++-- .../xml/internal/security/utils/XPathAPI.java | 66 + .../internal/security/utils/XPathFactory.java | 71 + .../security/utils/XPathFuncHereAPI.java | 306 -- .../security/utils/XalanXPathAPI.java | 210 + .../security/utils/XalanXPathFactory.java | 37 + .../utils/resolver/ResourceResolver.java | 49 +- .../resolver/ResourceResolverContext.java | 43 + .../resolver/ResourceResolverException.java | 213 +- .../utils/resolver/ResourceResolverSpi.java | 353 +- .../implementations/ResolverAnonymous.java | 97 +- .../implementations/ResolverDirectHTTP.java | 410 +- .../implementations/ResolverFragment.java | 174 +- .../ResolverLocalFilesystem.java | 264 +- .../implementations/ResolverXPointer.java | 231 +- .../dsig/internal/DigesterOutputStream.java | 66 +- .../xml/dsig/internal/MacOutputStream.java | 38 +- .../xml/dsig/internal/SignerOutputStream.java | 56 +- .../dom/AbstractDOMSignatureMethod.java | 218 + .../internal/dom/ApacheCanonicalizer.java | 122 +- .../jcp/xml/dsig/internal/dom/ApacheData.java | 32 +- .../dsig/internal/dom/ApacheNodeSetData.java | 51 +- .../internal/dom/ApacheOctetStreamData.java | 33 +- .../dsig/internal/dom/ApacheTransform.java | 104 +- .../dsig/internal/dom/DOMBase64Transform.java | 31 +- .../dom/DOMCanonicalXMLC14N11Method.java | 30 +- .../dom/DOMCanonicalXMLC14NMethod.java | 30 +- .../dom/DOMCanonicalizationMethod.java | 59 +- .../dsig/internal/dom/DOMCryptoBinary.java | 31 +- .../dsig/internal/dom/DOMDigestMethod.java | 89 +- .../internal/dom/DOMEnvelopedTransform.java | 30 +- .../dsig/internal/dom/DOMExcC14NMethod.java | 81 +- .../internal/dom/DOMHMACSignatureMethod.java | 135 +- .../jcp/xml/dsig/internal/dom/DOMKeyInfo.java | 121 +- .../dsig/internal/dom/DOMKeyInfoFactory.java | 59 +- .../jcp/xml/dsig/internal/dom/DOMKeyName.java | 48 +- .../xml/dsig/internal/dom/DOMKeyValue.java | 557 ++- .../xml/dsig/internal/dom/DOMManifest.java | 90 +- .../jcp/xml/dsig/internal/dom/DOMPGPData.java | 104 +- .../xml/dsig/internal/dom/DOMReference.java | 325 +- .../dsig/internal/dom/DOMRetrievalMethod.java | 126 +- .../dsig/internal/dom/DOMSignatureMethod.java | 410 +- .../internal/dom/DOMSignatureProperties.java | 90 +- .../internal/dom/DOMSignatureProperty.java | 103 +- .../xml/dsig/internal/dom/DOMSignedInfo.java | 153 +- .../xml/dsig/internal/dom/DOMStructure.java | 30 +- .../xml/dsig/internal/dom/DOMSubTreeData.java | 70 +- .../xml/dsig/internal/dom/DOMTransform.java | 103 +- .../dsig/internal/dom/DOMURIDereferencer.java | 47 +- .../jcp/xml/dsig/internal/dom/DOMUtils.java | 101 +- .../xml/dsig/internal/dom/DOMX509Data.java | 122 +- .../internal/dom/DOMX509IssuerSerial.java | 59 +- .../xml/dsig/internal/dom/DOMXMLObject.java | 144 +- .../dsig/internal/dom/DOMXMLSignature.java | 314 +- .../internal/dom/DOMXMLSignatureFactory.java | 113 +- .../dom/DOMXPathFilter2Transform.java | 96 +- .../dsig/internal/dom/DOMXPathTransform.java | 69 +- .../dsig/internal/dom/DOMXSLTTransform.java | 31 +- .../org/jcp/xml/dsig/internal/dom/Utils.java | 39 +- .../jcp/xml/dsig/internal/dom/XMLDSigRI.java | 91 +- 231 files changed, 27141 insertions(+), 23914 deletions(-) create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java delete mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java delete mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java delete mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java delete mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathFactory.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathAPI.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java delete mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathFactory.java create mode 100644 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java create mode 100644 jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/AbstractDOMSignatureMethod.java diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java index 62fd0fe4964..6b661bb31f3 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java @@ -2,82 +2,78 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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); - super(doc); + this.setAlgorithmURI(algorithmURI); + } - 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 + ); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java index 9e736518936..ca7d42a869a 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java @@ -114,6 +114,18 @@ public class JCEMapper { XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1, 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") @@ -154,6 +166,18 @@ public class JCEMapper { XMLCipher.AES_256, 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") @@ -162,6 +186,10 @@ public class JCEMapper { XMLCipher.RSA_OAEP, 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") diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java index 63a808ba745..d10c88c78bd 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java @@ -2,265 +2,254 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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. * *

      * MessageDigestAlgorithm.getInstance()
      * 
    - * */ 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; + /** Field algorithm stores the actual {@link java.security.MessageDigest} */ + private final MessageDigest algorithm; - /** - * 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) { + /** + * 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); - super(doc, algorithmURI); + algorithm = getDigestInstance(algorithmURI); + } - this.algorithm = messageDigest; - } + /** + * 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); + } - static ThreadLocal> instances=new - ThreadLocal>() { - protected Map initialValue() { - return new HashMap(); - }; - }; + private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException { + String algorithmID = JCEMapper.translateURItoJCEID(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); - } - -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); - } - - 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() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } catch (NoSuchProviderException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + if (algorithmID == null) { + Object[] exArgs = { algorithmURI }; + throw new XMLSignatureException("algorithms.NoSuchMap", exArgs); } - instances.get().put(algorithmURI, md); + + 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() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } catch (NoSuchProviderException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } + 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 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#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[], 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#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#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#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#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#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) { - this.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); - } - - /** @inheritDoc */ - public String getBaseNamespace() { - return Constants.SignatureSpecNS; - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_DIGESTMETHOD; - } + } + + /** + * 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; + } + + /** + * 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(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 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 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 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 algorithm.getDigestLength(); + } + + /** + * 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) { + 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) { + algorithm.update(buf, offset, len); + } + + /** @inheritDoc */ + public String getBaseNamespace() { + return Constants.SignatureSpecNS; + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_DIGESTMETHOD; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java index 5dbcf58e33b..4748a6bc882 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java @@ -74,7 +74,7 @@ public class SignatureAlgorithm extends Algorithm { this.algorithmURI = algorithmURI; signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(this._constructionElement); + signatureAlgorithm.engineGetContextFromElement(this.constructionElement); } /** @@ -92,10 +92,10 @@ public class SignatureAlgorithm extends Algorithm { 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 @@ public class SignatureAlgorithm extends Algorithm { } signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(this._constructionElement); + signatureAlgorithm.engineGetContextFromElement(this.constructionElement); } /** @@ -310,7 +310,7 @@ public class SignatureAlgorithm extends Algorithm { * @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 @@ public class SignatureAlgorithm extends Algorithm { * 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 ); @@ -409,6 +407,15 @@ public class SignatureAlgorithm extends Algorithm { algorithmHash.put( 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 ); diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java index c47be7e2c0d..77bcfa7fd98 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 java.security.spec.AlgorithmParameterSpec; 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 Transformation algorithm - * - * @return the URI representation of Transformation algorithm - */ - protected abstract String engineGetURI(); + /** + * Returns the URI representation of Transformation algorithm + * + * @return the URI representation of Transformation algorithm + */ + 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() { - } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java index 7231b069a18..8935e389728 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Document; 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()); - /** - * Method engineGetURI - * - *@inheritDoc - */ - public abstract String engineGetURI(); + /** Field macAlgorithm */ + private Mac macAlgorithm = null; - /** - * Returns the output length of the hash/digest. - */ - abstract int getDigestLength(); + /** Field HMACOutputLength */ + private int HMACOutputLength = 0; + private boolean HMACOutputLengthSet = false; - /** Field _macAlgorithm */ - private Mac _macAlgorithm = null; - private boolean _HMACOutputLengthSet = false; + /** + * Method engineGetURI + * + *@inheritDoc + */ + public abstract String engineGetURI(); - /** Field _HMACOutputLength */ - int _HMACOutputLength = 0; + /** + * Returns the output length of the hash/digest. + */ + abstract int getDigestLength(); - /** - * Method IntegrityHmacSHA1das - * - * @throws XMLSignatureException - */ - public IntegrityHmac() throws XMLSignatureException { + /** + * 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); + } - 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; + this.macAlgorithm.reset(); + } - 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 { - - 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)]; + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } - System.arraycopy(completeResult, 0, strippedResult, 0, bytes); + try { + this.macAlgorithm.init(secretKey); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } - if (abits > 0) { - byte[] MASK = { (byte) 0x00, (byte) 0x80, (byte) 0xC0, (byte) 0xE0, - (byte) 0xF0, (byte) 0xF8, (byte) 0xFC, (byte) 0xFE }; + /** + * 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 }; - strippedResult[bytes] = (byte) (completeResult[bytes] & MASK[abits]); - } + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } - return strippedResult; - } + 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 - * @throws XMLSignatureException - */ - protected void engineInitSign(Key secretKey) throws XMLSignatureException { + /** + * Method engineInitSign + * + * @param secretKey + * @param secureRandom + * @throws XMLSignatureException + */ + protected void engineInitSign(Key secretKey, SecureRandom secureRandom) + throws XMLSignatureException { + throw new XMLSignatureException("algorithms.CannotUseSecureRandomOnMAC"); + } - if (!(secretKey instanceof SecretKey)) { - String supplied = secretKey.getClass().getName(); - String needed = SecretKey.class.getName(); - Object exArgs[] = { supplied, needed }; + /** + * 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); + } + } - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + /** + * 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.init(secretKey); - } catch (InvalidKeyException 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); + } + } - /** - * Method engineInitSign - * - * @param secretKey - * @param algorithmParameterSpec - * @throws XMLSignatureException - */ - protected void engineInitSign( - Key secretKey, AlgorithmParameterSpec algorithmParameterSpec) - throws XMLSignatureException { + /** + * Method engineGetJCEAlgorithmString + * @inheritDoc + * + */ + protected String engineGetJCEAlgorithmString() { + return this.macAlgorithm.getAlgorithm(); + } - if (!(secretKey instanceof SecretKey)) { - String supplied = secretKey.getClass().getName(); - String needed = SecretKey.class.getName(); - Object exArgs[] = { supplied, needed }; + /** + * Method engineGetJCEAlgorithmString + * + * @inheritDoc + */ + protected String engineGetJCEProviderName() { + return this.macAlgorithm.getProvider().getName(); + } - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + /** + * Method engineSetHMACOutputLength + * + * @param HMACOutputLength + */ + protected void engineSetHMACOutputLength(int HMACOutputLength) { + this.HMACOutputLength = HMACOutputLength; + this.HMACOutputLengthSet = true; + } - try { - this._macAlgorithm.init(secretKey, algorithmParameterSpec); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } catch (InvalidAlgorithmParameterException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Method engineGetContextFromElement + * + * @param element + */ + protected void engineGetContextFromElement(Element element) { + super.engineGetContextFromElement(element); - /** - * Method engineInitSign - * - * @param secretKey - * @param secureRandom - * @throws XMLSignatureException - */ - protected void engineInitSign(Key secretKey, SecureRandom secureRandom) - throws XMLSignatureException { - throw new XMLSignatureException("algorithms.CannotUseSecureRandomOnMAC"); - } + if (element == null) { + throw new IllegalArgumentException("element null"); + } - /** - * 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 { + Text hmaclength = + XMLUtils.selectDsNodeText(element.getFirstChild(), Constants._TAG_HMACOUTPUTLENGTH, 0); - try { - this._macAlgorithm.update(input); - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } + if (hmaclength != null) { + this.HMACOutputLength = Integer.parseInt(hmaclength.getData()); + this.HMACOutputLengthSet = true; + } + } - /** - * 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 { + /** + * Method engineAddContextToElement + * + * @param element + */ + public void engineAddContextToElement(Element element) { + if (element == null) { + throw new IllegalArgumentException("null element"); + } - try { - this._macAlgorithm.update(input); - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } + if (this.HMACOutputLengthSet) { + Document doc = element.getOwnerDocument(); + Element HMElem = + XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_HMACOUTPUTLENGTH); + Text HMText = + doc.createTextNode(Integer.valueOf(this.HMACOutputLength).toString()); - /** - * 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 { + HMElem.appendChild(HMText); + XMLUtils.addReturnToElement(element); + element.appendChild(HMElem); + XMLUtils.addReturnToElement(element); + } + } - try { - this._macAlgorithm.update(buf, offset, len); - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Class IntegrityHmacSHA1 + */ + public static class IntegrityHmacSHA1 extends IntegrityHmac { - /** - * Method engineGetJCEAlgorithmString - * @inheritDoc - * - */ - protected String engineGetJCEAlgorithmString() { + /** + * Constructor IntegrityHmacSHA1 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA1() throws XMLSignatureException { + super(); + } - log.log(java.util.logging.Level.FINE, "engineGetJCEAlgorithmString()"); + /** + * Method engineGetURI + * @inheritDoc + * + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA1; + } - return this._macAlgorithm.getAlgorithm(); - } + int getDigestLength() { + return 160; + } + } - /** - * Method engineGetJCEAlgorithmString - * - * @inheritDoc - */ - protected String engineGetJCEProviderName() { - return this._macAlgorithm.getProvider().getName(); - } + /** + * Class IntegrityHmacSHA256 + */ + public static class IntegrityHmacSHA256 extends IntegrityHmac { - /** - * Method engineSetHMACOutputLength - * - * @param HMACOutputLength - */ - protected void engineSetHMACOutputLength(int HMACOutputLength) { - this._HMACOutputLength = HMACOutputLength; - this._HMACOutputLengthSet = true; - } + /** + * Constructor IntegrityHmacSHA256 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA256() throws XMLSignatureException { + super(); + } - /** - * Method engineGetContextFromElement - * - * @param element - */ - protected void engineGetContextFromElement(Element element) { + /** + * Method engineGetURI + * + * @inheritDoc + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA256; + } - super.engineGetContextFromElement(element); + int getDigestLength() { + return 256; + } + } - if (element == null) { - throw new IllegalArgumentException("element null"); - } + /** + * Class IntegrityHmacSHA384 + */ + public static class IntegrityHmacSHA384 extends IntegrityHmac { - Text hmaclength =XMLUtils.selectDsNodeText(element.getFirstChild(), - Constants._TAG_HMACOUTPUTLENGTH,0); + /** + * Constructor IntegrityHmacSHA384 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA384() throws XMLSignatureException { + super(); + } - if (hmaclength != null) { - this._HMACOutputLength = Integer.parseInt(hmaclength.getData()); - this._HMACOutputLengthSet = true; - } + /** + * Method engineGetURI + * @inheritDoc + * + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA384; + } - } + int getDigestLength() { + return 384; + } + } - /** - * Method engineAddContextToElement - * - * @param element - */ - public void engineAddContextToElement(Element element) { + /** + * Class IntegrityHmacSHA512 + */ + public static class IntegrityHmacSHA512 extends IntegrityHmac { - if (element == null) { - throw new IllegalArgumentException("null element"); - } + /** + * Constructor IntegrityHmacSHA512 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA512() throws XMLSignatureException { + super(); + } - if (this._HMACOutputLengthSet) { - Document doc = element.getOwnerDocument(); - Element HMElem = XMLUtils.createElementInSignatureSpace(doc, - Constants._TAG_HMACOUTPUTLENGTH); - Text HMText = - doc.createTextNode(new Integer(this._HMACOutputLength).toString()); + /** + * Method engineGetURI + * @inheritDoc + * + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA512; + } - HMElem.appendChild(HMText); - XMLUtils.addReturnToElement(element); - element.appendChild(HMElem); - XMLUtils.addReturnToElement(element); - } - } + int getDigestLength() { + return 512; + } + } - /** - * Class IntegrityHmacSHA1 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacSHA1 extends IntegrityHmac { + /** + * Class IntegrityHmacRIPEMD160 + */ + public static class IntegrityHmacRIPEMD160 extends IntegrityHmac { - /** - * Constructor IntegrityHmacSHA1 - * - * @throws XMLSignatureException - */ - public IntegrityHmacSHA1() throws XMLSignatureException { - super(); - } + /** + * Constructor IntegrityHmacRIPEMD160 + * + * @throws XMLSignatureException + */ + public IntegrityHmacRIPEMD160() 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_RIPEMD160; + } - int getDigestLength() { - return 160; - } - } + int getDigestLength() { + return 160; + } + } - /** - * Class IntegrityHmacSHA256 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacSHA256 extends IntegrityHmac { + /** + * Class IntegrityHmacMD5 + */ + public static class IntegrityHmacMD5 extends IntegrityHmac { - /** - * Constructor IntegrityHmacSHA256 - * - * @throws XMLSignatureException - */ - public IntegrityHmacSHA256() throws XMLSignatureException { - super(); - } + /** + * Constructor IntegrityHmacMD5 + * + * @throws XMLSignatureException + */ + public IntegrityHmacMD5() throws XMLSignatureException { + super(); + } - /** - * Method engineGetURI - * - * @inheritDoc - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_SHA256; - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5; + } - 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(); - } - - /** - * Method engineGetURI - * @inheritDoc - * - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_SHA384; - } - - int getDigestLength() { - return 384; - } - } - - /** - * Class IntegrityHmacSHA512 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacSHA512 extends IntegrityHmac { - - /** - * Constructor IntegrityHmacSHA512 - * - * @throws XMLSignatureException - */ - public IntegrityHmacSHA512() throws XMLSignatureException { - super(); - } - - /** - * Method engineGetURI - * @inheritDoc - * - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_SHA512; - } - - int getDigestLength() { - return 512; - } - } - - /** - * Class IntegrityHmacRIPEMD160 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacRIPEMD160 extends IntegrityHmac { - - /** - * Constructor IntegrityHmacRIPEMD160 - * - * @throws XMLSignatureException - */ - public IntegrityHmacRIPEMD160() throws XMLSignatureException { - super(); - } - - /** - * Method engineGetURI - * - * @inheritDoc - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160; - } - - int getDigestLength() { - return 160; - } - } - - /** - * Class IntegrityHmacMD5 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacMD5 extends IntegrityHmac { - - /** - * Constructor IntegrityHmacMD5 - * - * @throws XMLSignatureException - */ - public IntegrityHmacMD5() throws XMLSignatureException { - super(); - } - - /** - * Method engineGetURI - * - * @inheritDoc - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5; - } - - int getDigestLength() { - return 128; - } - } + int getDigestLength() { + return 128; + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java index ccc01b01c58..7460f66ffd6 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2007 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.algorithms.SignatureAlgorithmSpi 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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { * @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** * Class SignatureRSASHA256 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSASHA256 extends SignatureBaseRSA { @@ -287,9 +264,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** * Class SignatureRSASHA384 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSASHA384 extends SignatureBaseRSA { @@ -310,9 +284,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** * Class SignatureRSASHA512 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSASHA512 extends SignatureBaseRSA { @@ -333,9 +304,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** * Class SignatureRSARIPEMD160 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSARIPEMD160 extends SignatureBaseRSA { @@ -356,9 +324,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** * Class SignatureRSAMD5 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSAMD5 extends SignatureBaseRSA { diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java index 615aa436e46..0c6aca1361a 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.signature.XMLSignatureException; 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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @inheritDoc */ protected String engineGetURI() { - return SignatureDSA._URI; + return SignatureDSA.URI; } /** @@ -68,17 +66,17 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { */ 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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { */ 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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { */ 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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { /** * @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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @inheritDoc */ protected String engineGetJCEAlgorithmString() { - return this._signatureAlgorithm.getAlgorithm(); + return this.signatureAlgorithm.getAlgorithm(); } /** @@ -267,7 +254,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @inheritDoc */ protected String engineGetJCEProviderName() { - return this._signatureAlgorithm.getProvider().getName(); + return this.signatureAlgorithm.getProvider().getName(); } /** @@ -282,8 +269,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @throws IOException * @see 6.4.1 DSA */ - 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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { 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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @throws IOException * @see 6.4.1 DSA */ - 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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { int j = i; if (xmldsigBytes[20 - i] < 0) { - j += 1; + j += 1; } int k; @@ -373,10 +357,8 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @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"); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java index 18fdffe28fb..8da7a8c6e67 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.XMLSignature; 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 6.4.1 DSA - * @see 3.3. ECDSA Signatures - */ - 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 6.4.1 DSA + * @see 3.3. ECDSA Signatures + */ + 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[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]; - - System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 24 - i, - i); - System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes, - 48 - j, j); - - return xmldsigBytes; - } - - /** - * 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 6.4.1 DSA - * @see 3.3. ECDSA Signatures - */ - private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) - throws IOException { - - if (xmldsigBytes.length != 48) { - throw new IOException("Invalid XMLDSIG format of ECDSA signature"); - } - - int i; - - for (i = 24; (i > 0) && (xmldsigBytes[24 - i] == 0); i--); - - int j = i; - - if (xmldsigBytes[24 - i] < 0) { - j += 1; - } - - int k; - - for (k = 24; (k > 0) && (xmldsigBytes[48 - k] == 0); k--); - - int l = k; - - if (xmldsigBytes[48 - k] < 0) { - l += 1; - } - - byte asn1Bytes[] = new byte[6 + j + l]; - - 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; - - System.arraycopy(xmldsigBytes, 48 - k, asn1Bytes, (6 + j + l) - k, k); - - return asn1Bytes; - } - - /** - * Constructor SignatureRSA - * - * @throws XMLSignatureException - */ - public SignatureECDSA() throws XMLSignatureException { - - String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); - - 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() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } catch (NoSuchProviderException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + 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"); } - } - /** @inheritDoc */ - protected void engineSetParameter(AlgorithmParameterSpec params) - throws XMLSignatureException { + byte rLength = asn1Bytes[offset + 1]; + int i; - try { - this._signatureAlgorithm.setParameter(params); - } catch (InvalidAlgorithmParameterException ex) { - throw new XMLSignatureException("empty", ex); - } - } + for (i = rLength; (i > 0) && (asn1Bytes[(offset + 2 + rLength) - i] == 0); i--); - /** @inheritDoc */ - protected boolean engineVerify(byte[] signature) - throws XMLSignatureException { + byte sLength = asn1Bytes[offset + 2 + rLength + 1]; + int j; - try { - byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature); + for (j = sLength; + (j > 0) && (asn1Bytes[(offset + 2 + rLength + 2 + sLength) - j] == 0); j--); - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Called ECDSA.verify() on " + Base64.encode(signature)); + int rawLen = Math.max(i, j); - return this._signatureAlgorithm.verify(jcebytes); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); - } - } + 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]; - /** @inheritDoc */ - protected void engineInitVerify(Key publicKey) throws XMLSignatureException { + 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); - if (!(publicKey instanceof PublicKey)) { - String supplied = publicKey.getClass().getName(); - String needed = PublicKey.class.getName(); - Object exArgs[] = { supplied, needed }; + return xmldsigBytes; + } - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + /** + * 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 6.4.1 DSA + * @see 3.3. ECDSA Signatures + */ + public static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException { - try { - this._signatureAlgorithm.initVerify((PublicKey) publicKey); - } catch (InvalidKeyException ex) { + int rawLen = xmldsigBytes.length/2; + + int i; + + for (i = rawLen; (i > 0) && (xmldsigBytes[rawLen - i] == 0); i--); + + int j = i; + + if (xmldsigBytes[rawLen - i] < 0) { + j += 1; + } + + int k; + + for (k = rawLen; (k > 0) && (xmldsigBytes[2*rawLen - k] == 0); k--); + + int l = k; + + if (xmldsigBytes[2*rawLen - k] < 0) { + l += 1; + } + + 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, rawLen - i, asn1Bytes, (offset + j) - i, i); + + offset += j; + + asn1Bytes[offset++] = 2; + asn1Bytes[offset++] = (byte) l; + + System.arraycopy(xmldsigBytes, 2*rawLen - k, asn1Bytes, (offset + l) - k, k); + + return asn1Bytes; + } + + /** + * Constructor SignatureRSA + * + * @throws XMLSignatureException + */ + public SignatureECDSA() throws XMLSignatureException { + + String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); + + 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() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } catch (NoSuchProviderException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } + } + + /** @inheritDoc */ + protected void engineSetParameter(AlgorithmParameterSpec params) + throws XMLSignatureException { + try { + this.signatureAlgorithm.setParameter(params); + } catch (InvalidAlgorithmParameterException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @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)); + } + + 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 { + + if (!(publicKey instanceof PublicKey)) { + String supplied = publicKey.getClass().getName(); + String needed = PublicKey.class.getName(); + Object exArgs[] = { supplied, needed }; + + 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 { + /** @inheritDoc */ + protected byte[] engineSign() throws XMLSignatureException { + try { + byte jcebytes[] = this.signatureAlgorithm.sign(); - 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 }; - /** @inheritDoc */ - protected void engineInitSign(Key privateKey, SecureRandom secureRandom) - throws XMLSignatureException { + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } - if (!(privateKey instanceof PrivateKey)) { - String supplied = privateKey.getClass().getName(); - String needed = PrivateKey.class.getName(); - Object exArgs[] = { supplied, needed }; + try { + this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + /** @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 }; - try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey, - secureRandom); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } - /** @inheritDoc */ - protected void engineInitSign(Key privateKey) throws XMLSignatureException { + try { + this.signatureAlgorithm.initSign((PrivateKey) privateKey); + } 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 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 input) throws XMLSignatureException { + try { + this.signatureAlgorithm.update(input); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } - try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** @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); + } + } - /** @inheritDoc */ - protected void engineUpdate(byte[] input) throws XMLSignatureException { + /** @inheritDoc */ + protected String engineGetJCEAlgorithmString() { + return this.signatureAlgorithm.getAlgorithm(); + } - try { - this._signatureAlgorithm.update(input); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** @inheritDoc */ + protected String engineGetJCEProviderName() { + return this.signatureAlgorithm.getProvider().getName(); + } - /** @inheritDoc */ - protected void engineUpdate(byte input) throws XMLSignatureException { + /** @inheritDoc */ + protected void engineSetHMACOutputLength(int HMACOutputLength) + throws XMLSignatureException { + throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC"); + } - try { - this._signatureAlgorithm.update(input); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** @inheritDoc */ + protected void engineInitSign( + Key signingKey, AlgorithmParameterSpec algorithmParameterSpec + ) throws XMLSignatureException { + throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnRSA"); + } - /** @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 { - /** - * Class SignatureRSASHA1 - * - * @author $Author: mullan $ - * @version $Revision: 1.2 $ - */ - public static class SignatureECDSASHA1 extends SignatureECDSA { + /** + * Constructor SignatureRSASHA384 + * + * @throws XMLSignatureException + */ + public SignatureECDSASHA384() throws XMLSignatureException { + super(); + } - /** - * Constructor SignatureRSASHA1 - * - * @throws XMLSignatureException - */ - public SignatureECDSASHA1() throws XMLSignatureException { - super(); - } + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384; + } + } - /** @inheritDoc */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1; - } - } + /** + * Class SignatureRSASHA512 + * + * @author Alex Dupre + */ + public static class SignatureECDSASHA512 extends SignatureECDSA { + + /** + * Constructor SignatureRSASHA512 + * + * @throws XMLSignatureException + */ + public SignatureECDSASHA512() throws XMLSignatureException { + super(); + } + + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512; + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java index 36c98cfe790..aae62133dcc 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java @@ -2,29 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; */ 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); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java index db1d4c261b7..2f0b31f5ed4 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java @@ -39,6 +39,7 @@ import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicaliz 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 class Canonicalizer { */ 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> canonicalizerHash = new ConcurrentHashMap>(); @@ -202,6 +208,10 @@ public class Canonicalizer { Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS, Canonicalizer11_WithComments.class ); + canonicalizerHash.put( + Canonicalizer.ALGO_ID_C14N_PHYSICAL, + CanonicalizerPhysical.class + ); } /** diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java index 7e150e365b4..da5047d2052 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 java.util.Set; 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.Node; 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); - /* - * 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. - * - */ + DocumentBuilder db = dfactory.newDocumentBuilder(); - // ErrorHandler eh = new C14NErrorHandler(); - // db.setErrorHandler(eh); - Document document = db.parse(in); - byte result[] = this.engineCanonicalizeSubTree(document); - return result; - } + Document document = db.parse(in); + return this.engineCanonicalizeSubTree(document); + } - /** - * Method engineCanonicalizeXPathNodeSet - * - * @param xpathNodeSet - * @return the c14n bytes - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet) - throws CanonicalizationException { + /** + * Method engineCanonicalizeXPathNodeSet + * + * @param xpathNodeSet + * @return the c14n bytes + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet) + throws CanonicalizationException { + return this.engineCanonicalizeXPathNodeSet( + XMLUtils.convertNodelistToSet(xpathNodeSet) + ); + } - 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 { + /** + * Returns the URI of this engine. + * @return the URI + */ + public abstract String engineGetURI(); - return this - .engineCanonicalizeXPathNodeSet(XMLUtils - .convertNodelistToSet(xpathNodeSet), inclusiveNamespaces); - } + /** + * Returns true if comments are included + * @return true if comments are included + */ + public abstract boolean engineGetIncludeComments(); - //J- - /** Returns the URI of this engine. - * @return the URI - */ - public abstract String engineGetURI(); + /** + * C14n a nodeset + * + * @param xpathNodeSet + * @return the c14n bytes + * @throws CanonicalizationException + */ + public abstract byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet) + throws CanonicalizationException; - /** Returns the URI if include comments - * @return true if include. - */ - public abstract boolean engineGetIncludeComments(); + /** + * C14n a nodeset + * + * @param xpathNodeSet + * @param inclusiveNamespaces + * @return the c14n bytes + * @throws CanonicalizationException + */ + public abstract byte[] engineCanonicalizeXPathNodeSet( + Set xpathNodeSet, String inclusiveNamespaces + ) throws CanonicalizationException; - /** - * C14n a nodeset - * - * @param xpathNodeSet - * @return the c14n bytes - * @throws CanonicalizationException - */ - public abstract byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet) - 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 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 writer where the canonicalization ends. ByteArrayOutputStream if + * none is set. + * @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; - - /** - * Sets the writter where the cannocalization ends. ByteArrayOutputStream if - * none is setted. - * @param os - */ - public abstract void setWriter(OutputStream os); - - /** Reset the writter after a c14n */ - protected boolean reset=false; - //J+ } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java index 9fb1531b7e9..c0dee5e93f3 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java @@ -2,87 +2,82 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java index 8675b673c72..f17a6b0d469 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import java.util.Comparator; */ public class AttrCompare implements Comparator, 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 class AttrCompare implements Comparator, Serializable { * */ 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 @@ public class AttrCompare implements Comparator, Serializable { 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 @@ public class AttrCompare implements Comparator, Serializable { } // 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 @@ public class AttrCompare implements Comparator, Serializable { return name0.compareTo(name1); } return ATTR0_BEFORE_ATTR1; - } - - if (namespaceURI1 == null) { + } else if (namespaceURI1 == null) { return ATTR1_BEFORE_ATTR0; } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java index 0c720fd35f9..ecd0c52899c 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java @@ -2,33 +2,32 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import org.w3c.dom.NamedNodeMap; */ public class C14nHelper { - /** - * Constructor C14nHelper - * - */ - private C14nHelper() { + /** + * Constructor C14nHelper + * + */ + private C14nHelper() { + // don't allow instantiation + } - // 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 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) { + // 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) { + /** + * 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; + } - // assume empty namespaces are absolute - if (namespaceValue.length() == 0) { - return true; - } - return namespaceValue.indexOf(':')>0; - } + String nodeAttrName = attr.getNodeName(); + boolean definesDefaultNS = nodeAttrName.equals("xmlns"); + boolean definesNonDefaultNS = nodeAttrName.startsWith("xmlns:"); - /** - * 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; - } - - 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 { + /** + * 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() }; - if (!document.isSupported("Traversal", "2.0")) { - Object exArgs[] = { - document.getImplementation().getClass().getName() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.TraversalNotSupported", exArgs + ); + } + } - throw new CanonicalizationException( - "c14n.Canonicalizer.TraversalNotSupported", exArgs); - } - } + /** + * 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(); - /** - * 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"); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java index e0a46963ace..4d1fcbc0e6d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.URI; 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.Set; 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.NamedNodeMap; 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 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; * * @author Sean Mullan * @author Raul Benito - * @version $Revision: 1.2 $ */ public abstract class Canonicalizer11 extends CanonicalizerBase { - boolean firstCall = true; - final SortedSet result = new TreeSet(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 result = new TreeSet(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 nodes = new ArrayList(); }; + + int currentLevel = 0; + int lastlevel = 0; + XmlsStackElement cur; List levels = new ArrayList(); + 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } cur.nodes.add(n); } + void getXmlnsAttr(Collection 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { Map loa = new HashMap(); List baseAttrs = new ArrayList(); boolean successiveOmitted = true; - for (;size>=0;size--) { + for (; size >= 0; size--) { e = levels.get(size); if (e.rendered) { successiveOmitted = false; @@ -134,16 +140,15 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { Iterator 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 it = cur.nodes.iterator(); + Iterator it = col.iterator(); String base = null; Attr baseAttr = null; while (it.hasNext()) { @@ -164,7 +169,9 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { col.addAll(loa.values()); } }; - XmlAttrStack xmlattrStack = new XmlAttrStack(); + + private XmlAttrStack xmlattrStack = new XmlAttrStack(); /** * Constructor Canonicalizer11 @@ -189,194 +197,6 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { super(includeComments); } - /** - * Returns the Attr[]s to be outputted for the given element. - *
    - * 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 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 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. - *
    - * 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 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 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. * @@ -385,10 +205,10 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { * @return none it always fails * @throws CanonicalizationException always */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, - String inclusiveNamespaces) throws CanonicalizationException { - throw new CanonicalizationException( - "c14n.Canonicalizer.UnsupportedOperation"); + public byte[] engineCanonicalizeXPathNodeSet( + Set xpathNodeSet, String inclusiveNamespaces + ) throws CanonicalizationException { + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); } /** @@ -399,17 +219,189 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { * @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"); } - void circumventBugIfNeeded(XMLSignatureInput input) + /** + * Returns the Attr[]s to be output for the given element. + *
    + * 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 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 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(); + } + + /** + * Returns the Attr[]s to be output for the given element. + *
    + * 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 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 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { 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); - } - continue; - } + Attr attribute = (Attr) attrs.item(i); + String NName = attribute.getLocalName(); + String NValue = attribute.getNodeValue(); - String NName = N.getLocalName(); - String NValue = N.getNodeValue(); - if (XML.equals(NName) - && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { - continue; + if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())) { + if (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { + ns.addMapping(NName, NValue, attribute); + } + } else if (!"id".equals(NName) && XML_LANG_URI.equals(attribute.getNamespaceURI())) { + xmlattrStack.addXmlnsAttr(attribute); } - ns.addMapping(NName,NValue,N); + } + 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); } } - 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { bauthority = base.getAuthority(); bpath = base.getPath(); bquery = base.getQuery(); - bfragment = base.getFragment(); } URI r = new URI(relativeURI); @@ -472,9 +470,8 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } // 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { // 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } } 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('/'); diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java index 31903667f60..12a31f67d80 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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; diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java index ba650c10872..635e778b7a2 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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; diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java index b0b2e0b729c..3af83dd11f1 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.NamedNodeMap; import org.w3c.dom.Node; import org.xml.sax.SAXException; - /** * Implements Canonical * XML Version 1.0, a W3C Recommendation from 15 March 2001. * * @author Christian Geuer-Pollmann - * @version $Revision: 1.5 $ */ public abstract class Canonicalizer20010315 extends CanonicalizerBase { - boolean firstCall=true; - final SortedSet result= new TreeSet(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; - XmlsStackElement cur; + 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 result = new TreeSet(COMPARE); + + private static class XmlAttrStack { static class XmlsStackElement { - int level; - boolean rendered=false; - List nodes=new ArrayList(); + int level; + boolean rendered = false; + List nodes = new ArrayList(); }; - List levels=new ArrayList(); + + int currentLevel = 0; + int lastlevel = 0; + XmlsStackElement cur; + List levels = new ArrayList(); + 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 col) { - int size=levels.size()-1; - if (cur==null) { - cur=new XmlsStackElement(); - cur.level=currentLevel; - lastlevel=currentLevel; - levels.add(cur); + 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; } - 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; + } + Map loa = new HashMap(); + for (; size >= 0; size--) { + e = levels.get(size); + Iterator it = e.nodes.iterator(); + while (it.hasNext()) { + Attr n = it.next(); + if (!loa.containsKey(n.getName())) { + loa.put(n.getName(), n); + } } - if (parentRendered) { - col.addAll(cur.nodes); - cur.rendered=true; - return; - } + } - Map loa = new HashMap(); - for (;size>=0;size--) { - e=levels.get(size); - Iterator 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; - - }; - //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); - } - - /** - * Returns the Attr[]s to be outputted for the given element. - *
    - * 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 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 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(getSortedSetAsCollection(result)); - //output the attributes in the xml namespace. - xmlattrStack.getXmlnsAttr(result); - firstCall=false; - } - - return result.iterator(); - } - - /** - * Returns the Attr[]s to be outputted for the given element. - *
    - * 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 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(); + * Constructor Canonicalizer20010315 + * + * @param includeComments + */ + public Canonicalizer20010315(boolean includeComments) { + super(includeComments); } + /** + * 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 xpathNodeSet, String inclusiveNamespaces) + throws CanonicalizationException { - SortedSet result = this.result; - result.clear(); + /** $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) { - //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; - } + /** $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)) { - /* 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); - } + /** + * Returns the Attr[]s to be output for the given element. + *
    + * 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 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 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(); } - if (isRealVisible) { - //The element is visible, handle the xmlns definition - Attr xmlns = E.getAttributeNodeNS(XMLNS_URI, XMLNS); - Node n=null; - if (xmlns == null) { + + /** + * Returns the Attr[]s to be output for the given element. + *
    + * 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 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 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)) { + 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)) { + 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); + 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); } - //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(getSortedSetAsCollection(result)); + return result.iterator(); } - 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 xpathNodeSet, String inclusiveNamespaces) - throws CanonicalizationException { + 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); + } - /** $todo$ well, should we throw UnsupportedOperationException ? */ - throw new CanonicalizationException( - "c14n.Canonicalizer.UnsupportedOperation"); - } + @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(); - /** - * 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 { - - /** $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); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java index 9dec09b4588..b8c869c83f7 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java @@ -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.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; @@ -40,6 +41,7 @@ import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.xml.sax.SAXException; + /** * Implements " Exclusive XML @@ -52,301 +54,279 @@ import org.xml.sax.SAXException; * THIS implementation is a complete rewrite of the algorithm. * * @author Christian Geuer-Pollmann - * @version $Revision: 1.5 $ + * @version $Revision: 1147448 $ * @see * XML Canonicalization, Version 1.0 */ 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 _inclusiveNSSet = new TreeSet(); - static final String XMLNS_URI=Constants.NamespaceSpecNS; - final SortedSet result = new TreeSet(COMPARE); - /** - * Constructor Canonicalizer20010315Excl - * - * @param includeComments - */ - public Canonicalizer20010315Excl(boolean includeComments) { - super(includeComments); - } + private SortedSet inclusiveNSSet; - /** - * 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 + private final SortedSet result = new TreeSet(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 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); - } - - /** - * Method handleAttributesSubtree - * @inheritDoc - * @param E - * @throws CanonicalizationException - */ - Iterator 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 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 visiblyUtilized = getNSSetClone(); - - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - - 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(); - - 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; - } - - } else { - prefix=XMLNS; - } - visiblyUtilized.add(prefix); - - //This can be optimezed by I don't have time - Iterator 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(); - } - - /** - * Method engineCanonicalizeXPathNodeSet - * @inheritDoc - * @param xpathNodeSet - * @param inclusiveNamespaces - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, - String inclusiveNamespaces) throws CanonicalizationException { - - this._inclusiveNSSet = getInclusiveNameSpace(inclusiveNamespaces); - return super.engineCanonicalizeXPathNodeSet(xpathNodeSet); - - } - - @SuppressWarnings("unchecked") - private TreeSet getInclusiveNameSpace(String inclusiveNameSpaces) { - return (TreeSet)InclusiveNamespaces.prefixStr2Set(inclusiveNameSpaces); + * @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); } - - @SuppressWarnings("unchecked") - private SortedSet getNSSetClone() { - return (SortedSet) this._inclusiveNSSet.clone(); + /** + * + * @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); } - - /** + /** + * Method engineCanonicalizeXPathNodeSet * @inheritDoc - * @param E - * @throws CanonicalizationException - */ - final Iterator handleAttributes(Element E, NameSpaceSymbTable ns) - throws CanonicalizationException { - // result will contain the attrs which have to be outputted - SortedSet result = this.result; - result.clear(); - NamedNodeMap attrs = null; - int attrsLength = 0; - if (E.hasAttributes()) { - attrs = E.getAttributes(); - attrsLength = attrs.getLength(); + * @param xpathNodeSet + * @param inclusiveNamespaces + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeXPathNodeSet( + Set xpathNodeSet, String inclusiveNamespaces + ) throws CanonicalizationException { + inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces); + return super.engineCanonicalizeXPathNodeSet(xpathNodeSet); + } + + @Override + protected Iterator handleAttributesSubtree(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + // result will contain the attrs which have to be output + final SortedSet result = this.result; + result.clear(); + + // The prefix visibly utilized (in the attribute or in the name) in + // the element + SortedSet visiblyUtilized = new TreeSet(); + if (inclusiveNSSet != null && !inclusiveNSSet.isEmpty()) { + visiblyUtilized.addAll(inclusiveNSSet); } - //The prefix visibly utilized(in the attribute or in the name) in the element - Set 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; - } - String NName=N.getLocalName(); - if (isOutputElement && !isVisible(N) && NName!=XMLNS) { - ns.removeMappingIfNotRender(NName); - continue; - } - String NNodeValue=N.getNodeValue(); - - 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()}; + 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); + "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 (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 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(); } - 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()); - } + String prefix = null; + if (element.getNamespaceURI() != null + && !(element.getPrefix() == null || element.getPrefix().length() == 0)) { + prefix = element.getPrefix(); + } else { + prefix = XMLNS; + } + visiblyUtilized.add(prefix); - XMLUtils.circumventBug2650(doc); - } + for (String s : visiblyUtilized) { + Attr key = ns.getMapping(s); + if (key != null) { + result.add(key); + } + } + + return result.iterator(); + } + + /** + * @inheritDoc + * @param element + * @throws CanonicalizationException + */ + @Override + protected final Iterator handleAttributes(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + // result will contain the attrs which have to be output + final SortedSet result = this.result; + result.clear(); + + // The prefix visibly utilized (in the attribute or in the name) in + // the element + Set visiblyUtilized = null; + // It's the output selected. + boolean isOutputElement = isVisibleDO(element, ns.getLevel()) == 1; + if (isOutputElement) { + visiblyUtilized = new TreeSet(); + if (inclusiveNSSet != null && !inclusiveNSSet.isEmpty()) { + visiblyUtilized.addAll(inclusiveNSSet); + } + } + + 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.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); + } + // 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 (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 = 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); + } + + 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(); + } + + 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); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java index 0910b980484..0fb402275a1 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java @@ -2,48 +2,44 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java index 37550124879..1ea477ac970 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java @@ -2,52 +2,48 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java index 481642e6bac..2e21cc0b2dd 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java @@ -2,50 +2,48 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java index 4714e165bba..bf56bfb6950 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java @@ -2,47 +2,47 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java index 2f5f28904d2..4c9f277f65e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.List; 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.Node; import org.w3c.dom.ProcessingInstruction; import org.xml.sax.SAXException; - /** * Abstract base class for canonicalization algorithms. * * @author Christian Geuer-Pollmann - * @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"; - List nodeFilter; + protected static final AttrCompare COMPARE = new AttrCompare(); + protected static final Attr nullNode; - boolean _includeComments; - Set _xpathNodeSet = null; - /** - * The node to be skiped/excluded from the DOM tree - * in subtree canonicalizations. - */ - Node _excludeNode =null; - OutputStream _writer = new UnsyncByteArrayOutputStream();//null; + 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 = {'=','\"'}; - /** - * Constructor CanonicalizerBase - * - * @param includeComments - */ - public CanonicalizerBase(boolean includeComments) { - this._includeComments = includeComments; - } + 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; - /** - * 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 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 { + static { + // The null xmlns definition. 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(); + 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); + } + } - circumventBugIfNeeded(input); + private List nodeFilter; - if (input.getSubNode() != null) { - bytes = engineCanonicalizeXPathNodeSetInternal(input.getSubNode()); - } else { - bytes = engineCanonicalizeXPathNodeSet(input.getNodeSet()); - } - return bytes; + private boolean includeComments; + private Set xpathNodeSet; + /** + * The node to be skipped/excluded from the DOM tree + * in subtree canonicalizations. + */ + private Node excludeNode; + private OutputStream writer = new ByteArrayOutputStream(); - } - 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; + /** + * Constructor CanonicalizerBase + * + * @param includeComments + */ + public CanonicalizerBase(boolean includeComments) { + this.includeComments = includeComments; } /** - * 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; + * 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 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 { try { - NameSpaceSymbTable ns=new NameSpaceSymbTable(); - int nodeLevel=NODE_BEFORE_DOCUMENT_ELEMENT; - if (rootNode != null && rootNode.getNodeType() == Node.ELEMENT_NODE) { - //Fills the nssymbtable with the definitions of the parent of the root subnode - getParentNameSpaces((Element)rootNode,ns); - nodeLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } - 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(); + 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) { + 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); + } + } + + /** + * @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 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 && 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.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 cache=new HashMap(); + /** + * 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 cache = new HashMap(); do { - switch (currentNode.getNodeType()) { + switch (currentNode.getNodeType()) { - case Node.DOCUMENT_TYPE_NODE : - default : - break; - - 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.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.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 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; + case Node.COMMENT_NODE : + if (includeComments) { + outputCommentToWriter((Comment) currentNode, writer, documentLevel); } - 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; - } - } - if (sibling==null) - return; - currentNode=sibling; - sibling=currentNode.getNextSibling(); - } while(true); - } + 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; - 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(); - } - 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); - } - } - - /** - * 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; - 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 cache=new HashMap(); - do { - switch (currentNode.getNodeType()) { - - case Node.DOCUMENT_TYPE_NODE : - default : - 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.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.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.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(); - } - - Iterator 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(); - - 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; - } - 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 (sibling==null) - return; - currentNode=sibling; - sibling=currentNode.getNextSibling(); - } while(true); - } - int isVisibleDO(Node currentNode,int level) { - if (nodeFilter!=null) { - Iterator 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 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 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; - } - - 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 parents=new ArrayList(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 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 handleAttributes(Element E, NameSpaceSymbTable ns ) - throws CanonicalizationException; - - /** - * 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 handleAttributesSubtree(Element E, 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 - *
      - *
    • all ampersands (&) with &amp;
    • - *
    • all open angle brackets (<) with &lt;
    • - *
    • all quotation mark characters with &quot;
    • - *
    • and the whitespace characters #x9, #xA, and #xD, with character - * references. The character references are written in uppercase - * hexadecimal with no leading zeroes (for example, #xD is represented - * by the character reference &#xD;)
    • - *
    - * - * @param name - * @param value - * @param writer - * @throws IOException - */ - static final void outputAttrToWriter(final String name, final String value, final OutputStream writer, - final Map 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_; + 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 '<' : - 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); - }; - 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); - }; - } - } - - final String data = currentPI.getData(); - - length = data.length(); - - 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); + Iterator 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; + } + break; - 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 - */ - 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'); - } - } - - /** - * 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; - - 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 getSortedSetAsCollection(SortedSet result) { - return (Collection)(Collection)result; + 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; + } + 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.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(); + } 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); + } + } + + /** + * 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 && 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 cache = new HashMap(); + do { + 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.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.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.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(); + } + + Iterator 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(); + + 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; + } + 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); + } + + protected int isVisibleDO(Node currentNode, int level) { + if (nodeFilter != null) { + Iterator 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; + } + + protected int isVisibleInt(Node currentNode) { + if (nodeFilter != null) { + Iterator 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; + } + + protected boolean isVisible(Node currentNode) { + if (nodeFilter != null) { + Iterator 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; + } + + 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 parents = new ArrayList(); + Node parent = n1; + while (parent != null && Node.ELEMENT_NODE == parent.getNodeType()) { + parents.add((Element)parent); + parent = parent.getParentNode(); + } + //Visit them in reverse order. + ListIterator 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 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 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 + *
      + *
    • all ampersands (&) with &amp;
    • + *
    • all open angle brackets (<) with &lt;
    • + *
    • all quotation mark characters with &quot;
    • + *
    • and the whitespace characters #x9, #xA, and #xD, with character + * references. The character references are written in uppercase + * hexadecimal with no leading zeroes (for example, #xD is represented + * by the character reference &#xD;)
    • + *
    + * + * @param name + * @param value + * @param writer + * @throws IOException + */ + protected static final void outputAttrToWriter( + final String name, final String value, + final OutputStream writer, final Map 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); + } + continue; + } + writer.write(toWrite); + } + + writer.write('\"'); + } + + /** + * 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); + + 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); + } + } + } + + final String data = currentPI.getData(); + + length = data.length(); + + 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'); + } + } + + /** + * 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); + } + } + } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java new file mode 100644 index 00000000000..17d8705a210 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java @@ -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 result = new TreeSet(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 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. + *
    + * 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 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 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 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); + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java index 114bf7e0a86..54ae150b30e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 java.util.List; import org.w3c.dom.Attr; import org.w3c.dom.Node; - - /** - * A stack based Symble Table. + * A stack based Symbol Table. *
    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 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 level; + private boolean cloned = true; + /** * Default constractor **/ public NameSpaceSymbTable() { - level = new ArrayList(10); + level = new ArrayList(); //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 result) { - //List result=new ArrayList(); - Iterator 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 result) { + Iterator 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; + symb.put(n.prefix, n); + n.lastrendered = n.uri; + n.rendered = true; - result.add(n.n); - - } - } + 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(); - needsClone(); - symb.put(prefix,entry); - entry.rendered=true; - entry.level=nameSpaces; - entry.lastrendered=entry.uri; - // Return the node for outputing. - return entry.n; + 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.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); - 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; - } - } - return true; + 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; + } + } + return true; + } /** * Adds a definition and mark it as render. @@ -223,79 +219,91 @@ public class NameSpaceSymbTable { * @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); + public boolean removeMappingIfRender(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); } 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 @@ class NameSpaceSymbEntry implements Cloneable { 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 entrySet() { - List a=new ArrayList(); - for (int i=0;i a = new ArrayList(); + 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 @@ class SymbMap implements Cloneable { 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 @@ class SymbMap implements Cloneable { 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 @@ class SymbMap implements Cloneable { } 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; diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java index b62dd3b0869..0ba49747f31 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java @@ -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 @@ import java.util.Map; public class UtfHelpper { - final static void writeByte(final String str,final OutputStream out,Map 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 cache + ) throws IOException { + byte[] result = cache.get(str); + if (result == null) { + result = getStringInUtf8(str); + cache.put(str, result); + } - out.write(result); + out.write(result); + } - } - - final static void writeCharToUtf8(final char c,final OutputStream out) throws IOException{ - if (c < 0x80) { - out.write(c); - return; + 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); } - if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){ + 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)); + + } + + 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); + continue; + } + 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= 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); } - 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= 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; - } - - + 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java new file mode 100644 index 00000000000..a21f1488ec7 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java @@ -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 Strings into Nodes 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 String representation of the specified + * Element. + *

    + * Refer also to comments about setup of format. + * + * @param element the Element to serialize. + * @return the String representation of the serilaized + * Element. + * @throws Exception + */ + public String serialize(Element element) throws Exception { + return canonSerialize(element); + } + + /** + * Returns a byte[] representation of the specified + * Element. + * + * @param element the Element to serialize. + * @return the byte[] representation of the serilaized + * Element. + * @throws Exception + */ + public byte[] serializeToByteArray(Element element) throws Exception { + return canonSerializeToByteArray(element); + } + + /** + * Returns a String representation of the specified + * NodeList. + *

    + * This is a special case because the NodeList may represent a + * DocumentFragment. 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. + *

    + * 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. + *

    + * Refer also to comments about setup of format. + * + * @param content the NodeList to serialize. + * @return the String representation of the serialized + * NodeList. + * @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 byte[] representation of the specified + * NodeList. + * + * @param content the NodeList to serialize. + * @return the byte[] representation of the serialized + * NodeList. + * @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(" storedNamespaces = new HashMap(); + 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(""); + 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(" storedNamespaces = new HashMap(); + 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 + ""); + return sb.toString(); + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java index 803fca8c65f..c1da9befd71 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java @@ -2,30 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import org.w3c.dom.Element; * @author Axl Mattheus */ public interface AgreementMethod { + /** - * Returns an byte array. - * @return + * Returns a byte array. + * @return a byte array. */ byte[] getKANonce(); @@ -92,8 +93,8 @@ public interface AgreementMethod { void setKANonce(byte[] kanonce); /** - * Returns aditional information regarding the AgreementMethod. - * @return + * Returns additional information regarding the AgreementMethod. + * @return additional information regarding the AgreementMethod. */ Iterator getAgreementMethodInformation(); @@ -134,7 +135,7 @@ public interface AgreementMethod { 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. */ diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java index 8a03d389d7b..39654a9ff8d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java @@ -2,25 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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; - /** * CipherData provides encrypted data. It must either contain the * encrypted octet sequence as base64 encoded text of the @@ -42,10 +43,12 @@ package com.sun.org.apache.xml.internal.security.encryption; * @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 @@ public interface CipherData { * Returns a reference to an external location containing the encrypted * octet sequence (byte 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 CipherData'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; } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java index 1610741193f..75b0dcb7971 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java @@ -2,34 +2,34 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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; - /** * CipherReference identifies a source which, when processed, * yields the encrypted octet sequence. *

    * The actual value is obtained as follows. The CipherReference URI * contains an identifier that is dereferenced. Should the - * CipherReference element contain an OPTIONAL sequence of * Transforms, the data resulting from dereferencing the URI 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 @@ public interface CipherReference { /** * Returns an URI that contains an identifier that should be * dereferenced. - * @return + * @return an URI 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 Transforms that specifies how to transform the - * URI to yield the appropiate cipher value. + * URI 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 @@ public interface CipherReference { /** * Sets the Transforms that specifies how to transform the - * URI to yield the appropiate cipher value. + * URI to yield the appropriate cipher value. * * @param transforms the set of Transforms that specifies how * to transform the reference to yield the intended cipher value. */ void setTransforms(Transforms transforms); } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java index 28486365d72..193aef8a908 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java @@ -2,25 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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; - /** * CipherValue is the wrapper for cipher text. * @@ -28,20 +29,18 @@ package com.sun.org.apache.xml.internal.security.encryption; */ public interface CipherValue { /** - * Resturns the Base 64 encoded, encrypted octets that is the - * CihperValue. + * Returns the Base 64 encoded, encrypted octets that is the + * CipherValue. * * @return cipher value. */ - String getValue(); - // byte[] getValue(); + String getValue(); /** * Sets the Base 64 encoded, encrypted octets that is the - * CihperValue. + * CipherValue. * * @param value the cipher value. */ - void setValue(String value); - // void setValue(byte[] value); + void setValue(String value); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java new file mode 100644 index 00000000000..f0ffb91f1c2 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java @@ -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 Strings into Nodes 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); + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java index 79038a67cb5..c09eeceaa59 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java @@ -2,25 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 EncryptedData element is the core element in the syntax. Not * only does its CipherData child contain the encrypted data, but @@ -42,3 +43,4 @@ package com.sun.org.apache.xml.internal.security.encryption; */ public interface EncryptedData extends EncryptedType { } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java index 9607917108b..05fafaf873b 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 EncryptedKey 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 @@ package com.sun.org.apache.xml.internal.security.encryption; * @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 EncryptedKey. */ @@ -110,3 +110,4 @@ public interface EncryptedKey extends EncryptedType { */ void setCarriedName(String name); } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java index 17ffded82a5..61e7e51df9d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java @@ -2,28 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 EncryptedData and * EncryptedKey are derived. While these two latter element types @@ -50,6 +50,7 @@ import com.sun.org.apache.xml.internal.security.keys.KeyInfo; * @author Axl Mattheus */ public interface EncryptedType { + /** * Returns a String providing for the standard method of * assigning an id to the element within the document context. @@ -61,7 +62,7 @@ public interface EncryptedType { /** * Sets the id. * - * @param id. + * @param id */ void setId(String id); @@ -117,7 +118,7 @@ public interface EncryptedType { void setMimeType(String type); /** - * Retusn an URI representing the encoding of the + * Return an URI representing the encoding of the * EncryptedType. * * @return the encoding of this EncryptedType. @@ -128,7 +129,7 @@ public interface EncryptedType { * Sets the URI representing the encoding of the * EncryptedType. * - * @param encoding. + * @param encoding */ void setEncoding(String encoding); @@ -189,7 +190,8 @@ public interface EncryptedType { * Sets the EncryptionProperties that supplies additional * information about the generation of the EncryptedType. * - * @param properties. + * @param properties */ void setEncryptionProperties(EncryptionProperties properties); } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java index 2664db9ae94..05c3cdc76cd 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java @@ -2,29 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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; - /** * EncryptionMethod describes the encryption algorithm applied to * the cipher data. If the element is absent, the encryption algorithm must be @@ -82,6 +82,30 @@ public interface EncryptionMethod { */ 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 * EncryptionMethod. @@ -106,3 +130,4 @@ public interface EncryptionMethod { */ void removeEncryptionMethodInformation(Element information); } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java index da1eb65d255..736d63f151a 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java @@ -2,28 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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; - /** * EncryptionProperties can hold additional information concerning * the generation of the EncryptedData or @@ -46,6 +46,7 @@ import java.util.Iterator; * @author Axl Mattheus */ public interface EncryptionProperties { + /** * Returns the EncryptionProperties' id. * @@ -72,14 +73,15 @@ public interface EncryptionProperties { /** * Adds an EncryptionProperty. * - * @param property. + * @param property */ void addEncryptionProperty(EncryptionProperty property); /** * Removes the specified EncryptionProperty. * - * @param property. + * @param property */ void removeEncryptionProperty(EncryptionProperty property); } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java index 4cd6c4696cd..fc969018033 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java @@ -2,25 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import org.w3c.dom.Element; * @author Axl Mattheus */ public interface EncryptionProperty { + /** * Returns the EncryptedType being described. * @@ -61,7 +63,7 @@ public interface EncryptionProperty { /** * Sets the target. * - * @param target. + * @param target */ void setTarget(String target); @@ -75,7 +77,7 @@ public interface EncryptionProperty { /** * Sets the id. * - * @param id. + * @param id */ void setId(String id); @@ -98,7 +100,7 @@ public interface EncryptionProperty { /** * Returns the properties of the EncryptionProperty. * - * @return an Iterator over all the addiitonal encryption + * @return an Iterator over all the additional encryption * information contained in this class. */ Iterator getEncryptionInformation(); diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java index 4523a895aaf..dc528ce1a06 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java @@ -2,29 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 EncryptedKey to * items encrypted by that key value (EncryptedData or @@ -44,6 +44,13 @@ import org.w3c.dom.Element; * @see ReferenceList */ public interface Reference { + /** + * Returns the Element tag name for this Reference. + * + * @return the tag name of this Reference. + */ + String getType(); + /** * Returns a URI that points to an Element that * were encrypted using the key defined in the enclosing @@ -79,14 +86,14 @@ public interface Reference { /** * Adds retrieval information. * - * @param info. + * @param info */ void addElementRetrievalInformation(Element info); /** * Removes the specified retrieval information. * - * @param info. + * @param info */ void removeElementRetrievalInformation(Element info); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java index 2cf0ec5ed44..73d46a2f0b9 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java @@ -2,28 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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; - /** * ReferenceList is an element that contains pointers from a key * value of an EncryptedKey to items encrypted by that key value @@ -45,10 +45,12 @@ import java.util.Iterator; * @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 @@ public interface ReferenceList { * @throws IllegalAccessException if the Reference is not an * instance of DataReference or KeyReference. */ - public void add(Reference reference); + void add(Reference reference); /** * Removes a reference from the ReferenceList. * * @param reference the reference to remove. */ - public void remove(Reference reference); + void remove(Reference reference); /** * Returns the size of the ReferenceList. * * @return the size of the ReferenceList. */ - public int size(); + int size(); /** * Indicates if the ReferenceList is empty. @@ -79,29 +81,29 @@ public interface ReferenceList { * @return true if the ReferenceList is * empty, else false. */ - public boolean isEmpty(); + boolean isEmpty(); /** * Returns an Iterator over all the References - * contatined in this ReferenceList. + * contained in this ReferenceList. * * @return Iterator. */ - public Iterator getReferences(); + Iterator getReferences(); /** * DataReference factory method. Returns a * DataReference. * @param uri - * @return + * @return a DataReference. */ - public Reference newDataReference(String uri); + Reference newDataReference(String uri); /** * KeyReference factory method. Returns a * KeyReference. * @param uri - * @return + * @return a KeyReference. */ - public Reference newKeyReference(String uri); + Reference newKeyReference(String uri); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java new file mode 100644 index 00000000000..8f3cd8fac9a --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java @@ -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 Strings into Nodes and visa versa. + */ +public interface Serializer { + + /** + * Set the Canonicalizer object to use. + */ + void setCanonicalizer(Canonicalizer canon); + + /** + * Returns a byte[] representation of the specified + * Element. + * + * @param element the Element to serialize. + * @return the byte[] representation of the serilaized + * Element. + * @throws Exception + */ + byte[] serializeToByteArray(Element element) throws Exception; + + /** + * Returns a byte[] representation of the specified + * NodeList. + * + * @param content the NodeList to serialize. + * @return the byte[] representation of the serialized + * NodeList. + * @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; +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java index b2434c025a5..02d083b65ee 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java @@ -2,27 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 ds:Transforms. *

    @@ -40,36 +39,12 @@ package com.sun.org.apache.xml.internal.security.encryption; */ public interface Transforms { /** - * Returns an Iterator over all the transforms contained in - * this transform list. - * - * @return all transforms. + * 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. + *

    + * Note This will be removed in future versions */ - /* Iterator getTransforms(); */ - - /** - * Adds a ds:Transform to the list of transforms. - * - * @param transform. - */ - /* 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. - *

    - * Note 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(); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java index 8177cf34546..81d79b040cf 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java @@ -2,57 +2,62 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Constants; 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; - /** * XMLCipher encrypts and decrypts the contents of @@ -85,133 +84,245 @@ import org.xml.sax.SAXException; */ 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"; + 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; - /** Internal serializer class for going to/from UTF-8 */ - private Serializer _serializer; + /** Cipher created during initialisation that is used for encryption */ + private Cipher contextCipher; - /** Local copy of user's key */ - private Key _key; - /** Local copy of the kek (used to decrypt EncryptedKeys during a + /** 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; + private Key kek; - // The EncryptedKey being built (part of a WRAP operation) or read - // (part of an UNWRAP operation) + // The EncryptedKey being built (part of a WRAP operation) or read + // (part of an UNWRAP operation) + private EncryptedKey ek; - private EncryptedKey _ek; + // The EncryptedData being built (part of a WRAP operation) or read + // (part of an UNWRAP operation) + private EncryptedData ed; - // The EncryptedData being built (part of a WRAP operation) or read - // (part of an UNWRAP operation) + private SecureRandom random; - private EncryptedData _ed; + private boolean secureValidation; + + private String digestAlg; + + /** List of internal KeyResolvers for DECRYPT and UNWRAP modes. */ + private List 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 XMLCipher. * - * @since 1.0. + * @param transformation the name of the transformation, e.g., + * XMLCipher.TRIPLEDES. If null the XMLCipher can only + * be used for decrypt or unwrap operations where the encryption method + * is defined in the EncryptionMethod 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 + * null use standard serializer + * @param digestMethod An optional digestMethod to use. */ - private XMLCipher() { - logger.log(java.util.logging.Level.FINE, "Constructing XMLCipher..."); + 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(); - _serializer = new Serializer(); + 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 @@ public class XMLCipher { * @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., + * XMLCipher.TRIPLEDES which is shorthand for + * "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" + */ + 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 @@ public class XMLCipher { * the default provider package, other provider packages are searched. *

    * NOTE1: 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 @@ public class XMLCipher { * same pattern regarding exceptional conditions as that used in * javax.crypto.Cipher. Instead, it only throws an * XMLEncryptionException 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., * XMLCipher.TRIPLEDES which is shorthand for @@ -266,293 +395,169 @@ public class XMLCipher { * @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 XMLCipher 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. - *

    - * - * @param transformation the name of the transformation, e.g., - * XMLCipher.TRIPLEDES which is - * shorthand for - * "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" - * @param canon the name of the c14n algorithm, if - * null 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 XMLCipher 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. + *

    + * + * @param transformation the name of the transformation + * @param canon the name of the c14n algorithm, if null 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"); } + validateTransformation(transformation); + return new XMLCipher(transformation, null, canon, null); + } - 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); + /** + * Returns an XMLCipher 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. + *

    + * + * @param transformation the name of the transformation + * @param canon the name of the c14n algorithm, if null 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 XMLCipher that implements the specified * transformation and operates on the specified context document. * - * @param transformation the name of the transformation, e.g., - * XMLCipher.TRIPLEDES which is shorthand for - * "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" - * @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"); } - - return (instance); + if (null == provider) { + throw new NullPointerException("Provider unexpectedly null.."); + } + validateTransformation(transformation); + return new XMLCipher(transformation, provider, null, null); } - /** - * Returns an XMLCipher that implements the specified + /** + * Returns an XMLCipher 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. *

    - * - * @param transformation the name of the transformation, e.g., - * XMLCipher.TRIPLEDES which is - * shorthand for - * "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" - * @param provider the JCE provider that supplies the transformation - * @param canon the name of the c14n algorithm, if - * null 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 XMLCipher that implements no specific - * transformation, and can therefore only be used for decrypt or - * unwrap operations where the encryption method is defined in the - * EncryptionMethod 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 null 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); + } - 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); + /** + * Returns an XMLCipher 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. + *

    + * + * @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 null use standard + * serializer + * @param digestMethod An optional digestMethod to use + * @return the XMLCipher + * @throws XMLEncryptionException + */ + 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 XMLCipher that implements no specific - * transformation, and can therefore only be used for decrypt or - * unwrap operations where the encryption method is defined in the - * EncryptionMethod 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 + * EncryptionMethod 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 XMLCipher that implements no specific + * transformation, and can therefore only be used for decrypt or + * unwrap operations where the encryption method is defined in the + * EncryptionMethod 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 @@ public class XMLCipher { * 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 class XMLCipher { */ public void init(int opmode, Key key) throws XMLEncryptionException { // sanity checks - logger.log(java.util.logging.Level.FINE, "Initializing XMLCipher..."); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Initializing XMLCipher..."); + } - _ek = null; - _ed = null; + ek = null; + ed = null; - switch (opmode) { + 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; + 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; } - /** - * 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; + /** + * Set whether secure validation is enabled or not. The default is false. + */ + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } + /** + * 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(); } + internalKeyResolvers.add(keyResolver); + } - /** - * 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; + /** + * Get the EncryptedData being built + *

    + * 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; + } - /** - * Set a Key Encryption Key. - *

    - * 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; - + /** + * 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"); } + return ek; + } - /** - * Martial an EncryptedData - * - * Takes an EncryptedData object and returns a DOM Element that - * represents the appropriate EncryptedData - *

    - * Note: 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 Element representing the passed in - * object + /** + * Set a Key Encryption Key. + *

    + * 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 Element martial(EncryptedData encryptedData) { + public void setKEK(Key kek) { + this.kek = kek; + } - return (_factory.toElement (encryptedData)); + /** + * Martial an EncryptedData + * + * Takes an EncryptedData object and returns a DOM Element that + * represents the appropriate EncryptedData + *

    + * Note: 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 Element 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 EncryptedData + * + * @param context The document that will own the returned nodes + * @param encryptedData EncryptedData object to martial + * @return the DOM Element 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 EncryptedKey - * - *

    - * Note: 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 Element representing the passed in - * object */ + /** + * Martial an EncryptedKey + * + * Takes an EncryptedKey object and returns a DOM Element that + * represents the appropriate EncryptedKey + * + *

    + * Note: 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 Element representing the passed in + * object + */ + public Element martial(EncryptedKey encryptedKey) { + return factory.toElement(encryptedKey); + } - public Element martial(EncryptedKey encryptedKey) { + /** + * Martial an EncryptedKey + * + * Takes an EncryptedKey object and returns a DOM Element that + * represents the appropriate EncryptedKey + * + * @param context The document that will own the created nodes + * @param encryptedKey EncryptedKey object to martial + * @return the DOM Element representing the passed in + * object + */ + public Element martial(Document context, EncryptedKey encryptedKey) { + contextDocument = context; + return factory.toElement(encryptedKey); + } - return (_factory.toElement (encryptedKey)); + /** + * Martial a ReferenceList + * + * Takes a ReferenceList object and returns a DOM Element that + * represents the appropriate ReferenceList + * + *

    + * Note: 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 Element representing the passed in + * object + */ + public Element martial(ReferenceList referenceList) { + return factory.toElement(referenceList); + } - } - - /** - * Martial an EncryptedData - * - * Takes an EncryptedData object and returns a DOM Element that - * represents the appropriate EncryptedData - * - * @param context The document that will own the returned nodes - * @param encryptedData EncryptedData object to martial - * @return the DOM Element 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 EncryptedKey - * - * @param context The document that will own the created nodes - * @param encryptedKey EncryptedKey object to martial - * @return the DOM Element 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 ReferenceList + * + * @param context The document that will own the created nodes + * @param referenceList ReferenceList object to martial + * @return the DOM Element representing the passed in + * object + */ + public Element martial(Document context, ReferenceList referenceList) { + contextDocument = context; + return factory.toElement(referenceList); + } /** * Encrypts an Element and replaces it with its encrypted @@ -747,25 +804,28 @@ public class XMLCipher { * Element having replaced the source Element. * @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 (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); + if (algorithm == null) { + throw new XMLEncryptionException("XMLCipher instance without transformation specified"); + } + encryptData(contextDocument, element, false); - Element encryptedElement = _factory.toElement(_ed); + Element encryptedElement = factory.toElement(ed); Node sourceParent = element.getParentNode(); sourceParent.replaceChild(encryptedElement, element); - return (_contextDocument); + return contextDocument; } /** @@ -782,25 +842,28 @@ public class XMLCipher { * Element. * @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..."); + 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); + if (algorithm == null) { + throw new XMLEncryptionException("XMLCipher instance without transformation specified"); + } + encryptData(contextDocument, element, true); - Element encryptedElement = _factory.toElement(_ed); + Element encryptedElement = factory.toElement(ed); removeContent(element); element.appendChild(encryptedElement); - return (_contextDocument); + return contextDocument; } /** @@ -812,19 +875,22 @@ public class XMLCipher { * @return the processed Document. * @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..."); + 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; + contextDocument = context; Document result = null; - switch (_cipherMode) { + switch (cipherMode) { case DECRYPT_MODE: result = decryptElement(source.getDocumentElement()); break; @@ -832,15 +898,13 @@ public class XMLCipher { 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 @@ public class XMLCipher { * @return the processed Document. * @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..."); + 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; + contextDocument = context; Document result = null; - switch (_cipherMode) { + switch (cipherMode) { case DECRYPT_MODE: result = decryptElement(element); break; @@ -872,15 +939,13 @@ public class XMLCipher { 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 @@ public class XMLCipher { * @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..."); + 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; + contextDocument = context; Document result = null; - switch (_cipherMode) { + switch (cipherMode) { case DECRYPT_MODE: if (content) { result = decryptElementContent(element); @@ -923,15 +992,13 @@ public class XMLCipher { } 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 @@ public class XMLCipher { * you want to have full control over the contents of the * EncryptedData 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 Document. * @param element the Element that will be encrypted. @@ -947,7 +1014,7 @@ public class XMLCipher { * @throws Exception */ public EncryptedData encryptData(Document context, Element element) throws - /* XMLEncryption */Exception { + /* XMLEncryption */Exception { return encryptData(context, element, false); } @@ -965,16 +1032,21 @@ public class XMLCipher { * @return the EncryptedData * @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 @@ public class XMLCipher { * you want to have full control over the contents of the * EncryptedData 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 Document. * @param element the Element that will be encrypted. @@ -994,84 +1066,84 @@ public class XMLCipher { * @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 { + Document context, Element element, String type, InputStream serializedData + ) throws /* XMLEncryption */ Exception { + contextDocument = context; - _contextDocument = context; - - if (_algorithm == null) { - throw new XMLEncryptionException - ("XMLCipher instance without transformation specified"); + 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); + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Serialized octets:\n" + new String(serializedOctets, "UTF-8")); } - logger.log(java.util.logging.Level.FINE, "Serialized octets:\n" + serializedOctets); } 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 @@ public class XMLCipher { 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))); + } + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Actual cipher.outputSize = " + + Integer.toString(encryptedBytes.length)); } - logger.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,308 +1181,418 @@ public class XMLCipher { // 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 EncryptedData interface. Use this operation if * you want to load an EncryptedData structure from a DOM - * structure and manipulate the contents + * structure and manipulate the contents. * * @param context the context Document. * @param element the Element that will be loaded * @throws XMLEncryptionException - * @return + * @return the EncryptedData */ 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..."); + 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); + contextDocument = context; + ed = factory.newEncryptedData(element); - return (_ed); + return ed; } /** * Returns an EncryptedKey interface. Use this operation if * you want to load an EncryptedKey structure from a DOM - * structure and manipulate the contents. + * structure and manipulate the contents. * * @param context the context Document. * @param element the Element that will be loaded - * @return + * @return the EncryptedKey * @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..."); + 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); + contextDocument = context; + ek = factory.newEncryptedKey(element); + return ek; } /** * Returns an EncryptedKey interface. Use this operation if * you want to load an EncryptedKey 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 Element that will be loaded - * @return + * @return the EncryptedKey * @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 + * + * @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 EncryptedKey * @throws XMLEncryptionException */ + public EncryptedKey encryptKey(Document doc, Key key) throws XMLEncryptionException { + return encryptKey(doc, key, null, null); + } - public EncryptedKey encryptKey(Document doc, Key key) throws - XMLEncryptionException { + /** + * 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 + * @param mgfAlgorithm The xenc11 MGF Algorithm to use + * @param oaepParams The OAEPParams to use + * @return the EncryptedKey + * @throws XMLEncryptionException + */ + 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 ..."); + } - logger.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"); + } - 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..."); + contextDocument = doc; - if (_algorithm == null) { + byte[] encryptedBytes = null; + Cipher c; - 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); - } - - 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 (contextCipher == null) { + // Now create the working cipher + c = constructCipher(algorithm, null); + } else { + c = contextCipher; + } + // Now perform the encryption try { - EncryptionMethod method = _factory.newEncryptionMethod( - new URI(_algorithm).toString()); - _ek.setEncryptionMethod(method); - } catch (URI.MalformedURIException mfue) { - throw new XMLEncryptionException("empty", mfue); + // 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); } - return _ek; + String base64EncodedEncryptedOctets = Base64.encode(encryptedBytes); + 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()); + method.setDigestAlgorithm(digestAlg); + method.setMGFAlgorithm(mgfAlgorithm); + method.setOAEPparams(oaepParams); + ek.setEncryptionMethod(method); + } catch (URISyntaxException ex) { + throw new XMLEncryptionException("empty", ex); + } + 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 { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Decrypting key from previously loaded EncryptedKey..."); + } - public Key decryptKey(EncryptedKey encryptedKey, String algorithm) throws - XMLEncryptionException { + if (cipherMode != UNWRAP_MODE && log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE..."); + } - logger.log(java.util.logging.Level.FINE, "Decrypting key from previously loaded EncryptedKey..."); + if (algorithm == null) { + throw new XMLEncryptionException("Cannot decrypt a key without knowing the algorithm"); + } - 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"); - } - - 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"); - } - } - - // 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; - } - - Key ret; + 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 { - 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); + String keyWrapAlg = encryptedKey.getEncryptionMethod().getAlgorithm(); + String keyType = JCEMapper.getJCEKeyAlgorithmFromURI(keyWrapAlg); + if ("RSA".equals(keyType)) { + key = ki.getPrivateKey(); + } else { + key = ki.getSecretKey(); + } } + catch (Exception e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + } + } + 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"); + } + } - logger.log(java.util.logging.Level.FINE, "Decryption of key type " + algorithm + " OK"); + // Obtain the encrypted octets + XMLCipherInput cipherInput = new XMLCipherInput(encryptedKey); + cipherInput.setSecureValidation(secureValidation); + byte[] encryptedBytes = cipherInput.getBytes(); - return ret; + 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; } - /** - * 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 - * @throws XMLEncryptionException - */ + /** + * 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)) { - public Key decryptKey(EncryptedKey encryptedKey) throws - XMLEncryptionException { + String jceDigestAlgorithm = "SHA-1"; + if (digestAlgorithm != null) { + jceDigestAlgorithm = JCEMapper.translateURItoJCEID(digestAlgorithm); + } - return decryptKey(encryptedKey, _ed.getEncryptionMethod().getAlgorithm()); + 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"); + } + } + return new OAEPParameterSpec(jceDigestAlgorithm, "MGF1", mgfParameterSpec, pSource); } + return null; + } + + /** + * 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()); + } + /** * Removes the contents of a Node. * * @param node the Node to clear. */ private static void removeContent(Node node) { - while (node.hasChildNodes()) { + while (node.hasChildNodes()) { node.removeChild(node.getFirstChild()); } } @@ -1419,196 +1604,191 @@ public class XMLCipher { * @return the Node 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); - } - - - /** - * - * @param element - * @return - * @throws XMLEncryptionException - */ - private Document decryptElementContent(Element element) throws - XMLEncryptionException { - Element e = (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTEDDATA).item(0); - - if (null == e) { - throw new XMLEncryptionException("No EncryptedData child element."); + private Document decryptElement(Element element) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Decrypting element..."); } - return (decryptElement(e)); + 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; } - /** - * 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 Node as a result of the decrypt operation. * @throws XMLEncryptionException - */ + */ + private Document decryptElementContent(Element element) throws XMLEncryptionException { + Element e = + (Element) element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_ENCRYPTEDDATA + ).item(0); - public byte[] decryptToByteArray(Element element) - throws XMLEncryptionException { + if (null == e) { + throw new XMLEncryptionException("No EncryptedData child element."); + } - logger.log(java.util.logging.Level.FINE, "Decrypting to ByteArray..."); + return decryptElement(e); + } - if(_cipherMode != DECRYPT_MODE) - logger.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE..."); + /** + * 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 the bytes resulting from the decryption + * @throws XMLEncryptionException + */ + 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..."); + } - EncryptedData encryptedData = _factory.newEncryptedData(element); + if (cipherMode != DECRYPT_MODE) { + log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE..."); + } - if (_key == null) { + EncryptedData encryptedData = factory.newEncryptedData(element); - 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"); - } - } - - // 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; + if (key == null) { + KeyInfo ki = encryptedData.getKeyInfo(); + if (ki != null) { 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); + // 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)); + } + } + 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 + 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"); + } + } - // For now, we only work with Block ciphers, so this will work. - // This should probably be put into the JCE mapper. + // Obtain the encrypted octets + XMLCipherInput cipherInput = new XMLCipherInput(encryptedData); + cipherInput.setSecureValidation(secureValidation); + byte[] encryptedBytes = cipherInput.getBytes(); - int ivLen = c.getBlockSize(); - byte[] ivBytes = new byte[ivLen]; + // 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); + } - // 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. + 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); + } - System.arraycopy(encryptedBytes, 0, ivBytes, 0, ivLen); - IvParameterSpec iv = new IvParameterSpec(ivBytes); + // Calculate the IV length and copy out - try { - c.init(_cipherMode, _key, iv); - } catch (InvalidKeyException ike) { - throw new XMLEncryptionException("empty", ike); - } catch (InvalidAlgorithmParameterException iape) { - throw new XMLEncryptionException("empty", iape); - } + // For now, we only work with Block ciphers, so this will work. + // This should probably be put into the JCE mapper. - byte[] plainBytes; + 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 EncryptedData Element. * - * 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. - *

    - * 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. + *

    + * 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 * EncryptedData or the URI to set in the CipherReference - * (usage will depend on the type + * (usage will depend on the type * @return the EncryptedData Element. * * * @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 EncryptedKey Element. * - * 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. - *

    - * 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. + *

    + * 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 * EncryptedKey or the URI to set in the CipherReference - * (usage will depend on the type + * (usage will depend on the type * @return the EncryptedKey Element. * * * @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); + 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); + 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)); - } - - /** - * 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 - *

    - * Note: A context document must 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 requires a - * context document. - * - * @param doc Document that will own the created Transforms node - * @return - */ - public Transforms createTransforms(Document doc) { - return (_factory.newTransforms(doc)); - } - /** - * Converts Strings into Nodes and visa versa. - *

    - * NOTE: For internal use only. + * Create an AgreementMethod object * - * @author Axl Mattheus + * @param algorithm Algorithm of the agreement method + * @return a new AgreementMethod */ - - private class Serializer { - /** - * Initialize the XMLSerializer with the specified context - * Document. - *

    - * Setup OutputFormat in a way that the serialization does not - * 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 String representation of the specified - * Document. - *

    - * Refer also to comments about setup of format. - * - * @param document the Document to serialize. - * @return the String representation of the serilaized - * Document. - * @throws Exception - */ - String serialize(Document document) throws Exception { - return canonSerialize(document); - } - - /** - * Returns a String representation of the specified - * Element. - *

    - * Refer also to comments about setup of format. - * - * @param element the Element to serialize. - * @return the String representation of the serilaized - * Element. - * @throws Exception - */ - String serialize(Element element) throws Exception { - return canonSerialize(element); - } - - /** - * Returns a String representation of the specified - * NodeList. - *

    - * This is a special case because the NodeList may represent a - * DocumentFragment. 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. - *

    - * 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. - *

    - * Refer also to comments about setup of format. - * - * @param content the NodeList to serialize. - * @return the String representation of the serilaized - * NodeList. - * @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("<"+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 + ""); - 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 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 CipherData + */ + 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 CipherReference + */ + 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 CipherValue + */ + public CipherValue createCipherValue(String value) { + return factory.newCipherValue(value); + } + + /** + * Create an EncryptionMethod object + * + * @param algorithm Algorithm for the encryption + * @return a new EncryptionMethod + */ + public EncryptionMethod createEncryptionMethod(String algorithm) { + return factory.newEncryptionMethod(algorithm); + } + + /** + * Create an EncryptionProperties element + * @return a new EncryptionProperties + */ + public EncryptionProperties createEncryptionProperties() { + return factory.newEncryptionProperties(); + } + + /** + * Create a new EncryptionProperty element + * @return a new EncryptionProperty + */ + public EncryptionProperty createEncryptionProperty() { + return factory.newEncryptionProperty(); + } + + /** + * Create a new ReferenceList object + * @param type ReferenceList.DATA_REFERENCE or ReferenceList.KEY_REFERENCE + * @return a new ReferenceList + */ + public ReferenceList createReferenceList(int type) { + return factory.newReferenceList(type); + } + + /** + * Create a new Transforms object + *

    + * Note: A context document must have been set + * elsewhere (possibly via a call to doFinal). If not, use the + * createTransforms(Document) method. + * @return a new Transforms + */ + 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 requires a + * context document. + * + * @param doc Document that will own the created Transforms node + * @return a new Transforms + */ + public Transforms createTransforms(Document doc) { + return factory.newTransforms(doc); + } /** * @@ -2020,201 +1994,110 @@ public class XMLCipher { private class Factory { /** * @param algorithm - * @return - * + * @return a new AgreementMethod */ AgreementMethod newAgreementMethod(String algorithm) { - return (new AgreementMethodImpl(algorithm)); + return new AgreementMethodImpl(algorithm); } /** * @param type - * @return + * @return a new CipherData * */ CipherData newCipherData(int type) { - return (new CipherDataImpl(type)); + return new CipherDataImpl(type); } /** * @param uri - * @return - * + * @return a new CipherReference */ CipherReference newCipherReference(String uri) { - return (new CipherReferenceImpl(uri)); + return new CipherReferenceImpl(uri); } /** * @param value - * @return - * + * @return a new CipherValue */ CipherValue newCipherValue(String value) { - return (new CipherValueImpl(value)); + return new CipherValueImpl(value); } - /** - * - + /* CipherValue newCipherValue(byte[] value) { - return (new CipherValueImpl(value)); + return new CipherValueImpl(value); } - */ + */ + /** * @param data - * @return - * + * @return a new EncryptedData */ EncryptedData newEncryptedData(CipherData data) { - return (new EncryptedDataImpl(data)); + return new EncryptedDataImpl(data); } /** * @param data - * @return - * + * @return a new EncryptedKey */ EncryptedKey newEncryptedKey(CipherData data) { - return (new EncryptedKeyImpl(data)); + return new EncryptedKeyImpl(data); } /** * @param algorithm - * @return - * + * @return a new EncryptionMethod */ EncryptionMethod newEncryptionMethod(String algorithm) { - return (new EncryptionMethodImpl(algorithm)); + return new EncryptionMethodImpl(algorithm); } /** - * @return - * + * @return a new EncryptionProperties */ EncryptionProperties newEncryptionProperties() { - return (new EncryptionPropertiesImpl()); + return new EncryptionPropertiesImpl(); } /** - * @return - * + * @return a new EncryptionProperty */ EncryptionProperty newEncryptionProperty() { - return (new EncryptionPropertyImpl()); + return new EncryptionPropertyImpl(); } /** - * @param type - * @return - * + * @param type ReferenceList.DATA_REFERENCE or ReferenceList.KEY_REFERENCE + * @return a new ReferenceList */ ReferenceList newReferenceList(int type) { - return (new ReferenceListImpl(type)); + return new ReferenceListImpl(type); } /** - * @return - * + * @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 - * */ - // - // - // - // - // - // - // - // - // - // - // - 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.. - // - - // 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 - * - */ - // - // - // - // - // - // - // - 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 @@ public class XMLCipher { 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 @@ public class XMLCipher { result.setCipherReference(newCipherReference(e)); } - return (result); + return result; } /** * @param element - * @return + * @return a new CipherReference * @throws XMLEncryptionException * */ - // - // - // - // - // - // - // - CipherReference newCipherReference(Element element) throws - XMLEncryptionException { + CipherReference newCipherReference(Element element) throws XMLEncryptionException { - Attr URIAttr = - element.getAttributeNodeNS(null, EncryptionConstants._ATT_URI); - CipherReference result = new CipherReferenceImpl(URIAttr); + Attr uriAttr = + element.getAttributeNodeNS(null, EncryptionConstants._ATT_URI); + CipherReference result = new CipherReferenceImpl(uriAttr); - // Find any Transforms + // Find any Transforms + NodeList transformsElements = + element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_TRANSFORMS); + Element transformsElement = (Element) transformsElements.item(0); - 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); + } + } - 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; + 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 * */ - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - 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 @@ public class XMLCipher { 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 @@ public class XMLCipher { (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 @@ public class XMLCipher { 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 - * */ - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - 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 @@ public class XMLCipher { EncryptionConstants._TAG_ENCRYPTIONPROPERTIES).item(0); if (null != encryptionPropertiesElement) { result.setEncryptionProperties( - newEncryptionProperties(encryptionPropertiesElement)); + newEncryptionProperties(encryptionPropertiesElement) + ); } Element referenceListElement = @@ -2493,30 +2300,40 @@ public class XMLCipher { 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 + */ + 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 @@ public class XMLCipher { 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 // - return (result); + return result; } /** * @param element - * @return - * + * @return a new EncryptionProperties */ - // - // - // - // - // - // - // 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 */ - // - // - // - // - // - // - // - // - // 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... // // TODO: Make this work... // - return (result); + return result; } /** * @param element - * @return - * + * @return a new ReferenceList */ - // - // - // - // - // - // - // - // ReferenceList newReferenceList(Element element) { int type = 0; if (null != element.getElementsByTagNameNS( @@ -2629,84 +2437,38 @@ public class XMLCipher { 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 @@ public class XMLCipher { /** * @param encryptedKey - * @return - * + * @return the XML Element form of that EncryptedKey */ Element toElement(EncryptedKey encryptedKey) { return ((EncryptedKeyImpl) encryptedKey).toElement(); } /** - * @param encryptionMethod - * @return - * + * @param referenceList + * @return the XML Element form of that ReferenceList */ - Element toElement(EncryptionMethod encryptionMethod) { - return ((EncryptionMethodImpl) encryptionMethod).toElement(); - } - - /** - * @param encryptionProperties - * @return - * - */ - 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(); - } - - // - // - // - // - // - // - // - // - // - // - // private class AgreementMethodImpl implements AgreementMethod { private byte[] kaNonce = null; private List agreementMethodInformation = null; @@ -2787,15 +2505,16 @@ public class XMLCipher { 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 @@ public class XMLCipher { /** @inheritDoc */ public Iterator getAgreementMethodInformation() { - return (agreementMethodInformation.iterator()); + return agreementMethodInformation.iterator(); } /** @inheritDoc */ @@ -2820,7 +2539,7 @@ public class XMLCipher { /** @inheritDoc */ public KeyInfo getOriginatorKeyInfo() { - return (originatorKeyInfo); + return originatorKeyInfo; } /** @inheritDoc */ @@ -2830,7 +2549,7 @@ public class XMLCipher { /** @inheritDoc */ public KeyInfo getRecipientKeyInfo() { - return (recipientKeyInfo); + return recipientKeyInfo; } /** @inheritDoc */ @@ -2840,70 +2559,10 @@ public class XMLCipher { /** @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 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 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; } } - // - // - // - // - // - // - // private class CipherDataImpl implements CipherData { private static final String valueMessage = "Data type is reference type."; @@ -2922,16 +2581,16 @@ public class XMLCipher { /** @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 @@ public class XMLCipher { /** @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 @@ public class XMLCipher { /** @inheritDoc */ public int getDataType() { - return (cipherType); + return cipherType; } - // - // - // - // - // - // - // 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; } } - // - // - // - // - // - // - // 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 @@ public class XMLCipher { referenceTransforms = transforms; } - // - // - // - // - // - // - // 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)); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_CIPHERVALUE + ); + result.appendChild(contextDocument.createTextNode(cipherValue)); - return (result); + return result; } } - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - private class EncryptedDataImpl extends EncryptedTypeImpl implements - EncryptedData { + private class EncryptedDataImpl extends EncryptedTypeImpl implements EncryptedData { + /** * @param data */ @@ -3125,94 +2729,49 @@ public class XMLCipher { super(data); } - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // 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; } } - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - 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 @@ public class XMLCipher { /** @inheritDoc */ public String getRecipient() { - return (keyRecipient); + return keyRecipient; } /** @inheritDoc */ @@ -3236,7 +2795,7 @@ public class XMLCipher { /** @inheritDoc */ public ReferenceList getReferenceList() { - return (referenceList); + return referenceList; } /** @inheritDoc */ @@ -3246,7 +2805,7 @@ public class XMLCipher { /** @inheritDoc */ public String getCarriedName() { - return (carriedName); + return carriedName; } /** @inheritDoc */ @@ -3254,84 +2813,60 @@ public class XMLCipher { carriedName = name; } - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // 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 @@ public class XMLCipher { 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 class XMLCipher { 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 @@ public class XMLCipher { 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 class XMLCipher { public void setMimeType(String type) { mimeType = type; } + /** * - * @return + * @return the encoding */ public String getEncoding() { - return (encoding); + return encoding; } + /** * * @param encoding @@ -3418,19 +2965,22 @@ public class XMLCipher { 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 class XMLCipher { 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 class XMLCipher { 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; } } - // - // - // - // - // - // - // - // private class EncryptionMethodImpl implements EncryptionMethod { private String algorithm = null; private int keySize = Integer.MIN_VALUE; private byte[] oaepParams = null; private List 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(); } + /** @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 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); } - // - // - // - // - // - // - // - // 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 (!encryptionMethodInformation.isEmpty()) { - Iterator itr = encryptionMethodInformation.iterator(); + if (digestAlgorithm != null) { + Element digestElement = + XMLUtils.createElementInSignatureSpace(contextDocument, Constants._TAG_DIGESTMETHOD); + digestElement.setAttributeNS(null, "Algorithm", digestAlgorithm); + result.appendChild(digestElement); + } + 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 itr = encryptionMethodInformation.iterator(); + while (itr.hasNext()) { result.appendChild(itr.next()); } - return (result); + return result; } } - // - // - // - // - // - // - // private class EncryptionPropertiesImpl implements EncryptionProperties { private String id = null; private List encryptionProperties = null; + /** - * - * + * Constructor. */ public EncryptionPropertiesImpl() { encryptionProperties = new LinkedList(); } + /** @inheritDoc */ public String getId() { - return (id); + return id; } + /** @inheritDoc */ public void setId(String id) { this.id = id; } + /** @inheritDoc */ public Iterator 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 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 itr = getEncryptionProperties(); while (itr.hasNext()) { - result.appendChild(((EncryptionPropertyImpl) - itr.next()).toElement()); + result.appendChild(((EncryptionPropertyImpl)itr.next()).toElement()); } - return (result); + return result; } } - // - // - // - // - // - // - // - // - // private class EncryptionPropertyImpl implements EncryptionProperty { private String target = null; private String id = null; - private HashMap attributeMap = new HashMap(); + private Map attributeMap = new HashMap(); private List encryptionInformation = null; /** - * - * + * Constructor. */ public EncryptionPropertyImpl() { encryptionInformation = new LinkedList(); } + /** @inheritDoc */ public String getTarget() { - return (target); + return target; } + /** @inheritDoc */ public void setTarget(String target) { if (target == null || target.length() == 0) { @@ -3670,163 +3240,144 @@ public class XMLCipher { } 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 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 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; } } - // - // - // - // - // - private class TransformsImpl extends - com.sun.org.apache.xml.internal.security.transforms.Transforms - implements Transforms { + 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, ""); - - } + /** + * Construct Transforms + */ + public TransformsImpl() { + super(contextDocument); + } /** * - * @return + * @param doc */ - public Element toElement() { + public TransformsImpl(Document doc) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - if (_doc == null) - _doc = _contextDocument; + this.doc = doc; + this.constructionElement = + createElementForFamilyLocal( + this.doc, this.getBaseNamespace(), this.getBaseLocalName() + ); + } - return getElement(); - } + /** + * + * @param element + * @throws XMLSignatureException + * @throws InvalidTransformException + * @throws XMLSecurityException + * @throws TransformationException + */ + 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); - } + public com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms() { + return this; + } - - // Over-ride the namespace + // Over-ride the namespace /** @inheritDoc */ - public String getBaseNamespace() { - return EncryptionConstants.EncryptionSpecNS; - } - + public String getBaseNamespace() { + return EncryptionConstants.EncryptionSpecNS; + } } - // - // - // - // - // - // - // - // private class ReferenceListImpl implements ReferenceList { private Class sentry; private List references; + /** - * + * Constructor. * @param type */ public ReferenceListImpl(int type) { @@ -3839,13 +3390,15 @@ public class XMLCipher { } references = new LinkedList(); } + /** @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 @@ public class XMLCipher { } 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 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 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 @@ public class XMLCipher { private String uri; private List referenceInformation; - ReferenceImpl(String _uri) { - this.uri = _uri; + ReferenceImpl(String uri) { + this.uri = uri; referenceInformation = new LinkedList(); } + + /** @inheritDoc */ + public abstract String getType(); + /** @inheritDoc */ public String getURI() { - return (uri); + return uri; } + /** @inheritDoc */ public Iterator 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 - */ - public abstract Element toElement(); - Element toElement(String tagName) { - Element result = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - tagName); + /** + * @return the XML Element form of that Reference + */ + 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.. // - 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; } } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java index 65b9a604b66..583042680d1 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java @@ -2,23 +2,24 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 com.sun.org.apache.xml.internal.security.transforms.TransformationExcepti import org.w3c.dom.Attr; import com.sun.org.apache.xml.internal.security.utils.Base64; - /** * XMLCipherInput is used to wrap input passed into the * XMLCipher encryption operations. @@ -50,77 +50,79 @@ import com.sun.org.apache.xml.internal.security.utils.Base64; 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; - /** - * Constructor for processing encrypted octets - * - * @param data The CipherData 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"); - } + private boolean secureValidation; + /** + * Constructor for processing encrypted octets + * + * @param data The CipherData 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 EncryptedType 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 EncryptedType 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"); } + } - /** - * Dereferences the input and returns it as a single byte array. - * - * @throws XMLEncryptionException + /** + * 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 * @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 @@ public class XMLCipherInput { 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 @@ public class XMLCipherInput { 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); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java index e25e1fa2a61..1c74f02060d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java @@ -2,104 +2,85 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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"; } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java index 0c913145058..8d027a2d893 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; * */ public class XMLEncryptionException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - /** + /** * - * - */ - 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); - } + */ + private static final long serialVersionUID = 1L; + + /** + * + * + */ + 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); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java index bbdbaefa27d..1dcb10b9ec6 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java @@ -2,88 +2,80 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java index bf039a2602e..0b982c0b241 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ package com.sun.org.apache.xml.internal.security.exceptions; */ 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); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java index 4a4be909ab2..63cb4572e49 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 java.text.MessageFormat; 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 @@ import com.sun.org.apache.xml.internal.security.utils.I18n; */ public class XMLSecurityException extends Exception { + /** + * + */ + private static final long serialVersionUID = 1L; + /** Field msgID */ + protected String msgID; - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * Constructor XMLSecurityException + * + */ + public XMLSecurityException() { + super("Missing message string"); - /** Field originalException */ - protected Exception originalException = null; + this.msgID = null; + } - /** Field msgID */ - protected String msgID; + /** + * Constructor XMLSecurityException + * + * @param msgID + */ + public XMLSecurityException(String msgID) { + super(I18n.getExceptionMessage(msgID)); - /** - * Constructor XMLSecurityException - * - */ - public XMLSecurityException() { + this.msgID = msgID; + } - super("Missing message string"); + /** + * Constructor XMLSecurityException + * + * @param msgID + * @param exArgs + */ + public XMLSecurityException(String msgID, Object exArgs[]) { - this.msgID = null; - this.originalException = null; - } + super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs)); - /** - * Constructor XMLSecurityException - * - * @param _msgID - */ - public XMLSecurityException(String _msgID) { + this.msgID = msgID; + } - super(I18n.getExceptionMessage(_msgID)); + /** + * Constructor XMLSecurityException + * + * @param originalException + */ + public XMLSecurityException(Exception originalException) { - this.msgID = _msgID; - this.originalException = null; - } + 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 - */ - public XMLSecurityException(String _msgID, Object exArgs[]) { + /** + * Constructor XMLSecurityException + * + * @param msgID + * @param originalException + */ + public XMLSecurityException(String msgID, Exception originalException) { + super(I18n.getExceptionMessage(msgID, originalException), originalException); - super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs)); + this.msgID = msgID; + } - this.msgID = _msgID; - this.originalException = null; - } + /** + * Constructor XMLSecurityException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public XMLSecurityException(String msgID, Object exArgs[], Exception originalException) { + super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs), originalException); - /** - * Constructor XMLSecurityException - * - * @param _originalException - */ - public XMLSecurityException(Exception _originalException) { + this.msgID = msgID; + } - super("Missing message ID to locate message string in resource bundle \"" - + Constants.exceptionMessagesResourceBundleBase - + "\". Original Exception was a " - + _originalException.getClass().getName() + " and message " - + _originalException.getMessage()); + /** + * Method getMsgID + * + * @return the messageId + */ + public String getMsgID() { + if (msgID == null) { + return "Missing message ID"; + } + return msgID; + } - this.originalException = _originalException; - } + /** @inheritDoc */ + public String toString() { + String s = this.getClass().getName(); + String message = super.getLocalizedMessage(); - /** - * Constructor XMLSecurityException - * - * @param _msgID - * @param _originalException - */ - public XMLSecurityException(String _msgID, Exception _originalException) { + if (message != null) { + message = s + ": " + message; + } else { + message = s; + } - super(I18n.getExceptionMessage(_msgID, _originalException)); + if (super.getCause() != null) { + message = message + "\nOriginal Exception was " + super.getCause().toString(); + } - this.msgID = _msgID; - this.originalException = _originalException; - } + return message; + } - /** - * Constructor XMLSecurityException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public XMLSecurityException(String _msgID, Object exArgs[], - Exception _originalException) { + /** + * Method printStackTrace + * + */ + public void printStackTrace() { + synchronized (System.err) { + super.printStackTrace(System.err); + } + } - super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs)); + /** + * Method printStackTrace + * + * @param printwriter + */ + public void printStackTrace(PrintWriter printwriter) { + super.printStackTrace(printwriter); + } - this.msgID = _msgID; - this.originalException = _originalException; - } + /** + * Method printStackTrace + * + * @param printstream + */ + public void printStackTrace(PrintStream printstream) { + super.printStackTrace(printstream); + } - /** - * Method getMsgID - * - * @return the messageId - */ - public String getMsgID() { - - if (msgID == null) { - return "Missing message ID"; - } - return msgID; - } - - /** @inheritDoc */ - public String toString() { - - String s = this.getClass().getName(); - String message = super.getLocalizedMessage(); - - if (message != null) { - message = s + ": " + message; - } else { - message = s; - } - - if (originalException != null) { - message = message + "\nOriginal Exception was " - + originalException.toString(); - } - - return message; - } - - /** - * Method printStackTrace - * - */ - public void printStackTrace() { - - synchronized (System.err) { - super.printStackTrace(System.err); - - if (this.originalException != null) { - this.originalException.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 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java index 69a803b04c9..06cb920dabe 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java @@ -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 @@ import com.sun.org.apache.xml.internal.security.utils.I18n; * * @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() { + super("Missing message string"); - /** - * Constructor XMLSecurityRuntimeException - * - */ - public XMLSecurityRuntimeException() { + this.msgID = null; + } - super("Missing message string"); + /** + * Constructor XMLSecurityRuntimeException + * + * @param msgID + */ + public XMLSecurityRuntimeException(String msgID) { + super(I18n.getExceptionMessage(msgID)); - this.msgID = null; - this.originalException = null; - } + this.msgID = msgID; + } - /** - * Constructor XMLSecurityRuntimeException - * - * @param _msgID - */ - public XMLSecurityRuntimeException(String _msgID) { + /** + * Constructor XMLSecurityRuntimeException + * + * @param msgID + * @param exArgs + */ + public XMLSecurityRuntimeException(String msgID, Object exArgs[]) { + super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs)); - super(I18n.getExceptionMessage(_msgID)); + this.msgID = msgID; + } - this.msgID = _msgID; - this.originalException = null; - } + /** + * 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 exArgs - */ - public XMLSecurityRuntimeException(String _msgID, Object exArgs[]) { + /** + * Constructor XMLSecurityRuntimeException + * + * @param msgID + * @param originalException + */ + public XMLSecurityRuntimeException(String msgID, Exception originalException) { + super(I18n.getExceptionMessage(msgID, originalException), originalException); - super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs)); + this.msgID = msgID; + } - this.msgID = _msgID; - this.originalException = null; - } + /** + * 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 _originalException - */ - public XMLSecurityRuntimeException(Exception _originalException) { + this.msgID = msgID; + } - super("Missing message ID to locate message string in resource bundle \"" - + Constants.exceptionMessagesResourceBundleBase - + "\". Original Exception was a " - + _originalException.getClass().getName() + " and message " - + _originalException.getMessage()); + /** + * Method getMsgID + * + * @return the messageId + */ + public String getMsgID() { + if (msgID == null) { + return "Missing message ID"; + } + return msgID; + } - this.originalException = _originalException; - } + /** @inheritDoc */ + public String toString() { + String s = this.getClass().getName(); + String message = super.getLocalizedMessage(); - /** - * Constructor XMLSecurityRuntimeException - * - * @param _msgID - * @param _originalException - */ - public XMLSecurityRuntimeException(String _msgID, Exception _originalException) { + if (message != null) { + message = s + ": " + message; + } else { + message = s; + } - super(I18n.getExceptionMessage(_msgID, _originalException)); + if (this.getCause() != null) { + message = message + "\nOriginal Exception was " + this.getCause().toString(); + } - this.msgID = _msgID; - this.originalException = _originalException; - } + return message; + } - /** - * Constructor XMLSecurityRuntimeException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public XMLSecurityRuntimeException(String _msgID, Object exArgs[], - Exception _originalException) { + /** + * Method printStackTrace + * + */ + public void printStackTrace() { + synchronized (System.err) { + super.printStackTrace(System.err); + } + } - super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs)); + /** + * Method printStackTrace + * + * @param printwriter + */ + public void printStackTrace(PrintWriter printwriter) { + super.printStackTrace(printwriter); + } - this.msgID = _msgID; - this.originalException = _originalException; - } + /** + * Method printStackTrace + * + * @param printstream + */ + public void printStackTrace(PrintStream printstream) { + super.printStackTrace(printstream); + } - /** - * Method getMsgID - * - * @return the messageId - */ - public String getMsgID() { + /** + * Method getOriginalException + * + * @return the original exception + */ + public Exception getOriginalException() { + if (this.getCause() instanceof Exception) { + return (Exception)this.getCause(); + } + return null; + } - if (msgID == null) { - return "Missing message ID"; - } - return msgID; - } - - /** @inheritDoc */ - public String toString() { - - String s = this.getClass().getName(); - String message = super.getLocalizedMessage(); - - if (message != null) { - message = s + ": " + message; - } else { - message = s; - } - - if (originalException != null) { - message = message + "\nOriginal Exception was " - + originalException.toString(); - } - - return message; - } - - /** - * Method printStackTrace - * - */ - public void printStackTrace() { - - synchronized (System.err) { - super.printStackTrace(System.err); - - if (this.originalException != null) { - this.originalException.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 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; - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java index 6477d9bba2c..ad807c2d862 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java @@ -2,89 +2,83 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java index 3c273dea7ac..6716d80d899 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java @@ -2,30 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.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.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.KeyResolverExce 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.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.EncryptionConstants; 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.Element; 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 @@ import org.w3c.dom.NodeList; * The containsXXX() methods return whether 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 x509Datas=null; - List encryptedKeys=null; - static final List nullList; + // We need at least one StorageResolver otherwise + // the KeyResolvers would not be called. + // The default StorageResolver is null. + + private List x509Datas = null; + private List encryptedKeys = null; + + private static final List nullList; static { List list = new ArrayList(1); list.add(null); - nullList = Collections.unmodifiableList(list); + nullList = java.util.Collections.unmodifiableList(list); } - /** - * 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); - } - } - - /** - * Sets the Id attribute - * - * @param Id ID - */ - public void setId(String Id) { - - if (Id != null) { - setLocalIdAttribute(Constants._ATT_ID, Id); - } - } - - /** - * Returns the Id attribute - * - * @return the Id 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); - } - - /** - * Method add - * - * @param spkidata - */ - public void add(SPKIData spkidata) { - this._constructionElement.appendChild(spkidata.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addX509Data - * - * @param x509data - */ - public void add(X509Data x509data) { - if (x509Datas==null) - x509Datas=new ArrayList(); - x509Datas.add(x509data); - this._constructionElement.appendChild(x509data.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addEncryptedKey - * - * @param encryptedKey - * @throws XMLEncryptionException - */ - - public void add(EncryptedKey encryptedKey) - throws XMLEncryptionException { - if (encryptedKeys==null) - encryptedKeys=new ArrayList(); - encryptedKeys.add(encryptedKey); - XMLCipher cipher = XMLCipher.getInstance(); - this._constructionElement.appendChild(cipher.martial(encryptedKey)); - } - - /** - * Method addUnknownElement - * - * @param element - */ - public void addUnknownElement(Element element) { - this._constructionElement.appendChild(element); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * 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 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); - } - - /** - * 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); - - /** - * $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 { - - 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); - - 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 { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_PGPDATA,i); - - if (e != null) { - return new PGPData(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); - - if (e != null) { - return new RetrievalMethod(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 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 - */ - - 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) { - - 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 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 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; - } - - /** - * 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"); - - return pk; - } - 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) { - 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; - } + /** Field storageResolvers */ + private List storageResolvers = nullList; /** - * Searches the library wide keyresolvers for public keys + * Stores the individual (per-KeyInfo) {@link KeyResolverSpi}s + */ + private List internalKeyResolvers = new ArrayList(); + + 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 Id 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 Id attribute + * + * @return the Id 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); + } + + /** + * Method add + * + * @param spkidata + */ + public void add(SPKIData spkidata) { + this.constructionElement.appendChild(spkidata.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addX509Data + * + * @param x509data + */ + public void add(X509Data x509data) { + if (x509Datas == null) { + x509Datas = new ArrayList(); + } + x509Datas.add(x509data); + this.constructionElement.appendChild(x509data.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addEncryptedKey + * + * @param encryptedKey + * @throws XMLEncryptionException + */ + + public void add(EncryptedKey encryptedKey) throws XMLEncryptionException { + if (encryptedKeys == null) { + encryptedKeys = new ArrayList(); + } + encryptedKeys.add(encryptedKey); + XMLCipher cipher = XMLCipher.getInstance(); + this.constructionElement.appendChild(cipher.martial(encryptedKey)); + } + + /** + * Method addDEREncodedKeyValue + * + * @param pk + * @throws XMLSecurityException + */ + public void addDEREncodedKeyValue(PublicKey pk) throws XMLSecurityException { + this.add(new DEREncodedKeyValue(this.doc, pk)); + } + + /** + * Method add + * + * @param derEncodedKeyValue + */ + public void add(DEREncodedKeyValue derEncodedKeyValue) { + this.constructionElement.appendChild(derEncodedKeyValue.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addKeyInfoReference + * + * @param URI + * @throws XMLSecurityException + */ + public void addKeyInfoReference(String URI) throws XMLSecurityException { + this.add(new KeyInfoReference(this.doc, URI)); + } + + /** + * Method add + * + * @param keyInfoReference + */ + public void add(KeyInfoReference keyInfoReference) { + this.constructionElement.appendChild(keyInfoReference.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addUnknownElement + * + * @param element + */ + public void addUnknownElement(Element element) { + this.constructionElement.appendChild(element); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * 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 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); + } + + /** + * 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 lengthDEREncodedKeyValue + * + *@return the number of the DEREncodedKeyValue tags + */ + public int lengthDEREncodedKeyValue() { + return this.length(Constants.SignatureSpec11NS, Constants._TAG_DERENCODEDKEYVALUE); + } + + /** + * Method lengthKeyInfoReference + * + *@return the number of the KeyInfoReference tags + */ + public int lengthKeyInfoReference() { + return this.length(Constants.SignatureSpec11NS, Constants._TAG_KEYINFOREFERENCE); + } + + /** + * Method lengthUnknownElement + * NOTE possibly 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); + + /** + * $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 { + 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); + + 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 { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_PGPDATA, i); + + if (e != null) { + return new PGPData(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); + + if (e != null) { + return new RetrievalMethod(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 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); + + 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 + */ + 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 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 (e != null) { + return new DEREncodedKeyValue(e, this.baseURI); + } + return null; + } + + /** + * 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 @@ public class KeyInfo extends SignatureElementProxy { Iterator 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 @@ public class KeyInfo extends SignatureElementProxy { 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()); - - 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(); - } - } + 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 + ); - return null; - } + if (pk != null) { + return pk; + } + } + } + currentChild = currentChild.getNextSibling(); + } + } - /** - * Method getX509Certificate - * - * @return The certificate contined in this KeyInfo - * @throws KeyResolverException - */ - public X509Certificate getX509Certificate() throws KeyResolverException { + return null; + } - // First search using the individual resolvers from the user - X509Certificate cert = this.getX509CertificateFromInternalResolvers(); + /** + * 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(); - 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) { + 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"); + } - if (cert != null) { - log.log(java.util.logging.Level.FINE, - "I could 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 cert; - } - 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 @@ public class KeyInfo extends SignatureElementProxy { Iterator 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 @@ public class KeyInfo extends SignatureElementProxy { 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 @@ public class KeyInfo extends SignatureElementProxy { /** * Method getX509CertificateFromInternalResolvers * - * @return The certificate contined in this KeyInfo + * @return The certificate contained in this KeyInfo * @throws KeyResolverException */ X509Certificate getX509CertificateFromInternalResolvers() @@ -891,10 +1022,11 @@ public class KeyInfo extends SignatureElementProxy { ); } 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 @@ public class KeyInfo extends SignatureElementProxy { 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) { - log.log(java.util.logging.Level.FINE, "I could 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"); - - - sk = this.getSecretKeyFromStaticResolvers(); - - if (sk != null) { - log.log(java.util.logging.Level.FINE, "I could find a secret key using the system-wide key resolvers"); - - return sk; - } - 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 { - final int length=KeyResolver.length(); - int storageLength=this._storageResolvers.size(); - Iterator 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; - } - } + 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"); } - currentChild=currentChild.getNextSibling(); - } - } - return null; - } - /** - * Searches the per-KeyInfo keyresolvers for secret keys - * - * @return the secret key contained in this KeyInfo - * @throws KeyResolverException - */ + 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"); + } - 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()); + sk = this.getSecretKeyFromStaticResolvers(); - 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); + 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"); + } - SecretKey sk = keyResolver - .engineLookupAndResolveSecretKey((Element) currentChild, uri, storage); + 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"); + } - if (sk != null) { - return sk; - } + 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 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) { + return sk; + } + } } - } - currentChild=currentChild.getNextSibling(); - } - } + currentChild = currentChild.getNextSibling(); + } + } + return null; + } - return null; - } + /** + * Searches the per-KeyInfo KeyResolvers for secret keys + * + * @return the secret key contained in this KeyInfo + * @throws KeyResolverException + */ - /** - * Stores the individual (per-KeyInfo) {@link KeyResolver}s - */ - List _internalKeyResolvers = new ArrayList(); + 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 + ); - /** - * 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(); - } - this._internalKeyResolvers.add(realKeyResolver); - } + if (sk != null) { + return sk; + } + } + } + currentChild = currentChild.getNextSibling(); + } + } - /** - * Method lengthInternalKeyResolver - * @return the length of the key - */ - int lengthInternalKeyResolver() { - if (_internalKeyResolvers==null) - return 0; - return this._internalKeyResolvers.size(); - } + return null; + } - /** - * Method itemInternalKeyResolver - * - * @param i the index - * @return the KeyResolverSpi for the index. - */ - KeyResolverSpi itemInternalKeyResolver(int i) { - return this._internalKeyResolvers.get(i); - } + /** + * 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(); - /** Field _storageResolvers */ - private List _storageResolvers = nullList; + 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"); + } - /** - * Method addStorageResolver - * - * @param storageResolver - */ - public void addStorageResolver(StorageResolver storageResolver) { - if (_storageResolvers == nullList ){ - _storageResolvers=new ArrayList(); - } - this._storageResolvers.add(storageResolver); + 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; + } - //J- - static boolean _alreadyInitialized = false; - /** init the keyinfo (Still needed?)*/ - public static void init() { + /** + * Searches the library wide KeyResolvers for Private keys + * + * @return the private key contained in this KeyInfo + * @throws KeyResolverException + */ + PrivateKey getPrivateKeyFromStaticResolvers() throws KeyResolverException { + Iterator it = KeyResolver.iterator(); + while (it.hasNext()) { + KeyResolverSpi keyResolver = it.next(); + keyResolver.setSecureValidation(secureValidation); - if (!KeyInfo._alreadyInitialized) { - if (KeyInfo.log == null) { + 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 + ); - /** - * $todo$ why the hell does the static initialization from the - * start not work ? - */ - KeyInfo.log = - java.util.logging.Logger.getLogger(KeyInfo.class.getName()); + if (pk != null) { + return pk; + } + } + currentChild = currentChild.getNextSibling(); + } + } + return null; + } - log.log(java.util.logging.Level.SEVERE, "Had to assign log in the init() function"); - } + /** + * 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 + ); - // KeyInfo._contentHandlerHash = new HashMap(10); - KeyInfo._alreadyInitialized = true; - } - } + if (pk != null) { + return pk; + } + } + currentChild = currentChild.getNextSibling(); + } + } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_KEYINFO; - } + return null; + } + + /** + * 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(); + } + this.storageResolvers.add(storageResolver); + } + + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_KEYINFO; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java index 67ce204efba..8613c8197b7 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.KeyValue; 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 com.sun.org.apache.xml.internal.security.keys 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 " : "") + "\""); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java new file mode 100644 index 00000000000..0144025216a --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java @@ -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 dsig11:DEREncodedKeyvalue 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 Id 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 Id attribute + * + * @return the Id 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); + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java index 4d5a7a6b975..e753f1bb4ce 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java @@ -2,32 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 { } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java new file mode 100644 index 00000000000..f52f4a98e54 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java @@ -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 dsig11:KeyInfoReference 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 Id 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 Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_KEYINFOREFERENCE; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java index 6794ea67586..fbe2e0c1faf 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Document; 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 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 doc + * @param keyName + */ + public KeyName(Document doc, String keyName) { + super(doc); - 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java index 0d3ee810d23..db7a6836d56 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import org.w3c.dom.Element; * 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 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @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 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @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 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @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 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @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 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @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 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @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(); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java index 185e3557170..c037ee77f7d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Document; 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 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 doc + * @param mgmtData + */ + public MgmtData(Document doc, String mgmtData) { + super(doc); - 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java index 010c907a8d9..e4dbbf4b091 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java index 3c4956b7787..5ee9041f7b1 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Attr; 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 transformations + */ + public Transforms getTransforms() throws XMLSecurityException { + try { + Element transformsElem = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_TRANSFORMS, 0); - /** - * Method getTransforms - * - * - * @throws XMLSecurityException - * @return the transforamitons - */ - public Transforms getTransforms() throws XMLSecurityException { + if (transformsElem != null) { + return new Transforms(transformsElem, this.baseURI); + } - try { - Element transformsElem = - XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants - ._TAG_TRANSFORMS, 0); + return null; + } catch (XMLSignatureException ex) { + throw new XMLSecurityException("empty", ex); + } + } - if (transformsElem != null) { - return new Transforms(transformsElem, this._baseURI); - } - - 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java index 95cef8d5491..0177f9bcc12 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java index 199b1dcb020..55a2a0edd40 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java @@ -2,32 +2,33 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Document; 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) { + /** + * Constructor X509Data + * + * @param doc + */ + public X509Data(Document doc) { + super(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 { + super(element, baseURI); - /** - * Constructor X509Data - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public X509Data(Element element, String BaseURI) - throws XMLSecurityException { + 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); + } - 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); - } + /** + * 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) { - /** - * Method add - * - * @param xmlX509IssuerSerial - */ - public void add(XMLX509IssuerSerial xmlX509IssuerSerial) { + this.constructionElement.appendChild(xmlX509IssuerSerial.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - 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 addSKI - * - * @param skiBytes - */ - public void addSKI(byte[] skiBytes) { - this.add(new XMLX509SKI(this._doc, skiBytes)); - } + /** + * Method addSKI + * + * @param x509certificate + * @throws XMLSecurityException + */ + public void addSKI(X509Certificate x509certificate) + throws XMLSecurityException { + this.add(new XMLX509SKI(this.doc, x509certificate)); + } - /** - * Method addSKI - * - * @param x509certificate - * @throws XMLSecurityException - */ - public void addSKI(X509Certificate x509certificate) - throws XMLSecurityException { - this.add(new XMLX509SKI(this._doc, x509certificate)); - } + /** + * Method add + * + * @param xmlX509SKI + */ + public void add(XMLX509SKI xmlX509SKI) { + this.constructionElement.appendChild(xmlX509SKI.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method add - * - * @param xmlX509SKI - */ - public void add(XMLX509SKI xmlX509SKI) { - this._constructionElement.appendChild(xmlX509SKI.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } + /** + * Method addSubjectName + * + * @param subjectName + */ + public void addSubjectName(String subjectName) { + this.add(new XMLX509SubjectName(this.doc, subjectName)); + } - /** - * Method addSubjectName - * - * @param subjectName - */ - public void addSubjectName(String subjectName) { - this.add(new XMLX509SubjectName(this._doc, subjectName)); - } + /** + * Method addSubjectName + * + * @param x509certificate + */ + public void addSubjectName(X509Certificate x509certificate) { + this.add(new XMLX509SubjectName(this.doc, x509certificate)); + } - /** - * Method addSubjectName - * - * @param x509certificate - */ - public void addSubjectName(X509Certificate x509certificate) { - this.add(new XMLX509SubjectName(this._doc, x509certificate)); - } + /** + * Method add + * + * @param xmlX509SubjectName + */ + public void add(XMLX509SubjectName xmlX509SubjectName) { + this.constructionElement.appendChild(xmlX509SubjectName.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method add - * - * @param xmlX509SubjectName - */ - public void add(XMLX509SubjectName xmlX509SubjectName) { - this._constructionElement.appendChild(xmlX509SubjectName.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } + /** + * Method addCertificate + * + * @param x509certificate + * @throws XMLSecurityException + */ + public void addCertificate(X509Certificate x509certificate) + throws XMLSecurityException { + this.add(new XMLX509Certificate(this.doc, x509certificate)); + } - /** - * Method addCertificate - * - * @param x509certificate - * @throws XMLSecurityException - */ - public void addCertificate(X509Certificate x509certificate) - throws XMLSecurityException { - this.add(new XMLX509Certificate(this._doc, x509certificate)); - } + /** + * Method addCertificate + * + * @param x509certificateBytes + */ + public void addCertificate(byte[] x509certificateBytes) { + this.add(new XMLX509Certificate(this.doc, x509certificateBytes)); + } - /** - * Method addCertificate - * - * @param x509certificateBytes - */ - public void addCertificate(byte[] x509certificateBytes) { - this.add(new XMLX509Certificate(this._doc, x509certificateBytes)); - } + /** + * Method add + * + * @param xmlX509Certificate + */ + public void add(XMLX509Certificate xmlX509Certificate) { + this.constructionElement.appendChild(xmlX509Certificate.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * 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 addCRL - * - * @param crlBytes - */ - public void addCRL(byte[] crlBytes) { - this.add(new XMLX509CRL(this._doc, crlBytes)); - } + /** + * Method add + * + * @param xmlX509CRL + */ + public void add(XMLX509CRL xmlX509CRL) { + this.constructionElement.appendChild(xmlX509CRL.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method add - * - * @param xmlX509CRL - */ - public void add(XMLX509CRL xmlX509CRL) { - this._constructionElement.appendChild(xmlX509CRL.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 addUnknownElement - * - * @param element - */ - public void addUnknownElement(Element element) { - this._constructionElement.appendChild(element); - XMLUtils.addReturnToElement(this._constructionElement); - } + /** + * Method addDigest + * + * @param x509CertificateDigestByes + * @param algorithmURI + */ + public void addDigest(byte[] x509certificateDigestBytes, String algorithmURI) { + this.add(new XMLX509Digest(this.doc, x509certificateDigestBytes, algorithmURI)); + } - /** - * Method lengthIssuerSerial - * - * @return the number of IssuerSerial elements in this X509Data - */ - public int lengthIssuerSerial() { - return this.length(Constants.SignatureSpecNS, - Constants._TAG_X509ISSUERSERIAL); - } + /** + * Method add + * + * @param XMLX509Digest + */ + public void add(XMLX509Digest xmlX509Digest) { + this.constructionElement.appendChild(xmlX509Digest.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method lengthSKI - * - * @return the number of SKI elements in this X509Data - */ - public int lengthSKI() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SKI); - } + /** + * Method addUnknownElement + * + * @param element + */ + public void addUnknownElement(Element element) { + this.constructionElement.appendChild(element); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method lengthSubjectName - * - * @return the number of SubjectName elements in this X509Data - */ - public int lengthSubjectName() { - return this.length(Constants.SignatureSpecNS, - Constants._TAG_X509SUBJECTNAME); - } + /** + * Method lengthIssuerSerial + * + * @return the number of IssuerSerial elements in this X509Data + */ + public int lengthIssuerSerial() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509ISSUERSERIAL); + } - /** - * Method lengthCertificate - * - * @return the number of Certificate elements in this X509Data - */ - public int lengthCertificate() { - return this.length(Constants.SignatureSpecNS, - Constants._TAG_X509CERTIFICATE); - } + /** + * Method lengthSKI + * + * @return the number of SKI elements in this X509Data + */ + public int lengthSKI() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SKI); + } - /** - * Method lengthCRL - * - * @return the number of CRL elements in this X509Data - */ - public int lengthCRL() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CRL); - } + /** + * Method lengthSubjectName + * + * @return the number of SubjectName elements in this X509Data + */ + public int lengthSubjectName() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SUBJECTNAME); + } - /** - * Method lengthUnknownElement - * - * @return the number of UnknownElement elements in this X509Data - */ - public int lengthUnknownElement() { + /** + * Method lengthCertificate + * + * @return the number of Certificate elements in this X509Data + */ + public int lengthCertificate() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CERTIFICATE); + } - int result = 0; - Node n=this._constructionElement.getFirstChild(); - while (n!=null){ + /** + * Method lengthCRL + * + * @return the number of CRL elements in this X509Data + */ + public int lengthCRL() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CRL); + } - if ((n.getNodeType() == Node.ELEMENT_NODE) - &&!n.getNamespaceURI().equals(Constants.SignatureSpecNS)) { - result += 1; - } - n=n.getNextSibling(); - } + /** + * Method lengthDigest + * + * @return the number of X509Digest elements in this X509Data + */ + public int lengthDigest() { + return this.length(Constants.SignatureSpec11NS, Constants._TAG_X509DIGEST); + } - return result; - } + /** + * 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 itemIssuerSerial - * - * @param i - * @return the X509IssuerSerial, null if not present - * @throws XMLSecurityException - */ - public XMLX509IssuerSerial itemIssuerSerial(int i) - throws XMLSecurityException { + return result; + } - 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 { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509ISSUERSERIAL, i); - if (e != null) { - return new XMLX509IssuerSerial(e, this._baseURI); - } - return null; - } + if (e != null) { + return new XMLX509IssuerSerial(e, this.baseURI); + } + return null; + } - /** - * Method itemSKI - * - * @param i - * @return the X509SKI, null if not present - * @throws XMLSecurityException - */ - public XMLX509SKI itemSKI(int i) throws XMLSecurityException { + /** + * Method itemSKI + * + * @param i + * @return the X509SKI, null if not present + * @throws XMLSecurityException + */ + public XMLX509SKI itemSKI(int i) throws XMLSecurityException { - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509SKI,i); + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509SKI, i); - if (e != null) { - return new XMLX509SKI(e, this._baseURI); - } - return null; - } + if (e != null) { + return new XMLX509SKI(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 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); + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509SUBJECTNAME, i); - if (e != null) { - return new XMLX509SubjectName(e, this._baseURI); - } - return null; - } + if (e != null) { + return new XMLX509SubjectName(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 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_X509CERTIFICATE,i); + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509CERTIFICATE, i); - if (e != null) { - return new XMLX509Certificate(e, this._baseURI); - } - return null; - } + if (e != null) { + return new XMLX509Certificate(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 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_X509CRL,i); + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509CRL, i); - if (e != null) { - return new XMLX509CRL(e, this._baseURI); - } - return null; - } + if (e != null) { + return new XMLX509CRL(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 itemDigest + * + * @param i + * @return the X509Digest, null if not present + * @throws XMLSecurityException + */ + public XMLX509Digest itemDigest(int i) throws XMLSecurityException { - /** - * Method containsIssuerSerial - * - * @return true if this X509Data contains a IssuerSerial - */ - public boolean containsIssuerSerial() { - return this.lengthIssuerSerial() > 0; - } + Element e = + XMLUtils.selectDs11Node( + this.constructionElement.getFirstChild(), Constants._TAG_X509DIGEST, i); - /** - * Method containsSKI - * - * @return true if this X509Data contains a SKI - */ - public boolean containsSKI() { - return this.lengthSKI() > 0; - } + if (e != null) { + return new XMLX509Digest(e, this.baseURI); + } + return null; + } - /** - * Method containsSubjectName - * - * @return true if this X509Data contains a SubjectName - */ - public boolean containsSubjectName() { - return this.lengthSubjectName() > 0; - } + /** + * 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 containsCertificate - * - * @return true if this X509Data contains a Certificate - */ - public boolean containsCertificate() { - return this.lengthCertificate() > 0; - } + /** + * Method containsIssuerSerial + * + * @return true if this X509Data contains a IssuerSerial + */ + public boolean containsIssuerSerial() { + return this.lengthIssuerSerial() > 0; + } - /** - * Method containsCRL - * - * @return true if this X509Data contains a CRL - */ - public boolean containsCRL() { - return this.lengthCRL() > 0; - } + /** + * Method containsSKI + * + * @return true if this X509Data contains a SKI + */ + public boolean containsSKI() { + return this.lengthSKI() > 0; + } - /** - * Method containsUnknownElement - * - * @return true if this X509Data contains an UnknownElement - */ - public boolean containsUnknownElement() { - return this.lengthUnknownElement() > 0; - } + /** + * Method containsSubjectName + * + * @return true if this X509Data contains a SubjectName + */ + public boolean containsSubjectName() { + return this.lengthSubjectName() > 0; + } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_X509DATA; - } + /** + * 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 containsUnknownElement + * + * @return true if this X509Data contains an UnknownElement + */ + public boolean containsUnknownElement() { + return this.lengthUnknownElement() > 0; + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509DATA; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java index ef735c3dad6..2cfa51fc28c 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 com.sun.org.apache.xml.internal.security.utils.XMLUtils; 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) { + /** + * 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); - 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 { + super(doc); - /** - * Constructor DSAKeyValue - * - * @param doc - * @param key - * @throws IllegalArgumentException - */ - public DSAKeyValue(Document doc, Key key) throws IllegalArgumentException { + XMLUtils.addReturnToElement(this.constructionElement); - super(doc); + 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() }; - XMLUtils.addReturnToElement(this._constructionElement); + throw new IllegalArgumentException(I18n.translate("KeyValue.IllegalArgument", exArgs)); + } + } - 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() }; + /** @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); - throw new IllegalArgumentException(I18n - .translate("KeyValue.IllegalArgument", exArgs)); - } - } + return pk; + } catch (NoSuchAlgorithmException ex) { + throw new XMLSecurityException("empty", ex); + } catch (InvalidKeySpecException ex) { + throw new XMLSecurityException("empty", ex); + } + } - /** @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); - } - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_DSAKEYVALUE; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_DSAKEYVALUE; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java index 31e761443c5..d5ebe5b6937 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java @@ -2,46 +2,38 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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; + } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java index 71b23cda593..a12b8b45bd9 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 com.sun.org.apache.xml.internal.security.utils.XMLUtils; 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) { + /** + * Constructor RSAKeyValue + * + * @param doc + * @param modulus + * @param exponent + */ + public RSAKeyValue(Document doc, BigInteger modulus, BigInteger exponent) { + super(doc); - 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 { + super(doc); - /** - * Constructor RSAKeyValue - * - * @param doc - * @param key - * @throws IllegalArgumentException - */ - public RSAKeyValue(Document doc, Key key) throws IllegalArgumentException { + XMLUtils.addReturnToElement(this.constructionElement); - super(doc); + 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() }; - XMLUtils.addReturnToElement(this._constructionElement); + throw new IllegalArgumentException(I18n.translate("KeyValue.IllegalArgument", exArgs)); + } + } - 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() }; + /** @inheritDoc */ + public PublicKey getPublicKey() throws XMLSecurityException { + try { + KeyFactory rsaFactory = KeyFactory.getInstance("RSA"); - throw new IllegalArgumentException(I18n - .translate("KeyValue.IllegalArgument", exArgs)); - } - } + RSAPublicKeySpec rsaKeyspec = + new RSAPublicKeySpec( + this.getBigIntegerFromChildElement( + Constants._TAG_MODULUS, Constants.SignatureSpecNS + ), + this.getBigIntegerFromChildElement( + Constants._TAG_EXPONENT, Constants.SignatureSpecNS + ) + ); + PublicKey pk = rsaFactory.generatePublic(rsaKeyspec); - /** @inheritDoc */ - public PublicKey getPublicKey() throws XMLSecurityException { + return pk; + } catch (NoSuchAlgorithmException ex) { + throw new XMLSecurityException("empty", ex); + } catch (InvalidKeySpecException ex) { + throw new XMLSecurityException("empty", ex); + } + } - 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); - - 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java index b68c444dc08..0046c71d05c 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java index 630d9ccc279..1a5931ff5d8 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.PublicKey; 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 com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; 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 { + try { + this.addBase64Text(x509certificate.getEncoded()); + } catch (java.security.cert.CertificateEncodingException ex) { + throw new XMLSecurityException("empty", ex); + } + } - super(doc); + /** + * Method getCertificateBytes + * + * @return the certificate bytes + * @throws XMLSecurityException + */ + public byte[] getCertificateBytes() throws XMLSecurityException { + return this.getBytesFromTextChild(); + } - try { - this.addBase64Text(x509certificate.getEncoded()); - } catch (java.security.cert.CertificateEncodingException ex) { - throw new XMLSecurityException("empty", ex); - } - } + /** + * 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) + ); - /** - * Method getCertificateBytes - * - * @return the certificate bytes - * @throws XMLSecurityException - */ - public byte[] getCertificateBytes() throws XMLSecurityException { - return this.getBytesFromTextChild(); - } + if (cert != null) { + return cert; + } - /** - * Method getX509Certificate - * - * @return the x509 certificate - * @throws XMLSecurityException - */ - public X509Certificate getX509Certificate() throws XMLSecurityException { + return null; + } catch (CertificateException ex) { + throw new XMLSecurityException("empty", ex); + } + } - try { - byte certbytes[] = this.getCertificateBytes(); - CertificateFactory certFact = - CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); - X509Certificate cert = - (X509Certificate) certFact - .generateCertificate(new ByteArrayInputStream(certbytes)); + /** + * Method getPublicKey + * + * @return the publickey + * @throws XMLSecurityException + */ + public PublicKey getPublicKey() throws XMLSecurityException { + X509Certificate cert = this.getX509Certificate(); - if (cert != null) { - return cert; - } + if (cert != null) { + return cert.getPublicKey(); + } - return null; - } catch (CertificateException ex) { - throw new XMLSecurityException("empty", ex); - } - } - - /** - * Method getPublicKey - * - * @return teh publickey - * @throws XMLSecurityException - */ - public PublicKey getPublicKey() throws XMLSecurityException { - - 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java index 02bf9f82d39..2171572d3ab 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java @@ -2,32 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 { } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java new file mode 100644 index 00000000000..57acc678bd9 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java @@ -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 dsig11:X509Digest 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; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java index 1d16b2b622f..cf3274377cb 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 com.sun.org.apache.xml.internal.security.utils.XMLUtils; 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 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @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 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @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 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @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 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @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 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @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 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @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 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @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 */ diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java index fbbb17e6a54..e4617daead9 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java @@ -2,30 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import org.w3c.dom.Element; /** * Handles SubjectKeyIdentifier (SKI) for X.509v3. * - * @author $Author: mullan $ - * @see Interface X509Extension + * @see + * Interface X509Extension */ -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 @@ public class XMLX509SKI extends SignatureElementProxy * distinct keys used by the same subject to be differentiated * (e.g., as key updating occurs). *
    - * 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 @@ public class XMLX509SKI extends SignatureElementProxy * @throws XMLSecurityException */ public XMLX509SKI(Document doc, X509Certificate x509certificate) - throws XMLSecurityException { + throws XMLSecurityException { super(doc); this.addBase64Text(XMLX509SKI.getSKIBytesFromCert(x509certificate)); } @@ -89,8 +86,7 @@ public class XMLX509SKI extends SignatureElementProxy * @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 @@ public class XMLX509SKI extends SignatureElementProxy 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 @@ public class XMLX509SKI extends SignatureElementProxy * 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 @@ public class XMLX509SKI extends SignatureElementProxy /** @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; diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java index 8d51da2e2fd..c183abbf8af 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Document; 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 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 doc + * @param X509SubjectNameString + */ + public XMLX509SubjectName(Document doc, String X509SubjectNameString) { + super(doc); - super(doc); + this.addText(X509SubjectNameString); + } - this.addText(X509SubjectNameString); - } + /** + * Constructor XMLX509SubjectName + * + * @param doc + * @param x509certificate + */ + public XMLX509SubjectName(Document doc, X509Certificate x509certificate) { + this(doc, x509certificate.getSubjectX500Principal().getName()); + } - /** - * Constructor XMLX509SubjectName - * - * @param doc - * @param x509certificate - */ - public XMLX509SubjectName(Document doc, X509Certificate x509certificate) { - this(doc, - RFC2253Parser.normalize(x509certificate.getSubjectDN().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 @@ public class XMLX509SubjectName extends SignatureElementProxy 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java index 3b3508005cb..614a34f41e6 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java @@ -2,88 +2,80 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java index 00c60165f8a..fe541ff044f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java @@ -31,10 +31,13 @@ import java.util.concurrent.CopyOnWriteArrayList; 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 @@ public class KeyResolver { 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); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java index f0069949b2f..028a0e9dec2 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java @@ -2,90 +2,80 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java index 3e5c82ccfe5..78622d79336 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java @@ -2,24 +2,27 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; 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 *

      *  <KeyResolver URI="http://www.w3.org/2000/09/xmldsig#KeyValue"
      *   JAVACLASS="MyPackage.MyKeyValueImpl"//gt;
      * 
    - * - * @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(); - } - /** - * 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(); + /** Field properties */ + protected java.util.Map 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; + } + + /** + * 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 @@ public abstract class KeyResolverSpi { * 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 _properties = null; + /** + * 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; + } - protected boolean globalResolver=false; + /** + * Method engineSetProperty + * + * @param key + * @param value + */ + public void engineSetProperty(String key, String value) { + if (properties == null) { + properties = new HashMap(); + } + properties.put(key, value); + } - /** - * Method engineSetProperty - * - * @param key - * @param value - */ - public void engineSetProperty(String key, String value) { - if (_properties==null) - _properties=new HashMap(); - this._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 properties.get(key); + } - return this._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 properties.get(propertyToTest) != null; + } - return this._properties.get(propertyToTest)!=null; - } - public void setGlobalResolver(boolean globalResolver) { + public void setGlobalResolver(boolean globalResolver) { this.globalResolver = globalResolver; - } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java new file mode 100644 index 00000000000..dbd2e084f0c --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java @@ -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 + * dsig11:DEREncodedKeyValue 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; + } + + + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java index 20bf7bad777..784d5fc874d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java @@ -2,30 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Constants; 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; + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(DSAKeyValueResolver.class.getName()); + + + /** + * 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) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); } + //do nothing + } - 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; - } + 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java index 6adc050e893..a1be10b977f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java @@ -2,39 +2,43 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 EncryptedKeyResolver is not a generic resolver. It can * only be for specific instantiations, as the key being unwrapped will @@ -47,78 +51,100 @@ import org.w3c.dom.Element; * * @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 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; - _algorithm=algorithm; - } - - /** - * Constructor used for when a KEK has been set - * @param algorithm - * @param kek - */ - - public EncryptedKeyResolver(String algorithm, Key kek) { - _algorithm = algorithm; - _kek = kek; + /** + * 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 used for when a KEK has been set + * @param algorithm + * @param kek + */ + public EncryptedKeyResolver(String algorithm, Key kek) { + this.algorithm = algorithm; + this.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(); } + internalKeyResolvers.add(realKeyResolver); + } /** @inheritDoc */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) { + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) { + 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 + ) { + 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) { - SecretKey key=null; - 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; - } + 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); + } + } + } - boolean isEncryptedKey = XMLUtils.elementIsInEncryptionSpace(element, - EncryptionConstants._TAG_ENCRYPTEDKEY); - - 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java new file mode 100644 index 00000000000..0e63715e2df --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java @@ -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 + * dsig11:KeyInfoReference 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); + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java new file mode 100644 index 00000000000..708cda45049 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java @@ -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 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 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 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 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; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java index fb38e872590..b493f98182d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Constants; 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java index 4ba848a681d..e5159c084b6 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.ListIterator; 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.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.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 @@ import org.xml.sax.SAXException; * 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; - } - - 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; - } - - 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; - } - - /** - * 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); - 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; - } - - /** - * 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 - */ - 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; - } - - 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; - } - - /** - * 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); - } - } - - /** - * 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 set) { - Iterator 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; - } - - } - List parents=new ArrayList(10); - - //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 it2=parents.listIterator(parents.size()-1); - Element ele=null; - while (it2.hasPrevious()) { - ele=it2.previous(); - if (set.contains(ele)) { - return ele; - } + /** + * 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, 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; + } + } + + 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); + } + + 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; + } + } + + 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 + */ + 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 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; + } + + 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; + } + + /** + * 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; + } + + private static Element getDocumentElement(Set set) { + Iterator 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 parents = new ArrayList(); + + // 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; + } + // Visit them in reverse order. + ListIterator it2 = parents.listIterator(parents.size()-1); + Element ele = null; + while (it2.hasPrevious()) { + ele = (Element) it2.previous(); + if (set.contains(ele)) { + return ele; + } + } + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java new file mode 100644 index 00000000000..a5e239f2662 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java @@ -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; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java new file mode 100644 index 00000000000..4b23ef1e207 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java @@ -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; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java index 06a49c6708e..06511c37c29 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java @@ -2,30 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - /** * Resolves Certificates which are directly contained inside a * ds:X509Certificate 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 { + X509Certificate cert = + this.engineLookupResolveX509Certificate(element, BaseURI, storage); - /** - * Method engineResolvePublicKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - * @throws KeyResolverException - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + if (cert != null) { + return cert.getPublicKey(); + } - X509Certificate cert = this.engineLookupResolveX509Certificate(element, - BaseURI, storage); + return null; + } - if (cert != null) { - return cert.getPublicKey(); - } + /** + * 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 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; - } - - // 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; + 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; } - } - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - throw new KeyResolverException("generic.EmptyMessage", ex); - } - } + // 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) { + 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java new file mode 100644 index 00000000000..c1b44e68a86 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java @@ -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 + * dsig11:X509Digest 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 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; + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java index 8f717e71689..1d00692bd03 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java @@ -2,28 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.signature.XMLSignatureException; 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() + "?"); - - 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; - } - - 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); + /** @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) { 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()); + 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 (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + throw ex; } - for (int i=0; i storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate)storageIterator.next(); + XMLX509IssuerSerial certSerial = new XMLX509IssuerSerial(element.getOwnerDocument(), cert); - if (certSerial.equals(xmliss)) { - log.log(java.util.logging.Level.FINE, "match !!! "); + 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()); + } - return cert; - } - log.log(java.util.logging.Level.FINE, "no match..."); + 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 (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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java index ac90842059e..8dd381e59ba 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java @@ -2,28 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Constants; 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; - - 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); - - throw ex; - } - - x509childObject = new XMLX509SKI[x509childNodes.length]; - - 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); - - 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()); - - return cert; - } + /** + * 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"); } - } - } catch (XMLSecurityException ex) { - throw new KeyResolverException("empty", ex); - } + return null; + } + /** Field _x509childObject[] */ + XMLX509SKI x509childObject[] = null; - return null; - } + Element x509childNodes[] = null; + x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SKI); - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } + 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); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + + throw ex; + } + + x509childObject = new XMLX509SKI[x509childNodes.length]; + + for (int i = 0; i < x509childNodes.length; i++) { + x509childObject[i] = new XMLX509SKI(x509childNodes[i], baseURI); + } + + Iterator 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])) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Return PublicKey from " + cert.getSubjectX500Principal().getName()); + } + + return cert; + } + } + } + } catch (XMLSecurityException ex) { + throw new KeyResolverException("empty", ex); + } + + return null; + } + + /** + * Method engineResolveSecretKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * + */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java index 05e82226c4c..dc2ca4abd5a 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java @@ -2,28 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Constants; 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; } - try { - if (storage == null) { - Object exArgs[] = { Constants._TAG_X509SUBJECTNAME }; - KeyResolverException ex = - new KeyResolverException("KeyResolver.needStorageResolver", - exArgs); + x509childObject = new XMLX509SubjectName[x509childNodes.length]; - log.log(java.util.logging.Level.INFO, "", ex); - - throw ex; - } - - x509childObject = - new XMLX509SubjectName[x509childNodes.length]; - - for (int i = 0; i < x509childNodes.length; i++) { - x509childObject[i] = - new XMLX509SubjectName(x509childNodes[i], - BaseURI); - } - - 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])) { - log.log(java.util.logging.Level.FINE, "match !!! "); - - return cert; - } - log.log(java.util.logging.Level.FINE, "no match..."); + for (int i = 0; i < x509childNodes.length; i++) { + x509childObject[i] = new XMLX509SubjectName(x509childNodes[i], baseURI); } - } - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + Iterator storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate)storageIterator.next(); + XMLX509SubjectName certSN = + new XMLX509SubjectName(element.getOwnerDocument(), cert); - throw new KeyResolverException("generic.EmptyMessage", ex); - } - } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Certificate SN: " + certSN.getSubjectName()); + } - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } + 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()); + } + + if (certSN.equals(x509childObject[i])) { + 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) { + 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java index 7b11e848e8f..88392495d33 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java @@ -2,197 +2,187 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 _storageResolvers = null; + /** Field storageResolvers */ + private List storageResolvers = null; - /** Field _iterator */ - Iterator _iterator = 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(); + } + this.storageResolvers.add(resolver); + } - /** - * Method addResolver - * - * @param resolver - */ - public void add(StorageResolverSpi resolver) { - if (_storageResolvers==null) - _storageResolvers=new ArrayList(); - this._storageResolvers.add(resolver); + /** + * Constructor StorageResolver + * + * @param keyStore + */ + public StorageResolver(KeyStore keyStore) { + this.add(keyStore); + } - this._iterator = null; - } + /** + * 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 keyStore - */ - public StorageResolver(KeyStore keyStore) { - this.add(keyStore); - } + /** + * Constructor StorageResolver + * + * @param x509certificate + */ + public StorageResolver(X509Certificate x509certificate) { + this.add(x509certificate); + } - /** - * Method addKeyStore - * - * @param keyStore - */ - public void add(KeyStore keyStore) { + /** + * Method addCertificate + * + * @param x509certificate + */ + public void add(X509Certificate x509certificate) { + this.add(new SingleCertificateResolver(x509certificate)); + } - try { - this.add(new KeyStoreResolver(keyStore)); - } catch (StorageResolverException ex) { - log.log(java.util.logging.Level.SEVERE, "Could not add KeyStore because of: ", ex); - } - } + /** + * Method getIterator + * @return the iterator for the resolvers. + */ + public Iterator getIterator() { + return new StorageResolverIterator(this.storageResolvers.iterator()); + } - /** - * Constructor StorageResolver - * - * @param x509certificate - */ - public StorageResolver(X509Certificate x509certificate) { - this.add(x509certificate); - } + /** + * Class StorageResolverIterator + * This iterates over all the Certificates found in all the resolvers. + */ + static class StorageResolverIterator implements Iterator { - /** - * Method addCertificate - * - * @param x509certificate - */ - public void add(X509Certificate x509certificate) { - this.add(new SingleCertificateResolver(x509certificate)); - } + /** Field resolvers */ + Iterator resolvers = null; - /** - * Method getIterator - * @return the iterator for the resolvers. - * - */ - public Iterator getIterator() { + /** Field currentResolver */ + Iterator currentResolver = null; - if (this._iterator == null) { - if (_storageResolvers==null) - _storageResolvers=new ArrayList(); - this._iterator = new StorageResolverIterator(this._storageResolvers.iterator()); - } + /** + * Constructor StorageResolverIterator + * + * @param resolvers + */ + public StorageResolverIterator(Iterator resolvers) { + this.resolvers = resolvers; + currentResolver = findNextResolver(); + } - return this._iterator; - } + /** @inheritDoc */ + public boolean hasNext() { + if (currentResolver == null) { + return false; + } - /** - * Method hasNext - * - * @return true if there is more elements. - */ - public boolean hasNext() { + if (currentResolver.hasNext()) { + return true; + } - if (this._iterator == null) { - if (_storageResolvers==null) - _storageResolvers=new ArrayList(); - this._iterator = new StorageResolverIterator(this._storageResolvers.iterator()); - } + currentResolver = findNextResolver(); + return (currentResolver != null); + } - return this._iterator.hasNext(); - } + /** @inheritDoc */ + public Certificate next() { + if (hasNext()) { + return currentResolver.next(); + } - /** - * Method next - * - * @return the next element - */ - public X509Certificate next() { - return (X509Certificate) this._iterator.next(); - } + throw new NoSuchElementException(); + } - /** - * Class StorageResolverIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - static class StorageResolverIterator implements Iterator { + /** + * Method remove + */ + public void remove() { + throw new UnsupportedOperationException("Can't remove keys from KeyStore"); + } - /** Field _resolvers */ - Iterator _resolvers = null; + // Find the next storage with at least one element and return its Iterator + private Iterator findNextResolver() { + while (resolvers.hasNext()) { + StorageResolverSpi resolverSpi = resolvers.next(); + Iterator iter = resolverSpi.getIterator(); + if (iter.hasNext()) { + return iter; + } + } - /** - * Constructor FilesystemIterator - * - * @param resolvers - */ - public StorageResolverIterator(Iterator resolvers) { - this._resolvers = resolvers; - } - - /** @inheritDoc */ - public boolean hasNext() { - return _resolvers.hasNext(); - } - - /** @inheritDoc */ - public Object next() { - return _resolvers.next(); - } - - /** - * Method remove - */ - public void remove() { - throw new UnsupportedOperationException( - "Can't remove keys from KeyStore"); - } - } + return null; + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java index 29dff030f78..af8af531aab 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java @@ -2,86 +2,82 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java index 07211253d22..7cc075a36f9 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java @@ -2,39 +2,35 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 getIterator(); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java index 3b38e4a2572..6d7057e1e45 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.File; 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 @@ import com.sun.org.apache.xml.internal.security.utils.Base64; /** * 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 _certs = new ArrayList(); + /** Field certs */ + private List certs = new ArrayList(); - /** Field _iterator */ - Iterator _iterator = null; + /** + * @param directoryName + * @throws StorageResolverException + */ + public CertsInFilesystemDirectoryResolver(String directoryName) + throws StorageResolverException { + this.merlinsCertificatesDir = directoryName; - /** - * - * - * @param directoryName - * @throws StorageResolverException - */ - public CertsInFilesystemDirectoryResolver(String directoryName) - throws StorageResolverException { + this.readCertsFromHarddrive(); + } - this._merlinsCertificatesDir = directoryName; + /** + * Method readCertsFromHarddrive + * + * @throws StorageResolverException + */ + private void readCertsFromHarddrive() throws StorageResolverException { - this.readCertsFromHarddrive(); + File certDir = new File(this.merlinsCertificatesDir); + List al = new ArrayList(); + String[] names = certDir.list(); - this._iterator = new FilesystemIterator(this._certs); - } + for (int i = 0; i < names.length; i++) { + String currentFileName = names[i]; - /** - * Method readCertsFromHarddrive - * - * @throws StorageResolverException - */ - private void readCertsFromHarddrive() throws StorageResolverException { + if (currentFileName.endsWith(".crt")) { + al.add(names[i]); + } + } - File certDir = new File(this._merlinsCertificatesDir); - ArrayList al = new ArrayList(); - String[] names = certDir.list(); + CertificateFactory cf = null; - for (int i = 0; i < names.length; i++) { - String currentFileName = names[i]; + try { + cf = CertificateFactory.getInstance("X.509"); + } catch (CertificateException ex) { + throw new StorageResolverException("empty", ex); + } - if (currentFileName.endsWith(".crt")) { - al.add(names[i]); - } - } + if (cf == null) { + throw new StorageResolverException("empty"); + } - CertificateFactory cf = 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 { - cf = CertificateFactory.getInstance("X.509"); - } catch (CertificateException ex) { - throw new StorageResolverException("empty", ex); - } + FileInputStream fis = null; + try { + fis = new FileInputStream(file); + X509Certificate cert = + (X509Certificate) cf.generateCertificate(fis); - if (cf == null) { - throw new StorageResolverException("empty"); - } + //add to ArrayList + cert.checkValidity(); + this.certs.add(cert); - 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; + 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); + } + } + } - try { - FileInputStream fis = new FileInputStream(file); - X509Certificate cert = - (X509Certificate) cf.generateCertificate(fis); - - fis.close(); - - //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)) + if (added && log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Added certificate: " + dn); - } - } - } + } + } + } - /** @inheritDoc */ - public Iterator getIterator() { - return this._iterator; - } + /** @inheritDoc */ + public Iterator getIterator() { + return new FilesystemIterator(this.certs); + } - /** - * Class FilesystemIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - private static class FilesystemIterator implements Iterator { + /** + * Class FilesystemIterator + */ + private static class FilesystemIterator implements Iterator { - /** Field _certs */ - List _certs = null; + /** Field certs */ + List certs = null; - /** Field _i */ - int _i; + /** Field i */ + int i; - /** - * Constructor FilesystemIterator - * - * @param certs - */ - public FilesystemIterator(List certs) { - this._certs = certs; - this._i = 0; - } + /** + * Constructor FilesystemIterator + * + * @param certs + */ + public FilesystemIterator(List certs) { + this.certs = certs; + this.i = 0; + } - /** @inheritDoc */ - public boolean hasNext() { - return (this._i < this._certs.size()); - } + /** @inheritDoc */ + public boolean hasNext() { + return (this.i < this.certs.size()); + } - /** @inheritDoc */ - public X509Certificate next() { - return this._certs.get(this._i++); - } + /** @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 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 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 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() + "\""); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java index 2a5662101b8..1e325d121ee 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java @@ -2,147 +2,152 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 keyStore */ + private KeyStore keyStore = null; - /** Field _iterator */ - Iterator _iterator = 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 getIterator() { - return this._iterator; - } - - /** - * Class KeyStoreIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - static class KeyStoreIterator implements Iterator { - - /** Field _keyStore */ - KeyStore _keyStore = null; - - /** Field _aliases */ - Enumeration _aliases = null; - - /** - * Constructor KeyStoreIterator - * - * @param keyStore - * @throws StorageResolverException - */ - public KeyStoreIterator(KeyStore keyStore) - throws StorageResolverException { - - try { - this._keyStore = keyStore; - this._aliases = this._keyStore.aliases(); - } catch (KeyStoreException ex) { + /** + * 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); - } - } + } + } - /** @inheritDoc */ - public boolean hasNext() { - return this._aliases.hasMoreElements(); - } + /** @inheritDoc */ + public Iterator getIterator() { + return new KeyStoreIterator(this.keyStore); + } - /** @inheritDoc */ - @SuppressWarnings("unchecked") - public X509Certificate next() { + /** + * Class KeyStoreIterator + */ + static class KeyStoreIterator implements Iterator { - String alias = this._aliases.nextElement(); + /** Field keyStore */ + KeyStore keyStore = null; + + /** Field aliases */ + Enumeration aliases = null; + + /** Field nextCert */ + Certificate nextCert = null; + + /** + * 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() { + public boolean hasMoreElements() { + return false; + } + public String nextElement() { + return null; + } + }; + } + } + + /** @inheritDoc */ + public boolean hasNext() { + if (nextCert == null) { + nextCert = findNextCert(); + } + + return (nextCert != null); + } + + /** @inheritDoc */ + public Certificate next() { + if (nextCert == null) { + // maybe caller did not call hasNext() + nextCert = findNextCert(); + + if (nextCert == null) { + throw new NoSuchElementException(); + } + } + + Certificate ret = nextCert; + nextCert = null; + return ret; + } + + /** + * Method remove + */ + public void remove() { + throw new UnsupportedOperationException("Can't remove keys from KeyStore"); + } + + // 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; + } + } - try { - return (X509Certificate)this._keyStore.getCertificate(alias); - } catch (KeyStoreException ex) { return null; - } - } + } - /** - * 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 { - - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - - 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); - - for (Iterator i = krs.getIterator(); i.hasNext(); ) { - X509Certificate cert = i.next(); - byte[] ski = - com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI - .getSKIBytesFromCert(cert); - - System.out.println(com.sun.org.apache.xml.internal.security.utils.Base64.encode(ski)); - } - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java index 3048bb123ac..e007051fb10 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java @@ -2,102 +2,93 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 certificate */ + private X509Certificate certificate = null; - /** Field _iterator */ - Iterator _iterator = null; + /** + * @param x509cert the single {@link X509Certificate} + */ + public SingleCertificateResolver(X509Certificate x509cert) { + this.certificate = x509cert; + } - /** - * - * - * @param x509cert the single {@link X509Certificate} - */ - public SingleCertificateResolver(X509Certificate x509cert) { - this._certificate = x509cert; - this._iterator = new InternalIterator(this._certificate); - } + /** @inheritDoc */ + public Iterator getIterator() { + return new InternalIterator(this.certificate); + } - /** @inheritDoc */ - public Iterator getIterator() { - return this._iterator; - } + /** + * Class InternalIterator + */ + static class InternalIterator implements Iterator { - /** - * Class InternalIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - static class InternalIterator implements Iterator { + /** 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 Certificate next() { + if (this.alreadyReturned) { + throw new NoSuchElementException(); + } + this.alreadyReturned = true; + return this.certificate; + } - /** @inheritDoc */ - public X509Certificate next() { - - 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"); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml index aea1595741b..55c396c012e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml @@ -52,9 +52,6 @@ - - @@ -78,6 +75,12 @@ JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA512" /> + + + @@ -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"/> + SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt" + JCEName="SHA1withECDSA"/> + + + + + + @@ -260,7 +284,31 @@ KeyLength="256" RequiredKey="AES" JCEName="AES/CBC/ISO10126Padding"/> + + + + + + + JCEName="RSA/ECB/OAEPPadding"/> + + - - - - + @@ -330,32 +378,8 @@ + DESCRIPTION="A simple resolver for requests of XPointer fragments" /> - - - - - - - - - - diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties deleted file mode 100644 index e67ae2c79ef..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties +++ /dev/null @@ -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 - diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties index c285aa0f87d..746361d2923 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties @@ -5,6 +5,7 @@ algorithm.extendsWrongClass = Kann URI {0} nicht f 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 @@ prefix.AlreadyAssigned = Sie binden den Prefix {0} an den Namespace {1} aber er 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.InvalidDigestOrReference = Ung 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 diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties index f15104e94b5..a01124ee85f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties @@ -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 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 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} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java index 57da56c5cb2..7801315c02d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java @@ -2,85 +2,85 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 DigestValue. 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 DigestValue. + * 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); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java index 397c1293492..a216ebb4d17 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 DigestValue fails because of invalid signature. * @@ -30,58 +30,56 @@ package com.sun.org.apache.xml.internal.security.signature; */ 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); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java index 351dee5edaf..01d76effdff 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java @@ -2,33 +2,33 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Set; import java.util.Map; +import java.util.Set; import javax.xml.parsers.ParserConfigurationException; @@ -38,7 +38,6 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; 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.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; - - /** * Handles <ds:Manifest> elements. *

    This element holds the Reference elements

    - * @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 _references; - Element[] _referencesEl; + /** Field references */ + private List references; + private Element[] referencesEl; - /** Field verificationResults[] */ - private boolean verificationResults[] = null; + /** Field verificationResults[] */ + private boolean verificationResults[] = null; - /** Field _resolverProperties */ - Map _resolverProperties = null; + /** Field resolverProperties */ + private Map resolverProperties = null; - /** Field _perManifestResolvers */ - List _perManifestResolvers = null; + /** Field perManifestResolvers */ + private List perManifestResolvers = null; - /** - * Consturts {@link Manifest} - * - * @param doc the {@link Document} in which XMLsignature is placed - */ - public Manifest(Document doc) { + private boolean secureValidation; - super(doc); + /** + * Constructs {@link Manifest} + * + * @param doc the {@link Document} in which XMLsignature is placed + */ + public Manifest(Document doc) { + super(doc); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); - this._references = new ArrayList(); - } + this.references = new ArrayList(); + } - /** - * Constructor Manifest - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public Manifest(Element element, String BaseURI) - throws XMLSecurityException { + /** + * Constructor Manifest + * + * @param element + * @param baseURI + * @throws XMLSecurityException + */ + public Manifest(Element element, String baseURI) throws XMLSecurityException { + this(element, baseURI, false); - super(element, BaseURI); + } + /** + * Constructor Manifest + * + * @param element + * @param baseURI + * @param secureValidation + * @throws XMLSecurityException + */ + public Manifest( + Element element, String baseURI, boolean secureValidation + ) throws XMLSecurityException { + super(element, baseURI); - Attr attr = element.getAttributeNodeNS(null, "Id"); - if (attr != null) { - element.setIdAttributeNode(attr, true); - } - - // 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(le); + if (secureValidation && le > MAXIMUM_REFERENCE_COUNT) { + Object exArgs[] = { le, MAXIMUM_REFERENCE_COUNT }; - 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); - } - } + throw new XMLSecurityException("signature.tooManyReferences", exArgs); + } - /** - * This addDocument 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 URI attribute in Reference 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 { + // create List + this.references = new ArrayList(le); - // the this._doc is handed implicitly by the this.getOwnerDocument() - Reference ref = new Reference(this._doc, BaseURI, referenceURI, this, - transforms, digestURI); + 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); + } + } - if (ReferenceId != null) { - ref.setId(ReferenceId); - } + /** + * This addDocument 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 URI attribute in Reference 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); - if (ReferenceType != null) { - ref.setType(ReferenceType); - } + if (referenceId != null) { + ref.setId(referenceId); + } - // 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); - /** - * 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++) { + // 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 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 ith reference. Valid i - * values are 0 to {link@ getSize}-1. - * - * @param i Index of the requested {@link Reference} - * @return the ith reference - * @throws XMLSecurityException - */ - public Reference item(int i) throws XMLSecurityException { - - if (this._references.get(i) == null) { + /** + * Return the nonnegative number of added references. + * + * @return the number of references + */ + public int getLength() { + return this.references.size(); + } + /** + * Return the ith reference. Valid i + * values are 0 to {link@ getSize}-1. + * + * @param i Index of the requested {@link Reference} + * @return the ith 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); + Reference ref = + new Reference(referencesEl[i], this.baseURI, this, secureValidation); - this._references.set(i, ref); - } + this.references.set(i, ref); + } - return this._references.get(i); + return this.references.get(i); + } - } + /** + * Sets the Id attribute + * + * @param Id the Id attribute in ds:Manifest + */ + public void setId(String Id) { + if (Id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } + } - /** - * Sets the Id attribute - * - * @param Id the Id attribute in ds:Manifest - */ - public void setId(String Id) { + /** + * Returns the Id attribute + * + * @return the Id attribute in ds:Manifest + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } - if (Id != null) { - setLocalIdAttribute(Constants._ATT_ID, Id); - } - } + /** + * Used to do a reference + * validation of all enclosed references using the {@link Reference#verify} method. + * + *

    This step loops through all {@link Reference}s and does verify the hash + * values. If one or more verifications fail, the method returns + * false. If all verifications are successful, + * it returns true. 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); + } - /** - * Returns the Id attribute - * - * @return the Id attribute in ds:Manifest - */ - public String getId() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ID); - } + /** + * Used to do a reference + * validation of all enclosed references using the {@link Reference#verify} method. + * + *

    This step loops through all {@link Reference}s and does verify the hash + * values. If one or more verifications fail, the method returns + * false. If all verifications are successful, + * it returns true. 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 }; - /** - * Used to do a reference - * validation of all enclosed references using the {@link Reference#verify} method. - * - *

    This step loops through all {@link Reference}s and does verify the hash - * values. If one or more verifications fail, the method returns - * false. If all verifications are successful, - * it returns true. 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); - } + throw new XMLSecurityException("signature.tooManyReferences", exArgs); + } - /** - * Used to do a reference - * validation of all enclosed references using the {@link Reference#verify} method. - * - *

    This step loops through all {@link Reference}s and does verify the hash - * values. If one or more verifications fail, the method returns - * false. If all verifications are successful, - * it returns true. 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; + 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 (_referencesEl.length==0) { - throw new XMLSecurityException("empty"); - } + this.references.set(i, currentRef); - this.verificationResults = - new boolean[_referencesEl.length]; + // if only one item does not verify, the whole verification fails + try { + boolean currentRefVerified = currentRef.verify(); - for (int i = - 0; i < this._referencesEl.length; i++) { - Reference currentRef = - new Reference(_referencesEl[i], this._baseURI, this); + this.setVerificationResult(i, currentRefVerified); - this._references.set(i, currentRef); + 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 only one item does not verify, the whole verification fails */ - try { - boolean currentRefVerified = currentRef.verify(); + // 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"); + } - this.setVerificationResult(i, currentRefVerified); + try { + XMLSignatureInput signedManifestNodes = + currentRef.dereferenceURIandPerformTransforms(null); + Set nl = signedManifestNodes.getNodeSet(); + Manifest referencedManifest = null; + Iterator nlIterator = nl.iterator(); - 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()); + findManifest: while (nlIterator.hasNext()) { + Node n = nlIterator.next(); - // 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"); - - try { - XMLSignatureInput signedManifestNodes = - currentRef.dereferenceURIandPerformTransforms(null); - Set nl = signedManifestNodes.getNodeSet(); - Manifest referencedManifest = null; - Iterator nlIterator = nl.iterator(); - - 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) { - - // Hm, seems not to be a ds:Manifest + 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 + } + } } - } - } - if (referencedManifest == null) { + 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); + } - // 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 { + 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() }; - 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); - } + 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()]; + } - /** - * Method setVerificationResult - * - * @param index - * @param verify - */ - private void setVerificationResult(int index, boolean verify) - { + this.verificationResults[index] = verify; + } - if (this.verificationResults == null) { - this.verificationResults = new boolean[this.getLength()]; - } + /** + * 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) + ); - this.verificationResults[index] = verify; - } + throw new XMLSecurityException("generic.EmptyMessage", e); + } - /** - * 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 (this.verificationResults == null) { + try { + this.verifyReferences(); + } catch (Exception ex) { + throw new XMLSecurityException("generic.EmptyMessage", ex); + } + } - 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)); + return this.verificationResults[index]; + } - throw new XMLSecurityException("generic.EmptyMessage", e); - } + /** + * Adds Resource Resolver for retrieving resources at specified URI attribute + * in reference 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(); + } + this.perManifestResolvers.add(resolver); + } - if (this.verificationResults == null) { - try { - this.verifyReferences(); - } catch (Exception ex) { - throw new XMLSecurityException("generic.EmptyMessage", ex); - } - } + /** + * Adds Resource Resolver for retrieving resources at specified URI attribute + * in reference 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(); + } + perManifestResolvers.add(new ResourceResolver(resolverSpi)); + } - return this.verificationResults[index]; - } + /** + * Get the Per-Manifest Resolver List + * @return the per-manifest Resolver List + */ + public List getPerManifestResolvers() { + return perManifestResolvers; + } - /** - * Adds Resource Resolver for retrieving resources at specified URI attribute in reference element - * - * @param resolver {@link ResourceResolver} can provide the implemenatin subclass of {@link ResourceResolverSpi} for retrieving resource. - */ - public void addResourceResolver(ResourceResolver resolver) { + /** + * Get the resolver property map + * @return the resolver property map + */ + public Map getResolverProperties() { + return resolverProperties; + } - if (resolver == null) { - return; - } - if (_perManifestResolvers==null) - _perManifestResolvers = new ArrayList(); - this._perManifestResolvers.add(resolver); + /** + * 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(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); + } - /** - * Adds Resource Resolver for retrieving resources at specified URI attribute in reference element - * - * @param resolverSpi the implemenatin subclass of {@link ResourceResolverSpi} for retrieving resource. - */ - public void addResourceResolver(ResourceResolverSpi resolverSpi) { + /** + * 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); + } + } - if (resolverSpi == null) { - return; - } - if (_perManifestResolvers==null) - _perManifestResolvers = new ArrayList(); - this._perManifestResolvers.add(new ResourceResolver(resolverSpi)); + /** + * 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(); + } - /** - * 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(10); - } - this._resolverProperties.put(key, value); - } + /** + * Method getSignedContentLength + * + * @return The number of references contained in this reference. + */ + public int getSignedContentLength() { + return this.getLength(); + } - /** - * 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 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 getSignedContentLength - * - * @return The nu,ber 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java index 99f76041ee4..7da105d37be 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java @@ -2,28 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ package com.sun.org.apache.xml.internal.security.signature; */ public class MissingResourceFailureException extends XMLSignatureException { - /** - * - */ - private static final long serialVersionUID = 1L; - /** Field uninitializedReference */ - Reference uninitializedReference = null; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * MissingKeyResourceFailureException constructor. - * @param _msgID - * @param reference - * @see #getReference - */ - public MissingResourceFailureException(String _msgID, Reference reference) { + /** Field uninitializedReference */ + private Reference uninitializedReference = null; - 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 + ) { + super(msgID, originalException); - /** - * Constructor MissingResourceFailureException - * - * @param _msgID - * @param _originalException - * @param reference - * @see #getReference - */ - public MissingResourceFailureException(String _msgID, - Exception _originalException, - Reference reference) { + this.uninitializedReference = reference; + } - super(_msgID, _originalException); + /** + * 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); - 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) { + /** + * 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; + } - super(_msgID, exArgs, _originalException); - - 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java index 2ccf7a06905..6b670c1b274 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import org.w3c.dom.Node; /** * 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); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java index 8bbc4db2a62..bf2473295dc 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java @@ -2,27 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import org.w3c.dom.Node; */ public class ObjectContainer extends SignatureElementProxy { - /** - * Constructs {@link ObjectContainer} - * - * @param doc the {@link Document} in which Object element is placed - */ - public ObjectContainer(Document doc) { + /** + * Constructs {@link ObjectContainer} + * + * @param doc the {@link Document} in which Object element is placed + */ + public ObjectContainer(Document doc) { + super(doc); + } - super(doc); - } + /** + * Constructs {@link ObjectContainer} from {@link Element} + * + * @param element is Object 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 Object element - * @param BaseURI the URI of the resource where the XML instance was stored - * @throws XMLSecurityException - */ - public ObjectContainer(Element element, String BaseURI) - throws XMLSecurityException { + /** + * Sets the Id attribute + * + * @param Id Id 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); + } + } - super(element, BaseURI); - } + /** + * Returns the Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } - /** - * Sets the Id attribute - * - * @param Id Id attribute - */ - public void setId(String Id) { + /** + * Sets the MimeType attribute + * + * @param MimeType the MimeType attribute + */ + public void setMimeType(String MimeType) { + if (MimeType != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_MIMETYPE, MimeType); + } + } - if (Id != null) { - setLocalIdAttribute(Constants._ATT_ID, Id); - } - } + /** + * Returns the MimeType attribute + * + * @return the MimeType attribute + */ + public String getMimeType() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_MIMETYPE); + } - /** - * Returns the Id attribute - * - * @return the Id attribute - */ - public String getId() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ID); - } + /** + * Sets the Encoding attribute + * + * @param Encoding the Encoding attribute + */ + public void setEncoding(String Encoding) { + if (Encoding != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ENCODING, Encoding); + } + } - /** - * Sets the MimeType attribute - * - * @param MimeType the MimeType attribute - */ - public void setMimeType(String MimeType) { + /** + * Returns the Encoding attribute + * + * @return the Encoding attribute + */ + public String getEncoding() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ENCODING); + } - if ( (MimeType != null)) { - this._constructionElement.setAttributeNS(null, Constants._ATT_MIMETYPE, - MimeType); - } - } + /** + * Adds child Node + * + * @param node child Node + * @return the new node in the tree. + */ + public Node appendChild(Node node) { + return this.constructionElement.appendChild(node); + } - /** - * Returns the MimeType attribute - * - * @return the MimeType attribute - */ - public String getMimeType() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_MIMETYPE); - } - - /** - * Sets the Encoding attribute - * - * @param Encoding the Encoding attribute - */ - public void setEncoding(String Encoding) { - - if ((Encoding != null)) { - this._constructionElement.setAttributeNS(null, Constants._ATT_ENCODING, - Encoding); - } - } - - /** - * Returns the Encoding attribute - * - * @return the Encoding attribute - */ - public String getEncoding() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ENCODING); - } - - /** - * Adds child Node - * - * @param node child Node - * @return the new node in the tree. - */ - public Node appendChild(Node node) { - - Node result = null; - - result = this._constructionElement.appendChild(node); - - return result; - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_OBJECT; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_OBJECT; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java index 57bb7fa0f77..ece475c983d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java @@ -2,31 +2,32 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.CanonicalizationException; 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.transforms.params.InclusiveNames 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.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; - /** * Handles <ds:Reference> elements. * @@ -64,17 +67,17 @@ import org.w3c.dom.Text; * *

    Create a new reference

    *
    - * 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);
      * 
    * *

    Verify a reference

    *
    - * 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 @@ import org.w3c.dom.Text;
      */
     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() {
    -         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;
     
    -/*
    -   static {
    -      try {
    -         useC14N11 = Boolean.getBoolean("com.sun.org.apache.xml.internal.security.useC14N11");
    -      } catch (Exception e) {
    -         // ignore exceptions
    -      }
    -   }
    -*/
    +    /** Field MANIFEST_URI */
    +    public static final String MANIFEST_URI = Constants.SignatureSpecNS + Constants._TAG_MANIFEST;
     
    -   /** Field CacheSignedNodes */
    -   public final static boolean CacheSignedNodes = false;
    +    /**
    +     * The maximum number of transforms per reference, if secure validation is enabled.
    +     */
    +    public static final int MAXIMUM_TRANSFORM_COUNT = 5;
     
    -   /** {@link java.util.logging} logging facility */
    -    static java.util.logging.Logger log =
    +    private boolean secureValidation;
    +
    +    /**
    +     * 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() {
    +            public Boolean run() {
    +                return Boolean.valueOf(Boolean.getBoolean("com.sun.org.apache.xml.internal.security.useC14N11"));
    +            }
    +        })).booleanValue();
    +
    +    /** {@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;
    -
    -   /** Field MANIFEST_URI */
    -   public static final String MANIFEST_URI = Constants.SignatureSpecNS
    -                                             + Constants._TAG_MANIFEST;
    -   //J-
    -   Manifest _manifest = null;
    -   XMLSignatureInput _transformsOutput;
    -   //J+
    -
    -private Transforms transforms;
    -
    -private Element digestMethodElem;
    -
    -private Element digestValueElement;
    -
    -   /**
    -    * Constructor Reference
    -    *
    -    * @param doc the {@link Document} in which XMLsignature 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);
    -
    -      this._baseURI = BaseURI;
    -      this._manifest = manifest;
    -
    -      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"));
    -
    -      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);
    -
    -         this._constructionElement.appendChild(digestValueElement);
    -         XMLUtils.addReturnToElement(this._constructionElement);
    -      }
    -   }
    -
    -
    -   /**
    -    * Build a {@link Reference} from an {@link Element}
    -    *
    -    * @param element Reference 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;
    -      }
    -
    -      String uri = digestMethodElem.getAttributeNS(null,
    -         Constants._ATT_ALGORITHM);
    -
    -          if (uri == null) {
    -                  return null;
    -          }
    -
    -      return MessageDigestAlgorithm.getInstance(this._doc, uri);
    -   }
    -
    -   /**
    -    * Sets the URI of this Reference element
    -    *
    -    * @param URI the URI of this Reference element
    -    */
    -   public void setURI(String URI) {
    -
    -      if ( URI != null) {
    -         this._constructionElement.setAttributeNS(null, Constants._ATT_URI,
    -                                                  URI);
    -      }
    -   }
    -
    -   /**
    -    * Returns the URI of this Reference element
    -    *
    -    * @return URI the URI of this Reference element
    -    */
    -   public String getURI() {
    -      return this._constructionElement.getAttributeNS(null, Constants._ATT_URI);
    -   }
    -
    -   /**
    -    * Sets the Id attribute of this Reference element
    -    *
    -    * @param Id the Id attribute of this Reference element
    -    */
    -   public void setId(String Id) {
    -
    -      if ( Id != null ) {
    -          setLocalIdAttribute(Constants._ATT_ID, Id);
    -      }
    -   }
    -
    -   /**
    -    * Returns the Id attribute of this Reference element
    -    *
    -    * @return Id the Id attribute of this Reference element
    -    */
    -   public String getId() {
    -      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
    -   }
    -
    -   /**
    -    * Sets the type atttibute of the Reference indicate whether an ds:Object, ds:SignatureProperty, or ds:Manifest element
    -    *
    -    * @param Type the type attribute of the Reference
    -    */
    -   public void setType(String Type) {
    -
    -      if (Type != null) {
    -         this._constructionElement.setAttributeNS(null, Constants._ATT_TYPE,
    -                                                  Type);
    -      }
    -   }
    -
    -   /**
    -    * Return the type atttibute of the Reference indicate whether an ds:Object, ds:SignatureProperty, or ds:Manifest element
    -    *
    -    * @return the type attribute of the Reference
    -    */
    -   public String getType() {
    -      return this._constructionElement.getAttributeNS(null,
    -              Constants._ATT_TYPE);
    -   }
    -
    -   /**
    -    * Method isReferenceToObject
    -    *
    -    * This returns true if the Type attribute of the
    -    * Refernce element points to a #Object element
    -    *
    -    * @return true if the Reference type indicates that this Reference points to an Object
    -    */
    -   public boolean typeIsReferenceToObject() {
    -
    -      if (Reference.OBJECT_URI.equals(this.getType())) {
    -         return true;
    -      }
    -
    -      return false;
    -   }
    -
    -   /**
    -    * Method isReferenceToManifest
    -    *
    -    * This returns true if the Type attribute of the
    -    * Refernce element points to a #Manifest 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 false;
    -   }
    -
    -   /**
    -    * 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);
    -
    -         digestValueElement.appendChild(t);
    -   }
    -
    -   /**
    -    * 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 {
    -
    -      try {
    -         Attr URIAttr = this._constructionElement.getAttributeNodeNS(null,
    -            Constants._ATT_URI);
    -         String URI;
    -
    -         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 };
    -
    -            throw new ReferenceNotInitializedException(
    -               "signature.Verification.Reference.NoInput", exArgs);
    -         }
    -
    -         resolver.addProperties(this._manifest._resolverProperties);
    -
    -         XMLSignatureInput input = resolver.resolve(URIAttr, this._baseURI);
    -
    -
    -         return input;
    -      }  catch (ResourceResolverException ex) {
    -         throw new ReferenceNotInitializedException("empty", ex);
    -      } catch (XMLSecurityException ex) {
    -         throw new ReferenceNotInitializedException("empty", ex);
    -      }
    -   }
    -
    -   /**
    -    * 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;
    -
    -   }
    -
    -   private XMLSignatureInput getContentsAfterTransformation(XMLSignatureInput input, OutputStream os)
    -           throws XMLSignatureException {
    -
    -      try {
    -         Transforms transforms = this.getTransforms();
    -         XMLSignatureInput output = null;
    -
    -         if (transforms != null) {
    -            output = transforms.performTransforms(input,os);
    -            this._transformsOutput = output;//new XMLSignatureInput(output.getBytes());
    -
    -            //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();
    -
    -      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();
    -         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);
    +    private Manifest manifest;
    +    private XMLSignatureInput transformsOutput;
    +
    +    private Transforms transforms;
    +
    +    private Element digestMethodElem;
    +
    +    private Element digestValueElement;
    +
    +    private ReferenceData referenceData;
    +
    +    /**
    +     * Constructor Reference
    +     *
    +     * @param doc the {@link Document} in which XMLsignature 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);
    +
    +        this.baseURI = baseURI;
    +        this.manifest = manifest;
    +
    +        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"));
    +
    +        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);
    +
    +        this.constructionElement.appendChild(digestValueElement);
    +        XMLUtils.addReturnToElement(this.constructionElement);
    +    }
    +
    +
    +    /**
    +     * Build a {@link Reference} from an {@link Element}
    +     *
    +     * @param element Reference 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);
    +    }
    +
    +    /**
    +     * Build a {@link Reference} from an {@link Element}
    +     *
    +     * @param element Reference 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 };
    +
    +                throw new XMLSecurityException("signature.tooManyTransforms", exArgs);
    +            }
    +            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;
    +        }
    +
    +        String uri = digestMethodElem.getAttributeNS(null, Constants._ATT_ALGORITHM);
    +
    +        if (uri == null) {
    +            return null;
    +        }
    +
    +        if (secureValidation && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(uri)) {
    +            Object exArgs[] = { uri };
    +
    +            throw new XMLSignatureException("signature.signatureAlgorithm", exArgs);
    +        }
    +
    +        return MessageDigestAlgorithm.getInstance(this.doc, uri);
    +    }
    +
    +    /**
    +     * Sets the URI of this Reference element
    +     *
    +     * @param uri the URI of this Reference element
    +     */
    +    public void setURI(String uri) {
    +        if (uri != null) {
    +            this.constructionElement.setAttributeNS(null, Constants._ATT_URI, uri);
    +        }
    +    }
    +
    +    /**
    +     * Returns the URI of this Reference element
    +     *
    +     * @return URI the URI of this Reference element
    +     */
    +    public String getURI() {
    +        return this.constructionElement.getAttributeNS(null, Constants._ATT_URI);
    +    }
    +
    +    /**
    +     * Sets the Id attribute of this Reference element
    +     *
    +     * @param id the Id attribute of this Reference 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);
    +        }
    +    }
    +
    +    /**
    +     * Returns the Id attribute of this Reference element
    +     *
    +     * @return Id the Id attribute of this Reference element
    +     */
    +    public String getId() {
    +        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
    +    }
    +
    +    /**
    +     * Sets the type atttibute of the Reference indicate whether an
    +     * ds:Object, ds:SignatureProperty, or ds:Manifest
    +     * element.
    +     *
    +     * @param type the type attribute of the Reference
    +     */
    +    public void setType(String type) {
    +        if (type != null) {
    +            this.constructionElement.setAttributeNS(null, Constants._ATT_TYPE, type);
    +        }
    +    }
    +
    +    /**
    +     * Return the type atttibute of the Reference indicate whether an
    +     * ds:Object, ds:SignatureProperty, or ds:Manifest
    +     * element
    +     *
    +     * @return the type attribute of the Reference
    +     */
    +    public String getType() {
    +        return this.constructionElement.getAttributeNS(null, Constants._ATT_TYPE);
    +    }
    +
    +    /**
    +     * Method isReferenceToObject
    +     *
    +     * This returns true if the Type attribute of the
    +     * Reference element points to a #Object element
    +     *
    +     * @return true if the Reference type indicates that this Reference points to an
    +     * Object
    +     */
    +    public boolean typeIsReferenceToObject() {
    +        if (Reference.OBJECT_URI.equals(this.getType())) {
    +            return true;
    +        }
    +
    +        return false;
    +    }
    +
    +    /**
    +     * Method isReferenceToManifest
    +     *
    +     * This returns true if the Type attribute of the
    +     * Reference element points to a #Manifest 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 false;
    +    }
    +
    +    /**
    +     * 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);
    +
    +        digestValueElement.appendChild(t);
    +    }
    +
    +    /**
    +     * 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 {
    +        try {
    +            Attr uriAttr =
    +                this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI);
    +
    +            ResourceResolver resolver =
    +                ResourceResolver.getInstance(
    +                    uriAttr, this.baseURI, this.manifest.getPerManifestResolvers(), secureValidation
    +                );
    +            resolver.addProperties(this.manifest.getResolverProperties());
    +
    +            return resolver.resolve(uriAttr, this.baseURI, secureValidation);
    +        }  catch (ResourceResolverException ex) {
    +            throw new ReferenceNotInitializedException("empty", ex);
    +        }
    +    }
    +
    +    private XMLSignatureInput getContentsAfterTransformation(
    +        XMLSignatureInput input, OutputStream os
    +    ) throws XMLSignatureException {
    +        try {
    +            Transforms transforms = this.getTransforms();
    +            XMLSignatureInput output = null;
    +
    +            if (transforms != null) {
    +                output = transforms.performTransforms(input, os);
    +                this.transformsOutput = output;//new XMLSignatureInput(output.getBytes());
    +
    +                //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 inclusiveNamespaces = new HashSet();
    -
    -         {
                 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;
    +                        break doTransforms;
    +                    }
    +                }
                 }
     
    -            if (c14nTransform != null) {
    +            Set inclusiveNamespaces = new HashSet();
    +            if (c14nTransform != null
    +                && (c14nTransform.length(
    +                    InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
    +                    InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1)) {
     
    -               if (c14nTransform
    -                       .length(InclusiveNamespaces
    -                          .ExclusiveCanonicalizationNamespace, InclusiveNamespaces
    -                          ._TAG_EC_INCLUSIVENAMESPACES) == 1) {
    -
    -                  // there is one InclusiveNamespaces element
    -                  InclusiveNamespaces in = new InclusiveNamespaces(
    +                // there is one InclusiveNamespaces element
    +                InclusiveNamespaces in =
    +                    new InclusiveNamespaces(
                             XMLUtils.selectNode(
    -                        c14nTransform.getElement().getFirstChild(),
    -                                                InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
    -                        InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0), this.getBaseURI());
    +                            c14nTransform.getElement().getFirstChild(),
    +                            InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
    +                            InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,
    +                            0
    +                        ), this.getBaseURI());
     
    -                  inclusiveNamespaces = InclusiveNamespaces.prefixStr2Set(
    -                     in.getInclusiveNamespaces());
    -               }
    +                inclusiveNamespaces =
    +                    InclusiveNamespaces.prefixStr2Set(in.getInclusiveNamespaces());
                 }
    -         }
     
    -         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);
    -      }
    -   }
    +            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 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;
    -   }
    +    /**
    +     * 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;
    +    }
     
    -   /**
    -    * This method returns the {@link XMLSignatureInput} which is referenced by the
    -    * URI 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 {
    +    /**
    +     * Get the ReferenceData that corresponds to the cached representation of the dereferenced
    +     * object before transformation.
    +     */
    +    public ReferenceData getReferenceData() {
    +        return referenceData;
    +    }
     
    -      try {
    -         XMLSignatureInput input = this.getContentsBeforeTransformation();
    -         XMLSignatureInput output = this.getContentsAfterTransformation(input, os);
    +    /**
    +     * This method returns the {@link XMLSignatureInput} which is referenced by the
    +     * URI 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);
     
    -         /* 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) {
    +            XMLSignatureInput output = this.getContentsAfterTransformation(input, os);
    +            this.transformsOutput = output;
    +            return output;
    +        } catch (XMLSecurityException ex) {
    +            throw new ReferenceNotInitializedException("empty", ex);
    +        }
    +    }
     
    -            this._transformsOutput = output;//new XMLSignatureInput(output.getBytes());
    +    /**
    +     * Store the dereferenced Element(s) so that it/they can be retrieved later.
    +     */
    +    private void cacheDereferencedElement(XMLSignatureInput input) {
    +        if (input.isNodeSet()) {
    +            try {
    +                final Set s = input.getNodeSet();
    +                referenceData = new ReferenceNodeSetData() {
    +                    public Iterator iterator() {
    +                        return new Iterator() {
     
    -            //this._transformsOutput.setSourceURI(output.getSourceURI());
    -         }
    -         return output;
    -      } catch (XMLSecurityException ex) {
    -         throw new ReferenceNotInitializedException("empty", ex);
    -      }
    -   }
    +                            Iterator sIterator = s.iterator();
     
    -   /**
    -    * 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 {
    +                            public boolean hasNext() {
    +                                return sIterator.hasNext();
    +                            }
     
    -      return transforms;
    -   }
    +                            public Node next() {
    +                                return sIterator.next();
    +                            }
     
    -   /**
    -    * 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);
    +                            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);
    +            }
    +        }
    +    }
     
    -        byte[] signedBytes = output.getBytes();
    +    /**
    +     * 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;
    +    }
     
    -        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 {
    +            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();
     
    -         MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
    +            if (output.getOctetStreamReal() != null) {
    +                output.getOctetStreamReal().close();
    +            }
     
    -         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);
    +            //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 {
    +    /**
    +     * 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);
     
    -      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 {
    +            if (log.isLoggable(java.util.logging.Level.FINE)) {
    +                log.log(java.util.logging.Level.FINE, "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 {
    -         log.log(java.util.logging.Level.INFO, "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;
    +    }
     }
    diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java
    index 98dd0a2ee52..95da73e68b8 100644
    --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java
    +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java
    @@ -2,28 +2,26 @@
      * reserved comment block
      * DO NOT REMOVE OR ALTER!
      */
    -/*
    - * Copyright  1999-2004 The Apache Software Foundation.
    +/**
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements. See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership. The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License. You may obtain a copy of the License at
      *
    - *  Licensed under the Apache License, Version 2.0 (the "License");
    - *  you may not use this 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.
    + * http://www.apache.org/licenses/LICENSE-2.0
      *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express 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 @@ package com.sun.org.apache.xml.internal.security.signature;
      */
     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);
    +    }
     }
    diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java
    index e81875aa0ce..2dcbb3c28d0 100644
    --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java
    +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java
    @@ -2,34 +2,34 @@
      * reserved comment block
      * DO NOT REMOVE OR ALTER!
      */
    -/*
    - * Copyright  1999-2004 The Apache Software Foundation.
    +/**
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements. See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership. The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License. You may obtain a copy of the License at
      *
    - *  Licensed under the Apache License, Version 2.0 (the "License");
    - *  you may not use this 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.
    + * http://www.apache.org/licenses/LICENSE-2.0
      *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express 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 <ds:SignatureProperties> elements
      * This Element holds {@link SignatureProperty} that contian additional information items
    @@ -37,120 +37,112 @@ import org.w3c.dom.Element;
      * 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) {
    +    /**
    +     * Constructor SignatureProperties
    +     *
    +     * @param doc
    +     */
    +    public SignatureProperties(Document doc) {
    +        super(doc);
     
    -      super(doc);
    +        XMLUtils.addReturnToElement(this.constructionElement);
    +    }
     
    -      XMLUtils.addReturnToElement(this._constructionElement);
    -   }
    +    /**
    +     * Constructs {@link SignatureProperties} from {@link Element}
    +     * @param element SignatureProperties 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);
     
    -   /**
    -    * Constructs {@link SignatureProperties} from {@link Element}
    -    * @param element SignatureProperties 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);
    +        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(this.constructionElement, 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(getElement(), 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() {
    +        Element[] propertyElems =
    +            XMLUtils.selectDsNodes(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY);
     
    -   /**
    -    * Return the nonnegative number of added SignatureProperty elements.
    -    *
    -    * @return the number of SignatureProperty elements
    -    */
    -   public int getLength() {
    +        return propertyElems.length;
    +    }
     
    -         Element[] propertyElems =
    -            XMLUtils.selectDsNodes(this._constructionElement,
    -                                     Constants._TAG_SIGNATUREPROPERTY
    -                                    );
    +    /**
    +     * Return the ith SignatureProperty. Valid i
    +     * values are 0 to {link@ getSize}-1.
    +     *
    +     * @param i Index of the requested {@link SignatureProperty}
    +     * @return the ith SignatureProperty
    +     * @throws XMLSignatureException
    +     */
    +    public SignatureProperty item(int i) throws XMLSignatureException {
    +        try {
    +            Element propertyElem =
    +                XMLUtils.selectDsNode(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY, i);
     
    -         return propertyElems.length;
    -   }
    +            if (propertyElem == null) {
    +                return null;
    +            }
    +            return new SignatureProperty(propertyElem, this.baseURI);
    +        } catch (XMLSecurityException ex) {
    +            throw new XMLSignatureException("empty", ex);
    +        }
    +    }
     
    -   /**
    -    * Return the ith SignatureProperty.  Valid i
    -    * values are 0 to {link@ getSize}-1.
    -    *
    -    * @param i Index of the requested {@link SignatureProperty}
    -    * @return the ith SignatureProperty
    -    * @throws XMLSignatureException
    -    */
    -   public SignatureProperty item(int i) throws XMLSignatureException {
    -          try {
    -         Element propertyElem =
    -            XMLUtils.selectDsNode(this._constructionElement,
    -                                 Constants._TAG_SIGNATUREPROPERTY,
    -                                 i );
    +    /**
    +     * Sets the Id attribute
    +     *
    +     * @param Id the Id 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);
    +        }
    +    }
     
    -         if (propertyElem == null) {
    -            return null;
    -         }
    -         return new SignatureProperty(propertyElem, this._baseURI);
    -      } catch (XMLSecurityException ex) {
    -         throw new XMLSignatureException("empty", ex);
    -      }
    -   }
    +    /**
    +     * Returns the Id attribute
    +     *
    +     * @return the Id attribute
    +     */
    +    public String getId() {
    +        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
    +    }
     
    -   /**
    -    * Sets the Id attribute
    -    *
    -    * @param Id the Id attribute
    -    */
    -   public void setId(String Id) {
    +    /**
    +     * Method addSignatureProperty
    +     *
    +     * @param sp
    +     */
    +    public void addSignatureProperty(SignatureProperty sp) {
    +        this.constructionElement.appendChild(sp.getElement());
    +        XMLUtils.addReturnToElement(this.constructionElement);
    +    }
     
    -      if (Id != null) {
    -          setLocalIdAttribute(Constants._ATT_ID, Id);
    -      }
    -   }
    -
    -   /**
    -    * Returns the Id attribute
    -    *
    -    * @return the Id 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);
    -   }
    -
    -   /** @inheritDoc */
    -   public String getBaseLocalName() {
    -      return Constants._TAG_SIGNATUREPROPERTIES;
    -   }
    +    /** @inheritDoc */
    +    public String getBaseLocalName() {
    +        return Constants._TAG_SIGNATUREPROPERTIES;
    +    }
     }
    diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java
    index 969ee922e1b..3229a0487cc 100644
    --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java
    +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java
    @@ -2,27 +2,28 @@
      * reserved comment block
      * DO NOT REMOVE OR ALTER!
      */
    -/*
    - * Copyright  1999-2004 The Apache Software Foundation.
    +/**
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements. See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership. The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License. You may obtain a copy of the License at
      *
    - *  Licensed under the Apache License, Version 2.0 (the "License");
    - *  you may not use this 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.
    + * http://www.apache.org/licenses/LICENSE-2.0
      *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express 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 @@ import org.w3c.dom.Node;
      */
     public class SignatureProperty extends SignatureElementProxy {
     
    -   /**
    -    * Constructs{@link SignatureProperty} using specified Target attribute
    -    *
    -    * @param doc the {@link Document} in which XMLsignature is placed
    -    * @param Target the Target attribute references the Signature element to which the property applies SignatureProperty
    -    */
    -   public SignatureProperty(Document doc, String Target) {
    -      this(doc, Target, null);
    -   }
    +    /**
    +     * Constructs{@link SignatureProperty} using specified target attribute
    +     *
    +     * @param doc the {@link Document} in which XMLsignature is placed
    +     * @param target the target attribute references the Signature
    +     * element to which the property applies SignatureProperty
    +     */
    +    public SignatureProperty(Document doc, String target) {
    +        this(doc, target, null);
    +    }
     
    -   /**
    -    * Constructs {@link SignatureProperty} using sepcified Target attribute and Id attribute
    -    *
    -    * @param doc the {@link Document} in which XMLsignature is placed
    -    * @param Target the Target attribute references the Signature element to which the property applies
    -    * @param Id the Id will be specified by {@link Reference#getURI} in validation
    -    */
    -   public SignatureProperty(Document doc, String Target, String Id) {
    +    /**
    +     * Constructs {@link SignatureProperty} using sepcified target attribute and
    +     * id attribute
    +     *
    +     * @param doc the {@link Document} in which XMLsignature is placed
    +     * @param target the target attribute references the Signature
    +     *  element to which the property applies
    +     * @param id the id will be specified by {@link Reference#getURI} in validation
    +     */
    +    public SignatureProperty(Document doc, String target, String id) {
    +        super(doc);
     
    -      super(doc);
    +        this.setTarget(target);
    +        this.setId(id);
    +    }
     
    -      this.setTarget(Target);
    -      this.setId(Id);
    -   }
    +    /**
    +     * Constructs a {@link SignatureProperty} from an {@link Element}
    +     * @param element SignatureProperty 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);
    +    }
     
    -   /**
    -    * Constructs a {@link SignatureProperty} from an {@link Element}
    -    * @param element SignatureProperty 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);
    -   }
    +    /**
    +     *   Sets the id attribute
    +     *
    +     *   @param id the id 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);
    +        }
    +    }
     
    -   /**
    -    *   Sets the Id attribute
    -    *
    -    *   @param Id the Id attribute
    -    */
    -   public void setId(String Id) {
    +    /**
    +     * Returns the id attribute
    +     *
    +     * @return the id attribute
    +     */
    +    public String getId() {
    +        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
    +    }
     
    -      if (Id != null) {
    -          setLocalIdAttribute(Constants._ATT_ID, Id);
    -      }
    -   }
    +    /**
    +     * Sets the target attribute
    +     *
    +     * @param target the target attribute
    +     */
    +    public void setTarget(String target) {
    +        if (target != null) {
    +            this.constructionElement.setAttributeNS(null, Constants._ATT_TARGET, target);
    +        }
    +    }
     
    -   /**
    -    * Returns the Id attribute
    -    *
    -    * @return the Id attribute
    -    */
    -   public String getId() {
    -      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
    -   }
    +    /**
    +     * Returns the target attribute
    +     *
    +     * @return the target attribute
    +     */
    +    public String getTarget() {
    +        return this.constructionElement.getAttributeNS(null, Constants._ATT_TARGET);
    +    }
     
    -   /**
    -    * Sets the Target attribute
    -    *
    -    * @param Target the Target attribute
    -    */
    -   public void setTarget(String Target) {
    +    /**
    +     * Method appendChild
    +     *
    +     * @param node
    +     * @return the node in this element.
    +     */
    +    public Node appendChild(Node node) {
    +        return this.constructionElement.appendChild(node);
    +    }
     
    -      if ((Target != null)) {
    -         this._constructionElement.setAttributeNS(null, Constants._ATT_TARGET, Target);
    -      }
    -   }
    -
    -   /**
    -    * Returns the Target attribute
    -    *
    -    * @return the Target attribute
    -    */
    -   public String getTarget() {
    -      return this._constructionElement.getAttributeNS(null, Constants._ATT_TARGET);
    -   }
    -
    -   /**
    -    * 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;
    -   }
    +    /** @inheritDoc */
    +    public String getBaseLocalName() {
    +        return Constants._TAG_SIGNATUREPROPERTY;
    +    }
     }
    diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java
    index f2e04602984..98bfca4a9b2 100644
    --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java
    +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java
    @@ -2,21 +2,23 @@
      * reserved comment block
      * DO NOT REMOVE OR ALTER!
      */
    -/*
    - * Copyright  1999-2004 The Apache Software Foundation.
    +/**
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements. See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership. The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License. You may obtain a copy of the License at
      *
    - *  Licensed under the Apache License, Version 2.0 (the "License");
    - *  you may not use this 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.
    + * http://www.apache.org/licenses/LICENSE-2.0
      *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express 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 @@ import org.xml.sax.SAXException;
      */
     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 @@ public class SignedInfo extends Manifest {
          *    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 @@ public class SignedInfo extends Manifest {
          *    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 @@ public class SignedInfo extends Manifest {
          * @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 @@ public class SignedInfo extends Manifest {
          * @param element SignedInfo
          * @param baseURI the URI of the resource where the XML instance was stored
          * @throws XMLSecurityException
    -     * @see Question
    -     * @see Answer
    +     * @see 
    +     * Question
    +     * @see 
    +     * Answer
          */
    -    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 SignedInfo
    +     * @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 
    +     * Question
    +     * @see 
    +     * Answer
    +     */
    +    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 @@ public class SignedInfo extends Manifest {
                     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 ds:Manifests, 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 octedt stream of SignedInfo element
    -    * @throws CanonicalizationException
    -    * @throws InvalidCanonicalizerException
    -    * @throws XMLSecurityException
    -    */
    -   public byte[] getCanonicalizedOctetStream()
    -           throws CanonicalizationException, InvalidCanonicalizerException,
    -                 XMLSecurityException {
    -
    -      if ((this._c14nizedBytes == null)
    -              /*&& (this._state == ElementProxy.MODE_SIGN)*/) {
    -         Canonicalizer c14nizer =
    -            Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
    -
    -         this._c14nizedBytes =
    -            c14nizer.canonicalizeSubtree(this._constructionElement);
    -      }
    -
    -      // make defensive copy
    -      byte[] output = new byte[this._c14nizedBytes.length];
    -
    -      System.arraycopy(this._c14nizedBytes, 0, output, 0, output.length);
    -
    -      return output;
    -   }
    -
    -   /**
    -    *  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();
    -
    -       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);
         }
    -   }
     
    -   /**
    -    * Returns the Canonicalization method URI
    -    *
    -    * @return the Canonicalization method URI
    -    */
    -   public String getCanonicalizationMethodURI() {
    +    /**
    +     * Tests core validation process
    +     *
    +     * @param followManifests defines whether the verification process has to verify referenced ds:Manifests, 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 SignedInfo element
    +     * @throws CanonicalizationException
    +     * @throws InvalidCanonicalizerException
    +     * @throws XMLSecurityException
    +     */
    +    public byte[] getCanonicalizedOctetStream()
    +        throws CanonicalizationException, InvalidCanonicalizerException, XMLSecurityException {
    +        if (this.c14nizedBytes == null) {
    +            Canonicalizer c14nizer =
    +                Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
     
    -     return c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
    -   }
    +            this.c14nizedBytes =
    +                c14nizer.canonicalizeSubtree(this.constructionElement);
    +        }
     
    -   /**
    -    * Returns the Signature method URI
    -    *
    -    * @return the Signature method URI
    -    */
    -   public String getSignatureMethodURI() {
    +        // make defensive copy
    +        return this.c14nizedBytes.clone();
    +    }
     
    -      Element signatureElement = this.getSignatureMethodElement();
    +    /**
    +     * 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 (signatureElement != null) {
    -         return signatureElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
    -      }
    +            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);
    +            }
    +        }
    +    }
     
    -      return null;
    -   }
    +    /**
    +     * Returns the Canonicalization method URI
    +     *
    +     * @return the Canonicalization method URI
    +     */
    +    public String getCanonicalizationMethodURI() {
    +        return c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
    +    }
     
    -   /**
    -    * Method getSignatureMethodElement
    -    * @return gets The SignatureMethod Node.
    -    *
    -    */
    -   public Element getSignatureMethodElement() {
    -           return signatureMethod;
    -   }
    +    /**
    +     * Returns the Signature method URI
    +     *
    +     * @return the Signature method URI
    +     */
    +    public String getSignatureMethodURI() {
    +        Element signatureElement = this.getSignatureMethodElement();
     
    -   /**
    -    * 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)
    -   {
    +        if (signatureElement != null) {
    +            return signatureElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
    +        }
     
    -      return new SecretKeySpec(secretKeyBytes,
    -                               this._signatureAlgorithm
    -                                  .getJCEAlgorithmString());
    -   }
    +        return null;
    +    }
     
    -   protected SignatureAlgorithm getSignatureAlgorithm() {
    -           return _signatureAlgorithm;
    -   }
    -   /**
    -    * Method getBaseLocalName
    -    * @inheritDoc
    -    *
    -    */
    -   public String getBaseLocalName() {
    -      return Constants._TAG_SIGNEDINFO;
    -   }
    +    /**
    +     * Method getSignatureMethodElement
    +     * @return returns the SignatureMethod Element
    +     *
    +     */
    +    public Element getSignatureMethodElement() {
    +        return signatureMethod;
    +    }
     
    -   public String getInclusiveNamespaces() {
    +    /**
    +     * 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());
    +    }
     
    +    protected SignatureAlgorithm getSignatureAlgorithm() {
    +        return signatureAlgorithm;
    +    }
     
    +    /**
    +     * Method getBaseLocalName
    +     * @inheritDoc
    +     *
    +     */
    +    public String getBaseLocalName() {
    +        return Constants._TAG_SIGNEDINFO;
    +    }
     
    -     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"))) {
    +    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());
    +
    +        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;
         }
     }
    diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java
    index a1a69ddb1d4..490f184c57f 100644
    --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java
    +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java
    @@ -2,26 +2,26 @@
      * reserved comment block
      * DO NOT REMOVE OR ALTER!
      */
    -/*
    - * Copyright  1999-2004 The Apache Software Foundation.
    +/**
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements. See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership. The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License. You may obtain a copy of the License at
      *
    - *  Licensed under the Apache License, Version 2.0 (the "License");
    - *  you may not use this 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.
    + * http://www.apache.org/licenses/LICENSE-2.0
      *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express 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.transforms.Transforms;
     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.Node;
     import org.w3c.dom.NodeList;
     import org.w3c.dom.Text;
     
    -
     /**
      * Handles <ds:Signature> elements.
      * This is the main class that deals with creating and verifying signatures.
    @@ -64,7 +62,7 @@ import org.w3c.dom.Text;
      * 

    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 @@ import org.w3c.dom.Text; * ObjectContainer during signing. *

  • sign and checkSignatureValue methods are used to sign and validate the * signature.
  • - * - * @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; - /** Signature - Required DSAwithSHA1 (DSS) */ - public static final String ALGO_ID_SIGNATURE_DSA = Constants.SignatureSpecNS + "dsa-sha1"; + /** ds:Signature.ds:KeyInfo */ + private KeyInfo keyInfo; - /** 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"; + /** + * 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; - /** 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"; + private Element signatureValueElement; + private static final int MODE_SIGN = 0; + private static final int MODE_VERIFY = 1; + private int state = MODE_SIGN; - //J+ + /** + * This creates a new ds:Signature Element and adds an empty + * ds:SignedInfo. + * The ds:SignedInfo 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); + } - /** ds:Signature.ds:SignedInfo element */ - private SignedInfo _signedInfo = null; + /** + * 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 + ); + } - /** ds:Signature.ds:KeyInfo */ - private KeyInfo _keyInfo = null; + /** + * 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); + } - /** - * 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; + /** + * 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); -private Element signatureValueElement; + 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 creates a new ds:Signature Element and adds an empty - * ds:SignedInfo. - * The ds:SignedInfo 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); - } + this.baseURI = baseURI; + this.signedInfo = + new SignedInfo( + this.doc, signatureMethodURI, hmacOutputLength, 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); - } + this.constructionElement.appendChild(this.signedInfo.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); - /** - * 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); - } + // create an empty SignatureValue; this is filled by setSignatureValueElement + signatureValueElement = + XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_SIGNATUREVALUE); - /** - * 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 { + this.constructionElement.appendChild(signatureValueElement); + XMLUtils.addReturnToElement(this.constructionElement); + } - super(doc); + /** + * 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); - 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); + 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.baseURI = baseURI; + this.signedInfo = + new SignedInfo(this.doc, SignatureMethodElem, CanonicalizationMethodElem); - this._constructionElement.appendChild(this._signedInfo.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + 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); + // 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); - } - /** - * 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 { + this.constructionElement.appendChild(signatureValueElement); + XMLUtils.addReturnToElement(this.constructionElement); + } - super(doc); + /** + * 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); + } - 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 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); - this._baseURI = BaseURI; - this._signedInfo = new SignedInfo(this._doc, SignatureMethodElem, CanonicalizationMethodElem); + // check out SignedInfo child + Element signedInfoElem = XMLUtils.getNextElement(element.getFirstChild()); - this._constructionElement.appendChild(this._signedInfo.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + // check to see if it is there + if (signedInfoElem == null) { + Object exArgs[] = { Constants._TAG_SIGNEDINFO, Constants._TAG_SIGNATURE }; + throw new XMLSignatureException("xml.WrongContent", exArgs); + } - // create an empty SignatureValue; this is filled by setSignatureValueElement - signatureValueElement = - XMLUtils.createElementInSignatureSpace(this._doc, - Constants._TAG_SIGNATUREVALUE); + // 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()); - this._constructionElement.appendChild(signatureValueElement); - XMLUtils.addReturnToElement(this._constructionElement); - } + // check out SignatureValue child + this.signatureValueElement = + XMLUtils.getNextElement(signedInfoElem.getNextSibling()); - /** - * 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 { + // 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); + } - super(element, BaseURI); + // + Element keyInfoElem = + XMLUtils.getNextElement(signatureValueElement.getNextSibling()); - // check out SignedInfo child - Element signedInfoElem = XMLUtils.getNextElement(element.getFirstChild());// XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - //Constants._TAG_SIGNEDINFO,0); + // 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); + } - // check to see if it is there - if (signedInfoElem == null) { - Object exArgs[] = { Constants._TAG_SIGNEDINFO, - Constants._TAG_SIGNATURE }; + // + Element objectElem = + XMLUtils.getNextElement(signatureValueElement.getNextSibling()); + while (objectElem != null) { + Attr objectAttr = objectElem.getAttributeNodeNS(null, "Id"); + if (objectAttr != null) { + objectElem.setIdAttributeNode(objectAttr, true); + } - throw new XMLSignatureException("xml.WrongContent", exArgs); - } + 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); + } + } + } - // create a SignedInfo object from that element - this._signedInfo = new SignedInfo(signedInfoElem, BaseURI); + objectElem = XMLUtils.getNextElement(objectElem.getNextSibling()); + } - // check out SignatureValue child - this.signatureValueElement =XMLUtils.getNextElement(signedInfoElem.getNextSibling()); //XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - // Constants._TAG_SIGNATUREVALUE,0); + this.state = MODE_VERIFY; + } - // check to see if it exists - if (signatureValueElement == null) { - Object exArgs[] = { Constants._TAG_SIGNATUREVALUE, - Constants._TAG_SIGNATURE }; + /** + * Sets the Id 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); + } + } - throw new XMLSignatureException("xml.WrongContent", exArgs); - } - Attr signatureValueAttr = signatureValueElement.getAttributeNodeNS(null, "Id"); - if (signatureValueAttr != null) { - signatureValueElement.setIdAttributeNode(signatureValueAttr, true); - } + /** + * Returns the Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } - // - Element keyInfoElem = XMLUtils.getNextElement(signatureValueElement.getNextSibling());//XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - // Constants._TAG_KEYINFO,0); + /** + * Returns the completely parsed SignedInfo object. + * + * @return the completely parsed SignedInfo object. + */ + public SignedInfo getSignedInfo() { + return this.signedInfo; + } - // 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); - } - - // - 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); - } - } - } - - objectElem = XMLUtils.getNextElement(objectElem.getNextSibling()); - } - } - - /** - * Sets the Id attribute - * - * @param Id Id value to be used by the id attribute on the Signature Element - */ - public void setId(String Id) { - - if (Id != null) { - setLocalIdAttribute(Constants._ATT_ID, Id); - } - } - - /** - * Returns the Id attribute - * - * @return the Id attribute - */ - public String getId() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ID); - } - - /** - * Returns the completely parsed SignedInfo object. - * - * @return the completely parsed SignedInfo 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 Element signatureValueElement; 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 @@ private Element signatureValueElement; 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. - *
    - * 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. + *
    + * 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 java.lang.Object 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 java.lang.Object 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 ith ds:Object child of the signature - * or null if no such ds:Object element exists. - * - * @param i - * @return the ith ds:Object child of the signature or null if no such ds:Object element exists. - */ - public ObjectContainer getObjectItem(int i) { + /** + * Returns the ith ds:Object child of the signature + * or null if no such ds:Object element exists. + * + * @param i + * @return the ith ds:Object child of the signature + * or null if no such ds:Object 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 ds:Object elements. + * + * @return the number of all ds:Object elements. + */ + public int getObjectLength() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_OBJECT); + } - /** - * Returns the number of all ds:Object elements. - * - * @return the number of all ds:Object 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 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); + } + } - // 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); - } - } + /** + * 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 { + // see if cert is null + if (cert != null) { + // check the values with the public key from the cert + return this.checkSignatureValue(cert.getPublicKey()); + } - /** - * 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 { + Object exArgs[] = { "Didn't get a certificate" }; + throw new XMLSignatureException("empty", exArgs); + } - // 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); - - } - - /** - * 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 { + // Get the canonicalized (normalized) SignedInfo + SignerOutputStream so = new SignerOutputStream(sa); + OutputStream bos = new UnsyncBufferedOutputStream(so); + + si.signInOctetStream(bos); bos.close(); - } catch (IOException e) { - //Imposible - } + // 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; + } - //retrieve the byte[] from the stored signature - byte sigBytes[] = this.getSignatureValue(); + // 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 (XMLSignatureException ex) { + throw ex; + } catch (XMLSecurityException ex) { + throw new XMLSignatureException("empty", ex); + } + } - return si.verify(this._followManifestsDuringValidation); - } 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 { + X509Data x509data = new X509Data(this.doc); - /** - * 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.addCertificate(cert); + this.getKeyInfo().add(x509data); + } - X509Data x509data = new X509Data(this._doc); + /** + * 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); + } - x509data.addCertificate(cert); - this.getKeyInfo().add(x509data); - } + /** + * 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); + } - /** - * 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); - } + /** + * 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 + * Core validation section in the XML Signature Rec. + */ + public void setFollowNestedManifests(boolean followManifests) { + this.followManifestsDuringValidation = followManifests; + } - /** - * 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 Core validation section in the XML Signature Rec. - */ - 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java index 744f62dc461..863ddbbedca 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java @@ -2,29 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; */ 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); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java index 89990a10ac4..6451642cb70 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.ByteArrayOutputStream; 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 @@ import org.xml.sax.SAXException; * @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 @@ public class XMLSignatureInput implements Cloneable { * 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 _inputNodeSet = null; + private Set 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 nodeFilters=new ArrayList(); + private List nodeFilters = new ArrayList(); - boolean needsToBeExpanded=false; - OutputStream outputStream=null; + private boolean needsToBeExpanded = false; + private OutputStream outputStream = null; - /** - * Check if the structured is needed to be circumbented. - * @return true if so. - */ - public boolean isNeedsToBeExpanded() { - return needsToBeExpanded; - } - - /** - * 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 @@ public class XMLSignatureInput implements Cloneable { * @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 @@ public class XMLSignatureInput implements Cloneable { * @param inputOctetStream */ public XMLSignatureInput(InputStream inputOctetStream) { - this._inputOctetStreamProxy=inputOctetStream; - - //this(JavaUtils.getBytesFromStream(inputOctetStream)); - } - - /** - * Construct a XMLSignatureInput from a String. - *

    - * 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. - *

    - * 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 encoding - * @param encoding the encoding of inputStr - * @throws UnsupportedEncodingException - */ - @Deprecated - public XMLSignatureInput(String inputStr, String encoding) - throws UnsupportedEncodingException { - this(inputStr.getBytes(encoding)); + this.inputOctetStreamProxy = inputOctetStream; } /** @@ -193,19 +147,33 @@ public class XMLSignatureInput implements Cloneable { * * @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 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,11 +186,19 @@ public class XMLSignatureInput implements Cloneable { * @throws ParserConfigurationException * @throws CanonicalizationException */ - public Set getNodeSet() throws CanonicalizationException, - ParserConfigurationException, IOException, SAXException { + public Set getNodeSet() throws CanonicalizationException, ParserConfigurationException, + IOException, SAXException { return getNodeSet(false); } + /** + * Get the Input NodeSet. + * @return the Input NodeSet. + */ + public Set getInputNodeSet() { + return inputNodeSet; + } + /** * Returns the node set from input which was specified as the parameter of * {@link XMLSignatureInput} constructor @@ -234,51 +210,54 @@ public class XMLSignatureInput implements Cloneable { * @throws ParserConfigurationException * @throws CanonicalizationException */ - public Set getNodeSet(boolean circumvent) - throws ParserConfigurationException, IOException, SAXException, - CanonicalizationException { - if (this._inputNodeSet!=null) { - return this._inputNodeSet; + public Set 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(); - XMLUtils.getSet(_subNode,this._inputNodeSet, excludeNode, this.excludeComments); - - return this._inputNodeSet; - } else if (this.isOctetStream()) { + inputNodeSet = new LinkedHashSet(); + XMLUtils.getSet(subNode, inputNodeSet, excludeNode, excludeComments); + return inputNodeSet; + } else if (isOctetStream()) { convertToNodes(); - LinkedHashSet result = new LinkedHashSet(); - XMLUtils.getSet(_subNode, result,null,false); - //this._inputNodeSet=result; + Set result = new LinkedHashSet(); + 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 @@ public class XMLSignatureInput implements Cloneable { * @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 @@ public class XMLSignatureInput implements Cloneable { * @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 @@ public class XMLSignatureInput implements Cloneable { * @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 @@ public class XMLSignatureInput implements Cloneable { * @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 @@ public class XMLSignatureInput implements Cloneable { * @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 @@ public class XMLSignatureInput implements Cloneable { * @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 @@ public class XMLSignatureInput implements Cloneable { * @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 @@ public class XMLSignatureInput implements Cloneable { * @return The HTML representation for this XMLSignature */ public String getHTMLRepresentation() throws XMLSignatureException { - XMLSignatureInputDebugger db = new XMLSignatureInputDebugger(this); - return db.getHTMLRepresentation(); } @@ -451,11 +418,9 @@ public class XMLSignatureInput implements Cloneable { * @return The HTML representation for this XMLSignature */ public String getHTMLRepresentation(Set inclusiveNamespaces) - throws XMLSignatureException { - - XMLSignatureInputDebugger db = new XMLSignatureInputDebugger( this, - inclusiveNamespaces); - + throws XMLSignatureException { + XMLSignatureInputDebugger db = + new XMLSignatureInputDebugger(this, inclusiveNamespaces); return db.getHTMLRepresentation(); } @@ -480,7 +445,7 @@ public class XMLSignatureInput implements Cloneable { * @return The excludeNode set. */ public Node getSubNode() { - return _subNode; + return subNode; } /** @@ -503,19 +468,18 @@ public class XMLSignatureInput implements Cloneable { * @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 @@ public class XMLSignatureInput implements Cloneable { } 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 @@ public class XMLSignatureInput implements Cloneable { * @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 (bytes!=null) { - _inputOctetStreamProxy=new ByteArrayInputStream(bytes); - return _inputOctetStreamProxy; - } - if (_inputOctetStreamProxy ==null) + 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; + try { + bytes = JavaUtils.getBytesFromStream(inputOctetStreamProxy); + } finally { + inputOctetStreamProxy.close(); + } + return bytes; } /** @@ -578,7 +532,9 @@ public class XMLSignatureInput implements Cloneable { 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 @@ public class XMLSignatureInput implements Cloneable { * @return the node filters */ public List getNodeFilters() { - // TODO Auto-generated method stub return nodeFilters; } @@ -596,39 +551,42 @@ public class XMLSignatureInput implements Cloneable { * @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("".getBytes()); + baos.write("".getBytes("UTF-8")); baos.write(this.getBytes()); - baos.write("".getBytes()); + baos.write("".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; } + } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java index 3186ef4d6a8..e565b22aeee 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import org.w3c.dom.ProcessingInstruction; /** * Class XMLSignatureInputDebugger - * - * @author $Author: mullan $ - * @version $Revision: 1.3 $ */ public class XMLSignatureInputDebugger { + /** Field _xmlSignatureInput */ + private Set xpathNodeSet; + private Set inclusiveNamespaces; - /** Field _xmlSignatureInput */ - private Set _xpathNodeSet; + /** Field doc */ + private Document doc = null; - private Set _inclusiveNamespaces; + /** Field writer */ + private Writer writer = null; - /** Field _doc */ - private Document _doc = null; + /** The HTML Prefix* */ + static final String HTMLPrefix = + "\n" + + "\n" + + "\n" + + "Caninical XML node set\n" + + " \n" + + "\n" + + "\n" + + "

    Explanation of the output

    \n" + + "

    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.

    \n" + + "
      \n" + + "
    • A node which is in the node set is labeled using the INCLUDED style.
    • \n" + + "
    • A node which is NOT in the node set is labeled EXCLUDED style.
    • \n" + + "
    • A namespace which is in the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.
    • \n" + + "
    • A namespace which is in NOT the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.
    • \n" + + "
    \n" + "

    Output

    \n" + "
    \n";
     
    -        /** Field _writer */
    -        private Writer _writer = null;
    +    /** HTML Suffix * */
    +    static final String HTMLSuffix = "
    "; - // J- - // public static final String HTMLPrefix = "
    ";
    -        /** The HTML Prefix* */
    -        static final String HTMLPrefix = "\n"
    -                        + "\n"
    -                        + "\n"
    -                        + "Caninical XML node set\n"
    -                        + " \n"
    -                        + "\n"
    -                        + "\n"
    -                        + "

    Explanation of the output

    \n" - + "

    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.

    \n" - + "
      \n" - + "
    • A node which is in the node set is labeled using the INCLUDED style.
    • \n" - + "
    • A node which is NOT in the node set is labeled EXCLUDED style.
    • \n" - + "
    • A namespace which is in the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.
    • \n" - + "
    • A namespace which is in NOT the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.
    • \n" - + "
    \n" + "

    Output

    \n" + "
    \n";
    +    static final String HTMLExcludePrefix = "";
     
    -        /** HTML Suffix * */
    -        static final String HTMLSuffix = "
    "; + static final String HTMLIncludePrefix = ""; - static final String HTMLExcludePrefix = ""; + static final String HTMLIncludeOrExcludeSuffix = ""; - static final String HTMLExcludeSuffix = ""; + static final String HTMLIncludedInclusiveNamespacePrefix = ""; - static final String HTMLIncludePrefix = ""; + static final String HTMLExcludedInclusiveNamespacePrefix = ""; - static final String HTMLIncludeSuffix = ""; + private static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1; - static final String HTMLIncludedInclusiveNamespacePrefix = ""; + private static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0; - static final String HTMLIncludedInclusiveNamespaceSuffix = ""; + private static final int NODE_AFTER_DOCUMENT_ELEMENT = 1; - static final String HTMLExcludedInclusiveNamespacePrefix = ""; + static final AttrCompare ATTR_COMPARE = new AttrCompare(); - static final String HTMLExcludedInclusiveNamespaceSuffix = ""; + /** + * Constructor XMLSignatureInputDebugger + * + * @param xmlSignatureInput the signature to pretty print + */ + public XMLSignatureInputDebugger(XMLSignatureInput xmlSignatureInput) { + if (!xmlSignatureInput.isNodeSet()) { + this.xpathNodeSet = null; + } else { + this.xpathNodeSet = xmlSignatureInput.getInputNodeSet(); + } + } - private static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1; + /** + * Constructor XMLSignatureInputDebugger + * + * @param xmlSignatureInput the signatur to pretty print + * @param inclusiveNamespace + */ + public XMLSignatureInputDebugger( + XMLSignatureInput xmlSignatureInput, + Set inclusiveNamespace + ) { + this(xmlSignatureInput); + this.inclusiveNamespaces = inclusiveNamespace; + } - private static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0; - - private static final int NODE_AFTER_DOCUMENT_ELEMENT = 1; - - static final AttrCompare ATTR_COMPARE = new AttrCompare(); - - // J+ - private XMLSignatureInputDebugger() { - // do nothing + /** + * Method getHTMLRepresentation + * + * @return The HTML Representation. + * @throws XMLSignatureException + */ + public String getHTMLRepresentation() throws XMLSignatureException { + if ((this.xpathNodeSet == null) || (this.xpathNodeSet.size() == 0)) { + return HTMLPrefix + "no node set, sorry" + HTMLSuffix; } - /** - * Constructor XMLSignatureInputDebugger - * - * @param xmlSignatureInput the signatur to pretty print - */ - public XMLSignatureInputDebugger( - XMLSignatureInput xmlSignatureInput) { + // get only a single node as anchor to fetch the owner document + Node n = this.xpathNodeSet.iterator().next(); - if (!xmlSignatureInput.isNodeSet()) { - this._xpathNodeSet = null; + this.doc = XMLUtils.getOwnerDocument(n); + + try { + this.writer = new StringWriter(); + + 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 canonicalizeXPathNodeSet + * + * @param currentNode + * @throws XMLSignatureException + * @throws IOException + */ + private void canonicalizeXPathNodeSet(Node currentNode) + throws XMLSignatureException, IOException { + + int currentNodeType = currentNode.getNodeType(); + switch (currentNodeType) { + + + 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); + } + + 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); + + if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.writer.write(HTMLIncludeOrExcludeSuffix); + 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); + + if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.TEXT_NODE: + case Node.CDATA_SECTION_NODE: + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + 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()); + } + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.ELEMENT_NODE: + Element currentElement = (Element) currentNode; + + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + this.writer.write("<"); + this.writer.write(currentElement.getTagName()); + + this.writer.write(HTMLIncludeOrExcludeSuffix); + + // 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; + + 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()); + + if (included) { + if (inclusive) { + // included and inclusive + this.writer.write(HTMLIncludedInclusiveNamespacePrefix); + } else { + // included and not inclusive + this.writer.write(HTMLIncludePrefix); + } } else { - this._xpathNodeSet = xmlSignatureInput._inputNodeSet; - } - } - - /** - * Constructor XMLSignatureInputDebugger - * - * @param xmlSignatureInput the signatur to pretty print - * @param inclusiveNamespace - */ - public XMLSignatureInputDebugger( - XMLSignatureInput xmlSignatureInput, Set inclusiveNamespace) { - - this(xmlSignatureInput); - - this._inclusiveNamespaces = inclusiveNamespace; - } - - /** - * Method getHTMLRepresentation - * - * @return The HTML Representation. - * @throws XMLSignatureException - */ - public String getHTMLRepresentation() throws XMLSignatureException { - - if ((this._xpathNodeSet == null) || (this._xpathNodeSet.size() == 0)) { - return HTMLPrefix + "no node set, sorry" - + 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(); - - 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 canonicalizeXPathNodeSet - * - * @param currentNode - * @throws XMLSignatureException - * @throws IOException - */ - private void canonicalizeXPathNodeSet(Node currentNode) - throws XMLSignatureException, IOException { - - int currentNodeType = currentNode.getNodeType(); - switch (currentNodeType) { - - case Node.DOCUMENT_TYPE_NODE: - default: - break; - - 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); - } - - 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); - - 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); - - 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.TEXT_NODE: - case Node.CDATA_SECTION_NODE: - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - 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; - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - this._writer.write("<"); - this._writer.write(currentElement.getTagName()); - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - - // 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; - - 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()); - - 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.outputAttrToWriter(a.getNodeName(), a.getNodeValue()); - - if (included) { - if (inclusive) { - - // included and inclusive - this._writer - .write(HTMLIncludedInclusiveNamespaceSuffix); - } else { - - // included and not inclusive - this._writer.write(HTMLIncludeSuffix); - } - } else { - if (inclusive) { - - // excluded and inclusive - this._writer - .write(HTMLExcludedInclusiveNamespaceSuffix); - } else { - - // excluded and not inclusive - this._writer.write(HTMLExcludeSuffix); - } - } - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - this._writer.write(">"); - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - - // 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("</"); - this._writer.write(currentElement.getTagName()); - this._writer.write(">"); - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - 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; - } - - 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; - } - - /** - * Normalizes an {@link Attr}ibute value - * - * The string value of the node is modified by replacing - *
      - *
    • all ampersands (&) with &amp;
    • - *
    • all open angle brackets (<) with &lt;
    • - *
    • all quotation mark characters with &quot;
    • - *
    • and the whitespace characters #x9, #xA, and #xD, - * with character references. The character references are written in - * uppercase hexadecimal with no leading zeroes (for example, #xD - * is represented by the character reference &#xD;)
    • - *
    - * - * @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("=\""); - - int length = value.length(); - - for (int i = 0; i < length; i++) { - char c = value.charAt(i); - - switch (c) { - - case '&': - this._writer.write("&amp;"); - break; - - case '<': - this._writer.write("&lt;"); - break; - - case '"': - this._writer.write("&quot;"); - break; - - case 0x09: // '\t' - this._writer.write("&#x9;"); - break; - - case 0x0A: // '\n' - this._writer.write("&#xA;"); - break; - - case 0x0D: // '\r' - this._writer.write("&#xD;"); - break; - - default: - this._writer.write(c); - break; - } - } - - 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("<?"); - - 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("&#xD;"); - break; - - case ' ': - this._writer.write("·"); - break; - - case '\n': - this._writer.write("¶\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("&#xD;"); - break; - - default: - this._writer.write(c); - break; - } + if (inclusive) { + // excluded and inclusive + this.writer.write(HTMLExcludedInclusiveNamespacePrefix); + } else { + // excluded and not inclusive + this.writer.write(HTMLExcludePrefix); } } - this._writer.write("?>"); + 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(">"); + + 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("</"); + this.writer.write(currentElement.getTagName()); + this.writer.write(">"); + + 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; } - /** - * Method outputCommentToWriter - * - * @param currentComment - * @throws IOException - */ - private void outputCommentToWriter(Comment currentComment) - throws IOException { + Document doc = currentNode.getOwnerDocument(); - if (currentComment == null) { - return; - } - - this._writer.write("<!--"); - - 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("&#xD;"); - break; - - case ' ': - this._writer.write("·"); - break; - - case '\n': - this._writer.write("¶\n"); - break; - - default: - this._writer.write(c); - break; - } - } - - this._writer.write("-->"); + if (currentNode.getParentNode() != doc) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; } - /** - * Method outputTextToWriter - * - * @param text - * @throws IOException - */ - private void outputTextToWriter(String text) throws IOException { + Element documentElement = doc.getDocumentElement(); - if (text == null) { - return; - } - - int length = text.length(); - - for (int i = 0; i < length; i++) { - char c = text.charAt(i); - - switch (c) { - - case '&': - this._writer.write("&amp;"); - break; - - case '<': - this._writer.write("&lt;"); - break; - - case '>': - this._writer.write("&gt;"); - break; - - case 0xD: - this._writer.write("&#xD;"); - break; - - case ' ': - this._writer.write("·"); - break; - - case '\n': - this._writer.write("¶\n"); - break; - - default: - this._writer.write(c); - break; - } - } + if (documentElement == null) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; } + + 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; + } + + /** + * Normalizes an {@link Attr}ibute value + * + * The string value of the node is modified by replacing + *
      + *
    • all ampersands (&) with &amp;
    • + *
    • all open angle brackets (<) with &lt;
    • + *
    • all quotation mark characters with &quot;
    • + *
    • and the whitespace characters #x9, #xA, and #xD, + * with character references. The character references are written in + * uppercase hexadecimal with no leading zeroes (for example, #xD + * is represented by the character reference &#xD;)
    • + *
    + * + * @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("=\""); + + int length = value.length(); + + for (int i = 0; i < length; i++) { + char c = value.charAt(i); + + switch (c) { + + case '&': + this.writer.write("&amp;"); + break; + + case '<': + this.writer.write("&lt;"); + break; + + case '"': + this.writer.write("&quot;"); + break; + + case 0x09: // '\t' + this.writer.write("&#x9;"); + break; + + case 0x0A: // '\n' + this.writer.write("&#xA;"); + break; + + case 0x0D: // '\r' + this.writer.write("&#xD;"); + break; + + default: + this.writer.write(c); + break; + } + } + + 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("<?"); + + 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("&#xD;"); + break; + + case ' ': + this.writer.write("·"); + break; + + case '\n': + this.writer.write("¶\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("&#xD;"); + break; + + default: + this.writer.write(c); + break; + } + } + } + + this.writer.write("?>"); + } + + /** + * Method outputCommentToWriter + * + * @param currentComment + * @throws IOException + */ + private void outputCommentToWriter(Comment currentComment) throws IOException { + + if (currentComment == null) { + return; + } + + this.writer.write("<!--"); + + 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("&#xD;"); + break; + + case ' ': + this.writer.write("·"); + break; + + case '\n': + this.writer.write("¶\n"); + break; + + default: + this.writer.write(c); + break; + } + } + + this.writer.write("-->"); + } + + /** + * Method outputTextToWriter + * + * @param text + * @throws IOException + */ + private void outputTextToWriter(String text) throws IOException { + if (text == null) { + return; + } + + int length = text.length(); + + for (int i = 0; i < length; i++) { + char c = text.charAt(i); + + switch (c) { + + case '&': + this.writer.write("&amp;"); + break; + + case '<': + this.writer.write("&lt;"); + break; + + case '>': + this.writer.write("&gt;"); + break; + + case 0xD: + this.writer.write("&#xD;"); + break; + + case ' ': + this.writer.write("·"); + break; + + case '\n': + this.writer.write("¶\n"); + break; + + default: + this.writer.write(c); + break; + } + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java new file mode 100644 index 00000000000..81de122aead --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java @@ -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 { } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java new file mode 100644 index 00000000000..dc18c427eb7 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java @@ -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 ReferenceData type containing a node-set. + */ +public interface ReferenceNodeSetData extends ReferenceData { + + /** + * Returns a read-only iterator over the nodes contained in this + * NodeSetData in + * + * document order. Attempts to modify the returned iterator + * via the remove method throw + * UnsupportedOperationException. + * + * @return an Iterator over the nodes in this + * NodeSetData in document order + */ + Iterator iterator(); + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java new file mode 100644 index 00000000000..0f59fb95bcf --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java @@ -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 ReferenceData type containing an OctetStream. + */ +public class ReferenceOctetStreamData implements ReferenceData { + private InputStream octetStream; + private String uri; + private String mimeType; + + /** + * Creates a new ReferenceOctetStreamData. + * + * @param octetStream the input stream containing the octets + * @throws NullPointerException if octetStream is + * null + */ + public ReferenceOctetStreamData(InputStream octetStream) { + if (octetStream == null) { + throw new NullPointerException("octetStream is null"); + } + this.octetStream = octetStream; + } + + /** + * Creates a new ReferenceOctetStreamData. + * + * @param octetStream the input stream containing the octets + * @param uri the URI String identifying the data object (may be + * null) + * @param mimeType the MIME type associated with the data object (may be + * null) + * @throws NullPointerException if octetStream is + * null + */ + 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 ReferenceOctetStreamData. + * + * @return the input stream of this ReferenceOctetStreamData. + */ + public InputStream getOctetStream() { + return octetStream; + } + + /** + * Returns the URI String identifying the data object represented by this + * ReferenceOctetStreamData. + * + * @return the URI String or null if not applicable + */ + public String getURI() { + return uri; + } + + /** + * Returns the MIME type associated with the data object represented by this + * ReferenceOctetStreamData. + * + * @return the MIME type or null if not applicable + */ + public String getMimeType() { + return mimeType; + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java new file mode 100644 index 00000000000..cfa45e0435a --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java @@ -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 ReferenceNodeSetData 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 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 { + private Node root; + private List nodeSet; + private ListIterator 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 dereferenceSameDocumentURI(Node node) { + List nodeSet = new ArrayList(); + 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 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); + } + } + } + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java index 2236e950853..68ceb3bf243 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java @@ -2,86 +2,84 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java index 3c910219bfd..37d67ba9f24 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java @@ -263,7 +263,7 @@ public final class Transform extends SignatureElementProxy { * @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 @@ public final class Transform extends SignatureElementProxy { 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 transformSpiClass = transformSpiHash.get(algorithmURI); if (transformSpiClass == null) { @@ -360,7 +360,7 @@ public final class Transform extends SignatureElementProxy { // 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; diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java index d6c16fa771e..0624c8c7759 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java @@ -2,29 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java index 35aa9ff0f6e..7607d188be5 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import org.xml.sax.SAXException; * @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 @@ public abstract class TransformSpi { * @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 @@ public abstract class TransformSpi { * 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 @@ public abstract class TransformSpi { * @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 @@ public abstract class TransformSpi { * @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 Transformation algorithm * diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java index 10e8723e238..1296475f6b1 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java @@ -2,86 +2,83 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java index ce44e1713e4..7f29fd6a9f9 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import org.w3c.dom.NodeList; */ 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 class Transforms extends SignatureElementProxy { */ public Transforms(Document doc) { super(doc); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -125,24 +135,27 @@ public class Transforms extends SignatureElementProxy { * @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 Transform with the specified Transform * algorithm URI @@ -151,14 +164,13 @@ public class Transforms extends SignatureElementProxy { * 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 @@ public class Transforms extends SignatureElementProxy { * 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 @@ public class Transforms extends SignatureElementProxy { * 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 @@ public class Transforms extends SignatureElementProxy { * @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 @@ public class Transforms extends SignatureElementProxy { * @throws TransformationException */ public XMLSignatureInput performTransforms( - XMLSignatureInput xmlSignatureInput) throws TransformationException { + XMLSignatureInput xmlSignatureInput + ) throws TransformationException { return performTransforms(xmlSignatureInput, null); } @@ -250,21 +262,22 @@ public class Transforms extends SignatureElementProxy { * @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 @@ public class Transforms extends SignatureElementProxy { } } + 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 @@ public class Transforms extends SignatureElementProxy { * @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); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java index 15c1b576df5..7d8cc74e1ef 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 com.sun.org.apache.xpath.internal.res.XPATHErrorResources; 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 @@ import org.w3c.dom.Node; */ 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(); + Node xpathOwnerNode = (Node) xctxt.getOwnerObject(); - if (xpathOwnerNode == null) { - return null; - } + if (xpathOwnerNode == null) { + return null; + } - int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode); + int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode); - int currentNode = xctxt.getCurrentNode(); - DTM dtm = xctxt.getDTM(currentNode); - int docContext = dtm.getDocument(); + int currentNode = xctxt.getCurrentNode(); + DTM dtm = xctxt.getDTM(currentNode); + int docContext = dtm.getDocument(); - if (DTM.NULL == docContext) { - error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null); - } + if (DTM.NULL == docContext) { + error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null); + } - { + { + // 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); - // 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 (currentDoc != xpathOwnerDoc) { + throw new TransformerException(I18n.translate("xpath.funcHere.documentsDiffer")); + } + } - if (currentDoc != xpathOwnerDoc) { - throw new TransformerException(I18n - .translate("xpath.funcHere.documentsDiffer")); - } - } + XNodeSet nodes = new XNodeSet(xctxt.getDTMManager()); + NodeSetDTM nodeSet = nodes.mutableNodeset(); - XNodeSet nodes = new XNodeSet(xctxt.getDTMManager()); - NodeSetDTM nodeSet = nodes.mutableNodeset(); + { + int hereNode = DTM.NULL; - { - int hereNode = DTM.NULL; + switch (dtm.getNodeType(xpathOwnerNodeDTM)) { - switch (dtm.getNodeType(xpathOwnerNodeDTM)) { + case Node.ATTRIBUTE_NODE : + case Node.PROCESSING_INSTRUCTION_NODE : { + // returns a node-set containing the attribute / processing instruction node + hereNode = xpathOwnerNodeDTM; - case Node.ATTRIBUTE_NODE : { - // returns a node-set containing the attribute - 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.PROCESSING_INSTRUCTION_NODE : { - // returns a node-set containing the processing instruction node - hereNode = xpathOwnerNodeDTM; + nodeSet.addNode(hereNode); - nodeSet.addNode(hereNode); + break; + } + default : + break; + } + } - 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); + /** $todo$ Do I have to do this detach() call? */ + nodeSet.detach(); - nodeSet.addNode(hereNode); + return nodes; + } - break; - } - default : - break; - } - } - - /** $todo$ Do I have to do this detach() call? */ - nodeSet.detach(); - - 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 + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java deleted file mode 100644 index 6cc15ae3898..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java +++ /dev/null @@ -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 here() function. The here() function needs to know - * where 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. - * - *
    - * From: Scott_Boag\@lotus.com
    - * To: Christian Geuer-Pollmann 
    - * 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
    - * 
    - * - * @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 XML Signature - The here() function - */ -public class FuncHereContext extends XPathContext { - - /** - * This constuctor is disabled because if we use the here() function we - * always 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() + "\""); - } - } -} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java index b1d3de8bce7..206d31016cd 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import org.xml.sax.SAXException; */ 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(); - } - StringBuffer sb=new StringBuffer(); - traverseElement((Element)el,sb); - if (os==null) { + 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; + } + + 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(); } - } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java index 1b0c7fb6448..9c94199be05 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import com.sun.org.apache.xml.internal.security.transforms.Transforms; */ 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java index a4f6e34025f..b3510fc06b5 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ public class TransformC14N11 extends TransformSpi { 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); diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java index 1a7a213e718..e01f17312c7 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ public class TransformC14N11_WithComments extends TransformSpi { 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) { diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java index f4b2407055b..3b7bdd13691 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import org.w3c.dom.Element; /** * 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; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** - * 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); - } + 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 = c14n.engineCanonicalize(input, inclusiveNamespaces); - Canonicalizer20010315ExclOmitComments c14n = - new Canonicalizer20010315ExclOmitComments(); - if (os!=null) { - c14n.setWriter(os); - } - byte []result; - 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); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java index 2380750d052..d1456b30e00 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import org.w3c.dom.Element; */ public class TransformC14NExclusiveWithComments extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS; - /** - * Method engineGetURI - *@inheritDoc - * - */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** + * Method engineGetURI + *@inheritDoc + * + */ + protected String engineGetURI() { + return 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 { + 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(); + 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); } - - Canonicalizer20010315ExclWithComments c14n = - new Canonicalizer20010315ExclWithComments(); - if (os!=null) { - c14n.setWriter( os); - } - byte []result; - result =c14n.engineCanonicalize(input, inclusiveNamespaces); - XMLSignatureInput output=new XMLSignatureInput(result); - - return output; - } catch (XMLSecurityException ex) { - throw new CanonicalizationException("empty", ex); - } - } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java index b1087076d27..33aee9cd753 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import com.sun.org.apache.xml.internal.security.transforms.Transforms; */ public class TransformC14NWithComments extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_WITH_COMMENTS; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_WITH_COMMENTS; - /** @inheritDoc */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** @inheritDoc */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** @inheritDoc */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws CanonicalizationException { - return enginePerformTransform(input, null, _transformObject); - } - - /** @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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java index c447468bd63..9f108c1bb10 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java @@ -2,24 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import org.w3c.dom.Node; */ public class TransformEnvelopedSignature extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_ENVELOPED_SIGNATURE; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_ENVELOPED_SIGNATURE; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } - - /** - * @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. - */ - - Node signatureElement = _transformObject.getElement(); - - - signatureElement = searchSignatureElement(signatureElement); - input.setExcludeNode(signatureElement); - input.addNodeFilter(new EnvelopedNodeFilter(signatureElement)); - return input; - - // - - - } - - /** - * @param signatureElement - * @return the node that is the signature - * @throws TransformationException - */ - private static Node searchSignatureElement(Node signatureElement) throws TransformationException { - boolean found=false; - - 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; - } - - signatureElement = signatureElement.getParentNode(); - } - - if (!found) { - throw new TransformationException( - "envelopedSignatureTransformNotInSignatureElement"); - } - return signatureElement; + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; } - static class EnvelopedNodeFilter implements NodeFilter { - Node exclude; - EnvelopedNodeFilter(Node n) { - exclude=n; + + /** + * @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. + */ + + Node signatureElement = transformObject.getElement(); + + signatureElement = searchSignatureElement(signatureElement); + input.setExcludeNode(signatureElement); + input.addNodeFilter(new EnvelopedNodeFilter(signatureElement)); + return input; + } + + /** + * @param signatureElement + * @return the node that is the signature + * @throws TransformationException + */ + private static Node searchSignatureElement(Node signatureElement) + throws TransformationException { + boolean found = false; + + 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; + } + + signatureElement = signatureElement.getParentNode(); } - public int isNodeIncludeDO(Node n, int level) { - if ((n==exclude)) - return -1; - return 1; + + if (!found) { + throw new TransformationException( + "transform.envelopedSignatureTransformNotInSignatureElement"); + } + return signatureElement; } + + static class EnvelopedNodeFilter implements NodeFilter { + + Node exclude; + + EnvelopedNodeFilter(Node n) { + exclude = n; + } + + 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); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java index f7411344f42..db958096963 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java @@ -2,24 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Transform; 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 @@ import org.w3c.dom.Node; */ 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 engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** - * Method enginePerformTransform - * @inheritDoc - * @param input - * - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { + /** + * 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); - try { + if (xpathElement == null) { + Object exArgs[] = { "ds:XPath", "Transform" }; - /** - * 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()); + 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" + ); + } + 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); + } + } - - Element xpathElement =XMLUtils.selectDsNode( - _transformObject.getElement().getFirstChild(), - Constants._TAG_XPATH,0); - - if (xpathElement == null) { - Object exArgs[] = { "ds:XPath", "Transform" }; - - 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"); - } - - - input.addNodeFilter(new XPathNodeFilter( xpathElement, xpathnode, str)); - 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); } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java index 2d805d13dd2..d35142222ae 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java @@ -2,30 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.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.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 @@ import org.xml.sax.SAXException; /** * Implements the XML Signature XPath Filter v2.0 * - * @author $Author: mullan $ * @see XPath Filter v2.0 (TR) - * @see XPath Filter v2.0 (editors copy) */ 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; - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_XPATH2FILTER; - //J- - // contains the type of the filter + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } - // contains the node set + /** + * Method enginePerformTransform + * @inheritDoc + * @param input + * + * @throws TransformationException + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws TransformationException { + try { + List unionNodes = new ArrayList(); + List subtractNodes = new ArrayList(); + List intersectNodes = new ArrayList(); - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } + Element[] xpathElements = + XMLUtils.selectNodes( + transformObject.getElement().getFirstChild(), + XPath2FilterContainer.XPathFilter2NS, + XPath2FilterContainer._TAG_XPATH2 + ); + if (xpathElements.length == 0) { + Object exArgs[] = { Transforms.TRANSFORM_XPATH2FILTER, "XPath" }; + throw new TransformationException("xml.WrongContent", exArgs); + } + Document inputDoc = null; + if (input.getSubNode() != null) { + inputDoc = XMLUtils.getOwnerDocument(input.getSubNode()); + } else { + inputDoc = XMLUtils.getOwnerDocument(input.getNodeSet()); + } - /** - * Method enginePerformTransform - * @inheritDoc - * @param input - * - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { - CachedXPathAPIHolder.setDoc(_transformObject.getElement().getOwnerDocument()); - try { - List unionNodes=new ArrayList(); - List substractNodes=new ArrayList(); - List intersectNodes=new ArrayList(); + for (int i = 0; i < xpathElements.length; i++) { + Element xpathElement = xpathElements[i]; - CachedXPathFuncHereAPI xPathFuncHereAPI = - new CachedXPathFuncHereAPI(CachedXPathAPIHolder.getCachedXPathAPI()); + XPath2FilterContainer xpathContainer = + XPath2FilterContainer.newInstance(xpathElement, input.getSourceURI()); + String str = + XMLUtils.getStrFromNode(xpathContainer.getXPathFilterTextNode()); - Element []xpathElements =XMLUtils.selectNodes( - _transformObject.getElement().getFirstChild(), - XPath2FilterContainer.XPathFilter2NS, - XPath2FilterContainer._TAG_XPATH2); - int noOfSteps = xpathElements.length; + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPathAPI xpathAPIInstance = xpathFactory.newXPathAPI(); + 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); + } + } - if (noOfSteps == 0) { - Object exArgs[] = { Transforms.TRANSFORM_XPATH2FILTER, "XPath" }; - - throw new TransformationException("xml.WrongContent", exArgs); - } - - Document inputDoc = null; - if (input.getSubNode() != null) { - inputDoc = XMLUtils.getOwnerDocument(input.getSubNode()); - } else { - inputDoc = XMLUtils.getOwnerDocument(input.getNodeSet()); - } - - 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()); - - - 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); - } - } - - - 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 unionNodes, List substractNodes, - List intersectNodes) { - hasUnionFilter=!unionNodes.isEmpty(); - this.unionNodes=convertNodeListToSet(unionNodes); - hasSubstractFilter=!substractNodes.isEmpty(); - this.substractNodes=convertNodeListToSet(substractNodes); - hasIntersectFilter=!intersectNodes.isEmpty(); - this.intersectNodes=convertNodeListToSet(intersectNodes); + + boolean hasUnionFilter; + boolean hasSubtractFilter; + boolean hasIntersectFilter; + Set unionNodes; + Set subtractNodes; + Set intersectNodes; + int inSubtract = -1; + int inIntersect = -1; + int inUnion = -1; + + XPath2NodeFilter(List unionNodes, List subtractNodes, + List 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; + + if (hasSubtractFilter && rooted(currentNode, subtractNodes)) { + result = -1; + } else if (hasIntersectFilter && !rooted(currentNode, intersectNodes)) { + result = 0; } - Set unionNodes; - Set substractNodes; - Set intersectNodes; + //TODO OPTIMIZE + if (result == 1) { + return 1; + } + if (hasUnionFilter) { + if (rooted(currentNode, unionNodes)) { + return 1; + } + result = 0; + } + return result; + } - /** - * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node) - */ - public int isNodeInclude(Node currentNode) { - int result=1; + 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 (hasSubstractFilter && rooted(currentNode, substractNodes)) { - result = -1; - } else if (hasIntersectFilter && !rooted(currentNode, intersectNodes)) { - 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; + } - //TODO OPTIMIZE - if (result==1) - return 1; - if (hasUnionFilter) { - if (rooted(currentNode, unionNodes)) { - return 1; - } - result=0; - } - return result; + 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; - } - } - } - } + /** + * Method rooted + * @param currentNode + * @param nodeList + * + * @return if rooted bye the rootnodes + */ + static boolean rooted(Node currentNode, Set 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; + } - 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; - } - - /** - * Method rooted - * @param currentNode - * @param nodeList - * - * @return if rooted bye the rootnodes - */ - static boolean rooted(Node currentNode, Set 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; - } - - /** - * Method rooted - * @param currentNode - * @param nodeList - * - * @return if rooted bye the rootnodes - */ - static boolean inList(Node currentNode, Set nodeList ) { - return nodeList.contains(currentNode); - } - - private static Set convertNodeListToSet(List l){ - Set result=new HashSet(); + /** + * Method rooted + * @param currentNode + * @param nodeList + * + * @return if rooted bye the rootnodes + */ + static boolean inList(Node currentNode, Set nodeList) { + return nodeList.contains(currentNode); + } + private static Set convertNodeListToSet(List l) { + Set result = new HashSet(); for (NodeList rootNodes : l) { - int length = rootNodes.getLength(); - for (int i = 0; i < length; i++) { - Node rootNode = rootNodes.item(i); - result.add(rootNode); - } + int length = rootNodes.getLength(); + + for (int i = 0; i < length; i++) { + Node rootNode = rootNodes.item(i); + result.add(rootNode); + } } return result; } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java index 71ba9604d1c..e2cae9b0237 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java @@ -2,26 +2,27 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.TransformSpi; 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 @@ import com.sun.org.apache.xml.internal.security.transforms.Transforms; */ 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); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java index 12c8f636ca4..bf9adf5096e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2007 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.ByteArrayInputStream; 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 @@ import org.w3c.dom.Element; */ 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 java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - TransformXSLT.class.getName()); + static final String XSLTSpecNS = "http://www.w3.org/1999/XSL/Transform"; + static final String defaultXSLTSpecNSprefix = "xslt"; + static final String XSLTSTYLESHEET = "stylesheet"; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(TransformXSLT.class.getName()); - /** - * 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); - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream baos, Transform _transformObject) - throws IOException, - TransformationException { - try { - Element transformElement = _transformObject.getElement(); + 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); + Element xsltElement = + XMLUtils.selectNode(transformElement.getFirstChild(), XSLTSpecNS, "stylesheet", 0); - if (_xsltElement == null) { - Object exArgs[] = { "xslt:stylesheet", "Transform" }; + if (xsltElement == null) { + Object exArgs[] = { "xslt:stylesheet", "Transform" }; - throw new TransformationException("xml.WrongContent", exArgs); - } + throw new TransformationException("xml.WrongContent", exArgs); + } - TransformerFactory tFactory = TransformerFactory.newInstance(); + TransformerFactory tFactory = TransformerFactory.newInstance(); + // Process XSLT stylesheets in a secure manner + tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); - // 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 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); + transformer.transform(xmlSource, outputTarget); + return new XMLSignatureInput(baos1.toByteArray()); + } + StreamResult outputTarget = new StreamResult(baos); - 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); + XMLSignatureInput output = new XMLSignatureInput((byte[])null); + output.setOutputStream(baos); + return output; + } catch (XMLSecurityException ex) { + Object exArgs[] = { ex.getMessage() }; - transformer.transform(xmlSource, outputTarget); - 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); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java index f615881bade..2b6f5da2f16 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java @@ -2,30 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 com.sun.org.apache.xml.internal.security.utils.ElementProxy; 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 @@ import org.w3c.dom.Element; * * @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 prefixes) { + /** + * Constructor InclusiveNamespaces + * + * @param doc + * @param prefixes + */ + public InclusiveNamespaces(Document doc, Set prefixes) { + super(doc); - super(doc); + SortedSet prefixList = null; + if (prefixes instanceof SortedSet) { + prefixList = (SortedSet)prefixes; + } else { + prefixList = new TreeSet(prefixes); + } - StringBuffer sb = new StringBuffer(); - SortedSet prefixList = new TreeSet(prefixes); + StringBuilder sb = new StringBuilder(); + 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()); + } + /** + * Constructor InclusiveNamespaces + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public InclusiveNamespaces(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - for (String prefix : prefixList) { - if (prefix.equals("xmlns")) { - sb.append("#default "); - } else { - sb.append(prefix + " "); - } - } + /** + * Method getInclusiveNamespaces + * + * @return The Inclusive Namespace string + */ + public String getInclusiveNamespaces() { + return this.constructionElement.getAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST); + } - this._constructionElement - .setAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST, - sb.toString().trim()); - } + /** + * Decodes the inclusiveNamespaces String and returns all + * selected namespace prefixes as a Set. The #default + * namespace token is represented as an empty namespace prefix + * ("xmlns"). + *
    + * The String inclusiveNamespaces=" xenc ds #default" + * is returned as a Set containing the following Strings: + *
      + *
    • xmlns
    • + *
    • xenc
    • + *
    • ds
    • + *
    + * + * @param inclusiveNamespaces + * @return A set to string + */ + public static SortedSet prefixStr2Set(String inclusiveNamespaces) { + SortedSet prefixes = new TreeSet(); - /** - * Method getInclusiveNamespaces - * - * @return The Inclusive Namespace string - */ - public String getInclusiveNamespaces() { - return this._constructionElement - .getAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST); - } + if ((inclusiveNamespaces == null) || (inclusiveNamespaces.length() == 0)) { + return prefixes; + } - /** - * Constructor InclusiveNamespaces - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public InclusiveNamespaces(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + String[] tokens = inclusiveNamespaces.split("\\s"); + for (String prefix : tokens) { + if (prefix.equals("#default")) { + prefixes.add("xmlns"); + } else { + prefixes.add(prefix); + } + } - /** - * Decodes the inclusiveNamespaces String and returns all - * selected namespace prefixes as a Set. The #default - * namespace token is represented as an empty namespace prefix - * ("xmlns"). - *
    - * The String inclusiveNamespaces=" xenc ds #default" - * is returned as a Set containing the following Strings: - *
      - *
    • xmlns
    • - *
    • xenc
    • - *
    • ds
    • - *
    - * - * @param inclusiveNamespaces - * @return A set to string - */ - public static SortedSet prefixStr2Set(String inclusiveNamespaces) { + return prefixes; + } - SortedSet prefixes = new TreeSet(); + /** + * Method getBaseNamespace + * + * @inheritDoc + */ + public String getBaseNamespace() { + return InclusiveNamespaces.ExclusiveCanonicalizationNamespace; + } - if ((inclusiveNamespaces == null) - || (inclusiveNamespaces.length() == 0)) { - return prefixes; - } - - StringTokenizer st = new StringTokenizer(inclusiveNamespaces, " \t\r\n"); - - while (st.hasMoreTokens()) { - String prefix = st.nextToken(); - - if (prefix.equals("#default")) { - prefixes.add("xmlns" ); - } else { - prefixes.add( prefix); - } - } - - return prefixes; - } - - /** - * 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java index 366f31acf80..19de51976cf 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; - /** * Implements the parameters for the XPath Filter v2.0. * - * @author $Author: mullan $ + * @author $Author: coheigea $ * @see XPath Filter v2.0 (TR) - * @see XPath Filter v2.0 (editors copy) */ -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() { + /** + * Constructor XPath2FilterContainer + * + */ + private XPath2FilterContainer() { + // no instantiation + } - // no instantiation - } + /** + * Constructor XPath2FilterContainer + * + * @param doc + * @param xpath2filter + * @param filterType + */ + private XPath2FilterContainer(Document doc, String xpath2filter, String filterType) { + super(doc); - /** - * Constructor XPath2FilterContainer - * - * @param doc - * @param xpath2filter - * @param filterType - */ - private XPath2FilterContainer(Document doc, String xpath2filter, - String filterType) { + this.constructionElement.setAttributeNS( + null, XPath2FilterContainer._ATT_FILTER, filterType); + this.constructionElement.appendChild(doc.createTextNode(xpath2filter)); + } - super(doc); + /** + * Constructor XPath2FilterContainer + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + private XPath2FilterContainer(Element element, String BaseURI) throws XMLSecurityException { - this._constructionElement - .setAttributeNS(null, XPath2FilterContainer._ATT_FILTER, filterType); - this._constructionElement.appendChild(doc.createTextNode(xpath2filter)); - } + super(element, BaseURI); - /** - * Constructor XPath2FilterContainer - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - private XPath2FilterContainer(Element element, String BaseURI) - throws XMLSecurityException { + String filterStr = + this.constructionElement.getAttributeNS(null, XPath2FilterContainer._ATT_FILTER); - super(element, BaseURI); + 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 }; - String filterStr = this._constructionElement.getAttributeNS(null, - XPath2FilterContainer._ATT_FILTER); + throw new XMLSecurityException("attributeValueIllegal", exArgs); + } + } - 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 }; + /** + * 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); + } - throw new XMLSecurityException("attributeValueIllegal", exArgs); - } - } + /** + * 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); + } - /** - * Creates a new XPath2FilterContainer with the filter type "intersect". - * - * @param doc - * @param xpath2filter - * @return the filter. - */ - public static XPath2FilterContainer newInstanceIntersect(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_INTERSECT); - } + /** + * Method newInstances + * + * @param doc + * @param params + * @return the nodelist with the data + */ + public static NodeList newInstances(Document doc, String[][] params) { + HelperNodeList nl = new HelperNodeList(); - /** - * Creates a new XPath2FilterContainer with the filter type "subtract". - * - * @param doc - * @param xpath2filter - * @return the filter. - */ - public static XPath2FilterContainer newInstanceSubtract(Document doc, - String xpath2filter) { + XMLUtils.addReturnToElement(doc, nl); - return new XPath2FilterContainer(doc, xpath2filter, - XPath2FilterContainer - ._ATT_FILTER_VALUE_SUBTRACT); - } + for (int i = 0; i < params.length; i++) { + String type = params[i][0]; + String xpath = params[i][1]; - /** - * Creates a new XPath2FilterContainer with the filter type "union". - * - * @param doc - * @param xpath2filter - * @return the filter - */ - public static XPath2FilterContainer newInstanceUnion(Document doc, - String xpath2filter) { + 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"); + } - return new XPath2FilterContainer(doc, xpath2filter, - XPath2FilterContainer - ._ATT_FILTER_VALUE_UNION); - } + XPath2FilterContainer c = new XPath2FilterContainer(doc, xpath, type); - /** - * Method newInstances - * - * @param doc - * @param params - * @return the nodelist with the data - */ - public static NodeList newInstances(Document doc, String[][] params) { + nl.appendChild(c.getElement()); + XMLUtils.addReturnToElement(doc, nl); + } - HelperNodeList nl = new HelperNodeList(); + return nl; + } - XMLUtils.addReturnToElement(doc, 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); + } - for (int i = 0; i < params.length; i++) { - String type = params[i][0]; - String xpath = params[i][1]; + /** + * Returns true if the Filter attribute has value "intersect". + * + * @return true if the Filter attribute has value "intersect". + */ + public boolean isIntersect() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer._ATT_FILTER + ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT); + } - 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"); - } + /** + * Returns true if the Filter attribute has value "subtract". + * + * @return true if the Filter attribute has value "subtract". + */ + public boolean isSubtract() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer._ATT_FILTER + ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT); + } - XPath2FilterContainer c = new XPath2FilterContainer(doc, xpath, type); + /** + * Returns true if the Filter attribute has value "union". + * + * @return true if the Filter attribute has value "union". + */ + public boolean isUnion() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer._ATT_FILTER + ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION); + } - nl.appendChild(c.getElement()); - XMLUtils.addReturnToElement(doc, nl); - } + /** + * Returns the XPath 2 Filter String + * + * @return the XPath 2 Filter String + */ + public String getXPathFilterStr() { + return this.getTextFromTextChild(); + } - return nl; - } + /** + * 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: here()/ds:Signature[1] + * @return the first Text node which contains information from the XPath 2 Filter String + */ + public Node getXPathFilterTextNode() { - /** - * 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); - } + NodeList children = this.constructionElement.getChildNodes(); + int length = children.getLength(); - /** - * Returns true if the Filter attribute has value "intersect". - * - * @return true if the Filter attribute has value "intersect". - */ - public boolean isIntersect() { + for (int i = 0; i < length; i++) { + if (children.item(i).getNodeType() == Node.TEXT_NODE) { + return children.item(i); + } + } - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER) - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT); - } + return null; + } - /** - * Returns true if the Filter attribute has value "subtract". - * - * @return true if the Filter attribute has value "subtract". - */ - public boolean isSubtract() { + /** + * Method getBaseLocalName + * + * @return the XPATH2 tag + */ + public final String getBaseLocalName() { + return XPath2FilterContainer._TAG_XPATH2; + } - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER) - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT); - } - - /** - * Returns true if the Filter attribute has value "union". - * - * @return true if the Filter attribute has value "union". - */ - public boolean isUnion() { - - 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 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: here()/ds:Signature[1] - * @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; - } - - /** - * 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java index 25008eed743..2eed2cb1fdf 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; - /** * Implements the parameters for the XPath Filter v2.0. * - * @author $Author: mullan $ + * @author $Author: coheigea $ * @see XPath Filter v2.0 (TR) - * @see XPath Filter v2.0 (editors copy) */ -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) { + /** + * 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_INTERSECT); - } + /** + * 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 new XPath2FilterContainer04 with the filter type "subtract". - * - * @param doc - * @param xpath2filter - * @return the instance - */ - public static XPath2FilterContainer04 newInstanceSubtract(Document doc, - String xpath2filter) { + /** + * 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); + } - return new XPath2FilterContainer04(doc, xpath2filter, - XPath2FilterContainer04 - ._ATT_FILTER_VALUE_SUBTRACT); - } + /** + * Returns true if the Filter attribute has value "intersect". + * + * @return true if the Filter attribute has value "intersect". + */ + public boolean isIntersect() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER + ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT); + } - /** - * Creates a new XPath2FilterContainer04 with the filter type "union". - * - * @param doc - * @param xpath2filter - * @return the instance - */ - public static XPath2FilterContainer04 newInstanceUnion(Document doc, - String xpath2filter) { + /** + * Returns true if the Filter attribute has value "subtract". + * + * @return true if the Filter attribute has value "subtract". + */ + public boolean isSubtract() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER + ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT); + } - return new XPath2FilterContainer04(doc, xpath2filter, - XPath2FilterContainer04 - ._ATT_FILTER_VALUE_UNION); - } + /** + * Returns true if the Filter attribute has value "union". + * + * @return true if the Filter attribute has value "union". + */ + public boolean isUnion() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER + ).equals(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); - } + /** + * Returns the XPath 2 Filter String + * + * @return the XPath 2 Filter String + */ + public String getXPathFilterStr() { + return this.getTextFromTextChild(); + } - /** - * Returns true if the Filter attribute has value "intersect". - * - * @return true if the Filter attribute has value "intersect". - */ - public boolean isIntersect() { + /** + * 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: here()/ds:Signature[1] + * @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(); - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER) - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT); - } + for (int i = 0; i < length; i++) { + if (children.item(i).getNodeType() == Node.TEXT_NODE) { + return children.item(i); + } + } - /** - * Returns true if the Filter attribute has value "subtract". - * - * @return true if the Filter attribute has value "subtract". - */ - public boolean isSubtract() { + return null; + } - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER) - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT); - } + /** @inheritDoc */ + public final String getBaseLocalName() { + return XPath2FilterContainer04._TAG_XPATH2; + } - /** - * Returns true if the Filter attribute has value "union". - * - * @return true if the Filter attribute has value "union". - */ - public boolean isUnion() { - - 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 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: here()/ds:Signature[1] - * @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; - } - - /** @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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java index 717889d576f..74f2ff1f50d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java @@ -2,26 +2,27 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Text; - /** * This Object serves both as namespace prefix resolver and as container for * the ds:XPath Element. It implements the {@link org.w3c.dom.Element} interface @@ -39,45 +39,44 @@ import org.w3c.dom.Text; */ 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 ds:XPath Element. - * - * @param xpath - */ - public void setXPath(String xpath) { + /** + * Sets the TEXT value of the ds:XPath Element. + * + * @param xpath + */ + public void setXPath(String xpath) { + if (this.constructionElement.getChildNodes() != null) { + NodeList nl = this.constructionElement.getChildNodes(); - 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 ds:XPath Element. + * + * @return the TEXT value of the ds:XPath Element. + */ + public String getXPath() { + return this.getTextFromTextChild(); + } - /** - * Returns the TEXT value of the ds:XPath Element. - * - * @return the TEXT value of the ds:XPath Element. - */ - public String getXPath() { - return this.getTextFromTextChild(); - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_XPATH; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_XPATH; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java index 86199d7ab63..0bb4f7e5f09 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java @@ -2,320 +2,315 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 { - /** Field _ATT_FILTER_VALUE_INTERSECT */ - private static final String _TAG_INCLUDE_BUT_SEARCH = "IncludeButSearch"; + public static final String TRANSFORM_XPATHFILTERCHGP = + "http://www.nue.et-inf.uni-siegen.de/~geuer-pollmann/#xpathFilter"; - /** Field _ATT_FILTER_VALUE_SUBTRACT */ - private static final String _TAG_EXCLUDE_BUT_SEARCH = "ExcludeButSearch"; + /** Field _ATT_FILTER_VALUE_INTERSECT */ + private static final String _TAG_INCLUDE_BUT_SEARCH = "IncludeButSearch"; - /** Field _ATT_FILTER_VALUE_UNION */ - private static final String _TAG_EXCLUDE = "Exclude"; + /** Field _ATT_FILTER_VALUE_SUBTRACT */ + private static final String _TAG_EXCLUDE_BUT_SEARCH = "ExcludeButSearch"; - /** Field _TAG_XPATHCHGP */ - public static final String _TAG_XPATHCHGP = "XPathAlternative"; + /** Field _ATT_FILTER_VALUE_UNION */ + private static final String _TAG_EXCLUDE = "Exclude"; - /** Field _ATT_INCLUDESLASH */ - public static final String _ATT_INCLUDESLASH = "IncludeSlashPolicy"; + /** Field _TAG_XPATHCHGP */ + public static final String _TAG_XPATHCHGP = "XPathAlternative"; - /** Field IncludeSlash */ - public static final boolean IncludeSlash = true; + /** Field _ATT_INCLUDESLASH */ + public static final String _ATT_INCLUDESLASH = "IncludeSlashPolicy"; - /** Field ExcludeSlash */ - public static final boolean ExcludeSlash = false; + /** Field IncludeSlash */ + public static final boolean IncludeSlash = true; - /** - * Constructor XPathFilterCHGPContainer - * - */ - private XPathFilterCHGPContainer() { + /** Field ExcludeSlash */ + public static final boolean ExcludeSlash = false; - // 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) { + /** + * 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); - super(doc); + if (includeSlashPolicy) { + this.constructionElement.setAttributeNS( + null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "true" + ); + } else { + this.constructionElement.setAttributeNS( + null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "false" + ); + } - 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 ((includeButSearch != null) - && (includeButSearch.trim().length() > 0)) { - Element includeButSearchElem = - ElementProxy.createElementForFamily(doc, this.getBaseNamespace(), - XPathFilterCHGPContainer - ._TAG_INCLUDE_BUT_SEARCH); + includeButSearchElem.appendChild( + this.doc.createTextNode(indentXPathText(includeButSearch)) + ); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(includeButSearchElem); + } - includeButSearchElem - .appendChild(this._doc - .createTextNode(indentXPathText(includeButSearch))); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(includeButSearchElem); - } + if ((excludeButSearch != null) && (excludeButSearch.trim().length() > 0)) { + Element excludeButSearchElem = + ElementProxy.createElementForFamily( + doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH + ); - 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))); - excludeButSearchElem - .appendChild(this._doc - .createTextNode(indentXPathText(excludeButSearch))); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(excludeButSearchElem); - } + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(excludeButSearchElem); + } - if ((exclude != null) && (exclude.trim().length() > 0)) { - Element excludeElem = ElementProxy.createElementForFamily(doc, - this.getBaseNamespace(), - XPathFilterCHGPContainer._TAG_EXCLUDE); + if ((exclude != null) && (exclude.trim().length() > 0)) { + Element excludeElem = + ElementProxy.createElementForFamily( + doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_EXCLUDE); - excludeElem - .appendChild(this._doc.createTextNode(indentXPathText(exclude))); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(excludeElem); - } + excludeElem.appendChild(this.doc.createTextNode(indentXPathText(exclude))); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(excludeElem); + } - XMLUtils.addReturnToElement(this._constructionElement); - } + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method indentXPathText - * - * @param xp - * @return the string with enters - */ - static String indentXPathText(String xp) { + /** + * 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; + } - if ((xp.length() > 2) && (!Character.isWhitespace(xp.charAt(0)))) { - return "\n" + xp + "\n"; - } - return xp; + /** + * Constructor XPathFilterCHGPContainer + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + private XPathFilterCHGPContainer(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - } + /** + * 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); + } - /** - * Constructor XPathFilterCHGPContainer - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - private XPathFilterCHGPContainer(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * 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); + } - /** - * 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) { + /** + * Method getXStr + * + * @param type + * @return The Xstr + */ + private String getXStr(String type) { + if (this.length(this.getBaseNamespace(), type) != 1) { + return ""; + } - return new XPathFilterCHGPContainer(doc, includeSlashPolicy, - includeButSearch, excludeButSearch, - exclude); - } + 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) { + /** + * Method getIncludeButSearch + * + * @return the string + */ + public String getIncludeButSearch() { + return this.getXStr(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); + } - if (this.length(this.getBaseNamespace(), type) != 1) { - return ""; - } + /** + * Method getExcludeButSearch + * + * @return the string + */ + public String getExcludeButSearch() { + return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); + } - Element xElem = XMLUtils.selectNode(this._constructionElement.getFirstChild(), this.getBaseNamespace(), - type,0); + /** + * Method getExclude + * + * @return the string + */ + public String getExclude() { + return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE); + } - return XMLUtils.getFullTextChildrenFromElement(xElem); - } + /** + * Method getIncludeSlashPolicy + * + * @return the string + */ + public boolean getIncludeSlashPolicy() { + return this.constructionElement.getAttributeNS( + null, XPathFilterCHGPContainer._ATT_INCLUDESLASH).equals("true"); + } - /** - * Method getIncludeButSearch - * - * @return the string - */ - public String getIncludeButSearch() { - return this.getXStr(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); - } + /** + * 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: here()/ds:Signature[1] + * @param type + * @return the first Text node which contains information from the XPath 2 Filter String + */ + private Node getHereContextNode(String type) { - /** - * Method getExcludeButSearch - * - * @return the string - */ - public String getExcludeButSearch() { - return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); - } + if (this.length(this.getBaseNamespace(), type) != 1) { + return null; + } - /** - * Method getExclude - * - * @return the string - */ - public String getExclude() { - return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE); - } + return XMLUtils.selectNodeText( + this.constructionElement.getFirstChild(), this.getBaseNamespace(), type, 0 + ); + } - /** - * Method getIncludeSlashPolicy - * - * @return the string - */ - public boolean getIncludeSlashPolicy() { + /** + * Method getHereContextNodeIncludeButSearch + * + * @return the string + */ + public Node getHereContextNodeIncludeButSearch() { + return this.getHereContextNode(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); + } - return this._constructionElement - .getAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH) - .equals("true"); - } + /** + * Method getHereContextNodeExcludeButSearch + * + * @return the string + */ + public Node getHereContextNodeExcludeButSearch() { + return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); + } - /** - * 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: here()/ds:Signature[1] - * @param type - * @return the first Text node which contains information from the XPath 2 Filter String - */ - private Node getHereContextNode(String type) { + /** + * Method getHereContextNodeExclude + * + * @return the string + */ + public Node getHereContextNodeExclude() { + return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE); + } - if (this.length(this.getBaseNamespace(), type) != 1) { - return null; - } + /** + * Method getBaseLocalName + * + * @inheritDoc + */ + public final String getBaseLocalName() { + return XPathFilterCHGPContainer._TAG_XPATHCHGP; + } - return XMLUtils.selectNodeText(this._constructionElement.getFirstChild(), this.getBaseNamespace(), - type,0); - } - - /** - * Method getHereContextNodeIncludeButSearch - * - * @return the string - */ - public Node getHereContextNodeIncludeButSearch() { - return this - .getHereContextNode(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); - } - - /** - * Method getHereContextNodeExcludeButSearch - * - * @return the string - */ - public Node getHereContextNodeExcludeButSearch() { - return this - .getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); - } - - /** - * Method getHereContextNodeExclude - * - * @return the string - */ - public Node getHereContextNodeExclude() { - return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE); - } - - /** - * Method getBaseLocalName - * - * @inheritDoc - */ - public final String getBaseLocalName() { - return XPathFilterCHGPContainer._TAG_XPATHCHGP; - } - - /** - * Method getBaseNamespace - * - * @inheritDoc - */ - public final String getBaseNamespace() { - return Transforms.TRANSFORM_XPATHFILTERCHGP; - } + /** + * Method getBaseNamespace + * + * @inheritDoc + */ + public final String getBaseNamespace() { + return TRANSFORM_XPATHFILTERCHGP; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java index 9e9c7de8b0f..db1f49eaee4 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Element; 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 RFC 2045 + * @see RFC 2045 * @see com.sun.org.apache.xml.internal.security.transforms.implementations.TransformBase64Decode */ public class Base64 { - - /** Field BASE64DEFAULTLENGTH */ - public static final int BASE64DEFAULTLENGTH = 76; - - private Base64() { - // we don't allow instantiation - } - - /** - * Returns a byte-array representation of a {@link BigInteger}. - * No sign-bit is outputed. - * - * N.B.: {@link BigInteger}'s toByteArray - * retunrs eventually longer arrays because of the leading sign-bit. - * - * @param big BigInteger to be converted - * @param bitlen int the desired length in bits of the representation - * @return a byte array with bitlen bits of big - */ - static final byte[] getBytes(BigInteger big, int bitlen) { - - //round bitlen - bitlen = ((bitlen + 7) >> 3) << 3; - - if (bitlen < big.bitLength()) { - throw new IllegalArgumentException(I18n - .translate("utils.Base64.IllegalBitlength")); - } - - byte[] bigBytes = big.toByteArray(); - - 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]; - - System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); - - return resizedBytes; - - } - - /** - * Encode in Base64 the given {@link BigInteger}. - * - * @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 {@link BigInteger}. - * No sign-bit is outputed. - * - * N.B.: {@link BigInteger}'s toByteArray - * retunrs eventually longer arrays because of the leading sign-bit. - * - * @param big BigInteger to be converted - * @param bitlen int the desired length in bits of the representation - * @return a byte array with bitlen bits of big - */ - public static final byte[] encode(BigInteger big, int bitlen) { - - //round bitlen - bitlen = ((bitlen + 7) >> 3) << 3; - - if (bitlen < big.bitLength()) { - throw new IllegalArgumentException(I18n - .translate("utils.Base64.IllegalBitlength")); - } - - byte[] bigBytes = big.toByteArray(); - - 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]; - - System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); - - return resizedBytes; - - } - - /** - * 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 (encodedInt.length() > 76) { - encodedInt = "\n" + encodedInt + "\n"; - } - - Document doc = element.getOwnerDocument(); - Text text = doc.createTextNode(encodedInt); - - element.appendChild(text); - } - - /** - * Method decode - * - * Takes the Text children of the Element and interprets - * them as input for the Base64.decode() 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; - - sb.append(t.getData()); - } - sibling=sibling.getNextSibling(); - } - - return decode(sb.toString()); - } - - /** - * 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)); - - el.appendChild(text); - - return el; - } - - /** - * 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); - } - - - - /** - * Encode a byte array and fold lines at the standard 76th character unless - * ignore line breaks property is set. - * - * @param binaryData byte[] to be base64 encoded - * @return the String with encoded data - */ - public static final String encode(byte[] binaryData) { - return XMLUtils.ignoreLineBreaks() - ? encode(binaryData, Integer.MAX_VALUE) - : encode(binaryData, BASE64DEFAULTLENGTH); - } - - /** - * 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(); - } - - 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= '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); - - for (int i = 52, j = 0; i<=61; i++, j++) - lookUpBase64Alphabet[i] = (char)('0' + j); - lookUpBase64Alphabet[62] = '+'; - lookUpBase64Alphabet[63] = '/'; - - } - - 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); - } - - - /** - * 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 byte[] data to be encoded - * @param length int length of wrapped lines; No wrapping if less than 4. - * @return a String with encoded data - */ - public static final String encode(byte[] binaryData,int length) { - - if (length<4) { - length=Integer.MAX_VALUE; + /** Field BASE64DEFAULTLENGTH */ + public static final int BASE64DEFAULTLENGTH = 76; + + 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]; + + 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); } - if (binaryData == null) - return null; + for (int i = '9'; i >= '0'; i--) { + base64Alphabet[i] = (byte) (i - '0' + 52); + } - int lengthDataBits = binaryData.length*EIGHTBIT; - if (lengthDataBits == 0) { - return ""; - } + base64Alphabet['+'] = 62; + base64Alphabet['/'] = 63; - 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; + for (int i = 0; i <= 25; i++) { + lookUpBase64Alphabet[i] = (char)('A' + i); + } - encodedData = new char[numberQuartet*4+numberLines]; + for (int i = 26, j = 0; i <= 51; i++, j++) { + lookUpBase64Alphabet[i] = (char)('a' + j); + } - byte k=0, l=0, b1=0,b2=0,b3=0; + for (int i = 52, j = 0; i <= 61; i++, j++) { + lookUpBase64Alphabet[i] = (char)('0' + j); + } + lookUpBase64Alphabet[62] = '+'; + lookUpBase64Alphabet[63] = '/'; + } - 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; - } - - for (; i>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 ]; - } - - // 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 ); - - 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++] = lookUpBase64Alphabet[ val1 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ l<<2 ]; - encodedData[encodedIndex++] = PAD; - } - - //encodedData[encodedIndex] = 0xa; - - return new String(encodedData); - } + private Base64() { + // we don't allow instantiation + } /** - * Decodes Base64 data into octects + * Returns a byte-array representation of a {@link BigInteger}. + * No sign-bit is output. + * + * N.B.: {@link BigInteger}'s toByteArray + * returns eventually longer arrays because of the leading sign-bit. + * + * @param big BigInteger to be converted + * @param bitlen int the desired length in bits of the representation + * @return a byte array with bitlen bits of big + */ + static final byte[] getBytes(BigInteger big, int bitlen) { + + //round bitlen + bitlen = ((bitlen + 7) >> 3) << 3; + + if (bitlen < big.bitLength()) { + throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength")); + } + + byte[] bigBytes = big.toByteArray(); + + 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]; + + System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); + + return resizedBytes; + } + + /** + * Encode in Base64 the given {@link BigInteger}. + * + * @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 {@link BigInteger}. + * No sign-bit is output. + * + * N.B.: {@link BigInteger}'s toByteArray + * returns eventually longer arrays because of the leading sign-bit. + * + * @param big BigInteger to be converted + * @param bitlen int the desired length in bits of the representation + * @return a byte array with bitlen bits of big + */ + public static final byte[] encode(BigInteger big, int bitlen) { + + //round bitlen + bitlen = ((bitlen + 7) >> 3) << 3; + + if (bitlen < big.bitLength()) { + throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength")); + } + + byte[] bigBytes = big.toByteArray(); + + 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]; + + 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 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"; + } + + Document doc = element.getOwnerDocument(); + Text text = doc.createTextNode(encodedInt); + + element.appendChild(text); + } + + /** + * Method decode + * + * Takes the Text children of the Element and interprets + * them as input for the Base64.decode() 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; + + sb.append(t.getData()); + } + sibling = sibling.getNextSibling(); + } + + return decode(sb.toString()); + } + + /** + * 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)); + + el.appendChild(text); + + return el; + } + + /** + * 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 byte[] to be base64 encoded + * @return the String with encoded data + */ + public static final String encode(byte[] binaryData) { + return XMLUtils.ignoreLineBreaks() + ? encode(binaryData, Integer.MAX_VALUE) + : encode(binaryData, BASE64DEFAULTLENGTH); + } + + /** + * 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 { + + byte[] retBytes = null; + UnsyncByteArrayOutputStream baos = null; + try { + baos = new UnsyncByteArrayOutputStream(); + String line; + + 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); + } + + protected static final boolean isPad(byte octect) { + return (octect == PAD); + } + + /** + * 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 byte[] data to be encoded + * @param length int length of wrapped lines; No wrapping if less than 4. + * @return a String with encoded data + */ + public static final String encode(byte[] binaryData,int length) { + if (length < 4) { + length = Integer.MAX_VALUE; + } + + 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; + } + + 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]; + } + + // 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); + + 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++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2]; + encodedData[encodedIndex++] = PAD; + } + + //encodedData[encodedIndex] = 0xa; + + return new String(encodedData); + } + + /** + * 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); - return decodeInternal(bytes, len); + 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]; + } + byte decodedData[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; - int i = 0; - int encodedIndex = 0; - int dataIndex = 0; + 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)) { - throw new Base64DecodingException("decoding.general");//if found "no data" just return null + //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 { - - // remove white spaces - if (len==-1) - len = removeWhiteSpace(base64Data); - - if (len%FOURBYTE != 0) { - throw new Base64DecodingException("decoding.divisible.four"); - //should be divisible by four + decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4) ; + decodedData[encodedIndex++] = (byte)(((b2 & 0xf) << 4) |((b3 >> 2) & 0xf)); + decodedData[encodedIndex++] = (byte)(b3 << 6 | b4 ); + } + return decodedData; } - int numberQuadruple = (len/FOURBYTE ); + /** + * 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); + } - if (numberQuadruple == 0) - return; + /** + * 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); + } - //byte decodedData[] = null; - byte b1=0,b2=0,b3=0, b4=0; + protected static final void decode(byte[] base64Data, OutputStream os, int len) + throws Base64DecodingException, IOException { + // remove white spaces + if (len == -1) { + len = removeWhiteSpace(base64Data); + } - int i = 0; + if (len % FOURBYTE != 0) { + throw new Base64DecodingException("decoding.divisible.four"); + //should be divisible by four + } - int dataIndex = 0; + int numberQuadruple = (len / FOURBYTE); - //the begin - for (i=numberQuadruple-1; i>0; i--) { + if (numberQuadruple == 0) { + return; + } + + //byte decodedData[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; + + int i = 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"); + } + + 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; + } - os.write((byte)( b1 <<2 | b2>>4 ) ); - os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - os.write((byte)( b3<<6 | b4 )); - } + if ((data[index++] = readed) == -1) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); + } - 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; + if (index != 4) { + continue; + } + index = 0; + b1 = base64Alphabet[data[0]]; + b2 = base64Alphabet[data[1]]; + b3 = base64Alphabet[data[2]]; + b4 = base64Alphabet[data[3]]; - // 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; - } + 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)); + } + } + + /** + * 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java deleted file mode 100644 index 0a7503a9331..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java +++ /dev/null @@ -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 local=new ThreadLocal(); - static ThreadLocal localDoc=new ThreadLocal(); - - /** - * 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; - } -} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java deleted file mode 100644 index fe1ae841755..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java +++ /dev/null @@ -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 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"); - } - } - } -} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java new file mode 100644 index 00000000000..c9b910a4611 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java @@ -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.

    This method will try to load the resource + * using the following methods (in order): + *

      + *
    • From Thread.currentThread().getContextClassLoader() + *
    • From ClassLoaderUtil.class.getClassLoader() + *
    • callingClass.getClassLoader() + *
    + * + * @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.

    This method will try to load the resources + * using the following methods (in order): + *

      + *
    • From Thread.currentThread().getContextClassLoader() + *
    • From ClassLoaderUtil.class.getClassLoader() + *
    • callingClass.getClassLoader() + *
    + * + * @param resourceName The name of the resource to load + * @param callingClass The Class object of the calling object + */ + static List getResources(String resourceName, Class callingClass) { + List ret = new ArrayList(); + Enumeration urls = new Enumeration() { + 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.

    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.

    It will try to load the class in the + * following order: + *

      + *
    • From Thread.currentThread().getContextClassLoader() + *
    • Using the basic Class.forName() + *
    • From ClassLoaderUtil.class.getClassLoader() + *
    • From the callingClass.getClassLoader() + *
    + * + * @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; + } + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java index 39ec71d8794..78907b09595 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; * XML * Signature specification. * - * @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 configurationFileNew */ + public static final String configurationFileNew = ".xmlsecurityconfig"; - /** Field exceptionMessagesResourceBundleDir */ - public static final String exceptionMessagesResourceBundleDir = - "com/sun/org/apache/xml/internal/security/resource"; + /** Field exceptionMessagesResourceBundleDir */ + public static final String exceptionMessagesResourceBundleDir = + "com/sun/org/apache/xml/internal/security/resource"; - /** Field exceptionMessagesResourceBundleBase is the location of the ResourceBundle */ - public static final String exceptionMessagesResourceBundleBase = - exceptionMessagesResourceBundleDir + "/" + "xmlsecurity"; - //J- - /** - * The URL of the XML Signature specification - */ - public static final String SIGNATURESPECIFICATION_URL = "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; + /** Field exceptionMessagesResourceBundleBase is the location of the ResourceBundle */ + public static final String exceptionMessagesResourceBundleBase = + exceptionMessagesResourceBundleDir + "/" + "xmlsecurity"; - /** - * The namespace of the XML Signature specification - */ - 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/"; + /** + * The URL of the + * XML Signature specification + */ + 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"; - /** Tag of Attr Encoding**/ - public static final String _ATT_ENCODING = "Encoding"; - /** Tag of Attr Target**/ - public static final String _ATT_TARGET = "Target"; + /** + * The namespace of the + * XML Signature specification + */ + public static final String SignatureSpecNS = "http://www.w3.org/2000/09/xmldsig#"; - // 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) + /** + * The namespace of the + * XML Signature specification + */ + public static final String SignatureSpec11NS = "http://www.w3.org/2009/xmldsig11#"; - /** 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"; + /** The URL for more algorithms **/ + public static final String MoreAlgorithmsSpecNS = "http://www.w3.org/2001/04/xmldsig-more#"; - /** Digest - Required SHA1 */ - public static final String ALGO_ID_DIGEST_SHA1 = SignatureSpecNS + "sha1"; + /** The URI for XML spec*/ + public static final String XML_LANG_SPACE_SpecNS = "http://www.w3.org/XML/1998/namespace"; - /** - * @see - * draft-blake-wilson-xmldsig-ecdsa-02.txt - */ - public static final String ALGO_ID_SIGNATURE_ECDSA_CERTICOM = "http://www.certicom.com/2000/11/xmlecdsig#ecdsa-sha1"; - //J+ + /** The URI for XMLNS spec*/ + public static final String NamespaceSpecNS = "http://www.w3.org/2000/xmlns/"; - private Constants() { - // we don't allow instantiation - } + /** Tag of Attr Algorithm**/ + public static final String _ATT_ALGORITHM = "Algorithm"; - /** - * Sets the namespace prefix which will be used to identify elements in the - * XML Signature Namespace. - * - *
    -    * Constants.setSignatureSpecNSprefix("dsig");
    -    * 
    - * - * @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 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"; + + // 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 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 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"; + + /** Digest - Required SHA1 */ + public static final String ALGO_ID_DIGEST_SHA1 = SignatureSpecNS + "sha1"; + + /** + * @see + * draft-blake-wilson-xmldsig-ecdsa-02.txt + */ + 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 + } - /** - * Returns the XML namespace prefix which is used for elements in the XML - * Signature namespace. - * - * It is defaulted to dsig, 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); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java new file mode 100644 index 00000000000..b4572b481ca --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java @@ -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 namespaceMap = new HashMap(); + + 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 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()); + } + } + } + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java index bdf560dc78e..bd06b7d7c27 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorith * */ 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 class DigesterOutputStream extends ByteArrayOutputStream { 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 @@ public class DigesterOutputStream extends ByteArrayOutputStream { * @return the digest value */ public byte[] getDigestValue() { - return mda.digest(); + return mda.digest(); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java index 9da45ce8cd1..618659c9f19 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java @@ -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); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java index 5a94927d1c6..d71fd100384 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java @@ -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; + } - String localnameSHOULDBE = expected.getBaseLocalName(); - String namespaceSHOULDBE = expected.getBaseNamespace(); + /** A checker for DOM that interns NS */ + public static class InternedNsChecker extends ElementCheckerImpl { + public void guaranteeThatElementInCorrectSpace( + ElementProxy expected, Element actual + ) throws XMLSecurityException { - 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); - } - } + String expectedLocalname = expected.getBaseLocalName(); + String expectedNamespace = 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); + } } + } - /** An empty checker if schema checking is used */ - public static class EmptyChecker extends ElementCheckerImpl { - public void guaranteeThatElementInCorrectSpace(ElementProxy expected, - Element actual) throws XMLSecurityException { - } + /** A checker for DOM that interns NS */ + public static class FullChecker extends ElementCheckerImpl { + + 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 { + // empty + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java index 2d2fdeb61bb..ac7a53eba4f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java @@ -45,13 +45,13 @@ public abstract class ElementProxy { 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 prefixMappings = new ConcurrentHashMap(); @@ -73,9 +73,9 @@ public abstract class ElementProxy { 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 @@ public abstract class ElementProxy { 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 @@ public abstract class ElementProxy { 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 @@ public abstract class ElementProxy { * @return the Element which was constructed by the Object. */ public final Element getElement() { - return this._constructionElement; + return this.constructionElement; } /** @@ -208,9 +208,9 @@ public abstract class ElementProxy { 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 @@ public abstract class ElementProxy { * @return the Document where this element is contained. */ public Document getDocument() { - return this._doc; + return this.doc; } /** @@ -230,7 +230,7 @@ public abstract class ElementProxy { * @return the base uri of the namespace of this element */ public String getBaseURI() { - return this._baseURI; + return this.baseURI; } /** @@ -243,8 +243,8 @@ public abstract class ElementProxy { 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 abstract class ElementProxy { */ 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 abstract class ElementProxy { */ 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 @@ public abstract class ElementProxy { * @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 abstract class ElementProxy { 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 abstract class ElementProxy { */ 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 @@ public abstract class ElementProxy { ) throws Base64DecodingException { return Base64.decodeBigIntegerFromText( XMLUtils.selectNodeText( - this._constructionElement.getFirstChild(), namespace, localname, 0 + this.constructionElement.getFirstChild(), namespace, localname, 0 ) ); } @@ -360,7 +360,7 @@ public abstract class ElementProxy { 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 abstract class ElementProxy { */ public String getTextFromChildElement(String localname, String namespace) { return XMLUtils.selectNode( - this._constructionElement.getFirstChild(), + this.constructionElement.getFirstChild(), namespace, localname, 0).getTextContent(); @@ -388,7 +388,7 @@ public abstract class ElementProxy { * @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 @@ public abstract class ElementProxy { * element */ public String getTextFromTextChild() { - return XMLUtils.getFullTextChildrenFromElement(this._constructionElement); + return XMLUtils.getFullTextChildrenFromElement(this.constructionElement); } /** @@ -410,7 +410,7 @@ public abstract class ElementProxy { */ 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 @@ public abstract class ElementProxy { 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 @@ public abstract class ElementProxy { 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); - } - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java index e250bff2a16..175911e169f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java @@ -2,179 +2,238 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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; - - -/** - * - * @author $Author: mullan $ - */ public class EncryptionConstants { - //J- - // Attributes that exist in XML Signature in the same way + // 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; + public static final String _ATT_ALGORITHM = Constants._ATT_ALGORITHM; - // 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 Attr Id**/ + public static final String _ATT_ID = Constants._ATT_ID; - /** 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"; + /** Tag of Attr Target **/ + public static final String _ATT_TARGET = Constants._ATT_TARGET; - /** Field ENCRYPTIONSPECIFICATION_URL */ - public static final String ENCRYPTIONSPECIFICATION_URL = "http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/"; + /** Tag of Attr Type **/ + public static final String _ATT_TYPE = Constants._ATT_TYPE; - /** The namespace of the XML Encryption Syntax and Processing */ - public static final String EncryptionSpecNS = "http://www.w3.org/2001/04/xmlenc#"; + /** Tag of Attr URI **/ + public static final String _ATT_URI = Constants._ATT_URI; - /** 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/"; // + "*/*"; + // Attributes new in XML Encryption + /** Tag of Attr encoding **/ + public static final String _ATT_ENCODING = "Encoding"; - /** 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"; + /** Tag of Attr recipient **/ + public static final String _ATT_RECIPIENT = "Recipient"; - /** 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"; + /** Tag of Attr mimetype **/ + public static final String _ATT_MIMETYPE = "MimeType"; - /** Key Agreement - OPTIONAL Diffie-Hellman */ - public static final String ALGO_ID_KEYAGREEMENT_DH = EncryptionConstants.EncryptionSpecNS + "dh"; + /** Tag of Element CarriedKeyName **/ + public static final String _TAG_CARRIEDKEYNAME = "CarriedKeyName"; - /** 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"; + /** Tag of Element CipherData **/ + public static final String _TAG_CIPHERDATA = "CipherData"; - /* - // 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"; - */ + /** Tag of Element CipherReference **/ + public static final String _TAG_CIPHERREFERENCE = "CipherReference"; - /** Message Authentication - RECOMMENDED XML Digital Signature */ - public static final String ALGO_ID_AUTHENTICATION_XMLSIGNATURE = "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; + /** Tag of Element CipherValue **/ + public static final String _TAG_CIPHERVALUE = "CipherValue"; - /** 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"; + /** Tag of Element DataReference **/ + public static final String _TAG_DATAREFERENCE = "DataReference"; - /** Encoding - REQUIRED base64 */ - public static final String ALGO_ID_ENCODING_BASE64 = "http://www.w3.org/2000/09/xmldsig#base64"; - //J+ + /** Tag of Element EncryptedData **/ + public static final String _TAG_ENCRYPTEDDATA = "EncryptedData"; - private EncryptionConstants() { - // we don't allow instantiation - } + /** Tag of Element EncryptedKey **/ + public static final String _TAG_ENCRYPTEDKEY = "EncryptedKey"; - /** - * Method setEncryptionSpecNSprefix - * - * @param newPrefix - * @throws XMLSecurityException - */ - public static void setEncryptionSpecNSprefix(String newPrefix) - throws XMLSecurityException { - ElementProxy.setDefaultPrefix(EncryptionConstants.EncryptionSpecNS, - newPrefix); - } + /** 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 + * + * XML Encryption Syntax and Processing */ + 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#"; + + /** 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"; + + + private EncryptionConstants() { + // we don't allow instantiation + } - /** - * Method getEncryptionSpecNSprefix - * - * @return the prefix for this node. - */ - public static String getEncryptionSpecNSprefix() { - return ElementProxy - .getDefaultPrefix(EncryptionConstants.EncryptionSpecNS); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java index d6fd93d1aa7..53a5cc88c5e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java @@ -2,62 +2,62 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java index cd40b79d47a..8ba53a6153c 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Node; import org.w3c.dom.NodeList; /** - * * @author Christian Geuer-Pollmann - * */ public class HelperNodeList implements NodeList { - /** Field nodes */ - List nodes = new ArrayList(20); - boolean _allNodesMustHaveSameParent = false; + /** Field nodes */ + List nodes = new ArrayList(); + 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) { + /** + * Method item + * + * @param index + * @return node with index i + */ + public Node item(int index) { + return nodes.get(index); + } - // log.log(java.util.logging.Level.FINE, "item(" + index + ") of " + this.getLength() + " nodes"); + /** + * Method getLength + * + * @return length of the list + */ + public int getLength() { + return nodes.size(); + } - return nodes.get(index); - } - - /** - * 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)); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java index 4ee51ac92ab..ea9ec28d6e8 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java @@ -2,85 +2,42 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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... - *
    - * The problem is that if you do not validate a document, you cannot use the - * getElementByID 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 @Id attributes in an Element from the XML - * Signature namespace are of type ID. - * - * @author $Author: mullan $ - * @see "Identity Crisis" on xml.com + * 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>> docMap = - new WeakHashMap>>(); - - /** - * 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> elementMap; - synchronized (docMap) { - elementMap = docMap.get(doc); - if (elementMap == null) { - elementMap = new WeakHashMap>(); - docMap.put(doc, elementMap); - } - } - elementMap.put(idValue, new WeakReference(element)); + // we don't allow instantiation } /** @@ -90,7 +47,7 @@ public class IdResolver { * @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 @@ public class IdResolver { * @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> elementMap; - synchronized (docMap) { - elementMap = docMap.get(doc); - } - if (elementMap != null) { - WeakReference weakReference = elementMap.get(id); - if (weakReference != null) { - return weakReference.get(); - } - } - return null; - } - - private static java.util.List 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;i2) - 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; - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java index 6eae527a570..d06a41ffd20 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java @@ -2,82 +2,80 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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); } - - - /** @inheritDoc */ - public void error(SAXParseException ex) throws SAXException { - if (IgnoreAllErrorHandler.warnOnExceptions) { - log.log(java.util.logging.Level.SEVERE, "", ex); - } - if (IgnoreAllErrorHandler.throwExceptions) { - throw 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 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; + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java new file mode 100644 index 00000000000..242e80ff6e9 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java @@ -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; + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathFactory.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathFactory.java new file mode 100644 index 00000000000..98c1872898a --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathFactory.java @@ -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(); + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java index 540c722f45c..cf55f4088ba 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import java.io.InputStream; */ 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 @@ public class JavaUtils { * 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 @@ public class JavaUtils { 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 @@ public class JavaUtils { refBytes = baos.toByteArray(); } finally { - fisRef.close(); + if (baos != null) { + baos.close(); + } + if (fisRef != null) { + fisRef.close(); + } } return refBytes; @@ -80,7 +89,6 @@ public class JavaUtils { * @param bytes */ public static void writeBytesToFilename(String filename, byte[] bytes) { - FileOutputStream fos = null; try { if (filename != null && bytes != null) { @@ -91,13 +99,19 @@ public class JavaUtils { 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 @@ public class JavaUtils { * 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 { + public static byte[] getBytesFromStream(InputStream inputStream) throws IOException { + UnsyncByteArrayOutputStream baos = null; - byte refBytes[] = null; + byte[] retBytes = null; + try { + baos = new UnsyncByteArrayOutputStream(); + byte buf[] = new byte[4 * 1024]; + int len; - UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream(); - byte buf[] = new byte[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; } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java index 66a587511e8..1ab91701b6a 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java @@ -2,573 +2,473 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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()); - */ + return rfctoXML(normalized); + } - static boolean _TOXML = true; + /** + * Method xmldsigtoRFC2253 + * + * @param dn + * @return normalized string + */ + public static String xmldsigtoRFC2253(String dn) { + // Transform from RFC1779 to RFC2253 + String normalized = normalize(dn, false); - /** - * Method rfc2253toXMLdsig - * - * @param dn - * @return normalized string - * - */ - public static String rfc2253toXMLdsig(String dn) { + return xmltoRFC(normalized); + } - _TOXML = true; + /** + * Method normalize + * + * @param dn + * @return normalized string + */ + public static String normalize(String dn) { + return normalize(dn, true); + } - // Transform from RFC1779 to RFC2253 - String normalized = normalize(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 ""; + } - return rfctoXML(normalized); - } + try { + String DN = semicolonToComma(dn); + StringBuilder sb = new StringBuilder(); + int i = 0; + int l = 0; + int k; - /** - * Method xmldsigtoRFC2253 - * - * @param dn - * @return normalized string - */ - public static String xmldsigtoRFC2253(String dn) { + //for name component + for (int j = 0; (k = DN.indexOf(',', j)) >= 0; j = k + 1) { + l += countQuotes(DN, j, k); - _TOXML = false; + if ((k > 0) && (DN.charAt(k - 1) != '\\') && (l % 2) == 0) { + sb.append(parseRDN(DN.substring(i, k).trim(), toXml) + ","); - // Transform from RFC1779 to RFC2253 - String normalized = normalize(dn); - - return xmltoRFC(normalized); - } - - /** - * Method normalize - * - * @param dn - * @return normalized string - */ - public static String normalize(String dn) { - - //if empty string - if ((dn == null) || dn.equals("")) { - return ""; - } - - try { - String _DN = semicolonToComma(dn); - StringBuffer sb = new StringBuffer(); - 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); - - 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(parseRDN(trim(_DN.substring(i)))); + sb.append(parseRDN(trim(DN.substring(i)), toXml)); - return sb.toString(); - } catch (IOException ex) { - return dn; - } - } + return sb.toString(); + } catch (IOException ex) { + return dn; + } + } - /** - * Method parseRDN - * - * @param str - * @return normalized string - * @throws IOException - */ - static String parseRDN(String str) throws IOException { + /** + * 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; - 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); - 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) && (str.charAt(k - 1) != '\\') && (l % 2) != 1) { - sb.append(parseATAV(trim(str.substring(i, k))) + "+"); + i = k + 1; + l = 0; + } + } - i = k + 1; - l = 0; - } - } + sb.append(parseATAV(trim(str.substring(i)), toXml)); - sb.append(parseATAV(trim(str.substring(i)))); + return sb.toString(); + } - return sb.toString(); - } + /** + * 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 parseATAV - * - * @param str - * @return normalized string - * @throws IOException - */ - static String parseATAV(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); + } - int i = str.indexOf("="); + return attrType + "=" + attrValue; - 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)); - } + } - return attrType + "=" + attrValue; + /** + * Method normalizeAT + * + * @param str + * @return normalized string + */ + static String normalizeAT(String str) { - } + String at = str.toUpperCase().trim(); - /** - * Method normalizeAT - * - * @param str - * @return normalized string - */ - static String normalizeAT(String str) { + if (at.startsWith("OID")) { + at = at.substring(3); + } - String at = str.toUpperCase().trim(); + return at; + } - if (at.startsWith("OID")) { - at = at.substring(3); - } + /** + * Method normalizeV + * + * @param str + * @param toXml + * @return normalized string + * @throws IOException + */ + static String normalizeV(String str, boolean toXml) throws IOException { + String value = trim(str); - return at; - } + if (value.startsWith("\"")) { + StringBuilder sb = new StringBuilder(); + StringReader sr = new StringReader(value.substring(1, value.length() - 1)); + int i = 0; + char c; - /** - * Method normalizeV - * - * @param str - * @return normalized string - * @throws IOException - */ - static String normalizeV(String str) throws IOException { + while ((i = sr.read()) > -1) { + c = (char) i; - String value = trim(str); + //the following char is defined at 4.Relationship with RFC1779 and LDAPv2 inrfc2253 + if ((c == ',') || (c == '=') || (c == '+') || (c == '<') + || (c == '>') || (c == '#') || (c == ';')) { + sb.append('\\'); + } - if (value.startsWith("\"")) { - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(value.substring(1, - value.length() - 1)); - int i = 0; - char c; + sb.append(c); + } - for (; (i = sr.read()) > -1; ) { + value = trim(sb.toString()); + } + + if (toXml) { + 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; + } + } + + /** + * 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; + } + } + + /** + * 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; + + 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('\\'); - } + if (c == '\\') { + sb.append(c); - sb.append(c); - } + char c1 = (char) sr.read(); + char c2 = (char) sr.read(); - 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; - } - } - - /** - * 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; - } - } - - /** - * 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); + char ch = (char) Byte.parseByte("" + c1 + c2, 16); - sb.append(ch); + sb.append(ch); + } else { + sb.append(c1); + sb.append(c2); + } } else { - sb.append(c1); - sb.append(c2); + sb.append(c); } - } else { - sb.append(c); - } - } + } - return sb.toString(); - } + return sb.toString(); + } - /** - * Method changeLess32toXML - * - * @param string - * @return normalized string - * @throws IOException - */ - static String changeLess32toXML(String string) throws IOException { + /** + * 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; - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(string); - int i = 0; - - for (; (i = sr.read()) > -1; ) { - if (i < 32) { - sb.append('\\'); - sb.append(Integer.toHexString(i)); - } else { - sb.append((char) i); - } - } - - return sb.toString(); - } - - /** - * 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; + while ((i = sr.read()) > -1) { + c = (char) i; - for (int j = 0; (k = string.indexOf("\\20", j)) >= 0; j = k + 3) { - sb.append(trim(string.substring(i, k)) + "\\ "); + if (c == '\\') { + char c1 = (char) sr.read(); - i = k + 3; - } + if (c1 == ' ') { + sb.append('\\'); - sb.append(string.substring(i)); + String s = "20"; - return sb.toString(); - } + sb.append(s); + } else { + sb.append('\\'); + sb.append(c1); + } + } else { + sb.append(c); + } + } - /** - * Method semicolonToComma - * - * @param str - * @return normalized string - */ - static String semicolonToComma(String str) { - return removeWSandReplace(str, ";", ","); - } + 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; + } - for (int j = 0; (k = str.indexOf(symbol, j)) >= 0; j = k + 1) { - l += countQuotes(str, j, k); + sb.append(string.substring(i)); - if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) != 1) { - sb.append(trim(str.substring(i, k)) + replace); + return sb.toString(); + } - i = k + 1; - l = 0; - } - } + /** + * Method semicolonToComma + * + * @param str + * @return normalized string + */ + static String semicolonToComma(String str) { + return removeWSandReplace(str, ";", ","); + } - sb.append(trim(str.substring(i))); + /** + * Method removeWhiteSpace + * + * @param str + * @param symbol + * @return normalized string + */ + static String removeWhiteSpace(String str, String symbol) { + return removeWSandReplace(str, symbol, symbol); + } - return sb.toString(); - } + /** + * 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; - /** - * 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) { + for (int j = 0; (k = str.indexOf(symbol, j)) >= 0; j = k + 1) { + l += countQuotes(str, j, k); - int k = 0; + if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) == 0) { + sb.append(trim(str.substring(i, k)) + replace); - for (int l = i; l < j; l++) { - if (s.charAt(l) == '"') { - k++; - } - } + i = k + 1; + l = 0; + } + } - return k; - } + sb.append(trim(str.substring(i))); - //only for the end of a space character occurring at the end of the string from rfc2253 + return sb.toString(); + } - /** - * Method trim - * - * @param str - * @return the string - */ - static String trim(String str) { + /** + * 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; - String trimed = str.trim(); - int i = str.indexOf(trimed) + trimed.length(); + for (int l = i; l < j; l++) { + if (s.charAt(l) == '"') { + k++; + } + } - if ((str.length() > i) && trimed.endsWith("\\") - &&!trimed.endsWith("\\\\")) { - if (str.charAt(i) == ' ') { + 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(); + + if ((str.length() > i) && trimed.endsWith("\\") + && !trimed.endsWith("\\\\") && (str.charAt(i) == ' ')) { trimed = trimed + " "; - } - } + } - return trimed; - } + return trimed; + } - /** - * Method main - * - * @param args - * @throws Exception - */ - public static void main(String[] args) throws Exception { - - 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"); - - { - StringBuffer sb = new StringBuffer(); - - 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(); - - sb.append('L'); - sb.append('u'); - sb.append('\uc48d'); - sb.append('i'); - sb.append('\uc487'); - - String test7 = "SN=" + sb.toString(); - - testToRFC(test7); - } - } - - /** Field i */ - static int counter = 0; - - /** - * Method test - * - * @param st - */ - static void testToXML(String st) { - - System.out.println("start " + counter++ + ": " + st); - System.out.println(" " + rfc2253toXMLdsig(st)); - System.out.println(""); - } - - /** - * Method testToRFC - * - * @param st - */ - static void testToRFC(String st) { - - System.out.println("start " + counter++ + ": " + st); - System.out.println(" " + xmldsigtoRFC2253(st)); - System.out.println(""); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java new file mode 100644 index 00000000000..dffcd89f47b --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java @@ -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; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java index d49cc676acf..3a97bd3d411 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java @@ -2,70 +2,69 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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"); - } - this._doc = doc; - this._constructionElement = XMLUtils.createElementInSignatureSpace(this._doc, - this.getBaseLocalName()); - } + protected SignatureElementProxy() { + }; - /** - * Constructor SignatureElementProxy - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public SignatureElementProxy(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); + /** + * Constructor SignatureElementProxy + * + * @param doc + */ + public SignatureElementProxy(Document doc) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - } + this.doc = doc; + this.constructionElement = + XMLUtils.createElementInSignatureSpace(this.doc, this.getBaseLocalName()); + } - /** @inheritDoc */ - public String getBaseNamespace() { - return Constants.SignatureSpecNS; - } + /** + * 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java index 068d523bd64..c8f5747d396 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; * */ 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); } } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java index e9a7935e7ea..f424dd51b74 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.IOException; 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; - final byte[] buf; - static final int size=8*1024; - private static ThreadLocal bufCahce = new ThreadLocal() { - protected synchronized byte[] initialValue() { - return new byte[size]; + private int pointer = 0; + private final OutputStream out; + + private final byte[] buf; + + /** + * 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, 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; } - }; - 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; + System.arraycopy(arg0, arg1, buf, pointer, len); + pointer = newLen; + } + + private void flushBuffer() throws IOException { + if (pointer > 0) { + out.write(buf, 0, pointer); } + pointer = 0; - /** @inheritDoc */ - public void write(byte[] arg0) throws IOException { - write(arg0,0,arg0.length); + } + + /** @inheritDoc */ + public void write(int arg0) throws IOException { + if (pointer >= size) { + flushBuffer(); } + buf[pointer++] = (byte)arg0; - /** @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; + /** @inheritDoc */ + public void flush() throws IOException { + flushBuffer(); + out.flush(); + } - } - - /** @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 close() throws IOException { + flush(); + out.close(); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java index 2a2f7ddbd03..e6f3ea7c258 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2010 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import java.io.OutputStream; * */ public class UnsyncByteArrayOutputStream extends OutputStream { + private static final int INITIAL_SIZE = 8192; - private static ThreadLocal bufCache = new ThreadLocal() { - 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 class UnsyncByteArrayOutputStream extends OutputStream { } 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 class UnsyncByteArrayOutputStream extends OutputStream { } 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 @@ public class UnsyncByteArrayOutputStream extends OutputStream { 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); diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java index dc01897cca5..620b6735b8f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java @@ -2,35 +2,34 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.Element; 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 @@ import org.w3c.dom.Text; */ public class XMLUtils { - private static boolean ignoreLineBreaks = - AccessController.doPrivileged(new PrivilegedAction() { - public Boolean run() { - return Boolean.getBoolean - ("com.sun.org.apache.xml.internal.security.ignoreLineBreaks"); - } - }); + private static boolean ignoreLineBreaks = + AccessController.doPrivileged(new PrivilegedAction() { + 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 @@ -84,6 +85,14 @@ public class XMLUtils { dsPrefix = prefix; } + /** + * 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 @@ public class XMLUtils { 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; + } - } + 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 wheather comments or not - */ - public static void getSet(Node rootNode,Set result,Node exclude ,boolean com) { - if ((exclude!=null) && isDescendantOrSelf(exclude,rootNode)){ - return; - } - getSetRec(rootNode,result,exclude,com); - } + /** + * @param rootNode + * @param result + * @param exclude + * @param com whether comments or not + */ + public static void getSet(Node rootNode, Set 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 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 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}. If an Exception is - * thrown during execution, it's StackTrace is output to System.out, but the - * Exception is not re-thrown. - * - * @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}. If an Exception is + * thrown during execution, it's StackTrace is output to System.out, but the + * Exception is not re-thrown. + * + * @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("\n".getBytes("UTF-8")); + } - try { - if (addPreamble) { - os.write("\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 contextNode into the OutputStream, but + * suppresses all Exceptions. + *
    + * NOTE: 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 + * try{} statement, but handle the Exceptions appropriately. + * + * @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 contextNode into the OutputStream, but - * supresses all Exceptions. - *
    - * NOTE: 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 - * try{} statement, but handle the Exceptions appropriately. - * - * @param contextNode - * @param os - */ - public static void outputDOMc14nWithComments(Node contextNode, - OutputStream os) { + /** + * Method getFullTextChildrenFromElement + * + * @param element + * @return the string of children + */ + public static String getFullTextChildrenFromElement(Element element) { + StringBuilder sb = new StringBuilder(); - try { - os.write( - Canonicalizer.getInstance( - Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree( - contextNode)); - } catch (IOException 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 (InvalidCanonicalizerException ex) { + return sb.toString(); + } - // throw new RuntimeException(ex.getMessage()); - } catch (CanonicalizationException ex) { + /** + * 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"); + } - // throw new RuntimeException(ex.getMessage()); - } - } + if ((dsPrefix == null) || (dsPrefix.length() == 0)) { + return doc.createElementNS(Constants.SignatureSpecNS, elementName); + } + return doc.createElementNS(Constants.SignatureSpecNS, dsPrefix + ":" + elementName); + } + /** + * 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"); + } - /** - * Method getFullTextChildrenFromElement - * - * @param element - * @return the string of chi;ds - */ - public static String getFullTextChildrenFromElement(Element element) { + if ((ds11Prefix == null) || (ds11Prefix.length() == 0)) { + return doc.createElementNS(Constants.SignatureSpec11NS, elementName); + } + return doc.createElementNS(Constants.SignatureSpec11NS, ds11Prefix + ":" + elementName); + } - StringBuffer sb = new StringBuffer(); - NodeList children = element.getChildNodes(); - int iMax = children.getLength(); + /** + * 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"); + } - for (int i = 0; i < iMax; i++) { - Node curr = children.item(i); + if ((xencPrefix == null) || (xencPrefix.length() == 0)) { + return doc.createElementNS(EncryptionConstants.EncryptionSpecNS, elementName); + } + return + doc.createElementNS( + EncryptionConstants.EncryptionSpecNS, xencPrefix + ":" + elementName + ); + } - if (curr.getNodeType() == Node.TEXT_NODE) { - sb.append(((Text) curr).getData()); - } - } + /** + * 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"); + } - return sb.toString(); - } - - static Map namePrefixes=new HashMap(); - - /** - * 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"); - } - - 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); - } + 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,10 +358,11 @@ public class XMLUtils { * * @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) { + if (element == null){ return false; } @@ -301,48 +370,82 @@ public class XMLUtils { && 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.SignatureSpec11NS.equals(element.getNamespaceURI()) + && element.getLocalName().equals(localName); + } + /** * Returns true if the element is in XML Encryption namespace and the local * name equals the supplied one. * * @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 always returns a - * {@link Document}. {@link Node#getOwnerDocument} returns null - * 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 always returns a + * {@link Document}. {@link Node#getOwnerDocument} returns null + * 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 always returns a * {@link Document}. {@link Node#getOwnerDocument} returns null * if the {@link Node} is a {@link Document}. @@ -351,23 +454,23 @@ public class XMLUtils { * @return the owner document */ public static Document getOwnerDocument(Set 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 @@ public class XMLUtils { * @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"); + } - if ((prefix == null) || (prefix.trim().length() == 0)) { - throw new IllegalArgumentException("You must supply a prefix"); - } + Element ctx = doc.createElementNS(null, "namespaceContext"); - Element ctx = doc.createElementNS(null, "namespaceContext"); + ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(), namespace); - ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(), - namespace); - - return ctx; + return ctx; } - /** - * Method addReturnToElement - * - * @param e - */ - public static void addReturnToElement(Element e) { + /** + * Method addReturnToElement + * + * @param e + */ + public static void addReturnToElement(Element e) { + if (!ignoreLineBreaks) { + Document doc = e.getOwnerDocument(); + e.appendChild(doc.createTextNode("\n")); + } + } - 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 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); + } + } - 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 convertNodelistToSet(NodeList xpathNodeSet) { + if (xpathNodeSet == null) { + return new HashSet(); + } - /** - * Method convertNodelistToSet - * - * @param xpathNodeSet - * @return the set with the nodelist - */ - public static Set convertNodelistToSet(NodeList xpathNodeSet) { + int length = xpathNodeSet.getLength(); + Set set = new HashSet(length); - if (xpathNodeSet == null) { - return new HashSet(); - } + for (int i = 0; i < length; i++) { + set.add(xpathNodeSet.item(i)); + } - int length = xpathNodeSet.getLength(); - Set set = new HashSet(length); + return set; + } - for (int i = 0; i < length; i++) { - set.add(xpathNodeSet.item(i)); - } + /** + * 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 + * Namespace axis resolution is not XPath compliant + */ + public static void circumventBug2650(Document doc) { - return set; - } + Element documentElement = doc.getDocumentElement(); + // 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 Namespace axis resolution is not XPath compliant - */ - public static void circumventBug2650(Document doc) { + if (xmlnsAttr == null) { + documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", ""); + } - Element documentElement = doc.getDocumentElement(); + XMLUtils.circumventBug2650internal(doc); + } - // if the document element has no xmlns definition, we add xmlns="" - Attr xmlnsAttr = - documentElement.getAttributeNodeNS(Constants.NamespaceSpecNS, "xmlns"); - - if (xmlnsAttr == null) { - documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", ""); - } - - XMLUtils.circumventBug2650internal(doc); - } - - /** - * This is the work horse for {@link #circumventBug2650}. - * - * @param node - * @see Namespace axis resolution is not XPath compliant - */ - @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 + * Namespace axis resolution is not XPath compliant + */ + @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 (int i = 0; i < attributesLength; i++) { - Attr currentAttr = (Attr) attributes.item(i); - if (namespaceNs!=currentAttr.getNamespaceURI()) - continue; - if (childElement.hasAttributeNS(namespaceNs, - currentAttr.getLocalName())) { - continue; + for (Node child = element.getFirstChild(); child!=null; + child = child.getNextSibling()) { + + if (child.getNodeType() != Node.ELEMENT_NODE) { + continue; } - childElement.setAttributeNS(namespaceNs, - currentAttr.getName(), - currentAttr.getNodeValue()); - + 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; + } + 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) { @@ -554,6 +653,26 @@ public class XMLUtils { return null; } + /** + * @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 @@ -574,42 +693,61 @@ public class XMLUtils { 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 @@ public class XMLUtils { * @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 list = new ArrayList(); while (sibling != null) { if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri) @@ -659,73 +806,117 @@ public class XMLUtils { 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 excludeNodeFromSet(Node signatureElement, Set inputSet) { - Set resultSet = new HashSet(); - Iterator iterator = inputSet.iterator(); + Set resultSet = new HashSet(); + Iterator 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(); - if (ctx == descendantOrSelf) { - return true; - } + for (Node currentSibling = xpathnode.getParentNode().getFirstChild(); + currentSibling != null; + currentSibling = currentSibling.getNextSibling()) { + if (currentSibling.getNodeType() == Node.TEXT_NODE) { + sb.append(((Text) currentSibling).getData()); + } + } - Node parent = descendantOrSelf; + 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(); + } - while (true) { - if (parent == null) { - return false; - } + return null; + } - if (parent == ctx) { + /** + * 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.getNodeType() == Node.ATTRIBUTE_NODE) { - parent = ((Attr) parent).getOwnerElement(); - } else { - parent = parent.getParentNode(); - } - } - } + Node parent = descendantOrSelf; + + while (true) { + if (parent == null) { + return false; + } + + 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. + * + *

    This works around a limitation of the DOM + * Element.getAttributeNode 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 @@ public class XMLUtils { } /** - * 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 @@ public class XMLUtils { 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; } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathAPI.java new file mode 100644 index 00000000000..d5b55bac3f8 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathAPI.java @@ -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(); + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java new file mode 100644 index 00000000000..3de6129b935 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java @@ -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(); + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java deleted file mode 100644 index dbee521c11e..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java +++ /dev/null @@ -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 here() function. - *
    - * 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 XPath Specification - */ -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 ""; - } -} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java new file mode 100644 index 00000000000..f9fab3033d8 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java @@ -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"); + } + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathFactory.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathFactory.java new file mode 100644 index 00000000000..e6ee959d750 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathFactory.java @@ -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(); + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java index 67d635cb847..7570a019064 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java @@ -85,8 +85,14 @@ public class ResourceResolver { * @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 ResourceResolver internalGetInstance(ResourceResolverContext context) + throws ResourceResolverException { synchronized (resolverList) { for (ResourceResolver resolver : resolverList) { ResourceResolver resolverTmp = resolver; @@ -95,9 +101,9 @@ public class ResourceResolver { 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 @@ public class ResourceResolver { ); } - 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 @@ public class ResourceResolver { } } - 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 @@ public class ResourceResolver { ); } + 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 @@ public class ResourceResolver { 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); } /** @@ -269,6 +276,15 @@ public class ResourceResolver { } } + /** + * @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 * @@ -278,9 +294,10 @@ public class ResourceResolver { * * @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 @@ public class ResourceResolver { * @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); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java new file mode 100644 index 00000000000..5b8a9ce13f6 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java @@ -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; +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java index 5fa9ea35787..cf5c8d12ea2 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java @@ -2,144 +2,137 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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; - super(_msgID); + private Attr uri = null; - this._uri = uri; - this._BaseURI = BaseURI; - } + private String baseURI = null; - /** - * 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 uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Attr uri, String baseURI) { + super(msgID); - super(_msgID, exArgs); + 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) { + super(msgID, exArgs); - /** - * Constructor ResourceResolverException - * - * @param _msgID - * @param _originalException - * @param uri - * @param BaseURI - */ - public ResourceResolverException(String _msgID, Exception _originalException, - Attr uri, String BaseURI) { + this.uri = uri; + this.baseURI = baseURI; + } - super(_msgID, _originalException); + /** + * Constructor ResourceResolverException + * + * @param msgID + * @param originalException + * @param uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Exception originalException, + Attr uri, String baseURI) { + 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; - } + /** + * + * @param baseURI + */ + public void setbaseURI(String baseURI) { + this.baseURI = baseURI; + } - String _BaseURI; + /** + * + * @return the baseURI + */ + public String getbaseURI() { + return this.baseURI; + } - /** - * - * @param BaseURI - */ - public void setBaseURI(String BaseURI) { - this._BaseURI = BaseURI; - } - - /** - * - * @return the basUri - */ - public String getBaseURI() { - return this._BaseURI; - } - //J+ } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java index e9ba6d13171..0ca4523600d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java @@ -2,192 +2,239 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 _properties = null; + /** Field properties */ + protected java.util.Map 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(); - } - 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(); + } + properties.put(key, value); + } - /** - * - * @param properties - */ - public void engineAddProperies(Map properties) { - if (properties!=null) { - if (_properties==null) { - _properties=new HashMap(); - } - 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); + /** + * Method engineGetProperty + * + * @param key + * @return the value of the property + */ + public String engineGetProperty(String key) { + if (properties == null) { + return null; + } + return properties.get(key); + } - /** - * Method engineGetPropertyKeys - * - * @return the property keys - */ - public String[] engineGetPropertyKeys() { - return new String[0]; - } - - /** - * 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; + /** + * + * @param newProperties + */ + public void engineAddProperies(Map newProperties) { + if (newProperties != null && !newProperties.isEmpty()) { + if (properties == null) { + properties = new HashMap(); } - } - } + properties.putAll(newProperties); + } + } - return false; - } + /** + * 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(); + } + + /** + * This method helps the {@link ResourceResolver} to decide whether a + * {@link ResourceResolverSpi} is able to perform the requested action. + * + *

    New clients should override this method, and not override {@link #engineCanResolve(Attr, String)} + *

    + * @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 engineGetPropertyKeys + * + * @return the property keys + */ + public String[] engineGetPropertyKeys() { + return new String[0]; + } + + /** + * 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; + } - /** - * 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 != '/')); - - if (isDosFilename) { - if (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); - - if (ch1 == ':') { + // 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 (('A' <= ch0) && (ch0 <= 'Z')) { - str = "/" + str; + if (isDosFilename && log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found DOS filename: " + str); } - } - } + } - // done - return str; - } + // Windows fix + if (str.length() >= 2) { + char ch1 = str.charAt(1); + + if (ch1 == ':') { + char ch0 = Character.toUpperCase(str.charAt(0)); + + if (('A' <= ch0) && (ch0 <= 'Z')) { + str = "/" + str; + } + } + } + + // done + return str; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java index 0bd0c59120b..22aba4083b8 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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.IOException; 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]; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java index 706cccc6a4d..cd0967215a7 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java @@ -2,38 +2,42 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 @@ import org.w3c.dom.Attr; * resourceResolver.setProperty("http.proxy.password", "secretca"); *
    * - * - * @author $Author: mullan $ * @see Java Tip 42: Write Java apps that work with proxy-based firewalls * @see SUN J2SE docs for network properties * @see The JAVA FAQ Question 9.5: How do I make Java work with a proxy server? - * $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()); + /** {@link org.apache.commons.logging} logging facility */ + private 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" }; + /** 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 HttpProxyHost */ - private static final int HttpProxyHost = 0; + /** Field HttpProxyHost */ + private static final int HttpProxyHost = 0; - /** Field HttpProxyPort */ - private static final int HttpProxyPort = 1; + /** Field HttpProxyPort */ + private static final int HttpProxyPort = 1; - /** Field HttpProxyUser */ - private static final int HttpProxyUser = 2; + /** Field HttpProxyUser */ + private static final int HttpProxyUser = 2; - /** Field HttpProxyPass */ - private static final int HttpProxyPass = 3; + /** Field HttpProxyPass */ + private static final int HttpProxyPass = 3; - /** Field HttpProxyUser */ - private static final int HttpBasicUser = 4; + /** Field HttpProxyUser */ + private static final int HttpBasicUser = 4; - /** Field HttpProxyPass */ - private static final int HttpBasicPass = 5; + /** Field HttpProxyPass */ + private static final int HttpBasicPass = 5; - 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 { + @Override + public boolean engineIsThreadSafe() { + return true; + } - try { - boolean useProxy = false; - String proxyHost = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyHost]); - String proxyPort = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyPort]); + /** + * 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 { - if ((proxyHost != null) && (proxyPort != null)) { - useProxy = true; - } - - 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); - - // 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(); - - { - - // 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); - if ((user != null) && (pass != null)) { - urlConnection = url.openConnection(); + String password = user + ":" + pass; + String encodedPassword = Base64.encode(password.getBytes("ISO-8859-1")); - 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; + 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); + while ((read = inputStream.read(buf)) >= 0) { + baos.write(buf, 0, read); + summarized += 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()); + } - log.log(java.util.logging.Level.FINE, "Fetched " + summarized + " bytes from URI " - + uriNew.toString()); + XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray()); - XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray()); + result.setSourceURI(uriNew.toString()); + result.setMIMEType(mimeType); - // XMLSignatureInput result = new XMLSignatureInput(inputStream); - result.setSourceURI(uriNew.toString()); - result.setMIMEType(mimeType); + 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); + } + } - // switch off proxy usage - if (useProxy && switchBackProxy) { - System.setProperty("http.proxySet", oldProxySet); - System.setProperty("http.proxyHost", oldProxyHost); - System.setProperty("http.proxyPort", oldProxyPort); - } + private URLConnection openConnection(URL url) throws IOException { - return result; - } catch (MalformedURLException ex) { - throw new ResourceResolverException("generic.EmptyMessage", ex, uri, - BaseURI); - } catch (IOException ex) { - throw new ResourceResolverException("generic.EmptyMessage", ex, uri, - BaseURI); - } - } + 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]); - /** - * We resolve http URIs without 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"); + Proxy proxy = null; + if ((proxyHostProp != null) && (proxyPortProp != null)) { + int port = Integer.parseInt(proxyPortProp); + proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostProp, port)); + } - return false; - } + URLConnection urlConnection; + if (proxy != null) { + urlConnection = url.openConnection(proxy); - String uriNodeValue = uri.getNodeValue(); + if ((proxyUser != null) && (proxyPass != null)) { + String password = proxyUser + ":" + proxyPass; + String authString = "Basic " + Base64.encode(password.getBytes("ISO-8859-1")); - if (uriNodeValue.equals("") || (uriNodeValue.charAt(0)=='#')) { - log.log(java.util.logging.Level.FINE, "quick fail for empty URIs and local ones"); + urlConnection.setRequestProperty("Proxy-Authorization", authString); + } + } else { + urlConnection = url.openConnection(); + } - return false; - } + return urlConnection; + } - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + uriNodeValue); - } + /** + * We resolve http URIs without 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; + } - 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 (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; + } - return true; - } + 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 state that I can't 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; + } - return false; - } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I state that I can't resolve " + context.uriToResolve); + } - /** - * @inheritDoc - */ - public String[] engineGetPropertyKeys() { - return ResolverDirectHTTP.properties.clone(); - } + return false; + } - private URI getNewURI(String uri, String BaseURI) - throws URI.MalformedURIException { + /** + * @inheritDoc + */ + public String[] engineGetPropertyKeys() { + return ResolverDirectHTTP.properties.clone(); + } + + 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 + if (newUri.getFragment() != null) { + URI uriNewNoFrag = + new URI(newUri.getScheme(), newUri.getSchemeSpecificPart(), null); + return uriNewNoFrag; + } + return newUri; + } - if ((BaseURI == null) || "".equals(BaseURI)) { - return new URI(uri); - } - return new URI(new URI(BaseURI), uri); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java index d2750c84903..49eb0407382 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java @@ -2,148 +2,148 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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 The Reference processing model in the XML Signature spec * @see Same-Document URI-References in the XML Signature spec * @see Section 4.2 of RFC 2396 */ 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) { + /** + * 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; + } - if (uri == null) { - 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java index 07af53db296..c526286462d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java @@ -2,156 +2,160 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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; + } - try { - URI uriNew = getNewURI(uri.getNodeValue(), BaseURI); + /** + * @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(); + } + + 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java index 0f931f44193..345087bbcec 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java @@ -2,36 +2,35 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express 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. *
    @@ -45,15 +44,18 @@ import org.w3c.dom.Node; * 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 @@ public class ResolverXPointer extends ResourceResolverSpi { /** * @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) { - - if (uri == null) { - return false; - } - String uriStr =uri.getNodeValue(); - if (isXPointerSlash(uriStr) || isXPointerId(uriStr)) { - return true; - } - - return false; - } - - /** - * 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) { - - - 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)); - + /** + * @inheritDoc + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + return false; + } + if (isXPointerSlash(context.uriToResolve) || isXPointerId(context.uriToResolve)) { return true; - } - } + } - return false; - } + return false; + } - /** - * Method getXPointerId - * - * @param uri - * @return xpointerId to search. - */ - private static String getXPointerId(String uri) { + /** + * Method isXPointerSlash + * + * @param uri + * @return true if begins with xpointer + */ + private static boolean isXPointerSlash(String uri) { + if (uri.equals("#xpointer(/)")) { + return true; + } + 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 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); - return null; - } + 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; + } + + /** + * 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); + + 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; + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/DigesterOutputStream.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/DigesterOutputStream.java index c6f9d9c1c70..859b43183b4 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/DigesterOutputStream.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/DigesterOutputStream.java @@ -2,36 +2,37 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DigesterOutputStream.java,v 1.2 2008/07/24 15:20:31 mullan Exp $ + * $Id: DigesterOutputStream.java,v 1.5 2005/12/20 20:02:39 mullan Exp $ */ package org.jcp.xml.dsig.internal; import java.io.ByteArrayInputStream; +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.MessageDigest; -import java.util.logging.Logger; -import java.util.logging.Level; import com.sun.org.apache.xml.internal.security.utils.UnsyncByteArrayOutputStream; @@ -45,10 +46,12 @@ import com.sun.org.apache.xml.internal.security.utils.UnsyncByteArrayOutputStrea * @author Sean Mullan */ public class DigesterOutputStream extends OutputStream { - private boolean buffer = false; + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal"); + + private final boolean buffer; private UnsyncByteArrayOutputStream bos; private final MessageDigest md; - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal"); /** * Creates a DigesterOutputStream. @@ -73,12 +76,6 @@ public class DigesterOutputStream extends OutputStream { } } - /** @inheritDoc */ - public void write(byte[] input) { - write(input, 0, input.length); - } - - /** @inheritDoc */ public void write(int input) { if (buffer) { bos.write(input); @@ -86,18 +83,18 @@ public class DigesterOutputStream extends OutputStream { md.update((byte)input); } - /** @inheritDoc */ + @Override public void write(byte[] input, int offset, int len) { if (buffer) { bos.write(input, offset, len); } - if (log.isLoggable(Level.FINER)) { - log.log(Level.FINER, "Pre-digested input:"); - StringBuffer sb = new StringBuffer(len); - for (int i=offset; i<(offset+len); i++) { - sb.append((char) input[i]); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Pre-digested input:"); + StringBuilder sb = new StringBuilder(len); + for (int i = offset; i < (offset + len); i++) { + sb.append((char)input[i]); } - log.log(Level.FINER, sb.toString()); + log.log(java.util.logging.Level.FINE, sb.toString()); } md.update(input, offset, len); } @@ -120,4 +117,11 @@ public class DigesterOutputStream extends OutputStream { return null; } } + + @Override + public void close() throws IOException { + if (buffer) { + bos.close(); + } + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/MacOutputStream.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/MacOutputStream.java index 3309215bb96..ac3a3997c42 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/MacOutputStream.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/MacOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.jcp.xml.dsig.internal; @@ -38,19 +40,13 @@ public class MacOutputStream extends ByteArrayOutputStream { this.mac = mac; } - /** @inheritDoc */ - public void write(byte[] arg0) { - super.write(arg0, 0, arg0.length); - mac.update(arg0); - } - - /** @inheritDoc */ + @Override public void write(int arg0) { super.write(arg0); mac.update((byte) arg0); } - /** @inheritDoc */ + @Override public void write(byte[] arg0, int arg1, int arg2) { super.write(arg0, arg1, arg2); mac.update(arg0, arg1, arg2); diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/SignerOutputStream.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/SignerOutputStream.java index 09a25290852..6cfcf0e5e45 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/SignerOutputStream.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/SignerOutputStream.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: SignerOutputStream.java,v 1.2 2008/07/24 15:20:31 mullan Exp $ + * $Id: SignerOutputStream.java,v 1.2 2005/09/15 14:29:02 mullan Exp $ */ package org.jcp.xml.dsig.internal; @@ -32,8 +34,8 @@ import java.security.SignatureException; /** * Derived from Apache sources and changed to use java.security.Signature - * objects as input instead of com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm - * objects. + * objects as input instead of + * com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm objects. * * @author raul * @author Sean Mullan @@ -42,36 +44,26 @@ public class SignerOutputStream extends ByteArrayOutputStream { private final Signature sig; public SignerOutputStream(Signature sig) { - this.sig=sig; + this.sig = sig; } - /** @inheritDoc */ - public void write(byte[] arg0) { - super.write(arg0, 0, arg0.length); - try { - sig.update(arg0); - } catch (SignatureException e) { - throw new RuntimeException(""+e); - } - } - - /** @inheritDoc */ + @Override public void write(int arg0) { super.write(arg0); try { sig.update((byte)arg0); } catch (SignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException(e); } } - /** @inheritDoc */ + @Override public void write(byte[] arg0, int arg1, int arg2) { super.write(arg0, arg1, arg2); try { - sig.update(arg0,arg1,arg2); + sig.update(arg0, arg1, arg2); } catch (SignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException(e); } } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/AbstractDOMSignatureMethod.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/AbstractDOMSignatureMethod.java new file mode 100644 index 00000000000..de620ae759a --- /dev/null +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/AbstractDOMSignatureMethod.java @@ -0,0 +1,218 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jcp.xml.dsig.internal.dom; + +import java.security.Key; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.SignatureException; +import java.security.spec.AlgorithmParameterSpec; +import javax.xml.crypto.MarshalException; +import javax.xml.crypto.dom.DOMCryptoContext; +import javax.xml.crypto.dsig.SignatureMethod; +import javax.xml.crypto.dsig.SignedInfo; +import javax.xml.crypto.dsig.XMLSignature; +import javax.xml.crypto.dsig.XMLSignatureException; +import javax.xml.crypto.dsig.XMLSignContext; +import javax.xml.crypto.dsig.XMLValidateContext; +import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * An abstract class representing a SignatureMethod. Subclasses implement + * a specific XML DSig signature algorithm. + */ +abstract class AbstractDOMSignatureMethod extends DOMStructure + implements SignatureMethod { + + // denotes the type of signature algorithm + enum Type { DSA, RSA, ECDSA, HMAC } + + /** + * Verifies the passed-in signature with the specified key, using the + * underlying Signature or Mac algorithm. + * + * @param key the verification key + * @param si the SignedInfo + * @param sig the signature bytes to be verified + * @param context the XMLValidateContext + * @return true if the signature verified successfully, + * false if not + * @throws NullPointerException if key, si or + * sig are null + * @throws InvalidKeyException if the key is improperly encoded, of + * the wrong type, or parameters are missing, etc + * @throws SignatureException if an unexpected error occurs, such + * as the passed in signature is improperly encoded + * @throws XMLSignatureException if an unexpected error occurs + */ + abstract boolean verify(Key key, SignedInfo si, byte[] sig, + XMLValidateContext context) + throws InvalidKeyException, SignatureException, XMLSignatureException; + + /** + * Signs the bytes with the specified key, using the underlying + * Signature or Mac algorithm. + * + * @param key the signing key + * @param si the SignedInfo + * @param context the XMLSignContext + * @return the signature + * @throws NullPointerException if key or + * si are null + * @throws InvalidKeyException if the key is improperly encoded, of + * the wrong type, or parameters are missing, etc + * @throws XMLSignatureException if an unexpected error occurs + */ + abstract byte[] sign(Key key, SignedInfo si, XMLSignContext context) + throws InvalidKeyException, XMLSignatureException; + + /** + * Returns the java.security.Signature or javax.crypto.Mac standard + * algorithm name. + */ + abstract String getJCAAlgorithm(); + + /** + * Returns the type of signature algorithm. + */ + abstract Type getAlgorithmType(); + + /** + * This method invokes the {@link #marshalParams marshalParams} + * method to marshal any algorithm-specific parameters. + */ + public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) + throws MarshalException + { + Document ownerDoc = DOMUtils.getOwnerDocument(parent); + + Element smElem = DOMUtils.createElement(ownerDoc, "SignatureMethod", + XMLSignature.XMLNS, dsPrefix); + DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm()); + + if (getParameterSpec() != null) { + marshalParams(smElem, dsPrefix); + } + + parent.appendChild(smElem); + } + + /** + * Marshals the algorithm-specific parameters to an Element and + * appends it to the specified parent element. By default, this method + * throws an exception since most SignatureMethod algorithms do not have + * parameters. Subclasses should override it if they have parameters. + * + * @param parent the parent element to append the parameters to + * @param paramsPrefix the algorithm parameters prefix to use + * @throws MarshalException if the parameters cannot be marshalled + */ + void marshalParams(Element parent, String paramsPrefix) + throws MarshalException + { + throw new MarshalException("no parameters should " + + "be specified for the " + getAlgorithm() + + " SignatureMethod algorithm"); + } + + /** + * Unmarshals SignatureMethodParameterSpec from the specified + * Element. By default, this method throws an exception since + * most SignatureMethod algorithms do not have parameters. Subclasses should + * override it if they have parameters. + * + * @param paramsElem the Element holding the input params + * @return the algorithm-specific SignatureMethodParameterSpec + * @throws MarshalException if the parameters cannot be unmarshalled + */ + SignatureMethodParameterSpec unmarshalParams(Element paramsElem) + throws MarshalException + { + throw new MarshalException("no parameters should " + + "be specified for the " + getAlgorithm() + + " SignatureMethod algorithm"); + } + + /** + * Checks if the specified parameters are valid for this algorithm. By + * default, this method throws an exception if parameters are specified + * since most SignatureMethod algorithms do not have parameters. Subclasses + * should override it if they have parameters. + * + * @param params the algorithm-specific params (may be null) + * @throws InvalidAlgorithmParameterException if the parameters are not + * appropriate for this signature method + */ + void checkParams(SignatureMethodParameterSpec params) + throws InvalidAlgorithmParameterException + { + if (params != null) { + throw new InvalidAlgorithmParameterException("no parameters " + + "should be specified for the " + getAlgorithm() + + " SignatureMethod algorithm"); + } + } + + @Override + public boolean equals(Object o) + { + if (this == o) { + return true; + } + + if (!(o instanceof SignatureMethod)) { + return false; + } + SignatureMethod osm = (SignatureMethod)o; + + return (getAlgorithm().equals(osm.getAlgorithm()) && + paramsEqual(osm.getParameterSpec())); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + getAlgorithm().hashCode(); + AlgorithmParameterSpec spec = getParameterSpec(); + if (spec != null) { + result = 31 * result + spec.hashCode(); + } + + return result; + } + + /** + * Returns true if parameters are equal; false otherwise. + * + * Subclasses should override this method to compare algorithm-specific + * parameters. + */ + boolean paramsEqual(AlgorithmParameterSpec spec) + { + return (getParameterSpec() == spec); + } +} diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java index fac4024f8a4..97554e4d200 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java @@ -2,44 +2,42 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: ApacheCanonicalizer.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: ApacheCanonicalizer.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.IOException; import java.io.OutputStream; import java.security.spec.AlgorithmParameterSpec; import java.security.InvalidAlgorithmParameterException; import java.util.Set; -import java.util.logging.Logger; -import java.util.logging.Level; import javax.xml.crypto.*; import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.TransformException; import javax.xml.crypto.dsig.TransformService; -import javax.xml.crypto.dsig.XMLSignatureException; import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; @@ -48,7 +46,7 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.transforms.Transform; import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.NodeList; +import org.w3c.dom.Node; public abstract class ApacheCanonicalizer extends TransformService { @@ -56,7 +54,8 @@ public abstract class ApacheCanonicalizer extends TransformService { com.sun.org.apache.xml.internal.security.Init.init(); } - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); protected Canonicalizer apacheCanonicalizer; private Transform apacheTransform; protected String inclusiveNamespaces; @@ -64,51 +63,60 @@ public abstract class ApacheCanonicalizer extends TransformService { protected Document ownerDoc; protected Element transformElem; - public final AlgorithmParameterSpec getParameterSpec() { + public final AlgorithmParameterSpec getParameterSpec() + { return params; } public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (context != null && !(context instanceof DOMCryptoContext)) { throw new ClassCastException ("context must be of type DOMCryptoContext"); } + if (parent == null || !(parent instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("parent must be of type DOMStructure"); + } transformElem = (Element) - ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); + ((javax.xml.crypto.dom.DOMStructure)parent).getNode(); ownerDoc = DOMUtils.getOwnerDocument(transformElem); } public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { + throws MarshalException + { if (context != null && !(context instanceof DOMCryptoContext)) { throw new ClassCastException ("context must be of type DOMCryptoContext"); } + if (parent == null || !(parent instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("parent must be of type DOMStructure"); + } transformElem = (Element) - ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); + ((javax.xml.crypto.dom.DOMStructure)parent).getNode(); ownerDoc = DOMUtils.getOwnerDocument(transformElem); } public Data canonicalize(Data data, XMLCryptoContext xc) - throws TransformException { + throws TransformException + { return canonicalize(data, xc, null); } public Data canonicalize(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { - + throws TransformException + { if (apacheCanonicalizer == null) { try { apacheCanonicalizer = Canonicalizer.getInstance(getAlgorithm()); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Created canonicalizer for algorithm: " - + getAlgorithm()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Created canonicalizer for algorithm: " + getAlgorithm()); } } catch (InvalidCanonicalizerException ice) { throw new TransformException ("Couldn't find Canonicalizer for: " + getAlgorithm() + - ": " + ice.getMessage(), ice); + ": " + ice.getMessage(), ice); } } @@ -119,10 +127,10 @@ public abstract class ApacheCanonicalizer extends TransformService { } try { - Set nodeSet = null; + Set nodeSet = null; if (data instanceof ApacheData) { XMLSignatureInput in = - ((ApacheData) data).getXMLSignatureInput(); + ((ApacheData)data).getXMLSignatureInput(); if (in.isElement()) { if (inclusiveNamespaces != null) { return new OctetStreamData(new ByteArrayInputStream @@ -141,7 +149,7 @@ public abstract class ApacheCanonicalizer extends TransformService { Utils.readBytesFromStream(in.getOctetStream())))); } } else if (data instanceof DOMSubTreeData) { - DOMSubTreeData subTree = (DOMSubTreeData) data; + DOMSubTreeData subTree = (DOMSubTreeData)data; if (inclusiveNamespaces != null) { return new OctetStreamData(new ByteArrayInputStream (apacheCanonicalizer.canonicalizeSubtree @@ -152,12 +160,13 @@ public abstract class ApacheCanonicalizer extends TransformService { (subTree.getRoot()))); } } else if (data instanceof NodeSetData) { - NodeSetData nsd = (NodeSetData) data; + NodeSetData nsd = (NodeSetData)data; // convert Iterator to Set - nodeSet = Utils.toNodeSet(nsd.iterator()); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Canonicalizing " + nodeSet.size() - + " nodes"); + @SuppressWarnings("unchecked") + Set ns = Utils.toNodeSet(nsd.iterator()); + nodeSet = ns; + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Canonicalizing " + nodeSet.size() + " nodes"); } } else { return new OctetStreamData(new ByteArrayInputStream( @@ -179,7 +188,8 @@ public abstract class ApacheCanonicalizer extends TransformService { } public Data transform(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { + throws TransformException + { if (data == null) { throw new NullPointerException("data must not be null"); } @@ -193,12 +203,11 @@ public abstract class ApacheCanonicalizer extends TransformService { if (apacheTransform == null) { try { - apacheTransform = new Transform - (ownerDoc, getAlgorithm(), transformElem.getChildNodes()); + apacheTransform = + new Transform(ownerDoc, getAlgorithm(), transformElem.getChildNodes()); apacheTransform.setElement(transformElem, xc.getBaseURI()); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Created transform for algorithm: " - + getAlgorithm()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Created transform for algorithm: " + getAlgorithm()); } } catch (Exception ex) { throw new TransformException @@ -208,26 +217,27 @@ public abstract class ApacheCanonicalizer extends TransformService { XMLSignatureInput in; if (data instanceof ApacheData) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "ApacheData = true"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ApacheData = true"); } - in = ((ApacheData) data).getXMLSignatureInput(); + in = ((ApacheData)data).getXMLSignatureInput(); } else if (data instanceof NodeSetData) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "isNodeSet() = true"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "isNodeSet() = true"); } if (data instanceof DOMSubTreeData) { - DOMSubTreeData subTree = (DOMSubTreeData) data; + DOMSubTreeData subTree = (DOMSubTreeData)data; in = new XMLSignatureInput(subTree.getRoot()); in.setExcludeComments(subTree.excludeComments()); } else { - Set nodeSet = - Utils.toNodeSet(((NodeSetData) data).iterator()); + @SuppressWarnings("unchecked") + Set nodeSet = + Utils.toNodeSet(((NodeSetData)data).iterator()); in = new XMLSignatureInput(nodeSet); } } else { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "isNodeSet() = false"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "isNodeSet() = false"); } try { in = new XMLSignatureInput diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheData.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheData.java index 52c5d40274e..add556470bd 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheData.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheData.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: ApacheData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: ApacheData.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -39,5 +41,5 @@ public interface ApacheData extends Data { /** * Returns the XMLSignatureInput. */ - public XMLSignatureInput getXMLSignatureInput(); + XMLSignatureInput getXMLSignatureInput(); } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java index 2d9d2e090e8..7f12cf4a38c 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java @@ -2,32 +2,33 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: ApacheNodeSetData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: ApacheNodeSetData.java 1203890 2011-11-18 22:47:56Z mullan $ */ package org.jcp.xml.dsig.internal.dom; import java.util.Collections; -import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; @@ -65,24 +66,22 @@ public class ApacheNodeSetData implements ApacheData, NodeSetData { return xi; } - private Set getNodeSet(List nodeFilters) { + private Set getNodeSet(List nodeFilters) { if (xi.isNeedsToBeExpanded()) { XMLUtils.circumventBug2650 (XMLUtils.getOwnerDocument(xi.getSubNode())); } - Set inputSet = new LinkedHashSet(); - XMLUtils.getSet - (xi.getSubNode(), inputSet, null, !xi.isExcludeComments()); - Set nodeSet = new LinkedHashSet(); - Iterator i = inputSet.iterator(); - while (i.hasNext()) { - Node currentNode = (Node) i.next(); - Iterator it = nodeFilters.iterator(); + Set inputSet = new LinkedHashSet(); + XMLUtils.getSet(xi.getSubNode(), inputSet, + null, !xi.isExcludeComments()); + Set nodeSet = new LinkedHashSet(); + for (Node currentNode : inputSet) { + Iterator it = nodeFilters.iterator(); boolean skipNode = false; while (it.hasNext() && !skipNode) { - NodeFilter nf = (NodeFilter) it.next(); - if (nf.isNodeInclude(currentNode)!=1) { + NodeFilter nf = it.next(); + if (nf.isNodeInclude(currentNode) != 1) { skipNode = true; } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheOctetStreamData.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheOctetStreamData.java index 719f3358de2..713934d04b9 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheOctetStreamData.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheOctetStreamData.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: ApacheOctetStreamData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: ApacheOctetStreamData.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -37,7 +39,8 @@ public class ApacheOctetStreamData extends OctetStreamData private XMLSignatureInput xi; public ApacheOctetStreamData(XMLSignatureInput xi) - throws CanonicalizationException, IOException { + throws CanonicalizationException, IOException + { super(xi.getOctetStream(), xi.getSourceURI(), xi.getMIMEType()); this.xi = xi; } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java index b1d9c04686a..7df11e6204a 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: ApacheTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: ApacheTransform.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -30,11 +32,9 @@ import java.io.OutputStream; import java.security.InvalidAlgorithmParameterException; import java.security.spec.AlgorithmParameterSpec; import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.NodeList; +import org.w3c.dom.Node; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.transforms.Transform; @@ -58,7 +58,8 @@ public abstract class ApacheTransform extends TransformService { com.sun.org.apache.xml.internal.security.Init.init(); } - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); private Transform apacheTransform; protected Document ownerDoc; protected Element transformElem; @@ -69,37 +70,47 @@ public abstract class ApacheTransform extends TransformService { } public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (context != null && !(context instanceof DOMCryptoContext)) { throw new ClassCastException ("context must be of type DOMCryptoContext"); } + if (parent == null || !(parent instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("parent must be of type DOMStructure"); + } transformElem = (Element) ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); ownerDoc = DOMUtils.getOwnerDocument(transformElem); } public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { + throws MarshalException + { if (context != null && !(context instanceof DOMCryptoContext)) { throw new ClassCastException ("context must be of type DOMCryptoContext"); } + if (parent == null || !(parent instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("parent must be of type DOMStructure"); + } transformElem = (Element) ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); ownerDoc = DOMUtils.getOwnerDocument(transformElem); } public Data transform(Data data, XMLCryptoContext xc) - throws TransformException { + throws TransformException + { if (data == null) { throw new NullPointerException("data must not be null"); } - return transformIt(data, xc, (OutputStream) null); + return transformIt(data, xc, (OutputStream)null); } public Data transform(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { + throws TransformException + { if (data == null) { throw new NullPointerException("data must not be null"); } @@ -110,24 +121,24 @@ public abstract class ApacheTransform extends TransformService { } private Data transformIt(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { - + throws TransformException + { if (ownerDoc == null) { throw new TransformException("transform must be marshalled"); } if (apacheTransform == null) { try { - apacheTransform = new Transform - (ownerDoc, getAlgorithm(), transformElem.getChildNodes()); + apacheTransform = + new Transform(ownerDoc, getAlgorithm(), transformElem.getChildNodes()); apacheTransform.setElement(transformElem, xc.getBaseURI()); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Created transform for algorithm: " - + getAlgorithm()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Created transform for algorithm: " + + getAlgorithm()); } } catch (Exception ex) { - throw new TransformException - ("Couldn't find Transform for: " + getAlgorithm(), ex); + throw new TransformException("Couldn't find Transform for: " + + getAlgorithm(), ex); } } @@ -135,36 +146,37 @@ public abstract class ApacheTransform extends TransformService { String algorithm = getAlgorithm(); if (Transforms.TRANSFORM_XSLT.equals(algorithm)) { throw new TransformException( - "Transform " + algorithm + - " is forbidden when secure validation is enabled"); + "Transform " + algorithm + " is forbidden when secure validation is enabled" + ); } } XMLSignatureInput in; if (data instanceof ApacheData) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "ApacheData = true"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ApacheData = true"); } - in = ((ApacheData) data).getXMLSignatureInput(); + in = ((ApacheData)data).getXMLSignatureInput(); } else if (data instanceof NodeSetData) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "isNodeSet() = true"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "isNodeSet() = true"); } if (data instanceof DOMSubTreeData) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "DOMSubTreeData = true"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "DOMSubTreeData = true"); } - DOMSubTreeData subTree = (DOMSubTreeData) data; + DOMSubTreeData subTree = (DOMSubTreeData)data; in = new XMLSignatureInput(subTree.getRoot()); in.setExcludeComments(subTree.excludeComments()); } else { - Set nodeSet = - Utils.toNodeSet(((NodeSetData) data).iterator()); + @SuppressWarnings("unchecked") + Set nodeSet = + Utils.toNodeSet(((NodeSetData)data).iterator()); in = new XMLSignatureInput(nodeSet); } } else { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "isNodeSet() = false"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "isNodeSet() = false"); } try { in = new XMLSignatureInput diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMBase64Transform.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMBase64Transform.java index 8348b45ece4..3fdf0c88240 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMBase64Transform.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMBase64Transform.java @@ -2,33 +2,34 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMBase64Transform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMBase64Transform.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import java.security.InvalidAlgorithmParameterException; -import javax.xml.crypto.XMLStructure; import javax.xml.crypto.dsig.spec.TransformParameterSpec; /** diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14N11Method.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14N11Method.java index 08c3edc16a6..1338ea6e720 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14N11Method.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14N11Method.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMCanonicalXMLC14N11Method.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id$ */ package org.jcp.xml.dsig.internal.dom; diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14NMethod.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14NMethod.java index 0d37632b769..6e0ff530121 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14NMethod.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14NMethod.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMCanonicalXMLC14NMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMCanonicalXMLC14NMethod.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java index 700694e2dd6..82b7c7608b6 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java @@ -2,33 +2,36 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMCanonicalizationMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMCanonicalizationMethod.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import java.io.OutputStream; import java.security.InvalidAlgorithmParameterException; import java.security.Provider; +import java.security.spec.AlgorithmParameterSpec; import org.w3c.dom.Element; @@ -49,7 +52,8 @@ public class DOMCanonicalizationMethod extends DOMTransform * @param spi TransformService */ public DOMCanonicalizationMethod(TransformService spi) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { super(spi); if (!(spi instanceof ApacheCanonicalizer) && !isC14Nalg(spi.getAlgorithm())) { @@ -66,7 +70,9 @@ public class DOMCanonicalizationMethod extends DOMTransform * @param cmElem a CanonicalizationMethod element */ public DOMCanonicalizationMethod(Element cmElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { super(cmElem, context, provider); if (!(spi instanceof ApacheCanonicalizer) && !isC14Nalg(spi.getAlgorithm())) { @@ -88,15 +94,18 @@ public class DOMCanonicalizationMethod extends DOMTransform * canonicalizing the data */ public Data canonicalize(Data data, XMLCryptoContext xc) - throws TransformException { + throws TransformException + { return transform(data, xc); } public Data canonicalize(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { + throws TransformException + { return transform(data, xc, os); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -105,12 +114,24 @@ public class DOMCanonicalizationMethod extends DOMTransform if (!(o instanceof CanonicalizationMethod)) { return false; } - CanonicalizationMethod ocm = (CanonicalizationMethod) o; + CanonicalizationMethod ocm = (CanonicalizationMethod)o; return (getAlgorithm().equals(ocm.getAlgorithm()) && DOMUtils.paramsEqual(getParameterSpec(), ocm.getParameterSpec())); } + @Override + public int hashCode() { + int result = 17; + result = 31 * result + getAlgorithm().hashCode(); + AlgorithmParameterSpec spec = getParameterSpec(); + if (spec != null) { + result = 31 * result + spec.hashCode(); + } + + return result; + } + private static boolean isC14Nalg(String alg) { return (alg.equals(CanonicalizationMethod.INCLUSIVE) || alg.equals(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS) || diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCryptoBinary.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCryptoBinary.java index 3b963b2a058..f5ff15e2dcd 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCryptoBinary.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCryptoBinary.java @@ -2,34 +2,35 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMCryptoBinary.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMCryptoBinary.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import java.math.BigInteger; import javax.xml.crypto.*; import javax.xml.crypto.dom.DOMCryptoContext; -import javax.xml.crypto.dsig.*; import org.w3c.dom.Node; import org.w3c.dom.Text; diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMDigestMethod.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMDigestMethod.java index e6f81b71e24..06c7bbf7d2c 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMDigestMethod.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMDigestMethod.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMDigestMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMDigestMethod.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -45,7 +47,7 @@ import org.w3c.dom.Node; public abstract class DOMDigestMethod extends DOMStructure implements DigestMethod { - final static String SHA384 = + static final String SHA384 = "http://www.w3.org/2001/04/xmldsig-more#sha384"; // see RFC 4051 private DigestMethodParameterSpec params; @@ -57,13 +59,14 @@ public abstract class DOMDigestMethod extends DOMStructure * appropriate for this digest method */ DOMDigestMethod(AlgorithmParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params != null && !(params instanceof DigestMethodParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type DigestMethodParameterSpec"); } - checkParams((DigestMethodParameterSpec) params); - this.params = (DigestMethodParameterSpec) params; + checkParams((DigestMethodParameterSpec)params); + this.params = (DigestMethodParameterSpec)params; } /** @@ -96,8 +99,8 @@ public abstract class DOMDigestMethod extends DOMStructure } else if (alg.equals(DigestMethod.SHA512)) { return new SHA512(dmElem); } else { - throw new MarshalException - ("unsupported DigestMethod algorithm: " + alg); + throw new MarshalException("unsupported DigestMethod algorithm: " + + alg); } } @@ -112,11 +115,12 @@ public abstract class DOMDigestMethod extends DOMStructure * appropriate for this digest method */ void checkParams(DigestMethodParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params != null) { throw new InvalidAlgorithmParameterException("no parameters " + - "should be specified for the " + getMessageDigestAlgorithm() - + " DigestMethod algorithm"); + "should be specified for the " + getMessageDigestAlgorithm() + + " DigestMethod algorithm"); } } @@ -134,11 +138,13 @@ public abstract class DOMDigestMethod extends DOMStructure * @return the algorithm-specific DigestMethodParameterSpec * @throws MarshalException if the parameters cannot be unmarshalled */ - DigestMethodParameterSpec - unmarshalParams(Element paramsElem) throws MarshalException { + DigestMethodParameterSpec unmarshalParams(Element paramsElem) + throws MarshalException + { throw new MarshalException("no parameters should " + - "be specified for the " + getMessageDigestAlgorithm() + - " DigestMethod algorithm"); + "be specified for the " + + getMessageDigestAlgorithm() + + " DigestMethod algorithm"); } /** @@ -146,11 +152,12 @@ public abstract class DOMDigestMethod extends DOMStructure * method to marshal any algorithm-specific parameters. */ public void marshal(Node parent, String prefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - Element dmElem = DOMUtils.createElement - (ownerDoc, "DigestMethod", XMLSignature.XMLNS, prefix); + Element dmElem = DOMUtils.createElement(ownerDoc, "DigestMethod", + XMLSignature.XMLNS, prefix); DOMUtils.setAttribute(dmElem, "Algorithm", getAlgorithm()); if (params != null) { @@ -160,6 +167,7 @@ public abstract class DOMDigestMethod extends DOMStructure parent.appendChild(dmElem); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -168,7 +176,7 @@ public abstract class DOMDigestMethod extends DOMStructure if (!(o instanceof DigestMethod)) { return false; } - DigestMethod odm = (DigestMethod) o; + DigestMethod odm = (DigestMethod)o; boolean paramsEqual = (params == null ? odm.getParameterSpec() == null : params.equals(odm.getParameterSpec())); @@ -176,6 +184,17 @@ public abstract class DOMDigestMethod extends DOMStructure return (getAlgorithm().equals(odm.getAlgorithm()) && paramsEqual); } + @Override + public int hashCode() { + int result = 17; + if (params != null) { + result = 31 * result + params.hashCode(); + } + result = 31 * result + getAlgorithm().hashCode(); + + return result; + } + /** * Marshals the algorithm-specific parameters to an Element and * appends it to the specified parent element. By default, this method @@ -187,10 +206,12 @@ public abstract class DOMDigestMethod extends DOMStructure * @throws MarshalException if the parameters cannot be marshalled */ void marshalParams(Element parent, String prefix) - throws MarshalException { + throws MarshalException + { throw new MarshalException("no parameters should " + - "be specified for the " + getMessageDigestAlgorithm() + - " DigestMethod algorithm"); + "be specified for the " + + getMessageDigestAlgorithm() + + " DigestMethod algorithm"); } /** diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMEnvelopedTransform.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMEnvelopedTransform.java index 0f0917ecd7a..163cd6804a6 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMEnvelopedTransform.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMEnvelopedTransform.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMEnvelopedTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMEnvelopedTransform.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMExcC14NMethod.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMExcC14NMethod.java index 12d709117df..46943881fb3 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMExcC14NMethod.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMExcC14NMethod.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMExcC14NMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMExcC14NMethod.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -50,18 +52,20 @@ import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerExcepti public final class DOMExcC14NMethod extends ApacheCanonicalizer { public void init(TransformParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params != null) { if (!(params instanceof ExcC14NParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type ExcC14NParameterSpec"); } - this.params = (C14NMethodParameterSpec) params; + this.params = (C14NMethodParameterSpec)params; } } public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { super.init(parent, context); Element paramsElem = DOMUtils.getFirstChildElement(transformElem); if (paramsElem == null) { @@ -77,7 +81,7 @@ public final class DOMExcC14NMethod extends ApacheCanonicalizer { this.inclusiveNamespaces = prefixListAttr; int begin = 0; int end = prefixListAttr.indexOf(' '); - List prefixList = new ArrayList(); + List prefixList = new ArrayList(); while (end != -1) { prefixList.add(prefixListAttr.substring(begin, end)); begin = end + 1; @@ -90,39 +94,42 @@ public final class DOMExcC14NMethod extends ApacheCanonicalizer { } public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { - + throws MarshalException + { super.marshalParams(parent, context); AlgorithmParameterSpec spec = getParameterSpec(); if (spec == null) { return; } - String prefix = - DOMUtils.getNSPrefix(context, CanonicalizationMethod.EXCLUSIVE); - Element excElem = DOMUtils.createElement - (ownerDoc, "InclusiveNamespaces", - CanonicalizationMethod.EXCLUSIVE, prefix); + String prefix = DOMUtils.getNSPrefix(context, + CanonicalizationMethod.EXCLUSIVE); + Element eElem = DOMUtils.createElement(ownerDoc, + "InclusiveNamespaces", + CanonicalizationMethod.EXCLUSIVE, + prefix); if (prefix == null || prefix.length() == 0) { - excElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", - CanonicalizationMethod.EXCLUSIVE); + eElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", + CanonicalizationMethod.EXCLUSIVE); } else { - excElem.setAttributeNS("http://www.w3.org/2000/xmlns/", - "xmlns:" + prefix, CanonicalizationMethod.EXCLUSIVE); + eElem.setAttributeNS("http://www.w3.org/2000/xmlns/", + "xmlns:" + prefix, + CanonicalizationMethod.EXCLUSIVE); } - ExcC14NParameterSpec params = (ExcC14NParameterSpec) spec; + ExcC14NParameterSpec params = (ExcC14NParameterSpec)spec; StringBuffer prefixListAttr = new StringBuffer(""); - List prefixList = params.getPrefixList(); + @SuppressWarnings("unchecked") + List prefixList = params.getPrefixList(); for (int i = 0, size = prefixList.size(); i < size; i++) { - prefixListAttr.append((String) prefixList.get(i)); + prefixListAttr.append(prefixList.get(i)); if (i < size - 1) { prefixListAttr.append(" "); } } - DOMUtils.setAttribute(excElem, "PrefixList", prefixListAttr.toString()); + DOMUtils.setAttribute(eElem, "PrefixList", prefixListAttr.toString()); this.inclusiveNamespaces = prefixListAttr.toString(); - transformElem.appendChild(excElem); + transformElem.appendChild(eElem); } public String getParamsNSURI() { @@ -130,13 +137,13 @@ public final class DOMExcC14NMethod extends ApacheCanonicalizer { } public Data transform(Data data, XMLCryptoContext xc) - throws TransformException { - + throws TransformException + { // ignore comments if dereferencing same-document URI that require // you to omit comments, even if the Transform says otherwise - // this is to be compliant with section 4.3.3.3 of W3C Rec. if (data instanceof DOMSubTreeData) { - DOMSubTreeData subTree = (DOMSubTreeData) data; + DOMSubTreeData subTree = (DOMSubTreeData)data; if (subTree.excludeComments()) { try { apacheCanonicalizer = Canonicalizer.getInstance diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java index b72d788633d..d193fa214e4 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2009, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMHMACSignatureMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMHMACSignatureMethod.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -38,8 +40,6 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.security.spec.AlgorithmParameterSpec; -import java.util.logging.Level; -import java.util.logging.Logger; import javax.crypto.Mac; import javax.crypto.SecretKey; import org.w3c.dom.Document; @@ -52,13 +52,23 @@ import org.jcp.xml.dsig.internal.MacOutputStream; * * @author Sean Mullan */ -public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { +public abstract class DOMHMACSignatureMethod extends AbstractDOMSignatureMethod { + + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + + // see RFC 4051 for these algorithm definitions + static final String HMAC_SHA256 = + "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"; + static final String HMAC_SHA384 = + "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384"; + static final String HMAC_SHA512 = + "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512"; - private static Logger log = - Logger.getLogger("org.jcp.xml.dsig.internal.dom"); private Mac hmac; private int outputLength; private boolean outputLengthSet; + private SignatureMethodParameterSpec params; /** * Creates a DOMHMACSignatureMethod with the specified params @@ -67,8 +77,10 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { * @throws InvalidAlgorithmParameterException if params are inappropriate */ DOMHMACSignatureMethod(AlgorithmParameterSpec params) - throws InvalidAlgorithmParameterException { - super(params); + throws InvalidAlgorithmParameterException + { + checkParams((SignatureMethodParameterSpec)params); + this.params = (SignatureMethodParameterSpec)params; } /** @@ -77,54 +89,64 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { * @param smElem a SignatureMethod element */ DOMHMACSignatureMethod(Element smElem) throws MarshalException { - super(smElem); + Element paramsElem = DOMUtils.getFirstChildElement(smElem); + if (paramsElem != null) { + params = unmarshalParams(paramsElem); + } + try { + checkParams(params); + } catch (InvalidAlgorithmParameterException iape) { + throw new MarshalException(iape); + } } void checkParams(SignatureMethodParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params != null) { if (!(params instanceof HMACParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type HMACParameterSpec"); } - outputLength = ((HMACParameterSpec) params).getOutputLength(); + outputLength = ((HMACParameterSpec)params).getOutputLength(); outputLengthSet = true; - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, - "Setting outputLength from HMACParameterSpec to: " - + outputLength); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Setting outputLength from HMACParameterSpec to: " + outputLength); } - } else { - outputLength = -1; } } + public final AlgorithmParameterSpec getParameterSpec() { + return params; + } + SignatureMethodParameterSpec unmarshalParams(Element paramsElem) - throws MarshalException { - outputLength = new Integer - (paramsElem.getFirstChild().getNodeValue()).intValue(); + throws MarshalException + { + outputLength = Integer.valueOf(paramsElem.getFirstChild().getNodeValue()).intValue(); outputLengthSet = true; - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "unmarshalled outputLength: " + outputLength); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "unmarshalled outputLength: " + outputLength); } return new HMACParameterSpec(outputLength); } void marshalParams(Element parent, String prefix) - throws MarshalException { - + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); Element hmacElem = DOMUtils.createElement(ownerDoc, "HMACOutputLength", - XMLSignature.XMLNS, prefix); + XMLSignature.XMLNS, prefix); hmacElem.appendChild(ownerDoc.createTextNode (String.valueOf(outputLength))); parent.appendChild(hmacElem); } - boolean verify(Key key, DOMSignedInfo si, byte[] sig, - XMLValidateContext context) - throws InvalidKeyException, SignatureException, XMLSignatureException { + boolean verify(Key key, SignedInfo si, byte[] sig, + XMLValidateContext context) + throws InvalidKeyException, SignatureException, XMLSignatureException + { if (key == null || si == null || sig == null) { throw new NullPointerException(); } @@ -133,7 +155,7 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { } if (hmac == null) { try { - hmac = Mac.getInstance(getSignatureAlgorithm()); + hmac = Mac.getInstance(getJCAAlgorithm()); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } @@ -142,15 +164,16 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { throw new XMLSignatureException ("HMACOutputLength must not be less than " + getDigestLength()); } - hmac.init((SecretKey) key); - si.canonicalize(context, new MacOutputStream(hmac)); + hmac.init((SecretKey)key); + ((DOMSignedInfo)si).canonicalize(context, new MacOutputStream(hmac)); byte[] result = hmac.doFinal(); return MessageDigest.isEqual(sig, result); } - byte[] sign(Key key, DOMSignedInfo si, XMLSignContext context) - throws InvalidKeyException, XMLSignatureException { + byte[] sign(Key key, SignedInfo si, XMLSignContext context) + throws InvalidKeyException, XMLSignatureException + { if (key == null || si == null) { throw new NullPointerException(); } @@ -159,7 +182,7 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { } if (hmac == null) { try { - hmac = Mac.getInstance(getSignatureAlgorithm()); + hmac = Mac.getInstance(getJCAAlgorithm()); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } @@ -168,8 +191,8 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { throw new XMLSignatureException ("HMACOutputLength must not be less than " + getDigestLength()); } - hmac.init((SecretKey) key); - si.canonicalize(context, new MacOutputStream(hmac)); + hmac.init((SecretKey)key); + ((DOMSignedInfo)si).canonicalize(context, new MacOutputStream(hmac)); return hmac.doFinal(); } @@ -180,11 +203,15 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { if (!(spec instanceof HMACParameterSpec)) { return false; } - HMACParameterSpec ospec = (HMACParameterSpec) spec; + HMACParameterSpec ospec = (HMACParameterSpec)spec; return (outputLength == ospec.getOutputLength()); } + Type getAlgorithmType() { + return Type.HMAC; + } + /** * Returns the output length of the hash/digest. */ @@ -201,7 +228,7 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { public String getAlgorithm() { return SignatureMethod.HMAC_SHA1; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "HmacSHA1"; } int getDigestLength() { @@ -220,7 +247,7 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { public String getAlgorithm() { return HMAC_SHA256; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "HmacSHA256"; } int getDigestLength() { @@ -239,7 +266,7 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { public String getAlgorithm() { return HMAC_SHA384; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "HmacSHA384"; } int getDigestLength() { @@ -258,7 +285,7 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { public String getAlgorithm() { return HMAC_SHA512; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "HmacSHA512"; } int getDigestLength() { diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java index e9a3f1eca03..a7e70c07fc0 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java @@ -2,38 +2,40 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMKeyInfo.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMKeyInfo.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import javax.xml.crypto.*; import javax.xml.crypto.dsig.*; -import javax.xml.crypto.dsig.dom.DOMSignContext; import javax.xml.crypto.dsig.keyinfo.KeyInfo; import javax.xml.crypto.dom.*; import java.security.Provider; import java.util.*; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -48,7 +50,7 @@ import org.w3c.dom.NodeList; public final class DOMKeyInfo extends DOMStructure implements KeyInfo { private final String id; - private final List keyInfoTypes; + private final List keyInfoTypes; /** * Creates a DOMKeyInfo. @@ -62,21 +64,21 @@ public final class DOMKeyInfo extends DOMStructure implements KeyInfo { * @throws ClassCastException if content contains any entries * that are not of type {@link XMLStructure} */ - public DOMKeyInfo(List content, String id) { + public DOMKeyInfo(List content, String id) { if (content == null) { throw new NullPointerException("content cannot be null"); } - List typesCopy = new ArrayList(content); - if (typesCopy.isEmpty()) { + this.keyInfoTypes = + Collections.unmodifiableList(new ArrayList(content)); + if (this.keyInfoTypes.isEmpty()) { throw new IllegalArgumentException("content cannot be empty"); } - for (int i = 0, size = typesCopy.size(); i < size; i++) { - if (!(typesCopy.get(i) instanceof XMLStructure)) { + for (int i = 0, size = this.keyInfoTypes.size(); i < size; i++) { + if (!(this.keyInfoTypes.get(i) instanceof XMLStructure)) { throw new ClassCastException ("content["+i+"] is not a valid KeyInfo type"); } } - this.keyInfoTypes = Collections.unmodifiableList(typesCopy); this.id = id; } @@ -86,7 +88,9 @@ public final class DOMKeyInfo extends DOMStructure implements KeyInfo { * @param kiElem KeyInfo element */ public DOMKeyInfo(Element kiElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { // get Id attribute, if specified Attr attr = kiElem.getAttributeNodeNS(null, "Id"); if (attr != null) { @@ -103,24 +107,24 @@ public final class DOMKeyInfo extends DOMStructure implements KeyInfo { throw new MarshalException ("KeyInfo must contain at least one type"); } - List content = new ArrayList(length); + List content = new ArrayList(length); for (int i = 0; i < length; i++) { Node child = nl.item(i); // ignore all non-Element nodes if (child.getNodeType() != Node.ELEMENT_NODE) { continue; } - Element childElem = (Element) child; + Element childElem = (Element)child; String localName = childElem.getLocalName(); if (localName.equals("X509Data")) { content.add(new DOMX509Data(childElem)); } else if (localName.equals("KeyName")) { content.add(new DOMKeyName(childElem)); } else if (localName.equals("KeyValue")) { - content.add(new DOMKeyValue(childElem)); + content.add(DOMKeyValue.unmarshal(childElem)); } else if (localName.equals("RetrievalMethod")) { - content.add - (new DOMRetrievalMethod(childElem, context, provider)); + content.add(new DOMRetrievalMethod(childElem, + context, provider)); } else if (localName.equals("PGPData")) { content.add(new DOMPGPData(childElem)); } else { //may be MgmtData, SPKIData or element from other namespace @@ -139,51 +143,58 @@ public final class DOMKeyInfo extends DOMStructure implements KeyInfo { } public void marshal(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { + throws MarshalException + { if (parent == null) { throw new NullPointerException("parent is null"); } + if (!(parent instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("parent must be of type DOMStructure"); + } - Node pNode = ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); + Node pNode = ((javax.xml.crypto.dom.DOMStructure)parent).getNode(); String dsPrefix = DOMUtils.getSignaturePrefix(context); Element kiElem = DOMUtils.createElement (DOMUtils.getOwnerDocument(pNode), "KeyInfo", XMLSignature.XMLNS, dsPrefix); if (dsPrefix == null || dsPrefix.length() == 0) { - kiElem.setAttributeNS - ("http://www.w3.org/2000/xmlns/", "xmlns", XMLSignature.XMLNS); + kiElem.setAttributeNS("http://www.w3.org/2000/xmlns/", + "xmlns", XMLSignature.XMLNS); } else { - kiElem.setAttributeNS - ("http://www.w3.org/2000/xmlns/", "xmlns:" + dsPrefix, - XMLSignature.XMLNS); + kiElem.setAttributeNS("http://www.w3.org/2000/xmlns/", + "xmlns:" + dsPrefix, XMLSignature.XMLNS); } - marshal(pNode, kiElem, null, dsPrefix, (DOMCryptoContext) context); + marshal(pNode, kiElem, null, dsPrefix, (DOMCryptoContext)context); } public void marshal(Node parent, String dsPrefix, - DOMCryptoContext context) throws MarshalException { + DOMCryptoContext context) + throws MarshalException + { marshal(parent, null, dsPrefix, context); } public void marshal(Node parent, Node nextSibling, String dsPrefix, - DOMCryptoContext context) throws MarshalException { + DOMCryptoContext context) + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element kiElem = DOMUtils.createElement - (ownerDoc, "KeyInfo", XMLSignature.XMLNS, dsPrefix); + Element kiElem = DOMUtils.createElement(ownerDoc, "KeyInfo", + XMLSignature.XMLNS, dsPrefix); marshal(parent, kiElem, nextSibling, dsPrefix, context); } private void marshal(Node parent, Element kiElem, Node nextSibling, - String dsPrefix, DOMCryptoContext context) throws MarshalException { + String dsPrefix, DOMCryptoContext context) + throws MarshalException + { // create and append KeyInfoType elements - for (int i = 0, size = keyInfoTypes.size(); i < size; i++) { - XMLStructure kiType = (XMLStructure) keyInfoTypes.get(i); + for (XMLStructure kiType : keyInfoTypes) { if (kiType instanceof DOMStructure) { - ((DOMStructure) kiType).marshal(kiElem, dsPrefix, context); + ((DOMStructure)kiType).marshal(kiElem, dsPrefix, context); } else { DOMUtils.appendChild(kiElem, - ((javax.xml.crypto.dom.DOMStructure) kiType).getNode()); + ((javax.xml.crypto.dom.DOMStructure)kiType).getNode()); } } @@ -193,6 +204,7 @@ public final class DOMKeyInfo extends DOMStructure implements KeyInfo { parent.insertBefore(kiElem, nextSibling); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -201,11 +213,22 @@ public final class DOMKeyInfo extends DOMStructure implements KeyInfo { if (!(o instanceof KeyInfo)) { return false; } - KeyInfo oki = (KeyInfo) o; + KeyInfo oki = (KeyInfo)o; - boolean idsEqual = (id == null ? oki.getId() == null : - id.equals(oki.getId())); + boolean idsEqual = (id == null ? oki.getId() == null + : id.equals(oki.getId())); return (keyInfoTypes.equals(oki.getContent()) && idsEqual); } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + result = 31 * result + keyInfoTypes.hashCode(); + + return result; + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfoFactory.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfoFactory.java index 4db8575c792..33f2a227c7c 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfoFactory.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfoFactory.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMKeyInfoFactory.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMKeyInfoFactory.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,8 +33,7 @@ import java.security.KeyException; import java.security.PublicKey; import java.util.List; import javax.xml.crypto.*; -import javax.xml.crypto.dsig.*; -import javax.xml.crypto.dom.*; +import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.keyinfo.*; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -51,6 +52,7 @@ public final class DOMKeyInfoFactory extends KeyInfoFactory { return newKeyInfo(content, null); } + @SuppressWarnings("unchecked") public KeyInfo newKeyInfo(List content, String id) { return new DOMKeyInfo(content, id); } @@ -60,17 +62,28 @@ public final class DOMKeyInfoFactory extends KeyInfoFactory { } public KeyValue newKeyValue(PublicKey key) throws KeyException { - return new DOMKeyValue(key); + String algorithm = key.getAlgorithm(); + if (algorithm.equals("DSA")) { + return new DOMKeyValue.DSA(key); + } else if (algorithm.equals("RSA")) { + return new DOMKeyValue.RSA(key); + } else if (algorithm.equals("EC")) { + return new DOMKeyValue.EC(key); + } else { + throw new KeyException("unsupported key algorithm: " + algorithm); + } } public PGPData newPGPData(byte[] keyId) { return newPGPData(keyId, null, null); } + @SuppressWarnings("unchecked") public PGPData newPGPData(byte[] keyId, byte[] keyPacket, List other) { return new DOMPGPData(keyId, keyPacket, other); } + @SuppressWarnings("unchecked") public PGPData newPGPData(byte[] keyPacket, List other) { return new DOMPGPData(keyPacket, other); } @@ -79,6 +92,7 @@ public final class DOMKeyInfoFactory extends KeyInfoFactory { return newRetrievalMethod(uri, null, null); } + @SuppressWarnings("unchecked") public RetrievalMethod newRetrievalMethod(String uri, String type, List transforms) { if (uri == null) { @@ -87,6 +101,7 @@ public final class DOMKeyInfoFactory extends KeyInfoFactory { return new DOMRetrievalMethod(uri, type, transforms); } + @SuppressWarnings("unchecked") public X509Data newX509Data(List content) { return new DOMX509Data(content); } @@ -113,6 +128,9 @@ public final class DOMKeyInfoFactory extends KeyInfoFactory { if (xmlStructure == null) { throw new NullPointerException("xmlStructure cannot be null"); } + if (!(xmlStructure instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("xmlStructure must be of type DOMStructure"); + } Node node = ((javax.xml.crypto.dom.DOMStructure) xmlStructure).getNode(); node.normalize(); @@ -134,9 +152,14 @@ public final class DOMKeyInfoFactory extends KeyInfoFactory { "support DOM Level 2 and be namespace aware"); } if (tag.equals("KeyInfo")) { - return new DOMKeyInfo(element, null, getProvider()); + return new DOMKeyInfo(element, new UnmarshalContext(), getProvider()); } else { throw new MarshalException("invalid KeyInfo tag: " + tag); } } + + private static class UnmarshalContext extends DOMCryptoContext { + UnmarshalContext() {} + } + } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyName.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyName.java index 55d4b881bc6..41db19aa725 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyName.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyName.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMKeyName.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMKeyName.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -71,15 +73,17 @@ public final class DOMKeyName extends DOMStructure implements KeyName { } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); // prepend namespace prefix, if necessary - Element knElem = DOMUtils.createElement - (ownerDoc, "KeyName", XMLSignature.XMLNS, dsPrefix); + Element knElem = DOMUtils.createElement(ownerDoc, "KeyName", + XMLSignature.XMLNS, dsPrefix); knElem.appendChild(ownerDoc.createTextNode(name)); parent.appendChild(knElem); } + @Override public boolean equals(Object obj) { if (this == obj) { return true; @@ -87,7 +91,15 @@ public final class DOMKeyName extends DOMStructure implements KeyName { if (!(obj instanceof KeyName)) { return false; } - KeyName okn = (KeyName) obj; + KeyName okn = (KeyName)obj; return name.equals(okn.getName()); } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + name.hashCode(); + + return result; + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java index 6ff3eb79d04..9ebf06c2afb 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMKeyValue.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMKeyValue.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,14 +33,25 @@ import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.keyinfo.KeyValue; +// import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.security.AccessController; import java.security.KeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; import java.security.PublicKey; import java.security.interfaces.DSAParams; import java.security.interfaces.DSAPublicKey; +import java.security.interfaces.ECPublicKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.DSAPublicKeySpec; +import java.security.spec.ECParameterSpec; +import java.security.spec.ECPoint; +import java.security.spec.ECPublicKeySpec; +import java.security.spec.EllipticCurve; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.security.spec.RSAPublicKeySpec; @@ -46,59 +59,46 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; +import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException; +import com.sun.org.apache.xml.internal.security.utils.Base64; + /** * DOM-based implementation of KeyValue. * * @author Sean Mullan */ -public final class DOMKeyValue extends DOMStructure implements KeyValue { +public abstract class DOMKeyValue extends DOMStructure implements KeyValue { - private KeyFactory rsakf, dsakf; - private PublicKey publicKey; - private javax.xml.crypto.dom.DOMStructure externalPublicKey; + private static final String XMLDSIG_11_XMLNS + = "http://www.w3.org/2009/xmldsig11#"; + private final PublicKey publicKey; - // DSAKeyValue CryptoBinaries - private DOMCryptoBinary p, q, g, y, j, seed, pgen; - - // RSAKeyValue CryptoBinaries - private DOMCryptoBinary modulus, exponent; - - public DOMKeyValue(PublicKey key) throws KeyException { + public DOMKeyValue(PublicKey key) throws KeyException { if (key == null) { throw new NullPointerException("key cannot be null"); } this.publicKey = key; - if (key instanceof DSAPublicKey) { - DSAPublicKey dkey = (DSAPublicKey) key; - DSAParams params = dkey.getParams(); - p = new DOMCryptoBinary(params.getP()); - q = new DOMCryptoBinary(params.getQ()); - g = new DOMCryptoBinary(params.getG()); - y = new DOMCryptoBinary(dkey.getY()); - } else if (key instanceof RSAPublicKey) { - RSAPublicKey rkey = (RSAPublicKey) key; - exponent = new DOMCryptoBinary(rkey.getPublicExponent()); - modulus = new DOMCryptoBinary(rkey.getModulus()); - } else { - throw new KeyException("unsupported key algorithm: " + - key.getAlgorithm()); - } } /** * Creates a DOMKeyValue from an element. * - * @param kvElem a KeyValue element + * @param kvtElem a KeyValue child element */ - public DOMKeyValue(Element kvElem) throws MarshalException { + public DOMKeyValue(Element kvtElem) throws MarshalException { + this.publicKey = unmarshalKeyValue(kvtElem); + } + + static KeyValue unmarshal(Element kvElem) throws MarshalException { Element kvtElem = DOMUtils.getFirstChildElement(kvElem); if (kvtElem.getLocalName().equals("DSAKeyValue")) { - publicKey = unmarshalDSAKeyValue(kvtElem); + return new DSA(kvtElem); } else if (kvtElem.getLocalName().equals("RSAKeyValue")) { - publicKey = unmarshalRSAKeyValue(kvtElem); + return new RSA(kvtElem); + } else if (kvtElem.getLocalName().equals("ECKeyValue")) { + return new EC(kvtElem); } else { - publicKey = null; - externalPublicKey = new javax.xml.crypto.dom.DOMStructure(kvtElem); + return new Unknown(kvtElem); } } @@ -111,133 +111,25 @@ public final class DOMKeyValue extends DOMStructure implements KeyValue { } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); // create KeyValue element - Element kvElem = DOMUtils.createElement - (ownerDoc, "KeyValue", XMLSignature.XMLNS, dsPrefix); + Element kvElem = DOMUtils.createElement(ownerDoc, "KeyValue", + XMLSignature.XMLNS, dsPrefix); marshalPublicKey(kvElem, ownerDoc, dsPrefix, context); parent.appendChild(kvElem); } - private void marshalPublicKey(Node parent, Document doc, String dsPrefix, - DOMCryptoContext context) throws MarshalException { - if (publicKey != null) { - if (publicKey instanceof DSAPublicKey) { - // create and append DSAKeyValue element - marshalDSAPublicKey(parent, doc, dsPrefix, context); - } else if (publicKey instanceof RSAPublicKey) { - // create and append RSAKeyValue element - marshalRSAPublicKey(parent, doc, dsPrefix, context); - } else { - throw new MarshalException(publicKey.getAlgorithm() + - " public key algorithm not supported"); - } - } else { - parent.appendChild(externalPublicKey.getNode()); - } - } + abstract void marshalPublicKey(Node parent, Document doc, String dsPrefix, + DOMCryptoContext context) throws MarshalException; - private void marshalDSAPublicKey(Node parent, Document doc, - String dsPrefix, DOMCryptoContext context) throws MarshalException { - Element dsaElem = DOMUtils.createElement - (doc, "DSAKeyValue", XMLSignature.XMLNS, dsPrefix); - // parameters J, Seed & PgenCounter are not included - Element pElem = DOMUtils.createElement - (doc, "P", XMLSignature.XMLNS, dsPrefix); - Element qElem = DOMUtils.createElement - (doc, "Q", XMLSignature.XMLNS, dsPrefix); - Element gElem = DOMUtils.createElement - (doc, "G", XMLSignature.XMLNS, dsPrefix); - Element yElem = DOMUtils.createElement - (doc, "Y", XMLSignature.XMLNS, dsPrefix); - p.marshal(pElem, dsPrefix, context); - q.marshal(qElem, dsPrefix, context); - g.marshal(gElem, dsPrefix, context); - y.marshal(yElem, dsPrefix, context); - dsaElem.appendChild(pElem); - dsaElem.appendChild(qElem); - dsaElem.appendChild(gElem); - dsaElem.appendChild(yElem); - parent.appendChild(dsaElem); - } + abstract PublicKey unmarshalKeyValue(Element kvtElem) + throws MarshalException; - private void marshalRSAPublicKey(Node parent, Document doc, - String dsPrefix, DOMCryptoContext context) throws MarshalException { - Element rsaElem = DOMUtils.createElement - (doc, "RSAKeyValue", XMLSignature.XMLNS, dsPrefix); - Element modulusElem = DOMUtils.createElement - (doc, "Modulus", XMLSignature.XMLNS, dsPrefix); - Element exponentElem = DOMUtils.createElement - (doc, "Exponent", XMLSignature.XMLNS, dsPrefix); - modulus.marshal(modulusElem, dsPrefix, context); - exponent.marshal(exponentElem, dsPrefix, context); - rsaElem.appendChild(modulusElem); - rsaElem.appendChild(exponentElem); - parent.appendChild(rsaElem); - } - - private DSAPublicKey unmarshalDSAKeyValue(Element kvtElem) - throws MarshalException { - if (dsakf == null) { - try { - dsakf = KeyFactory.getInstance("DSA"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("unable to create DSA KeyFactory: " + - e.getMessage()); - } - } - Element curElem = DOMUtils.getFirstChildElement(kvtElem); - // check for P and Q - if (curElem.getLocalName().equals("P")) { - p = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - q = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - } - if (curElem.getLocalName().equals("G")) { - g = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - } - y = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - if (curElem != null && curElem.getLocalName().equals("J")) { - j = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - } - if (curElem != null) { - seed = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - pgen = new DOMCryptoBinary(curElem.getFirstChild()); - } - //@@@ do we care about j, pgenCounter or seed? - DSAPublicKeySpec spec = new DSAPublicKeySpec - (y.getBigNum(), p.getBigNum(), q.getBigNum(), g.getBigNum()); - return (DSAPublicKey) generatePublicKey(dsakf, spec); - } - - private RSAPublicKey unmarshalRSAKeyValue(Element kvtElem) - throws MarshalException { - if (rsakf == null) { - try { - rsakf = KeyFactory.getInstance("RSA"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("unable to create RSA KeyFactory: " + - e.getMessage()); - } - } - Element modulusElem = DOMUtils.getFirstChildElement(kvtElem); - modulus = new DOMCryptoBinary(modulusElem.getFirstChild()); - Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem); - exponent = new DOMCryptoBinary(exponentElem.getFirstChild()); - RSAPublicKeySpec spec = new RSAPublicKeySpec - (modulus.getBigNum(), exponent.getBigNum()); - return (RSAPublicKey) generatePublicKey(rsakf, spec); - } - - private PublicKey generatePublicKey(KeyFactory kf, KeySpec keyspec) { + private static PublicKey generatePublicKey(KeyFactory kf, KeySpec keyspec) { try { return kf.generatePublic(keyspec); } catch (InvalidKeySpecException e) { @@ -246,6 +138,7 @@ public final class DOMKeyValue extends DOMStructure implements KeyValue { } } + @Override public boolean equals(Object obj) { if (this == obj) { return true; @@ -254,7 +147,7 @@ public final class DOMKeyValue extends DOMStructure implements KeyValue { return false; } try { - KeyValue kv = (KeyValue) obj; + KeyValue kv = (KeyValue)obj; if (publicKey == null ) { if (kv.getPublicKey() != null) { return false; @@ -269,4 +162,340 @@ public final class DOMKeyValue extends DOMStructure implements KeyValue { return true; } + + @Override + public int hashCode() { + int result = 17; + if (publicKey != null) { + result = 31 * result + publicKey.hashCode(); + } + + return result; + } + + static final class RSA extends DOMKeyValue { + // RSAKeyValue CryptoBinaries + private DOMCryptoBinary modulus, exponent; + private KeyFactory rsakf; + + RSA(PublicKey key) throws KeyException { + super(key); + RSAPublicKey rkey = (RSAPublicKey)key; + exponent = new DOMCryptoBinary(rkey.getPublicExponent()); + modulus = new DOMCryptoBinary(rkey.getModulus()); + } + + RSA(Element elem) throws MarshalException { + super(elem); + } + + void marshalPublicKey(Node parent, Document doc, String dsPrefix, + DOMCryptoContext context) throws MarshalException { + Element rsaElem = DOMUtils.createElement(doc, "RSAKeyValue", + XMLSignature.XMLNS, + dsPrefix); + Element modulusElem = DOMUtils.createElement(doc, "Modulus", + XMLSignature.XMLNS, + dsPrefix); + Element exponentElem = DOMUtils.createElement(doc, "Exponent", + XMLSignature.XMLNS, + dsPrefix); + modulus.marshal(modulusElem, dsPrefix, context); + exponent.marshal(exponentElem, dsPrefix, context); + rsaElem.appendChild(modulusElem); + rsaElem.appendChild(exponentElem); + parent.appendChild(rsaElem); + } + + PublicKey unmarshalKeyValue(Element kvtElem) + throws MarshalException + { + if (rsakf == null) { + try { + rsakf = KeyFactory.getInstance("RSA"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException + ("unable to create RSA KeyFactory: " + e.getMessage()); + } + } + Element modulusElem = DOMUtils.getFirstChildElement(kvtElem); + modulus = new DOMCryptoBinary(modulusElem.getFirstChild()); + Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem); + exponent = new DOMCryptoBinary(exponentElem.getFirstChild()); + RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus.getBigNum(), + exponent.getBigNum()); + return generatePublicKey(rsakf, spec); + } + } + + static final class DSA extends DOMKeyValue { + // DSAKeyValue CryptoBinaries + private DOMCryptoBinary p, q, g, y, j; //, seed, pgen; + private KeyFactory dsakf; + + DSA(PublicKey key) throws KeyException { + super(key); + DSAPublicKey dkey = (DSAPublicKey) key; + DSAParams params = dkey.getParams(); + p = new DOMCryptoBinary(params.getP()); + q = new DOMCryptoBinary(params.getQ()); + g = new DOMCryptoBinary(params.getG()); + y = new DOMCryptoBinary(dkey.getY()); + } + + DSA(Element elem) throws MarshalException { + super(elem); + } + + void marshalPublicKey(Node parent, Document doc, String dsPrefix, + DOMCryptoContext context) + throws MarshalException + { + Element dsaElem = DOMUtils.createElement(doc, "DSAKeyValue", + XMLSignature.XMLNS, + dsPrefix); + // parameters J, Seed & PgenCounter are not included + Element pElem = DOMUtils.createElement(doc, "P", XMLSignature.XMLNS, + dsPrefix); + Element qElem = DOMUtils.createElement(doc, "Q", XMLSignature.XMLNS, + dsPrefix); + Element gElem = DOMUtils.createElement(doc, "G", XMLSignature.XMLNS, + dsPrefix); + Element yElem = DOMUtils.createElement(doc, "Y", XMLSignature.XMLNS, + dsPrefix); + p.marshal(pElem, dsPrefix, context); + q.marshal(qElem, dsPrefix, context); + g.marshal(gElem, dsPrefix, context); + y.marshal(yElem, dsPrefix, context); + dsaElem.appendChild(pElem); + dsaElem.appendChild(qElem); + dsaElem.appendChild(gElem); + dsaElem.appendChild(yElem); + parent.appendChild(dsaElem); + } + + PublicKey unmarshalKeyValue(Element kvtElem) + throws MarshalException + { + if (dsakf == null) { + try { + dsakf = KeyFactory.getInstance("DSA"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException + ("unable to create DSA KeyFactory: " + e.getMessage()); + } + } + Element curElem = DOMUtils.getFirstChildElement(kvtElem); + // check for P and Q + if (curElem.getLocalName().equals("P")) { + p = new DOMCryptoBinary(curElem.getFirstChild()); + curElem = DOMUtils.getNextSiblingElement(curElem); + q = new DOMCryptoBinary(curElem.getFirstChild()); + curElem = DOMUtils.getNextSiblingElement(curElem); + } + if (curElem.getLocalName().equals("G")) { + g = new DOMCryptoBinary(curElem.getFirstChild()); + curElem = DOMUtils.getNextSiblingElement(curElem); + } + y = new DOMCryptoBinary(curElem.getFirstChild()); + curElem = DOMUtils.getNextSiblingElement(curElem); + if (curElem != null && curElem.getLocalName().equals("J")) { + j = new DOMCryptoBinary(curElem.getFirstChild()); + // curElem = DOMUtils.getNextSiblingElement(curElem); + } + /* + if (curElem != null) { + seed = new DOMCryptoBinary(curElem.getFirstChild()); + curElem = DOMUtils.getNextSiblingElement(curElem); + pgen = new DOMCryptoBinary(curElem.getFirstChild()); + } + */ + //@@@ do we care about j, pgenCounter or seed? + DSAPublicKeySpec spec = new DSAPublicKeySpec(y.getBigNum(), + p.getBigNum(), + q.getBigNum(), + g.getBigNum()); + return generatePublicKey(dsakf, spec); + } + } + + static final class EC extends DOMKeyValue { + // ECKeyValue CryptoBinaries + private byte[] ecPublicKey; + private KeyFactory eckf; + private ECParameterSpec ecParams; + private Method encodePoint, decodePoint, getCurveName, + getECParameterSpec; + + EC(PublicKey key) throws KeyException { + super(key); + ECPublicKey ecKey = (ECPublicKey)key; + ECPoint ecPoint = ecKey.getW(); + ecParams = ecKey.getParams(); + try { + AccessController.doPrivileged( + new PrivilegedExceptionAction() { + public Void run() throws + ClassNotFoundException, NoSuchMethodException + { + getMethods(); + return null; + } + } + ); + } catch (PrivilegedActionException pae) { + throw new KeyException("ECKeyValue not supported", + pae.getException()); + } + Object[] args = new Object[] { ecPoint, ecParams.getCurve() }; + try { + ecPublicKey = (byte[])encodePoint.invoke(null, args); + } catch (IllegalAccessException iae) { + throw new KeyException(iae); + } catch (InvocationTargetException ite) { + throw new KeyException(ite); + } + } + + EC(Element dmElem) throws MarshalException { + super(dmElem); + } + + void getMethods() throws ClassNotFoundException, NoSuchMethodException { + Class c = Class.forName("sun.security.ec.ECParameters"); + Class[] params = new Class[] { ECPoint.class, EllipticCurve.class }; + encodePoint = c.getMethod("encodePoint", params); + params = new Class[] { ECParameterSpec.class }; + getCurveName = c.getMethod("getCurveName", params); + params = new Class[] { byte[].class, EllipticCurve.class }; + decodePoint = c.getMethod("decodePoint", params); + c = Class.forName("sun.security.ec.NamedCurve"); + params = new Class[] { String.class }; + getECParameterSpec = c.getMethod("getECParameterSpec", params); + } + + void marshalPublicKey(Node parent, Document doc, String dsPrefix, + DOMCryptoContext context) + throws MarshalException + { + String prefix = DOMUtils.getNSPrefix(context, XMLDSIG_11_XMLNS); + Element ecKeyValueElem = DOMUtils.createElement(doc, "ECKeyValue", + XMLDSIG_11_XMLNS, + prefix); + Element namedCurveElem = DOMUtils.createElement(doc, "NamedCurve", + XMLDSIG_11_XMLNS, + prefix); + Element publicKeyElem = DOMUtils.createElement(doc, "PublicKey", + XMLDSIG_11_XMLNS, + prefix); + Object[] args = new Object[] { ecParams }; + try { + String oid = (String) getCurveName.invoke(null, args); + DOMUtils.setAttribute(namedCurveElem, "URI", "urn:oid:" + oid); + } catch (IllegalAccessException iae) { + throw new MarshalException(iae); + } catch (InvocationTargetException ite) { + throw new MarshalException(ite); + } + String qname = (prefix == null || prefix.length() == 0) + ? "xmlns" : "xmlns:" + prefix; + namedCurveElem.setAttributeNS("http://www.w3.org/2000/xmlns/", + qname, XMLDSIG_11_XMLNS); + ecKeyValueElem.appendChild(namedCurveElem); + String encoded = Base64.encode(ecPublicKey); + publicKeyElem.appendChild + (DOMUtils.getOwnerDocument(publicKeyElem).createTextNode(encoded)); + ecKeyValueElem.appendChild(publicKeyElem); + parent.appendChild(ecKeyValueElem); + } + + PublicKey unmarshalKeyValue(Element kvtElem) + throws MarshalException + { + if (eckf == null) { + try { + eckf = KeyFactory.getInstance("EC"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException + ("unable to create EC KeyFactory: " + e.getMessage()); + } + } + try { + AccessController.doPrivileged( + new PrivilegedExceptionAction() { + public Void run() throws + ClassNotFoundException, NoSuchMethodException + { + getMethods(); + return null; + } + } + ); + } catch (PrivilegedActionException pae) { + throw new MarshalException("ECKeyValue not supported", + pae.getException()); + } + ECParameterSpec ecParams = null; + Element curElem = DOMUtils.getFirstChildElement(kvtElem); + if (curElem.getLocalName().equals("ECParameters")) { + throw new UnsupportedOperationException + ("ECParameters not supported"); + } else if (curElem.getLocalName().equals("NamedCurve")) { + String uri = DOMUtils.getAttributeValue(curElem, "URI"); + // strip off "urn:oid" + if (uri.startsWith("urn:oid:")) { + String oid = uri.substring(8); + try { + Object[] args = new Object[] { oid }; + ecParams = (ECParameterSpec) + getECParameterSpec.invoke(null, args); + } catch (IllegalAccessException iae) { + throw new MarshalException(iae); + } catch (InvocationTargetException ite) { + throw new MarshalException(ite); + } + } else { + throw new MarshalException("Invalid NamedCurve URI"); + } + } else { + throw new MarshalException("Invalid ECKeyValue"); + } + curElem = DOMUtils.getNextSiblingElement(curElem); + ECPoint ecPoint = null; + try { + Object[] args = new Object[] { Base64.decode(curElem), + ecParams.getCurve() }; + ecPoint = (ECPoint)decodePoint.invoke(null, args); + } catch (Base64DecodingException bde) { + throw new MarshalException("Invalid EC PublicKey", bde); + } catch (IllegalAccessException iae) { + throw new MarshalException(iae); + } catch (InvocationTargetException ite) { + throw new MarshalException(ite); + } +/* + ecPoint = sun.security.ec.ECParameters.decodePoint( + Base64.decode(curElem), ecParams.getCurve()); +*/ + ECPublicKeySpec spec = new ECPublicKeySpec(ecPoint, ecParams); + return generatePublicKey(eckf, spec); + } + } + + static final class Unknown extends DOMKeyValue { + private javax.xml.crypto.dom.DOMStructure externalPublicKey; + Unknown(Element elem) throws MarshalException { + super(elem); + } + PublicKey unmarshalKeyValue(Element kvElem) throws MarshalException { + externalPublicKey = new javax.xml.crypto.dom.DOMStructure(kvElem); + return null; + } + void marshalPublicKey(Node parent, Document doc, String dsPrefix, + DOMCryptoContext context) + throws MarshalException + { + parent.appendChild(externalPublicKey.getNode()); + } + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java index 0da7241ec59..e8f41ef4e06 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMManifest.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMManifest.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -32,6 +34,7 @@ import javax.xml.crypto.dsig.*; import java.security.Provider; import java.util.*; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -44,7 +47,7 @@ import org.w3c.dom.Node; */ public final class DOMManifest extends DOMStructure implements Manifest { - private final List references; + private final List references; private final String id; /** @@ -60,22 +63,22 @@ public final class DOMManifest extends DOMStructure implements Manifest { * @throws ClassCastException if references contains any * entries that are not of type {@link Reference} */ - public DOMManifest(List references, String id) { + public DOMManifest(List references, String id) { if (references == null) { throw new NullPointerException("references cannot be null"); } - List refCopy = new ArrayList(references); - if (refCopy.isEmpty()) { + this.references = + Collections.unmodifiableList(new ArrayList(references)); + if (this.references.isEmpty()) { throw new IllegalArgumentException("list of references must " + "contain at least one entry"); } - for (int i = 0, size = refCopy.size(); i < size; i++) { - if (!(refCopy.get(i) instanceof Reference)) { + for (int i = 0, size = this.references.size(); i < size; i++) { + if (!(this.references.get(i) instanceof Reference)) { throw new ClassCastException ("references["+i+"] is not a valid type"); } } - this.references = Collections.unmodifiableList(refCopy); this.id = id; } @@ -85,7 +88,9 @@ public final class DOMManifest extends DOMStructure implements Manifest { * @param manElem a Manifest element */ public DOMManifest(Element manElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { Attr attr = manElem.getAttributeNodeNS(null, "Id"); if (attr != null) { this.id = attr.getValue(); @@ -95,8 +100,10 @@ public final class DOMManifest extends DOMStructure implements Manifest { } boolean secVal = Utils.secureValidation(context); + Element refElem = DOMUtils.getFirstChildElement(manElem); - List refs = new ArrayList(); + List refs = new ArrayList(); + int refCount = 0; while (refElem != null) { refs.add(new DOMReference(refElem, context, provider)); @@ -104,10 +111,8 @@ public final class DOMManifest extends DOMStructure implements Manifest { refCount++; if (secVal && (refCount > DOMSignedInfo.MAXIMUM_REFERENCE_COUNT)) { - String error = "A maxiumum of " + - DOMSignedInfo.MAXIMUM_REFERENCE_COUNT + - " references per Manifest are allowed with" + - " secure validation"; + String error = "A maxiumum of " + DOMSignedInfo.MAXIMUM_REFERENCE_COUNT + " " + + "references per Manifest are allowed with secure validation"; throw new MarshalException(error); } } @@ -123,22 +128,22 @@ public final class DOMManifest extends DOMStructure implements Manifest { } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element manElem = DOMUtils.createElement - (ownerDoc, "Manifest", XMLSignature.XMLNS, dsPrefix); + Element manElem = DOMUtils.createElement(ownerDoc, "Manifest", + XMLSignature.XMLNS, dsPrefix); DOMUtils.setAttributeID(manElem, "Id", id); // add references - for (int i = 0, size = references.size(); i < size; i++) { - DOMReference ref = (DOMReference) references.get(i); - ref.marshal(manElem, dsPrefix, context); + for (Reference ref : references) { + ((DOMReference)ref).marshal(manElem, dsPrefix, context); } parent.appendChild(manElem); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -147,11 +152,22 @@ public final class DOMManifest extends DOMStructure implements Manifest { if (!(o instanceof Manifest)) { return false; } - Manifest oman = (Manifest) o; + Manifest oman = (Manifest)o; - boolean idsEqual = (id == null ? oman.getId() == null : - id.equals(oman.getId())); + boolean idsEqual = (id == null ? oman.getId() == null + : id.equals(oman.getId())); return (idsEqual && references.equals(oman.getReferences())); } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + result = 31 * result + references.hashCode(); + + return result; + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMPGPData.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMPGPData.java index b8a65ce2aa2..d37cb62880c 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMPGPData.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMPGPData.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMPGPData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMPGPData.java 1203846 2011-11-18 21:18:17Z mullan $ */ package org.jcp.xml.dsig.internal.dom; @@ -48,7 +50,7 @@ public final class DOMPGPData extends DOMStructure implements PGPData { private final byte[] keyId; private final byte[] keyPacket; - private final List externalElements; + private final List externalElements; /** * Creates a DOMPGPData containing the specified key packet. @@ -67,23 +69,23 @@ public final class DOMPGPData extends DOMStructure implements PGPData { * @throws ClassCastException if other contains any * entries that are not of type {@link XMLStructure} */ - public DOMPGPData(byte[] keyPacket, List other) { + public DOMPGPData(byte[] keyPacket, List other) { if (keyPacket == null) { throw new NullPointerException("keyPacket cannot be null"); } if (other == null || other.isEmpty()) { - this.externalElements = Collections.EMPTY_LIST; + this.externalElements = Collections.emptyList(); } else { - List otherCopy = new ArrayList(other); - for (int i = 0, size = otherCopy.size(); i < size; i++) { - if (!(otherCopy.get(i) instanceof XMLStructure)) { + this.externalElements = + Collections.unmodifiableList(new ArrayList(other)); + for (int i = 0, size = this.externalElements.size(); i < size; i++) { + if (!(this.externalElements.get(i) instanceof XMLStructure)) { throw new ClassCastException ("other["+i+"] is not a valid PGPData type"); } } - this.externalElements = Collections.unmodifiableList(otherCopy); } - this.keyPacket = (byte []) keyPacket.clone(); + this.keyPacket = (byte[])keyPacket.clone(); checkKeyPacket(keyPacket); this.keyId = null; } @@ -108,7 +110,9 @@ public final class DOMPGPData extends DOMStructure implements PGPData { * @throws ClassCastException if other contains any * entries that are not of type {@link XMLStructure} */ - public DOMPGPData(byte[] keyId, byte[] keyPacket, List other) { + public DOMPGPData(byte[] keyId, byte[] keyPacket, + List other) + { if (keyId == null) { throw new NullPointerException("keyId cannot be null"); } @@ -117,19 +121,20 @@ public final class DOMPGPData extends DOMStructure implements PGPData { throw new IllegalArgumentException("keyId must be 8 bytes long"); } if (other == null || other.isEmpty()) { - this.externalElements = Collections.EMPTY_LIST; + this.externalElements = Collections.emptyList(); } else { - List otherCopy = new ArrayList(other); - for (int i = 0, size = otherCopy.size(); i < size; i++) { - if (!(otherCopy.get(i) instanceof XMLStructure)) { + this.externalElements = + Collections.unmodifiableList(new ArrayList(other)); + for (int i = 0, size = this.externalElements.size(); i < size; i++) { + if (!(this.externalElements.get(i) instanceof XMLStructure)) { throw new ClassCastException ("other["+i+"] is not a valid PGPData type"); } } - this.externalElements = Collections.unmodifiableList(otherCopy); } - this.keyId = (byte []) keyId.clone(); - this.keyPacket = keyPacket == null ? null : (byte []) keyPacket.clone(); + this.keyId = (byte[])keyId.clone(); + this.keyPacket = keyPacket == null ? null + : (byte[])keyPacket.clone(); if (keyPacket != null) { checkKeyPacket(keyPacket); } @@ -146,11 +151,11 @@ public final class DOMPGPData extends DOMStructure implements PGPData { byte[] keyPacket = null; NodeList nl = pdElem.getChildNodes(); int length = nl.getLength(); - List other = new ArrayList(length); + List other = new ArrayList(length); for (int x = 0; x < length; x++) { Node n = nl.item(x); if (n.getNodeType() == Node.ELEMENT_NODE) { - Element childElem = (Element) n; + Element childElem = (Element)n; String localName = childElem.getLocalName(); try { if (localName.equals("PGPKeyID")) { @@ -172,11 +177,11 @@ public final class DOMPGPData extends DOMStructure implements PGPData { } public byte[] getKeyId() { - return (keyId == null ? null : (byte []) keyId.clone()); + return (keyId == null ? null : (byte[])keyId.clone()); } public byte[] getKeyPacket() { - return (keyPacket == null ? null : (byte []) keyPacket.clone()); + return (keyPacket == null ? null : (byte[])keyPacket.clone()); } public List getExternalElements() { @@ -184,16 +189,17 @@ public final class DOMPGPData extends DOMStructure implements PGPData { } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element pdElem = DOMUtils.createElement - (ownerDoc, "PGPData", XMLSignature.XMLNS, dsPrefix); + Element pdElem = DOMUtils.createElement(ownerDoc, "PGPData", + XMLSignature.XMLNS, dsPrefix); // create and append PGPKeyID element if (keyId != null) { - Element keyIdElem = DOMUtils.createElement - (ownerDoc, "PGPKeyID", XMLSignature.XMLNS, dsPrefix); + Element keyIdElem = DOMUtils.createElement(ownerDoc, "PGPKeyID", + XMLSignature.XMLNS, + dsPrefix); keyIdElem.appendChild (ownerDoc.createTextNode(Base64.encode(keyId))); pdElem.appendChild(keyIdElem); @@ -201,17 +207,19 @@ public final class DOMPGPData extends DOMStructure implements PGPData { // create and append PGPKeyPacket element if (keyPacket != null) { - Element keyPktElem = DOMUtils.createElement - (ownerDoc, "PGPKeyPacket", XMLSignature.XMLNS, dsPrefix); + Element keyPktElem = DOMUtils.createElement(ownerDoc, + "PGPKeyPacket", + XMLSignature.XMLNS, + dsPrefix); keyPktElem.appendChild (ownerDoc.createTextNode(Base64.encode(keyPacket))); pdElem.appendChild(keyPktElem); } // create and append any elements - for (int i = 0, size = externalElements.size(); i < size; i++) { + for (XMLStructure extElem : externalElements) { DOMUtils.appendChild(pdElem, ((javax.xml.crypto.dom.DOMStructure) - externalElements.get(i)).getNode()); + extElem).getNode()); } parent.appendChild(pdElem); @@ -229,26 +237,26 @@ public final class DOMPGPData extends DOMStructure implements PGPData { // and minimally one byte of content if (keyPacket.length < 3) { throw new IllegalArgumentException("keypacket must be at least " + - "3 bytes long"); + "3 bytes long"); } int tag = keyPacket[0]; // first bit must be set if ((tag & 128) != 128) { throw new IllegalArgumentException("keypacket tag is invalid: " + - "bit 7 is not set"); + "bit 7 is not set"); } // make sure using new format if ((tag & 64) != 64) { throw new IllegalArgumentException("old keypacket tag format is " + - "unsupported"); + "unsupported"); } // tag value must be 6, 14, 5 or 7 if (((tag & 6) != 6) && ((tag & 14) != 14) && ((tag & 5) != 5) && ((tag & 7) != 7)) { throw new IllegalArgumentException("keypacket tag is invalid: " + - "must be 6, 14, 5, or 7"); + "must be 6, 14, 5, or 7"); } } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java index 6d92f75bf86..132497838e3 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. @@ -29,7 +31,7 @@ * =========================================================================== */ /* - * $Id: DOMReference.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMReference.java 1334007 2012-05-04 14:59:46Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -43,8 +45,6 @@ import java.net.URI; import java.net.URISyntaxException; import java.security.*; import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -66,11 +66,10 @@ import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream public final class DOMReference extends DOMStructure implements Reference, DOMURIReference { - /** - * The maximum number of transforms per reference, if secure validation - * is enabled. - */ - public static final int MAXIMUM_TRANSFORM_COUNT = 5; + /** + * The maximum number of transforms per reference, if secure validation is enabled. + */ + public static final int MAXIMUM_TRANSFORM_COUNT = 5; /** * Look up useC14N11 system property. If true, an explicit C14N11 transform @@ -82,17 +81,18 @@ public final class DOMReference extends DOMStructure private static boolean useC14N11 = AccessController.doPrivileged(new PrivilegedAction() { public Boolean run() { - return Boolean.getBoolean - ("com.sun.org.apache.xml.internal.security.useC14N11"); + return Boolean.valueOf(Boolean.getBoolean + ("com.sun.org.apache.xml.internal.security.useC14N11")); } }); - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); private final DigestMethod digestMethod; private final String id; - private final List transforms; - private List allTransforms; + private final List transforms; + private List allTransforms; private final Data appliedTransformData; private Attr here; private final String uri; @@ -124,46 +124,51 @@ public final class DOMReference extends DOMStructure * not of type Transform */ public DOMReference(String uri, String type, DigestMethod dm, - List transforms, String id, Provider provider) { + List transforms, String id, + Provider provider) + { this(uri, type, dm, null, null, transforms, id, null, provider); } public DOMReference(String uri, String type, DigestMethod dm, - List appliedTransforms, Data result, List transforms, String id, - Provider provider) { + List appliedTransforms, + Data result, List transforms, + String id, Provider provider) + { this(uri, type, dm, appliedTransforms, result, transforms, id, null, provider); } public DOMReference(String uri, String type, DigestMethod dm, - List appliedTransforms, Data result, List transforms, String id, - byte[] digestValue, Provider provider) { + List appliedTransforms, + Data result, List transforms, + String id, byte[] digestValue, Provider provider) + { if (dm == null) { throw new NullPointerException("DigestMethod must be non-null"); } - this.allTransforms = new ArrayList(); - if (appliedTransforms != null) { - List transformsCopy = new ArrayList(appliedTransforms); - for (int i = 0, size = transformsCopy.size(); i < size; i++) { - if (!(transformsCopy.get(i) instanceof Transform)) { + if (appliedTransforms == null) { + this.allTransforms = new ArrayList(); + } else { + this.allTransforms = new ArrayList(appliedTransforms); + for (int i = 0, size = this.allTransforms.size(); i < size; i++) { + if (!(this.allTransforms.get(i) instanceof Transform)) { throw new ClassCastException ("appliedTransforms["+i+"] is not a valid type"); } } - this.allTransforms = transformsCopy; } if (transforms == null) { - this.transforms = Collections.EMPTY_LIST; + this.transforms = Collections.emptyList(); } else { - List transformsCopy = new ArrayList(transforms); - for (int i = 0, size = transformsCopy.size(); i < size; i++) { - if (!(transformsCopy.get(i) instanceof Transform)) { + this.transforms = new ArrayList(transforms); + for (int i = 0, size = this.transforms.size(); i < size; i++) { + if (!(this.transforms.get(i) instanceof Transform)) { throw new ClassCastException ("transforms["+i+"] is not a valid type"); } } - this.transforms = transformsCopy; - this.allTransforms.addAll(transformsCopy); + this.allTransforms.addAll(this.transforms); } this.digestMethod = dm; this.uri = uri; @@ -177,7 +182,7 @@ public final class DOMReference extends DOMStructure this.type = type; this.id = id; if (digestValue != null) { - this.digestValue = (byte[]) digestValue.clone(); + this.digestValue = (byte[])digestValue.clone(); this.digested = true; } this.appliedTransformData = result; @@ -190,12 +195,14 @@ public final class DOMReference extends DOMStructure * @param refElem a Reference element */ public DOMReference(Element refElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { boolean secVal = Utils.secureValidation(context); // unmarshal Transforms, if specified Element nextSibling = DOMUtils.getFirstChildElement(refElem); - List transforms = new ArrayList(5); + List transforms = new ArrayList(5); if (nextSibling.getLocalName().equals("Transforms")) { Element transformElem = DOMUtils.getFirstChildElement(nextSibling); @@ -207,9 +214,8 @@ public final class DOMReference extends DOMStructure transformCount++; if (secVal && (transformCount > MAXIMUM_TRANSFORM_COUNT)) { - String error = "A maxiumum of " + MAXIMUM_TRANSFORM_COUNT + - " transforms per Reference are allowed" + - " with secure validation"; + String error = "A maxiumum of " + MAXIMUM_TRANSFORM_COUNT + " " + + "transforms per Reference are allowed with secure validation"; throw new MarshalException(error); } } @@ -221,11 +227,10 @@ public final class DOMReference extends DOMStructure this.digestMethod = DOMDigestMethod.unmarshal(dmElem); String digestMethodAlgorithm = this.digestMethod.getAlgorithm(); if (secVal - && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(digestMethodAlgorithm)) - { - throw new MarshalException("It is forbidden to use algorithm " + - digestMethod + - " when secure validation is enabled"); + && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(digestMethodAlgorithm)) { + throw new MarshalException( + "It is forbidden to use algorithm " + digestMethod + " when secure validation is enabled" + ); } // unmarshal DigestValue @@ -277,23 +282,24 @@ public final class DOMReference extends DOMStructure } public byte[] getDigestValue() { - return (digestValue == null ? null : (byte[]) digestValue.clone()); + return (digestValue == null ? null : (byte[])digestValue.clone()); } public byte[] getCalculatedDigestValue() { return (calcDigestValue == null ? null - : (byte[]) calcDigestValue.clone()); + : (byte[])calcDigestValue.clone()); } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Marshalling Reference"); + throws MarshalException + { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Marshalling Reference"); } Document ownerDoc = DOMUtils.getOwnerDocument(parent); - refElem = DOMUtils.createElement - (ownerDoc, "Reference", XMLSignature.XMLNS, dsPrefix); + refElem = DOMUtils.createElement(ownerDoc, "Reference", + XMLSignature.XMLNS, dsPrefix); // set attributes DOMUtils.setAttributeID(refElem, "Id", id); @@ -302,25 +308,28 @@ public final class DOMReference extends DOMStructure // create and append Transforms element if (!allTransforms.isEmpty()) { - Element transformsElem = DOMUtils.createElement - (ownerDoc, "Transforms", XMLSignature.XMLNS, dsPrefix); + Element transformsElem = DOMUtils.createElement(ownerDoc, + "Transforms", + XMLSignature.XMLNS, + dsPrefix); refElem.appendChild(transformsElem); - for (int i = 0, size = allTransforms.size(); i < size; i++) { - DOMStructure transform = - (DOMStructure) allTransforms.get(i); - transform.marshal(transformsElem, dsPrefix, context); + for (Transform transform : allTransforms) { + ((DOMStructure)transform).marshal(transformsElem, + dsPrefix, context); } } // create and append DigestMethod element - ((DOMDigestMethod) digestMethod).marshal(refElem, dsPrefix, context); + ((DOMDigestMethod)digestMethod).marshal(refElem, dsPrefix, context); // create and append DigestValue element - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Adding digestValueElem"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Adding digestValueElem"); } - Element digestValueElem = DOMUtils.createElement - (ownerDoc, "DigestValue", XMLSignature.XMLNS, dsPrefix); + Element digestValueElem = DOMUtils.createElement(ownerDoc, + "DigestValue", + XMLSignature.XMLNS, + dsPrefix); if (digestValue != null) { digestValueElem.appendChild (ownerDoc.createTextNode(Base64.encode(digestValue))); @@ -332,7 +341,8 @@ public final class DOMReference extends DOMStructure } public void digest(XMLSignContext signContext) - throws XMLSignatureException { + throws XMLSignatureException + { Data data = null; if (appliedTransformData == null) { data = dereference(signContext); @@ -343,8 +353,8 @@ public final class DOMReference extends DOMStructure // insert digestValue into DigestValue element String encodedDV = Base64.encode(digestValue); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Reference object uri = " + uri); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Reference object uri = " + uri); } Element digestElem = DOMUtils.getLastChildElement(refElem); if (digestElem == null) { @@ -355,13 +365,14 @@ public final class DOMReference extends DOMStructure (refElem.getOwnerDocument().createTextNode(encodedDV)); digested = true; - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Reference digesting completed"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Reference digesting completed"); } } public boolean validate(XMLValidateContext validateContext) - throws XMLSignatureException { + throws XMLSignatureException + { if (validateContext == null) { throw new NullPointerException("validateContext cannot be null"); } @@ -371,11 +382,9 @@ public final class DOMReference extends DOMStructure Data data = dereference(validateContext); calcDigestValue = transform(data, validateContext); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Expected digest: " - + Base64.encode(digestValue)); - log.log(Level.FINE, "Actual digest: " - + Base64.encode(calcDigestValue)); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Expected digest: " + Base64.encode(digestValue)); + log.log(java.util.logging.Level.FINE, "Actual digest: " + Base64.encode(calcDigestValue)); } validationStatus = Arrays.equals(digestValue, calcDigestValue); @@ -392,7 +401,8 @@ public final class DOMReference extends DOMStructure } private Data dereference(XMLCryptoContext context) - throws XMLSignatureException { + throws XMLSignatureException + { Data data = null; // use user-specified URIDereferencer if specified; otherwise use deflt @@ -402,11 +412,9 @@ public final class DOMReference extends DOMStructure } try { data = deref.dereference(this, context); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "URIDereferencer class name: " - + deref.getClass().getName()); - log.log(Level.FINE, "Data class name: " - + data.getClass().getName()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "URIDereferencer class name: " + deref.getClass().getName()); + log.log(java.util.logging.Level.FINE, "Data class name: " + data.getClass().getName()); } } catch (URIReferenceException ure) { throw new XMLSignatureException(ure); @@ -416,12 +424,13 @@ public final class DOMReference extends DOMStructure } private byte[] transform(Data dereferencedData, - XMLCryptoContext context) throws XMLSignatureException { - + XMLCryptoContext context) + throws XMLSignatureException + { if (md == null) { try { md = MessageDigest.getInstance - (((DOMDigestMethod) digestMethod).getMessageDigestAlgorithm()); + (((DOMDigestMethod)digestMethod).getMessageDigestAlgorithm()); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } @@ -430,28 +439,25 @@ public final class DOMReference extends DOMStructure DigesterOutputStream dos; Boolean cache = (Boolean) context.getProperty("javax.xml.crypto.dsig.cacheReference"); - if (cache != null && cache.booleanValue() == true) { + if (cache != null && cache.booleanValue()) { this.derefData = copyDerefData(dereferencedData); dos = new DigesterOutputStream(md, true); } else { dos = new DigesterOutputStream(md); } - OutputStream os = new UnsyncBufferedOutputStream(dos); + OutputStream os = null; Data data = dereferencedData; - for (int i = 0, size = transforms.size(); i < size; i++) { - DOMTransform transform = (DOMTransform) transforms.get(i); - try { + try { + os = new UnsyncBufferedOutputStream(dos); + for (int i = 0, size = transforms.size(); i < size; i++) { + DOMTransform transform = (DOMTransform)transforms.get(i); if (i < size - 1) { data = transform.transform(data, context); } else { data = transform.transform(data, context, os); } - } catch (TransformException te) { - throw new XMLSignatureException(te); } - } - try { if (data != null) { XMLSignatureInput xi; // explicitly use C14N 1.1 when generating signature @@ -460,9 +466,9 @@ public final class DOMReference extends DOMStructure String c14nalg = CanonicalizationMethod.INCLUSIVE; if (context instanceof XMLSignContext) { if (!c14n11) { - Boolean prop = (Boolean) context.getProperty + Boolean prop = (Boolean)context.getProperty ("com.sun.org.apache.xml.internal.security.useC14N11"); - c14n11 = (prop != null && prop.booleanValue() == true); + c14n11 = (prop != null && prop.booleanValue()); if (c14n11) { c14nalg = "http://www.w3.org/2006/12/xml-c14n11"; } @@ -471,17 +477,20 @@ public final class DOMReference extends DOMStructure } } if (data instanceof ApacheData) { - xi = ((ApacheData) data).getXMLSignatureInput(); + xi = ((ApacheData)data).getXMLSignatureInput(); } else if (data instanceof OctetStreamData) { xi = new XMLSignatureInput (((OctetStreamData)data).getOctetStream()); } else if (data instanceof NodeSetData) { TransformService spi = null; - try { + if (provider == null) { spi = TransformService.getInstance(c14nalg, "DOM"); - } catch (NoSuchAlgorithmException nsae) { - spi = TransformService.getInstance - (c14nalg, "DOM", provider); + } else { + try { + spi = TransformService.getInstance(c14nalg, "DOM", provider); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(c14nalg, "DOM"); + } } data = spi.transform(data, context); xi = new XMLSignatureInput @@ -491,8 +500,18 @@ public final class DOMReference extends DOMStructure } if (context instanceof XMLSignContext && c14n11 && !xi.isOctetStream() && !xi.isOutputStreamSet()) { - DOMTransform t = new DOMTransform - (TransformService.getInstance(c14nalg, "DOM")); + TransformService spi = null; + if (provider == null) { + spi = TransformService.getInstance(c14nalg, "DOM"); + } else { + try { + spi = TransformService.getInstance(c14nalg, "DOM", provider); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(c14nalg, "DOM"); + } + } + + DOMTransform t = new DOMTransform(spi); Element transformsElem = null; String dsPrefix = DOMUtils.getSignaturePrefix(context); if (allTransforms.isEmpty()) { @@ -504,7 +523,8 @@ public final class DOMReference extends DOMStructure } else { transformsElem = DOMUtils.getFirstChildElement(refElem); } - t.marshal(transformsElem, dsPrefix, (DOMCryptoContext) context); + t.marshal(transformsElem, dsPrefix, + (DOMCryptoContext)context); allTransforms.add(t); xi.updateOutputStream(os, true); } else { @@ -512,12 +532,35 @@ public final class DOMReference extends DOMStructure } } os.flush(); - if (cache != null && cache.booleanValue() == true) { + if (cache != null && cache.booleanValue()) { this.dis = dos.getInputStream(); } return dos.getDigestValue(); - } catch (Exception e) { + } catch (NoSuchAlgorithmException e) { throw new XMLSignatureException(e); + } catch (TransformException e) { + throw new XMLSignatureException(e); + } catch (MarshalException e) { + throw new XMLSignatureException(e); + } catch (IOException e) { + throw new XMLSignatureException(e); + } catch (com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException e) { + throw new XMLSignatureException(e); + } finally { + if (os != null) { + try { + os.close(); + } catch (IOException e) { + throw new XMLSignatureException(e); + } + } + if (dos != null) { + try { + dos.close(); + } catch (IOException e) { + throw new XMLSignatureException(e); + } + } } } @@ -525,6 +568,7 @@ public final class DOMReference extends DOMStructure return here; } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -533,19 +577,41 @@ public final class DOMReference extends DOMStructure if (!(o instanceof Reference)) { return false; } - Reference oref = (Reference) o; + Reference oref = (Reference)o; - boolean idsEqual = (id == null ? oref.getId() == null : - id.equals(oref.getId())); - boolean urisEqual = (uri == null ? oref.getURI() == null : - uri.equals(oref.getURI())); - boolean typesEqual = (type == null ? oref.getType() == null : - type.equals(oref.getType())); + boolean idsEqual = (id == null ? oref.getId() == null + : id.equals(oref.getId())); + boolean urisEqual = (uri == null ? oref.getURI() == null + : uri.equals(oref.getURI())); + boolean typesEqual = (type == null ? oref.getType() == null + : type.equals(oref.getType())); boolean digestValuesEqual = Arrays.equals(digestValue, oref.getDigestValue()); - return (digestMethod.equals(oref.getDigestMethod()) && idsEqual && - urisEqual && typesEqual && allTransforms.equals(oref.getTransforms())); + return digestMethod.equals(oref.getDigestMethod()) && idsEqual && + urisEqual && typesEqual && + allTransforms.equals(oref.getTransforms()) && digestValuesEqual; + } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + if (uri != null) { + result = 31 * result + uri.hashCode(); + } + if (type != null) { + result = 31 * result + type.hashCode(); + } + if (digestValue != null) { + result = 31 * result + Arrays.hashCode(digestValue); + } + result = 31 * result + digestMethod.hashCode(); + result = 31 * result + allTransforms.hashCode(); + + return result; } boolean isDigested() { @@ -555,18 +621,17 @@ public final class DOMReference extends DOMStructure private static Data copyDerefData(Data dereferencedData) { if (dereferencedData instanceof ApacheData) { // need to make a copy of the Data - ApacheData ad = (ApacheData) dereferencedData; + ApacheData ad = (ApacheData)dereferencedData; XMLSignatureInput xsi = ad.getXMLSignatureInput(); if (xsi.isNodeSet()) { try { - final Set s = xsi.getNodeSet(); + final Set s = xsi.getNodeSet(); return new NodeSetData() { public Iterator iterator() { return s.iterator(); } }; } catch (Exception e) { // log a warning - log.log(Level.WARNING, - "cannot cache dereferenced data: " + e); + log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + e); return null; } } else if (xsi.isElement()) { @@ -574,12 +639,12 @@ public final class DOMReference extends DOMStructure (xsi.getSubNode(), xsi.isExcludeComments()); } else if (xsi.isOctetStream() || xsi.isByteArray()) { try { - return new OctetStreamData - (xsi.getOctetStream(), xsi.getSourceURI(), xsi.getMIMEType()); + return new OctetStreamData + (xsi.getOctetStream(), xsi.getSourceURI(), + xsi.getMIMEType()); } catch (IOException ioe) { // log a warning - log.log(Level.WARNING, - "cannot cache dereferenced data: " + ioe); + log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + ioe); return null; } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java index 8b8e5275c43..001126a6336 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. @@ -29,7 +31,7 @@ * =========================================================================== */ /* - * $Id: DOMRetrievalMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMRetrievalMethod.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -38,6 +40,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.security.Provider; import java.util.*; + import javax.xml.XMLConstants; import javax.xml.crypto.*; import javax.xml.crypto.dsig.*; @@ -50,8 +53,6 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; -import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; - /** * DOM-based implementation of RetrievalMethod. * @@ -61,7 +62,7 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; public final class DOMRetrievalMethod extends DOMStructure implements RetrievalMethod, DOMURIReference { - private final List transforms; + private final List transforms; private String uri; private String type; private Attr here; @@ -83,24 +84,26 @@ public final class DOMRetrievalMethod extends DOMStructure * @throws ClassCastException if transforms contains any * entries that are not of type {@link Transform} */ - public DOMRetrievalMethod(String uri, String type, List transforms) { + public DOMRetrievalMethod(String uri, String type, + List transforms) + { if (uri == null) { throw new NullPointerException("uri cannot be null"); } if (transforms == null || transforms.isEmpty()) { - this.transforms = Collections.EMPTY_LIST; + this.transforms = Collections.emptyList(); } else { - List transformsCopy = new ArrayList(transforms); - for (int i = 0, size = transformsCopy.size(); i < size; i++) { - if (!(transformsCopy.get(i) instanceof Transform)) { + this.transforms = Collections.unmodifiableList( + new ArrayList(transforms)); + for (int i = 0, size = this.transforms.size(); i < size; i++) { + if (!(this.transforms.get(i) instanceof Transform)) { throw new ClassCastException ("transforms["+i+"] is not a valid type"); } } - this.transforms = Collections.unmodifiableList(transformsCopy); } this.uri = uri; - if ((uri != null) && (!uri.equals(""))) { + if (!uri.equals("")) { try { new URI(uri); } catch (URISyntaxException e) { @@ -117,7 +120,9 @@ public final class DOMRetrievalMethod extends DOMStructure * @param rmElem a RetrievalMethod element */ public DOMRetrievalMethod(Element rmElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { // get URI and Type attributes uri = DOMUtils.getAttributeValue(rmElem, "URI"); type = DOMUtils.getAttributeValue(rmElem, "Type"); @@ -128,7 +133,7 @@ public final class DOMRetrievalMethod extends DOMStructure boolean secVal = Utils.secureValidation(context); // get Transforms, if specified - List transforms = new ArrayList(); + List transforms = new ArrayList(); Element transformsElem = DOMUtils.getFirstChildElement(rmElem); int transformCount = 0; @@ -141,19 +146,15 @@ public final class DOMRetrievalMethod extends DOMStructure transformElem = DOMUtils.getNextSiblingElement(transformElem); transformCount++; - if (secVal && - (transformCount > DOMReference.MAXIMUM_TRANSFORM_COUNT)) - { - String error = "A maxiumum of " + - DOMReference.MAXIMUM_TRANSFORM_COUNT + - " transforms per Reference are allowed" + - " with secure validation"; + if (secVal && (transformCount > DOMReference.MAXIMUM_TRANSFORM_COUNT)) { + String error = "A maxiumum of " + DOMReference.MAXIMUM_TRANSFORM_COUNT + " " + + "transforms per Reference are allowed with secure validation"; throw new MarshalException(error); } } } if (transforms.isEmpty()) { - this.transforms = Collections.EMPTY_LIST; + this.transforms = Collections.emptyList(); } else { this.transforms = Collections.unmodifiableList(transforms); } @@ -172,11 +173,11 @@ public final class DOMRetrievalMethod extends DOMStructure } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element rmElem = DOMUtils.createElement - (ownerDoc, "RetrievalMethod", XMLSignature.XMLNS, dsPrefix); + Element rmElem = DOMUtils.createElement(ownerDoc, "RetrievalMethod", + XMLSignature.XMLNS, dsPrefix); // add URI and Type attributes DOMUtils.setAttribute(rmElem, "URI", uri); @@ -184,12 +185,14 @@ public final class DOMRetrievalMethod extends DOMStructure // add Transforms elements if (!transforms.isEmpty()) { - Element transformsElem = DOMUtils.createElement - (ownerDoc, "Transforms", XMLSignature.XMLNS, dsPrefix); + Element transformsElem = DOMUtils.createElement(ownerDoc, + "Transforms", + XMLSignature.XMLNS, + dsPrefix); rmElem.appendChild(transformsElem); - for (int i = 0, size = transforms.size(); i < size; i++) { - ((DOMTransform) transforms.get(i)).marshal - (transformsElem, dsPrefix, context); + for (Transform transform : transforms) { + ((DOMTransform)transform).marshal(transformsElem, + dsPrefix, context); } } @@ -204,8 +207,8 @@ public final class DOMRetrievalMethod extends DOMStructure } public Data dereference(XMLCryptoContext context) - throws URIReferenceException { - + throws URIReferenceException + { if (context == null) { throw new NullPointerException("context cannot be null"); } @@ -223,9 +226,8 @@ public final class DOMRetrievalMethod extends DOMStructure // pass dereferenced data through Transforms try { - for (int i = 0, size = transforms.size(); i < size; i++) { - Transform transform = (Transform) transforms.get(i); - data = ((DOMTransform) transform).transform(data, context); + for (Transform transform : transforms) { + data = ((DOMTransform)transform).transform(data, context); } } catch (Exception e) { throw new URIReferenceException(e); @@ -249,14 +251,13 @@ public final class DOMRetrievalMethod extends DOMStructure } public XMLStructure dereferenceAsXMLStructure(XMLCryptoContext context) - throws URIReferenceException { - + throws URIReferenceException + { try { - ApacheData data = (ApacheData) dereference(context); + ApacheData data = (ApacheData)dereference(context); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, - Boolean.TRUE); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new ByteArrayInputStream (data.getXMLSignatureInput().getBytes())); @@ -271,6 +272,7 @@ public final class DOMRetrievalMethod extends DOMStructure } } + @Override public boolean equals(Object obj) { if (this == obj) { return true; @@ -278,12 +280,24 @@ public final class DOMRetrievalMethod extends DOMStructure if (!(obj instanceof RetrievalMethod)) { return false; } - RetrievalMethod orm = (RetrievalMethod) obj; + RetrievalMethod orm = (RetrievalMethod)obj; - boolean typesEqual = (type == null ? orm.getType() == null : - type.equals(orm.getType())); + boolean typesEqual = (type == null ? orm.getType() == null + : type.equals(orm.getType())); return (uri.equals(orm.getURI()) && transforms.equals(orm.getTransforms()) && typesEqual); } + + @Override + public int hashCode() { + int result = 17; + if (type != null) { + result = 31 * result + type.hashCode(); + } + result = 31 * result + uri.hashCode(); + result = 31 * result + transforms.hashCode(); + + return result; + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java index 21179dd41f1..4ce9c3cb64c 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java @@ -2,44 +2,42 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMSignatureMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMSignatureMethod.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import javax.xml.crypto.*; -import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec; import java.io.IOException; import java.security.*; import java.security.spec.AlgorithmParameterSpec; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.Node; +import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA; import org.jcp.xml.dsig.internal.SignerOutputStream; /** @@ -47,29 +45,30 @@ import org.jcp.xml.dsig.internal.SignerOutputStream; * * @author Sean Mullan */ -public abstract class DOMSignatureMethod extends DOMStructure - implements SignatureMethod { +public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod { - private static Logger log = - Logger.getLogger("org.jcp.xml.dsig.internal.dom"); - - // see RFC 4051 for these algorithm definitions - final static String RSA_SHA256 = - "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; - final static String RSA_SHA384 = - "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384"; - final static String RSA_SHA512 = - "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"; - final static String HMAC_SHA256 = - "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"; - final static String HMAC_SHA384 = - "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384"; - final static String HMAC_SHA512 = - "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512"; + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); private SignatureMethodParameterSpec params; private Signature signature; + // see RFC 4051 for these algorithm definitions + static final String RSA_SHA256 = + "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; + static final String RSA_SHA384 = + "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384"; + static final String RSA_SHA512 = + "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"; + static final String ECDSA_SHA1 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"; + static final String ECDSA_SHA256 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"; + static final String ECDSA_SHA384 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384"; + static final String ECDSA_SHA512 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"; + /** * Creates a DOMSignatureMethod. * @@ -78,19 +77,20 @@ public abstract class DOMSignatureMethod extends DOMStructure * appropriate for this signature method */ DOMSignatureMethod(AlgorithmParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params != null && !(params instanceof SignatureMethodParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type SignatureMethodParameterSpec"); } - checkParams((SignatureMethodParameterSpec) params); - this.params = (SignatureMethodParameterSpec) params; + checkParams((SignatureMethodParameterSpec)params); + this.params = (SignatureMethodParameterSpec)params; } /** * Creates a DOMSignatureMethod from an element. This ctor - * invokes the abstract {@link #unmarshalParams unmarshalParams} method to + * invokes the {@link #unmarshalParams unmarshalParams} method to * unmarshal any algorithm-specific input parameters. * * @param smElem a SignatureMethod element @@ -119,13 +119,21 @@ public abstract class DOMSignatureMethod extends DOMStructure return new SHA512withRSA(smElem); } else if (alg.equals(SignatureMethod.DSA_SHA1)) { return new SHA1withDSA(smElem); + } else if (alg.equals(ECDSA_SHA1)) { + return new SHA1withECDSA(smElem); + } else if (alg.equals(ECDSA_SHA256)) { + return new SHA256withECDSA(smElem); + } else if (alg.equals(ECDSA_SHA384)) { + return new SHA384withECDSA(smElem); + } else if (alg.equals(ECDSA_SHA512)) { + return new SHA512withECDSA(smElem); } else if (alg.equals(SignatureMethod.HMAC_SHA1)) { return new DOMHMACSignatureMethod.SHA1(smElem); - } else if (alg.equals(HMAC_SHA256)) { + } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA256)) { return new DOMHMACSignatureMethod.SHA256(smElem); - } else if (alg.equals(HMAC_SHA384)) { + } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA384)) { return new DOMHMACSignatureMethod.SHA384(smElem); - } else if (alg.equals(HMAC_SHA512)) { + } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA512)) { return new DOMHMACSignatureMethod.SHA512(smElem); } else { throw new MarshalException @@ -133,86 +141,14 @@ public abstract class DOMSignatureMethod extends DOMStructure } } - /** - * Checks if the specified parameters are valid for this algorithm. By - * default, this method throws an exception if parameters are specified - * since most SignatureMethod algorithms do not have parameters. Subclasses - * should override it if they have parameters. - * - * @param params the algorithm-specific params (may be null) - * @throws InvalidAlgorithmParameterException if the parameters are not - * appropriate for this signature method - */ - void checkParams(SignatureMethodParameterSpec params) - throws InvalidAlgorithmParameterException { - if (params != null) { - throw new InvalidAlgorithmParameterException("no parameters " + - "should be specified for the " + getSignatureAlgorithm() - + " SignatureMethod algorithm"); - } - } - public final AlgorithmParameterSpec getParameterSpec() { return params; } - /** - * Unmarshals SignatureMethodParameterSpec from the specified - * Element. By default, this method throws an exception since - * most SignatureMethod algorithms do not have parameters. Subclasses should - * override it if they have parameters. - * - * @param paramsElem the Element holding the input params - * @return the algorithm-specific SignatureMethodParameterSpec - * @throws MarshalException if the parameters cannot be unmarshalled - */ - SignatureMethodParameterSpec - unmarshalParams(Element paramsElem) throws MarshalException { - throw new MarshalException("no parameters should " + - "be specified for the " + getSignatureAlgorithm() + - " SignatureMethod algorithm"); - } - - /** - * This method invokes the abstract {@link #marshalParams marshalParams} - * method to marshal any algorithm-specific parameters. - */ - public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { - Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element smElem = DOMUtils.createElement - (ownerDoc, "SignatureMethod", XMLSignature.XMLNS, dsPrefix); - DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm()); - - if (params != null) { - marshalParams(smElem, dsPrefix); - } - - parent.appendChild(smElem); - } - - /** - * Verifies the passed-in signature with the specified key, using the - * underlying signature or MAC algorithm. - * - * @param key the verification key - * @param si the DOMSignedInfo - * @param signature the signature bytes to be verified - * @param context the XMLValidateContext - * @return true if the signature verified successfully, - * false if not - * @throws NullPointerException if key, si or - * signature are null - * @throws InvalidKeyException if the key is improperly encoded, of - * the wrong type, or parameters are missing, etc - * @throws SignatureException if an unexpected error occurs, such - * as the passed in signature is improperly encoded - * @throws XMLSignatureException if an unexpected error occurs - */ - boolean verify(Key key, DOMSignedInfo si, byte[] sig, - XMLValidateContext context) throws InvalidKeyException, - SignatureException, XMLSignatureException { + boolean verify(Key key, SignedInfo si, byte[] sig, + XMLValidateContext context) + throws InvalidKeyException, SignatureException, XMLSignatureException + { if (key == null || si == null || sig == null) { throw new NullPointerException(); } @@ -222,49 +158,40 @@ public abstract class DOMSignatureMethod extends DOMStructure } if (signature == null) { try { - Provider p = (Provider) context.getProperty + Provider p = (Provider)context.getProperty ("org.jcp.xml.dsig.internal.dom.SignatureProvider"); signature = (p == null) - ? Signature.getInstance(getSignatureAlgorithm()) - : Signature.getInstance(getSignatureAlgorithm(), p); + ? Signature.getInstance(getJCAAlgorithm()) + : Signature.getInstance(getJCAAlgorithm(), p); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } } - signature.initVerify((PublicKey) key); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Signature provider:"+ signature.getProvider()); - log.log(Level.FINE, "verifying with key: " + key); + signature.initVerify((PublicKey)key); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Signature provider:" + signature.getProvider()); + log.log(java.util.logging.Level.FINE, "verifying with key: " + key); } - si.canonicalize(context, new SignerOutputStream(signature)); + ((DOMSignedInfo)si).canonicalize(context, + new SignerOutputStream(signature)); - if (getAlgorithm().equals(SignatureMethod.DSA_SHA1)) { - try { + try { + Type type = getAlgorithmType(); + if (type == Type.DSA) { return signature.verify(convertXMLDSIGtoASN1(sig)); - } catch (IOException ioe) { - throw new XMLSignatureException(ioe); + } else if (type == Type.ECDSA) { + return signature.verify(SignatureECDSA.convertXMLDSIGtoASN1(sig)); + } else { + return signature.verify(sig); } - } else { - return signature.verify(sig); + } catch (IOException ioe) { + throw new XMLSignatureException(ioe); } } - /** - * Signs the bytes with the specified key, using the underlying - * signature or MAC algorithm. - * - * @param key the signing key - * @param si the DOMSignedInfo - * @param context the XMLSignContext - * @return the signature - * @throws NullPointerException if key or - * si are null - * @throws InvalidKeyException if the key is improperly encoded, of - * the wrong type, or parameters are missing, etc - * @throws XMLSignatureException if an unexpected error occurs - */ - byte[] sign(Key key, DOMSignedInfo si, XMLSignContext context) - throws InvalidKeyException, XMLSignatureException { + byte[] sign(Key key, SignedInfo si, XMLSignContext context) + throws InvalidKeyException, XMLSignatureException + { if (key == null || si == null) { throw new NullPointerException(); } @@ -274,26 +201,30 @@ public abstract class DOMSignatureMethod extends DOMStructure } if (signature == null) { try { - Provider p = (Provider) context.getProperty + Provider p = (Provider)context.getProperty ("org.jcp.xml.dsig.internal.dom.SignatureProvider"); signature = (p == null) - ? Signature.getInstance(getSignatureAlgorithm()) - : Signature.getInstance(getSignatureAlgorithm(), p); + ? Signature.getInstance(getJCAAlgorithm()) + : Signature.getInstance(getJCAAlgorithm(), p); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } } - signature.initSign((PrivateKey) key); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Signature provider:" +signature.getProvider()); - log.log(Level.FINE, "Signing with key: " + key); + signature.initSign((PrivateKey)key); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Signature provider:" + signature.getProvider()); + log.log(java.util.logging.Level.FINE, "Signing with key: " + key); } - si.canonicalize(context, new SignerOutputStream(signature)); + ((DOMSignedInfo)si).canonicalize(context, + new SignerOutputStream(signature)); try { - if (getAlgorithm().equals(SignatureMethod.DSA_SHA1)) { + Type type = getAlgorithmType(); + if (type == Type.DSA) { return convertASN1toXMLDSIG(signature.sign()); + } else if (type == Type.ECDSA) { + return SignatureECDSA.convertASN1toXMLDSIG(signature.sign()); } else { return signature.sign(); } @@ -304,52 +235,6 @@ public abstract class DOMSignatureMethod extends DOMStructure } } - /** - * Marshals the algorithm-specific parameters to an Element and - * appends it to the specified parent element. By default, this method - * throws an exception since most SignatureMethod algorithms do not have - * parameters. Subclasses should override it if they have parameters. - * - * @param parent the parent element to append the parameters to - * @param paramsPrefix the algorithm parameters prefix to use - * @throws MarshalException if the parameters cannot be marshalled - */ - void marshalParams(Element parent, String paramsPrefix) - throws MarshalException { - throw new MarshalException("no parameters should " + - "be specified for the " + getSignatureAlgorithm() + - " SignatureMethod algorithm"); - } - - /** - * Returns the java.security.Signature standard algorithm name. - */ - abstract String getSignatureAlgorithm(); - - /** - * Returns true if parameters are equal; false otherwise. - * - * Subclasses should override this method to compare algorithm-specific - * parameters. - */ - boolean paramsEqual(AlgorithmParameterSpec spec) { - return (getParameterSpec() == spec); - } - - public boolean equals(Object o) { - if (this == o) { - return true; - } - - if (!(o instanceof SignatureMethod)) { - return false; - } - SignatureMethod osm = (SignatureMethod) o; - - return (getAlgorithm().equals(osm.getAlgorithm()) && - paramsEqual(osm.getParameterSpec())); - } - /** * Converts an ASN.1 DSA value to a XML Signature DSA Value. * @@ -362,8 +247,8 @@ public abstract class DOMSignatureMethod extends DOMStructure * @see 6.4.1 DSA */ private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) - throws IOException { - + throws IOException + { byte rLength = asn1Bytes[3]; int i; @@ -384,7 +269,7 @@ public abstract class DOMSignatureMethod extends DOMStructure System.arraycopy(asn1Bytes, (4+rLength)-i, xmldsigBytes, 20-i, i); System.arraycopy(asn1Bytes, (6+rLength+sLength)-j, xmldsigBytes, - 40 - j, j); + 40 - j, j); return xmldsigBytes; } @@ -402,8 +287,8 @@ public abstract class DOMSignatureMethod extends DOMStructure * @see 6.4.1 DSA */ private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) - throws IOException { - + throws IOException + { if (xmldsigBytes.length != 40) { throw new IOException("Invalid XMLDSIG format of DSA signature"); } @@ -431,9 +316,9 @@ public abstract class DOMSignatureMethod extends DOMStructure byte asn1Bytes[] = new byte[6 + j + l]; asn1Bytes[0] = 48; - asn1Bytes[1] = (byte) (4 + j + l); + asn1Bytes[1] = (byte)(4 + j + l); asn1Bytes[2] = 2; - asn1Bytes[3] = (byte) j; + asn1Bytes[3] = (byte)j; System.arraycopy(xmldsigBytes, 20 - i, asn1Bytes, (4 + j) - i, i); @@ -456,9 +341,12 @@ public abstract class DOMSignatureMethod extends DOMStructure public String getAlgorithm() { return SignatureMethod.RSA_SHA1; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "SHA1withRSA"; } + Type getAlgorithmType() { + return Type.RSA; + } } static final class SHA256withRSA extends DOMSignatureMethod { @@ -472,9 +360,12 @@ public abstract class DOMSignatureMethod extends DOMStructure public String getAlgorithm() { return RSA_SHA256; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "SHA256withRSA"; } + Type getAlgorithmType() { + return Type.RSA; + } } static final class SHA384withRSA extends DOMSignatureMethod { @@ -488,9 +379,12 @@ public abstract class DOMSignatureMethod extends DOMStructure public String getAlgorithm() { return RSA_SHA384; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "SHA384withRSA"; } + Type getAlgorithmType() { + return Type.RSA; + } } static final class SHA512withRSA extends DOMSignatureMethod { @@ -504,9 +398,12 @@ public abstract class DOMSignatureMethod extends DOMStructure public String getAlgorithm() { return RSA_SHA512; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "SHA512withRSA"; } + Type getAlgorithmType() { + return Type.RSA; + } } static final class SHA1withDSA extends DOMSignatureMethod { @@ -520,8 +417,87 @@ public abstract class DOMSignatureMethod extends DOMStructure public String getAlgorithm() { return SignatureMethod.DSA_SHA1; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "SHA1withDSA"; } + Type getAlgorithmType() { + return Type.DSA; + } + } + + static final class SHA1withECDSA extends DOMSignatureMethod { + SHA1withECDSA(AlgorithmParameterSpec params) + throws InvalidAlgorithmParameterException { + super(params); + } + SHA1withECDSA(Element dmElem) throws MarshalException { + super(dmElem); + } + public String getAlgorithm() { + return ECDSA_SHA1; + } + String getJCAAlgorithm() { + return "SHA1withECDSA"; + } + Type getAlgorithmType() { + return Type.ECDSA; + } + } + + static final class SHA256withECDSA extends DOMSignatureMethod { + SHA256withECDSA(AlgorithmParameterSpec params) + throws InvalidAlgorithmParameterException { + super(params); + } + SHA256withECDSA(Element dmElem) throws MarshalException { + super(dmElem); + } + public String getAlgorithm() { + return ECDSA_SHA256; + } + String getJCAAlgorithm() { + return "SHA256withECDSA"; + } + Type getAlgorithmType() { + return Type.ECDSA; + } + } + + static final class SHA384withECDSA extends DOMSignatureMethod { + SHA384withECDSA(AlgorithmParameterSpec params) + throws InvalidAlgorithmParameterException { + super(params); + } + SHA384withECDSA(Element dmElem) throws MarshalException { + super(dmElem); + } + public String getAlgorithm() { + return ECDSA_SHA384; + } + String getJCAAlgorithm() { + return "SHA384withECDSA"; + } + Type getAlgorithmType() { + return Type.ECDSA; + } + } + + static final class SHA512withECDSA extends DOMSignatureMethod { + SHA512withECDSA(AlgorithmParameterSpec params) + throws InvalidAlgorithmParameterException { + super(params); + } + SHA512withECDSA(Element dmElem) throws MarshalException { + super(dmElem); + } + public String getAlgorithm() { + return ECDSA_SHA512; + } + String getJCAAlgorithm() { + return "SHA512withECDSA"; + } + Type getAlgorithmType() { + return Type.ECDSA; + } } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java index 424724f1d28..ecfa41a11bc 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMSignatureProperties.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMSignatureProperties.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,6 +33,7 @@ import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.*; import java.util.*; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -46,7 +49,7 @@ public final class DOMSignatureProperties extends DOMStructure implements SignatureProperties { private final String id; - private final List properties; + private final List properties; /** * Creates a DOMSignatureProperties from the specified @@ -61,20 +64,22 @@ public final class DOMSignatureProperties extends DOMStructure * @throws IllegalArgumentException if properties is empty * @throws NullPointerException if properties */ - public DOMSignatureProperties(List properties, String id) { + public DOMSignatureProperties(List properties, + String id) + { if (properties == null) { throw new NullPointerException("properties cannot be null"); } else if (properties.isEmpty()) { throw new IllegalArgumentException("properties cannot be empty"); } else { - List propsCopy = new ArrayList(properties); - for (int i = 0, size = propsCopy.size(); i < size; i++) { - if (!(propsCopy.get(i) instanceof SignatureProperty)) { + this.properties = Collections.unmodifiableList( + new ArrayList(properties)); + for (int i = 0, size = this.properties.size(); i < size; i++) { + if (!(this.properties.get(i) instanceof SignatureProperty)) { throw new ClassCastException ("properties["+i+"] is not a valid type"); } } - this.properties = Collections.unmodifiableList(propsCopy); } this.id = id; } @@ -85,7 +90,9 @@ public final class DOMSignatureProperties extends DOMStructure * @param propsElem a SignatureProperties element * @throws MarshalException if a marshalling error occurs */ - public DOMSignatureProperties(Element propsElem) throws MarshalException{ + public DOMSignatureProperties(Element propsElem, XMLCryptoContext context) + throws MarshalException + { // unmarshal attributes Attr attr = propsElem.getAttributeNodeNS(null, "Id"); if (attr != null) { @@ -97,11 +104,13 @@ public final class DOMSignatureProperties extends DOMStructure NodeList nodes = propsElem.getChildNodes(); int length = nodes.getLength(); - List properties = new ArrayList(length); + List properties = + new ArrayList(length); for (int i = 0; i < length; i++) { Node child = nodes.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { - properties.add(new DOMSignatureProperty((Element) child)); + properties.add(new DOMSignatureProperty((Element)child, + context)); } } if (properties.isEmpty()) { @@ -120,25 +129,27 @@ public final class DOMSignatureProperties extends DOMStructure } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element propsElem = DOMUtils.createElement - (ownerDoc, "SignatureProperties", XMLSignature.XMLNS, dsPrefix); + Element propsElem = DOMUtils.createElement(ownerDoc, + "SignatureProperties", + XMLSignature.XMLNS, + dsPrefix); // set attributes DOMUtils.setAttributeID(propsElem, "Id", id); // create and append any properties - for (int i = 0, size = properties.size(); i < size; i++) { - DOMSignatureProperty property = - (DOMSignatureProperty) properties.get(i); - property.marshal(propsElem, dsPrefix, context); + for (SignatureProperty property : properties) { + ((DOMSignatureProperty)property).marshal(propsElem, dsPrefix, + context); } parent.appendChild(propsElem); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -147,11 +158,22 @@ public final class DOMSignatureProperties extends DOMStructure if (!(o instanceof SignatureProperties)) { return false; } - SignatureProperties osp = (SignatureProperties) o; + SignatureProperties osp = (SignatureProperties)o; - boolean idsEqual = (id == null ? osp.getId() == null : - id.equals(osp.getId())); + boolean idsEqual = (id == null ? osp.getId() == null + : id.equals(osp.getId())); return (properties.equals(osp.getProperties()) && idsEqual); } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + result = 31 * result + properties.hashCode(); + + return result; + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java index 9bb8838aadb..117c4657cc7 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMSignatureProperty.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMSignatureProperty.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,6 +33,7 @@ import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.*; import java.util.*; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -47,7 +50,7 @@ public final class DOMSignatureProperty extends DOMStructure private final String id; private final String target; - private final List content; + private final List content; /** * Creates a SignatureProperty from the specified parameters. @@ -63,7 +66,9 @@ public final class DOMSignatureProperty extends DOMStructure * @throws NullPointerException if content or * target is null */ - public DOMSignatureProperty(List content, String target, String id) { + public DOMSignatureProperty(List content, + String target, String id) + { if (target == null) { throw new NullPointerException("target cannot be null"); } else if (content == null) { @@ -71,14 +76,14 @@ public final class DOMSignatureProperty extends DOMStructure } else if (content.isEmpty()) { throw new IllegalArgumentException("content cannot be empty"); } else { - List contentCopy = new ArrayList(content); - for (int i = 0, size = contentCopy.size(); i < size; i++) { - if (!(contentCopy.get(i) instanceof XMLStructure)) { + this.content = Collections.unmodifiableList( + new ArrayList(content)); + for (int i = 0, size = this.content.size(); i < size; i++) { + if (!(this.content.get(i) instanceof XMLStructure)) { throw new ClassCastException ("content["+i+"] is not a valid type"); } } - this.content = Collections.unmodifiableList(contentCopy); } this.target = target; this.id = id; @@ -89,7 +94,9 @@ public final class DOMSignatureProperty extends DOMStructure * * @param propElem a SignatureProperty element */ - public DOMSignatureProperty(Element propElem) throws MarshalException { + public DOMSignatureProperty(Element propElem, XMLCryptoContext context) + throws MarshalException + { // unmarshal attributes target = DOMUtils.getAttributeValue(propElem, "Target"); if (target == null) { @@ -105,7 +112,7 @@ public final class DOMSignatureProperty extends DOMStructure NodeList nodes = propElem.getChildNodes(); int length = nodes.getLength(); - List content = new ArrayList(length); + List content = new ArrayList(length); for (int i = 0; i < length; i++) { content.add(new javax.xml.crypto.dom.DOMStructure(nodes.item(i))); } @@ -129,26 +136,26 @@ public final class DOMSignatureProperty extends DOMStructure } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element propElem = DOMUtils.createElement - (ownerDoc, "SignatureProperty", XMLSignature.XMLNS, dsPrefix); + Element propElem = DOMUtils.createElement(ownerDoc, "SignatureProperty", + XMLSignature.XMLNS, dsPrefix); // set attributes DOMUtils.setAttributeID(propElem, "Id", id); DOMUtils.setAttribute(propElem, "Target", target); // create and append any elements and mixed content - for (int i = 0, size = content.size(); i < size; i++) { - javax.xml.crypto.dom.DOMStructure property = - (javax.xml.crypto.dom.DOMStructure) content.get(i); - DOMUtils.appendChild(propElem, property.getNode()); + for (XMLStructure property : content) { + DOMUtils.appendChild(propElem, + ((javax.xml.crypto.dom.DOMStructure)property).getNode()); } parent.appendChild(propElem); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -157,31 +164,43 @@ public final class DOMSignatureProperty extends DOMStructure if (!(o instanceof SignatureProperty)) { return false; } - SignatureProperty osp = (SignatureProperty) o; + SignatureProperty osp = (SignatureProperty)o; - boolean idsEqual = (id == null ? osp.getId() == null : - id.equals(osp.getId())); + boolean idsEqual = (id == null ? osp.getId() == null + : id.equals(osp.getId())); - return (equalsContent(osp.getContent()) && - target.equals(osp.getTarget()) && idsEqual); + @SuppressWarnings("unchecked") + List ospContent = osp.getContent(); + return (equalsContent(ospContent) && + target.equals(osp.getTarget()) && idsEqual); } - private boolean equalsContent(List otherContent) { + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + result = 31 * result + target.hashCode(); + result = 31 * result + content.hashCode(); + + return result; + } + + private boolean equalsContent(List otherContent) { int osize = otherContent.size(); if (content.size() != osize) { return false; } for (int i = 0; i < osize; i++) { - XMLStructure oxs = (XMLStructure) otherContent.get(i); - XMLStructure xs = (XMLStructure) content.get(i); + XMLStructure oxs = otherContent.get(i); + XMLStructure xs = content.get(i); if (oxs instanceof javax.xml.crypto.dom.DOMStructure) { if (!(xs instanceof javax.xml.crypto.dom.DOMStructure)) { return false; } - Node onode = - ((javax.xml.crypto.dom.DOMStructure) oxs).getNode(); - Node node = - ((javax.xml.crypto.dom.DOMStructure) xs).getNode(); + Node onode = ((javax.xml.crypto.dom.DOMStructure)oxs).getNode(); + Node node = ((javax.xml.crypto.dom.DOMStructure)xs).getNode(); if (!DOMUtils.nodesEqual(node, onode)) { return false; } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java index 36ebabc612d..fea139be24f 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMSignedInfo.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMSignedInfo.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -33,13 +35,11 @@ import javax.xml.crypto.dsig.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; -import java.io.IOException; -import java.io.InputStreamReader; import java.io.OutputStream; +import java.io.IOException; import java.security.Provider; import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; + import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -47,7 +47,6 @@ import org.w3c.dom.Node; import com.sun.org.apache.xml.internal.security.utils.Base64; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream; -import com.sun.org.apache.xml.internal.security.utils.XMLUtils; /** * DOM-based implementation of SignedInfo. @@ -57,12 +56,12 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; public final class DOMSignedInfo extends DOMStructure implements SignedInfo { /** - * The maximum number of references per Manifest, if secure validation is - * enabled. + * The maximum number of references per Manifest, if secure validation is enabled. */ public static final int MAXIMUM_REFERENCE_COUNT = 30; - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); /** Signature - NOT Recommended RSAwithMD5 */ private static final String ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5 = @@ -72,7 +71,7 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { private static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 = Constants.MoreAlgorithmsSpecNS + "hmac-md5"; - private List references; + private List references; private CanonicalizationMethod canonicalizationMethod; private SignatureMethod signatureMethod; private String id; @@ -95,14 +94,14 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { * type Reference */ public DOMSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, - List references) { + List references) { if (cm == null || sm == null || references == null) { throw new NullPointerException(); } this.canonicalizationMethod = cm; this.signatureMethod = sm; - this.references = Collections.unmodifiableList - (new ArrayList(references)); + this.references = Collections.unmodifiableList( + new ArrayList(references)); if (this.references.isEmpty()) { throw new IllegalArgumentException("list of references must " + "contain at least one entry"); @@ -132,7 +131,7 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { * type Reference */ public DOMSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, - List references, String id) { + List references, String id) { this(cm, sm, references); this.id = id; } @@ -142,8 +141,8 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { * * @param siElem a SignedInfo element */ - public DOMSignedInfo(Element siElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + public DOMSignedInfo(Element siElem, XMLCryptoContext context, Provider provider) + throws MarshalException { localSiElem = siElem; ownerDoc = siElem.getOwnerDocument(); @@ -152,26 +151,26 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { // unmarshal CanonicalizationMethod Element cmElem = DOMUtils.getFirstChildElement(siElem); - canonicalizationMethod = new DOMCanonicalizationMethod - (cmElem, context, provider); + canonicalizationMethod = new DOMCanonicalizationMethod(cmElem, context, provider); // unmarshal SignatureMethod Element smElem = DOMUtils.getNextSiblingElement(cmElem); signatureMethod = DOMSignatureMethod.unmarshal(smElem); boolean secVal = Utils.secureValidation(context); - String sigMethAlg = signatureMethod.getAlgorithm(); - if (secVal && ((ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(sigMethAlg) - || ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(sigMethAlg)))) - { - throw new MarshalException("It is forbidden to use algorithm " + - signatureMethod + - " when secure validation is enabled"); + + String signatureMethodAlgorithm = signatureMethod.getAlgorithm(); + if (secVal && ((ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(signatureMethodAlgorithm) + || ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(signatureMethodAlgorithm)))) { + throw new MarshalException( + "It is forbidden to use algorithm " + signatureMethod + " when secure validation is enabled" + ); } // unmarshal References - ArrayList refList = new ArrayList(5); + ArrayList refList = new ArrayList(5); Element refElem = DOMUtils.getNextSiblingElement(smElem); + int refCount = 0; while (refElem != null) { refList.add(new DOMReference(refElem, context, provider)); @@ -179,9 +178,8 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { refCount++; if (secVal && (refCount > MAXIMUM_REFERENCE_COUNT)) { - String error = "A maxiumum of " + MAXIMUM_REFERENCE_COUNT + - " references per SignedInfo are allowed with" + - " secure validation"; + String error = "A maxiumum of " + MAXIMUM_REFERENCE_COUNT + " " + + "references per Manifest are allowed with secure validation"; throw new MarshalException(error); } } @@ -208,9 +206,8 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { return canonData; } - public void canonicalize(XMLCryptoContext context,ByteArrayOutputStream bos) + public void canonicalize(XMLCryptoContext context, ByteArrayOutputStream bos) throws XMLSignatureException { - if (context == null) { throw new NullPointerException("context cannot be null"); } @@ -219,14 +216,17 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { try { os.close(); } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } // Impossible } DOMSubTreeData subTree = new DOMSubTreeData(localSiElem, true); try { - Data data = ((DOMCanonicalizationMethod) - canonicalizationMethod).canonicalize(subTree, context, os); + ((DOMCanonicalizationMethod) + canonicalizationMethod).canonicalize(subTree, context, bos); } catch (TransformException te) { throw new XMLSignatureException(te); } @@ -234,44 +234,37 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { byte[] signedInfoBytes = bos.toByteArray(); // this whole block should only be done if logging is enabled - if (log.isLoggable(Level.FINE)) { - InputStreamReader isr = new InputStreamReader - (new ByteArrayInputStream(signedInfoBytes)); - char[] siBytes = new char[signedInfoBytes.length]; - try { - isr.read(siBytes); - log.log(Level.FINE, "Canonicalized SignedInfo:\n" - + new String(siBytes)); - } catch (IOException ioex) { - log.log(Level.FINE, "IOException reading SignedInfo bytes"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Canonicalized SignedInfo:"); + StringBuilder sb = new StringBuilder(signedInfoBytes.length); + for (int i = 0; i < signedInfoBytes.length; i++) { + sb.append((char)signedInfoBytes[i]); } - log.log(Level.FINE, "Data to be signed/verified:" - + Base64.encode(signedInfoBytes)); + log.log(java.util.logging.Level.FINE, sb.toString()); + log.log(java.util.logging.Level.FINE, "Data to be signed/verified:" + Base64.encode(signedInfoBytes)); } this.canonData = new ByteArrayInputStream(signedInfoBytes); } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element siElem = DOMUtils.createElement - (ownerDoc, "SignedInfo", XMLSignature.XMLNS, dsPrefix); + Element siElem = DOMUtils.createElement(ownerDoc, "SignedInfo", + XMLSignature.XMLNS, dsPrefix); // create and append CanonicalizationMethod element DOMCanonicalizationMethod dcm = - (DOMCanonicalizationMethod) canonicalizationMethod; + (DOMCanonicalizationMethod)canonicalizationMethod; dcm.marshal(siElem, dsPrefix, context); // create and append SignatureMethod element - ((DOMSignatureMethod) signatureMethod).marshal - (siElem, dsPrefix, context); + ((DOMStructure)signatureMethod).marshal(siElem, dsPrefix, context); // create and append Reference elements - for (int i = 0, size = references.size(); i < size; i++) { - DOMReference reference = (DOMReference) references.get(i); - reference.marshal(siElem, dsPrefix, context); + for (Reference reference : references) { + ((DOMReference)reference).marshal(siElem, dsPrefix, context); } // append Id attribute @@ -281,6 +274,7 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { localSiElem = siElem; } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -289,13 +283,26 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { if (!(o instanceof SignedInfo)) { return false; } - SignedInfo osi = (SignedInfo) o; + SignedInfo osi = (SignedInfo)o; - boolean idEqual = (id == null ? osi.getId() == null : - id.equals(osi.getId())); + boolean idEqual = (id == null ? osi.getId() == null + : id.equals(osi.getId())); return (canonicalizationMethod.equals(osi.getCanonicalizationMethod()) - && signatureMethod.equals(osi.getSignatureMethod()) && - references.equals(osi.getReferences()) && idEqual); + && signatureMethod.equals(osi.getSignatureMethod()) && + references.equals(osi.getReferences()) && idEqual); + } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + result = 31 * result + canonicalizationMethod.hashCode(); + result = 31 * result + signatureMethod.hashCode(); + result = 31 * result + references.hashCode(); + + return result; } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMStructure.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMStructure.java index f3cb1d93d9f..02ea86f37e6 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMStructure.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMStructure.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMStructure.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMStructure.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSubTreeData.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSubTreeData.java index c80992b661f..ca33a18e726 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSubTreeData.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSubTreeData.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2006 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMSubTreeData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id$ */ package org.jcp.xml.dsig.internal.dom; @@ -45,17 +47,15 @@ import org.w3c.dom.Node; public class DOMSubTreeData implements NodeSetData { private boolean excludeComments; - private Iterator ni; private Node root; public DOMSubTreeData(Node root, boolean excludeComments) { this.root = root; - this.ni = new DelayedNodeIterator(root, excludeComments); this.excludeComments = excludeComments; } public Iterator iterator() { - return ni; + return new DelayedNodeIterator(root, excludeComments); } public Node getRoot() { @@ -70,10 +70,10 @@ public class DOMSubTreeData implements NodeSetData { * This is an Iterator that contains a backing node-set that is * not populated until the caller first attempts to advance the iterator. */ - static class DelayedNodeIterator implements Iterator { + static class DelayedNodeIterator implements Iterator { private Node root; - private List nodeSet; - private ListIterator li; + private List nodeSet; + private ListIterator li; private boolean withComments; DelayedNodeIterator(Node root, boolean excludeComments) { @@ -89,13 +89,13 @@ public class DOMSubTreeData implements NodeSetData { return li.hasNext(); } - public Object next() { + public Node next() { if (nodeSet == null) { nodeSet = dereferenceSameDocumentURI(root); li = nodeSet.listIterator(); } if (li.hasNext()) { - return (Node) li.next(); + return li.next(); } else { throw new NoSuchElementException(); } @@ -109,11 +109,11 @@ public class DOMSubTreeData implements NodeSetData { * Dereferences a same-document URI fragment. * * @param node the node (document or element) referenced by the - * URI fragment. If null, returns an empty set. + * URI fragment. If null, returns an empty set. * @return a set of nodes (minus any comment nodes) */ - private List dereferenceSameDocumentURI(Node node) { - List nodeSet = new ArrayList(); + private List dereferenceSameDocumentURI(Node node) { + List nodeSet = new ArrayList(); if (node != null) { nodeSetMinusCommentNodes(node, nodeSet, null); } @@ -129,8 +129,10 @@ public class DOMSubTreeData implements NodeSetData { * @param nodeSet the set of nodes traversed so far * @param the previous sibling node */ - private void nodeSetMinusCommentNodes(Node node, List nodeSet, - Node prevSibling) { + @SuppressWarnings("fallthrough") + private void nodeSetMinusCommentNodes(Node node, List nodeSet, + Node prevSibling) + { switch (node.getNodeType()) { case Node.ELEMENT_NODE : NamedNodeMap attrs = node.getAttributes(); @@ -140,7 +142,6 @@ public class DOMSubTreeData implements NodeSetData { } } nodeSet.add(node); - case Node.DOCUMENT_NODE : Node pSibling = null; for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { @@ -148,14 +149,25 @@ public class DOMSubTreeData implements NodeSetData { 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; + prevSibling.getNodeType() == Node.CDATA_SECTION_NODE)) { + return; } + nodeSet.add(node); + break; case Node.PROCESSING_INSTRUCTION_NODE : nodeSet.add(node); break; diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java index a9398e592c1..d7a40e0e2c6 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMTransform.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -35,13 +37,11 @@ import java.security.spec.AlgorithmParameterSpec; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; -import org.w3c.dom.NodeList; import javax.xml.crypto.*; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.dom.DOMSignContext; -import javax.xml.crypto.dsig.spec.TransformParameterSpec; /** * DOM-based abstract implementation of Transform. @@ -69,15 +69,26 @@ public class DOMTransform extends DOMStructure implements Transform { * @param transElem a Transform element */ public DOMTransform(Element transElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { String algorithm = DOMUtils.getAttributeValue(transElem, "Algorithm"); - try { - spi = TransformService.getInstance(algorithm, "DOM"); - } catch (NoSuchAlgorithmException e1) { + + if (provider == null) { + try { + spi = TransformService.getInstance(algorithm, "DOM"); + } catch (NoSuchAlgorithmException e1) { + throw new MarshalException(e1); + } + } else { try { spi = TransformService.getInstance(algorithm, "DOM", provider); - } catch (NoSuchAlgorithmException e2) { - throw new MarshalException(e2); + } catch (NoSuchAlgorithmException nsae) { + try { + spi = TransformService.getInstance(algorithm, "DOM"); + } catch (NoSuchAlgorithmException e2) { + throw new MarshalException(e2); + } } } try { @@ -100,21 +111,25 @@ public class DOMTransform extends DOMStructure implements Transform { * method to marshal any algorithm-specific parameters. */ public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); Element transformElem = null; if (parent.getLocalName().equals("Transforms")) { - transformElem = DOMUtils.createElement - (ownerDoc, "Transform", XMLSignature.XMLNS, dsPrefix); + transformElem = DOMUtils.createElement(ownerDoc, "Transform", + XMLSignature.XMLNS, + dsPrefix); } else { - transformElem = DOMUtils.createElement - (ownerDoc, "CanonicalizationMethod", XMLSignature.XMLNS, dsPrefix); + transformElem = DOMUtils.createElement(ownerDoc, + "CanonicalizationMethod", + XMLSignature.XMLNS, + dsPrefix); } DOMUtils.setAttribute(transformElem, "Algorithm", getAlgorithm()); - spi.marshalParams - (new javax.xml.crypto.dom.DOMStructure(transformElem), context); + spi.marshalParams(new javax.xml.crypto.dom.DOMStructure(transformElem), + context); parent.appendChild(transformElem); } @@ -131,7 +146,8 @@ public class DOMTransform extends DOMStructure implements Transform { * executing the transform */ public Data transform(Data data, XMLCryptoContext xc) - throws TransformException { + throws TransformException + { return spi.transform(data, xc); } @@ -149,10 +165,12 @@ public class DOMTransform extends DOMStructure implements Transform { * executing the transform */ public Data transform(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { + throws TransformException + { return spi.transform(data, xc, os); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -161,11 +179,23 @@ public class DOMTransform extends DOMStructure implements Transform { if (!(o instanceof Transform)) { return false; } - Transform otransform = (Transform) o; + Transform otransform = (Transform)o; return (getAlgorithm().equals(otransform.getAlgorithm()) && - DOMUtils.paramsEqual - (getParameterSpec(), otransform.getParameterSpec())); + DOMUtils.paramsEqual(getParameterSpec(), + otransform.getParameterSpec())); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + getAlgorithm().hashCode(); + AlgorithmParameterSpec spec = getParameterSpec(); + if (spec != null) { + result = 31 * result + spec.hashCode(); + } + + return result; } /** @@ -185,9 +215,10 @@ public class DOMTransform extends DOMStructure implements Transform { * executing the transform */ Data transform(Data data, XMLCryptoContext xc, DOMSignContext context) - throws MarshalException, TransformException { + throws MarshalException, TransformException + { marshal(context.getParent(), - DOMUtils.getSignaturePrefix(context), context); + DOMUtils.getSignaturePrefix(context), context); return transform(data, xc); } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java index cca0c9e2e03..33e0a90224f 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMURIDereferencer.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMURIDereferencer.java 1231033 2012-01-13 12:12:12Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -37,7 +39,6 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import javax.xml.crypto.*; import javax.xml.crypto.dom.*; -import javax.xml.crypto.dsig.*; /** * DOM-based implementation of URIDereferencer. @@ -82,21 +83,17 @@ public class DOMURIDereferencer implements URIDereferencer { id = id.substring(i1+1, i2); } - Node refElem = dcc.getElementById(id); - if (refElem != null) { + Node referencedElem = dcc.getElementById(id); + if (referencedElem != null) { if (secVal) { - Element start = - refElem.getOwnerDocument().getDocumentElement(); - if (!XMLUtils.protectAgainstWrappingAttack(start, - (Element)refElem, - id)) { - String error = "Multiple Elements with the same ID " + - id + " were detected"; + Element start = referencedElem.getOwnerDocument().getDocumentElement(); + if (!XMLUtils.protectAgainstWrappingAttack(start, (Element)referencedElem, id)) { + String error = "Multiple Elements with the same ID " + id + " were detected"; throw new URIReferenceException(error); } } - XMLSignatureInput result = new XMLSignatureInput(refElem); + XMLSignatureInput result = new XMLSignatureInput(referencedElem); if (!uri.substring(1).startsWith("xpointer(id(")) { result.setExcludeComments(true); } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java index 184a6d34426..c55a13ae323 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMUtils.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMUtils.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -34,7 +36,6 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.crypto.*; -import javax.xml.crypto.dsig.dom.DOMSignContext; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.spec.*; @@ -56,7 +57,7 @@ public class DOMUtils { */ public static Document getOwnerDocument(Node node) { if (node.getNodeType() == Node.DOCUMENT_NODE) { - return (Document) node; + return (Document)node; } else { return node.getOwnerDocument(); } @@ -72,8 +73,9 @@ public class DOMUtils { * @param prefix the namespace prefix * @return the newly created element */ - public static Element createElement(Document doc, String tag, String nsURI, - String prefix) { + public static Element createElement(Document doc, String tag, + String nsURI, String prefix) + { String qName = (prefix == null || prefix.length() == 0) ? tag : prefix + ":" + tag; return doc.createElementNS(nsURI, qName); @@ -88,7 +90,9 @@ public class DOMUtils { * @param value the attribute value. If null, no attribute is set. */ public static void setAttribute(Element elem, String name, String value) { - if (value == null) return; + if (value == null) { + return; + } elem.setAttributeNS(null, name, value); } @@ -103,7 +107,9 @@ public class DOMUtils { * @param value the attribute value. If null, no attribute is set. */ public static void setAttributeID(Element elem, String name, String value) { - if (value == null) return; + if (value == null) { + return; + } elem.setAttributeNS(null, name, value); elem.setIdAttributeNS(null, name, true); } @@ -122,7 +128,7 @@ public class DOMUtils { while (child != null && child.getNodeType() != Node.ELEMENT_NODE) { child = child.getNextSibling(); } - return (Element) child; + return (Element)child; } /** @@ -139,7 +145,7 @@ public class DOMUtils { while (child != null && child.getNodeType() != Node.ELEMENT_NODE) { child = child.getPreviousSibling(); } - return (Element) child; + return (Element)child; } /** @@ -156,7 +162,7 @@ public class DOMUtils { while (sibling != null && sibling.getNodeType() != Node.ELEMENT_NODE) { sibling = sibling.getNextSibling(); } - return (Element) sibling; + return (Element)sibling; } /** @@ -185,25 +191,25 @@ public class DOMUtils { * @param nl the NodeList * @return a Set of Nodes */ - public static Set nodeSet(NodeList nl) { + public static Set nodeSet(NodeList nl) { return new NodeSet(nl); } - static class NodeSet extends AbstractSet { + static class NodeSet extends AbstractSet { private NodeList nl; public NodeSet(NodeList nl) { this.nl = nl; } public int size() { return nl.getLength(); } - public Iterator iterator() { - return new Iterator() { + public Iterator iterator() { + return new Iterator() { int index = 0; public void remove() { throw new UnsupportedOperationException(); } - public Object next() { + public Node next() { if (!hasNext()) { throw new NoSuchElementException(); } @@ -291,39 +297,41 @@ public class DOMUtils { } if (spec1 instanceof XPathFilter2ParameterSpec && spec2 instanceof XPathFilter2ParameterSpec) { - return paramsEqual((XPathFilter2ParameterSpec) spec1, - (XPathFilter2ParameterSpec) spec2); + return paramsEqual((XPathFilter2ParameterSpec)spec1, + (XPathFilter2ParameterSpec)spec2); } if (spec1 instanceof ExcC14NParameterSpec && spec2 instanceof ExcC14NParameterSpec) { return paramsEqual((ExcC14NParameterSpec) spec1, - (ExcC14NParameterSpec) spec2); + (ExcC14NParameterSpec)spec2); } if (spec1 instanceof XPathFilterParameterSpec && spec2 instanceof XPathFilterParameterSpec) { - return paramsEqual((XPathFilterParameterSpec) spec1, - (XPathFilterParameterSpec) spec2); + return paramsEqual((XPathFilterParameterSpec)spec1, + (XPathFilterParameterSpec)spec2); } if (spec1 instanceof XSLTTransformParameterSpec && spec2 instanceof XSLTTransformParameterSpec) { - return paramsEqual((XSLTTransformParameterSpec) spec1, - (XSLTTransformParameterSpec) spec2); + return paramsEqual((XSLTTransformParameterSpec)spec1, + (XSLTTransformParameterSpec)spec2); } return false; } private static boolean paramsEqual(XPathFilter2ParameterSpec spec1, - XPathFilter2ParameterSpec spec2) { - - List types = spec1.getXPathList(); - List otypes = spec2.getXPathList(); + XPathFilter2ParameterSpec spec2) + { + @SuppressWarnings("unchecked") + List types = spec1.getXPathList(); + @SuppressWarnings("unchecked") + List otypes = spec2.getXPathList(); int size = types.size(); if (size != otypes.size()) { return false; } for (int i = 0; i < size; i++) { - XPathType type = (XPathType) types.get(i); - XPathType otype = (XPathType) otypes.get(i); + XPathType type = types.get(i); + XPathType otype = otypes.get(i); if (!type.getExpression().equals(otype.getExpression()) || !type.getNamespaceMap().equals(otype.getNamespaceMap()) || type.getFilter() != otype.getFilter()) { @@ -334,18 +342,21 @@ public class DOMUtils { } private static boolean paramsEqual(ExcC14NParameterSpec spec1, - ExcC14NParameterSpec spec2) { + ExcC14NParameterSpec spec2) + { return spec1.getPrefixList().equals(spec2.getPrefixList()); } private static boolean paramsEqual(XPathFilterParameterSpec spec1, - XPathFilterParameterSpec spec2) { + XPathFilterParameterSpec spec2) + { return (spec1.getXPath().equals(spec2.getXPath()) && - spec1.getNamespaceMap().equals(spec2.getNamespaceMap())); + spec1.getNamespaceMap().equals(spec2.getNamespaceMap())); } private static boolean paramsEqual(XSLTTransformParameterSpec spec1, - XSLTTransformParameterSpec spec2) { + XSLTTransformParameterSpec spec2) + { XMLStructure ostylesheet = spec2.getStylesheet(); if (!(ostylesheet instanceof javax.xml.crypto.dom.DOMStructure)) { diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509Data.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509Data.java index d9a50864f04..11076a7ccfc 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509Data.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509Data.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMX509Data.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMX509Data.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -51,7 +53,7 @@ import com.sun.org.apache.xml.internal.security.utils.Base64; //@@@ check for illegal combinations of data violating MUSTs in W3c spec public final class DOMX509Data extends DOMStructure implements X509Data { - private final List content; + private final List content; private CertificateFactory cf; /** @@ -69,18 +71,18 @@ public final class DOMX509Data extends DOMStructure implements X509Data { * @throws ClassCastException if content contains any entries * that are not of one of the valid types mentioned above */ - public DOMX509Data(List content) { + public DOMX509Data(List content) { if (content == null) { throw new NullPointerException("content cannot be null"); } - List contentCopy = new ArrayList(content); + List contentCopy = new ArrayList(content); if (contentCopy.isEmpty()) { throw new IllegalArgumentException("content cannot be empty"); } for (int i = 0, size = contentCopy.size(); i < size; i++) { Object x509Type = contentCopy.get(i); if (x509Type instanceof String) { - new X500Principal((String) x509Type); + new X500Principal((String)x509Type); } else if (!(x509Type instanceof byte[]) && !(x509Type instanceof X509Certificate) && !(x509Type instanceof X509CRL) && @@ -102,7 +104,7 @@ public final class DOMX509Data extends DOMStructure implements X509Data { // get all children nodes NodeList nl = xdElem.getChildNodes(); int length = nl.getLength(); - List content = new ArrayList(length); + List content = new ArrayList(length); for (int i = 0; i < length; i++) { Node child = nl.item(i); // ignore all non-Element nodes @@ -110,7 +112,7 @@ public final class DOMX509Data extends DOMStructure implements X509Data { continue; } - Element childElem = (Element) child; + Element childElem = (Element)child; String localName = childElem.getLocalName(); if (localName.equals("X509Certificate")) { content.add(unmarshalX509Certificate(childElem)); @@ -138,32 +140,32 @@ public final class DOMX509Data extends DOMStructure implements X509Data { } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element xdElem = DOMUtils.createElement - (ownerDoc, "X509Data", XMLSignature.XMLNS, dsPrefix); + Element xdElem = DOMUtils.createElement(ownerDoc, "X509Data", + XMLSignature.XMLNS, dsPrefix); // append children and preserve order for (int i = 0, size = content.size(); i < size; i++) { Object object = content.get(i); if (object instanceof X509Certificate) { - marshalCert((X509Certificate) object,xdElem,ownerDoc,dsPrefix); + marshalCert((X509Certificate)object,xdElem,ownerDoc,dsPrefix); } else if (object instanceof XMLStructure) { if (object instanceof X509IssuerSerial) { - ((DOMX509IssuerSerial) object).marshal + ((DOMX509IssuerSerial)object).marshal (xdElem, dsPrefix, context); } else { javax.xml.crypto.dom.DOMStructure domContent = - (javax.xml.crypto.dom.DOMStructure) object; + (javax.xml.crypto.dom.DOMStructure)object; DOMUtils.appendChild(xdElem, domContent.getNode()); } } else if (object instanceof byte[]) { - marshalSKI((byte[]) object, xdElem, ownerDoc, dsPrefix); + marshalSKI((byte[])object, xdElem, ownerDoc, dsPrefix); } else if (object instanceof String) { - marshalSubjectName((String) object, xdElem, ownerDoc,dsPrefix); + marshalSubjectName((String)object, xdElem, ownerDoc,dsPrefix); } else if (object instanceof X509CRL) { - marshalCRL((X509CRL) object, xdElem, ownerDoc, dsPrefix); + marshalCRL((X509CRL)object, xdElem, ownerDoc, dsPrefix); } } @@ -171,31 +173,32 @@ public final class DOMX509Data extends DOMStructure implements X509Data { } private void marshalSKI(byte[] skid, Node parent, Document doc, - String dsPrefix) { - - Element skidElem = DOMUtils.createElement - (doc, "X509SKI", XMLSignature.XMLNS, dsPrefix); + String dsPrefix) + { + Element skidElem = DOMUtils.createElement(doc, "X509SKI", + XMLSignature.XMLNS, dsPrefix); skidElem.appendChild(doc.createTextNode(Base64.encode(skid))); parent.appendChild(skidElem); } private void marshalSubjectName(String name, Node parent, Document doc, - String dsPrefix) { - - Element snElem = DOMUtils.createElement - (doc, "X509SubjectName", XMLSignature.XMLNS, dsPrefix); + String dsPrefix) + { + Element snElem = DOMUtils.createElement(doc, "X509SubjectName", + XMLSignature.XMLNS, dsPrefix); snElem.appendChild(doc.createTextNode(name)); parent.appendChild(snElem); } private void marshalCert(X509Certificate cert, Node parent, Document doc, - String dsPrefix) throws MarshalException { - - Element certElem = DOMUtils.createElement - (doc, "X509Certificate", XMLSignature.XMLNS, dsPrefix); + String dsPrefix) + throws MarshalException + { + Element certElem = DOMUtils.createElement(doc, "X509Certificate", + XMLSignature.XMLNS, dsPrefix); try { certElem.appendChild(doc.createTextNode - (Base64.encode(cert.getEncoded()))); + (Base64.encode(cert.getEncoded()))); } catch (CertificateEncodingException e) { throw new MarshalException("Error encoding X509Certificate", e); } @@ -203,13 +206,14 @@ public final class DOMX509Data extends DOMStructure implements X509Data { } private void marshalCRL(X509CRL crl, Node parent, Document doc, - String dsPrefix) throws MarshalException { - - Element crlElem = DOMUtils.createElement - (doc, "X509CRL", XMLSignature.XMLNS, dsPrefix); + String dsPrefix) + throws MarshalException + { + Element crlElem = DOMUtils.createElement(doc, "X509CRL", + XMLSignature.XMLNS, dsPrefix); try { crlElem.appendChild(doc.createTextNode - (Base64.encode(crl.getEncoded()))); + (Base64.encode(crl.getEncoded()))); } catch (CRLException e) { throw new MarshalException("Error encoding X509CRL", e); } @@ -217,10 +221,11 @@ public final class DOMX509Data extends DOMStructure implements X509Data { } private X509Certificate unmarshalX509Certificate(Element elem) - throws MarshalException { + throws MarshalException + { try { ByteArrayInputStream bs = unmarshalBase64Binary(elem); - return (X509Certificate) cf.generateCertificate(bs); + return (X509Certificate)cf.generateCertificate(bs); } catch (CertificateException e) { throw new MarshalException("Cannot create X509Certificate", e); } @@ -229,7 +234,7 @@ public final class DOMX509Data extends DOMStructure implements X509Data { private X509CRL unmarshalX509CRL(Element elem) throws MarshalException { try { ByteArrayInputStream bs = unmarshalBase64Binary(elem); - return (X509CRL) cf.generateCRL(bs); + return (X509CRL)cf.generateCRL(bs); } catch (CRLException e) { throw new MarshalException("Cannot create X509CRL", e); } @@ -249,6 +254,7 @@ public final class DOMX509Data extends DOMStructure implements X509Data { } } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -257,9 +263,9 @@ public final class DOMX509Data extends DOMStructure implements X509Data { if (!(o instanceof X509Data)) { return false; } - X509Data oxd = (X509Data) o; + X509Data oxd = (X509Data)o; - List ocontent = oxd.getContent(); + @SuppressWarnings("unchecked") List ocontent = oxd.getContent(); int size = content.size(); if (size != ocontent.size()) { return false; @@ -270,7 +276,7 @@ public final class DOMX509Data extends DOMStructure implements X509Data { Object ox = ocontent.get(i); if (x instanceof byte[]) { if (!(ox instanceof byte[]) || - !Arrays.equals((byte[]) x, (byte[]) ox)) { + !Arrays.equals((byte[])x, (byte[])ox)) { return false; } } else { @@ -282,4 +288,12 @@ public final class DOMX509Data extends DOMStructure implements X509Data { return true; } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + content.hashCode(); + + return result; + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509IssuerSerial.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509IssuerSerial.java index f3cad8333a0..318d9cfe886 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509IssuerSerial.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509IssuerSerial.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMX509IssuerSerial.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMX509IssuerSerial.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -94,15 +96,16 @@ public final class DOMX509IssuerSerial extends DOMStructure } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - Element isElem = DOMUtils.createElement - (ownerDoc, "X509IssuerSerial", XMLSignature.XMLNS, dsPrefix); - Element inElem = DOMUtils.createElement - (ownerDoc, "X509IssuerName", XMLSignature.XMLNS, dsPrefix); - Element snElem = DOMUtils.createElement - (ownerDoc, "X509SerialNumber", XMLSignature.XMLNS, dsPrefix); + Element isElem = DOMUtils.createElement(ownerDoc, "X509IssuerSerial", + XMLSignature.XMLNS, dsPrefix); + Element inElem = DOMUtils.createElement(ownerDoc, "X509IssuerName", + XMLSignature.XMLNS, dsPrefix); + Element snElem = DOMUtils.createElement(ownerDoc, "X509SerialNumber", + XMLSignature.XMLNS, dsPrefix); inElem.appendChild(ownerDoc.createTextNode(issuerName)); snElem.appendChild(ownerDoc.createTextNode(serialNumber.toString())); isElem.appendChild(inElem); @@ -110,6 +113,7 @@ public final class DOMX509IssuerSerial extends DOMStructure parent.appendChild(isElem); } + @Override public boolean equals(Object obj) { if (this == obj) { return true; @@ -117,8 +121,17 @@ public final class DOMX509IssuerSerial extends DOMStructure if (!(obj instanceof X509IssuerSerial)) { return false; } - X509IssuerSerial ois = (X509IssuerSerial) obj; + X509IssuerSerial ois = (X509IssuerSerial)obj; return (issuerName.equals(ois.getIssuerName()) && - serialNumber.equals(ois.getSerialNumber())); + serialNumber.equals(ois.getSerialNumber())); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + issuerName.hashCode(); + result = 31 * result + serialNumber.hashCode(); + + return result; } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java index a5416f5d770..01c7bcc1628 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMXMLObject.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXMLObject.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -32,6 +34,7 @@ import javax.xml.crypto.dsig.*; import java.security.Provider; import java.util.*; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -48,7 +51,8 @@ public final class DOMXMLObject extends DOMStructure implements XMLObject { private final String id; private final String mimeType; private final String encoding; - private final List content; + private final List content; + private Element objectElem; /** * Creates an XMLObject from the specified parameters. @@ -63,19 +67,20 @@ public final class DOMXMLObject extends DOMStructure implements XMLObject { * @throws ClassCastException if content contains any * entries that are not of type {@link XMLStructure} */ - public DOMXMLObject(List content, String id, String mimeType, - String encoding) { + public DOMXMLObject(List content, String id, + String mimeType, String encoding) + { if (content == null || content.isEmpty()) { - this.content = Collections.EMPTY_LIST; + this.content = Collections.emptyList(); } else { - List contentCopy = new ArrayList(content); - for (int i = 0, size = contentCopy.size(); i < size; i++) { - if (!(contentCopy.get(i) instanceof XMLStructure)) { + this.content = Collections.unmodifiableList( + new ArrayList(content)); + for (int i = 0, size = this.content.size(); i < size; i++) { + if (!(this.content.get(i) instanceof XMLStructure)) { throw new ClassCastException ("content["+i+"] is not a valid type"); } } - this.content = Collections.unmodifiableList(contentCopy); } this.id = id; this.mimeType = mimeType; @@ -89,7 +94,9 @@ public final class DOMXMLObject extends DOMStructure implements XMLObject { * @throws MarshalException if there is an error when unmarshalling */ public DOMXMLObject(Element objElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { // unmarshal attributes this.encoding = DOMUtils.getAttributeValue(objElem, "Encoding"); @@ -104,17 +111,17 @@ public final class DOMXMLObject extends DOMStructure implements XMLObject { NodeList nodes = objElem.getChildNodes(); int length = nodes.getLength(); - List content = new ArrayList(length); + List content = new ArrayList(length); for (int i = 0; i < length; i++) { Node child = nodes.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { - Element childElem = (Element) child; + Element childElem = (Element)child; String tag = childElem.getLocalName(); if (tag.equals("Manifest")) { content.add(new DOMManifest(childElem, context, provider)); continue; } else if (tag.equals("SignatureProperties")) { - content.add(new DOMSignatureProperties(childElem)); + content.add(new DOMSignatureProperties(childElem, context)); continue; } else if (tag.equals("X509Data")) { content.add(new DOMX509Data(childElem)); @@ -125,10 +132,11 @@ public final class DOMXMLObject extends DOMStructure implements XMLObject { content.add(new javax.xml.crypto.dom.DOMStructure(child)); } if (content.isEmpty()) { - this.content = Collections.EMPTY_LIST; + this.content = Collections.emptyList(); } else { this.content = Collections.unmodifiableList(content); } + this.objectElem = objElem; } public List getContent() { @@ -151,29 +159,32 @@ public final class DOMXMLObject extends DOMStructure implements XMLObject { throws MarshalException { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - Element objElem = DOMUtils.createElement - (ownerDoc, "Object", XMLSignature.XMLNS, dsPrefix); + Element objElem = objectElem != null ? objectElem : null; + if (objElem == null) { + objElem = DOMUtils.createElement(ownerDoc, "Object", + XMLSignature.XMLNS, dsPrefix); - // set attributes - DOMUtils.setAttributeID(objElem, "Id", id); - DOMUtils.setAttribute(objElem, "MimeType", mimeType); - DOMUtils.setAttribute(objElem, "Encoding", encoding); + // set attributes + DOMUtils.setAttributeID(objElem, "Id", id); + DOMUtils.setAttribute(objElem, "MimeType", mimeType); + DOMUtils.setAttribute(objElem, "Encoding", encoding); - // create and append any elements and mixed content, if necessary - for (int i = 0, size = content.size(); i < size; i++) { - XMLStructure object = (XMLStructure) content.get(i); - if (object instanceof DOMStructure) { - ((DOMStructure) object).marshal(objElem, dsPrefix, context); - } else { - javax.xml.crypto.dom.DOMStructure domObject = - (javax.xml.crypto.dom.DOMStructure) object; - DOMUtils.appendChild(objElem, domObject.getNode()); + // create and append any elements and mixed content, if necessary + for (XMLStructure object : content) { + if (object instanceof DOMStructure) { + ((DOMStructure)object).marshal(objElem, dsPrefix, context); + } else { + javax.xml.crypto.dom.DOMStructure domObject = + (javax.xml.crypto.dom.DOMStructure)object; + DOMUtils.appendChild(objElem, domObject.getNode()); + } } } parent.appendChild(objElem); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -182,34 +193,53 @@ public final class DOMXMLObject extends DOMStructure implements XMLObject { if (!(o instanceof XMLObject)) { return false; } - XMLObject oxo = (XMLObject) o; + XMLObject oxo = (XMLObject)o; - boolean idsEqual = (id == null ? oxo.getId() == null : - id.equals(oxo.getId())); - boolean encodingsEqual = (encoding == null ? oxo.getEncoding() == null : - encoding.equals(oxo.getEncoding())); - boolean mimeTypesEqual = (mimeType == null ? oxo.getMimeType() == null : - mimeType.equals(oxo.getMimeType())); + boolean idsEqual = (id == null ? oxo.getId() == null + : id.equals(oxo.getId())); + boolean encodingsEqual = + (encoding == null ? oxo.getEncoding() == null + : encoding.equals(oxo.getEncoding())); + boolean mimeTypesEqual = + (mimeType == null ? oxo.getMimeType() == null + : mimeType.equals(oxo.getMimeType())); + @SuppressWarnings("unchecked") + List oxoContent = oxo.getContent(); return (idsEqual && encodingsEqual && mimeTypesEqual && - equalsContent(oxo.getContent())); + equalsContent(oxoContent)); } - private boolean equalsContent(List otherContent) { + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + if (encoding != null) { + result = 31 * result + encoding.hashCode(); + } + if (mimeType != null) { + result = 31 * result + mimeType.hashCode(); + } + result = 31 * result + content.hashCode(); + + return result; + } + + private boolean equalsContent(List otherContent) { if (content.size() != otherContent.size()) { return false; } for (int i = 0, osize = otherContent.size(); i < osize; i++) { - XMLStructure oxs = (XMLStructure) otherContent.get(i); - XMLStructure xs = (XMLStructure) content.get(i); + XMLStructure oxs = otherContent.get(i); + XMLStructure xs = content.get(i); if (oxs instanceof javax.xml.crypto.dom.DOMStructure) { if (!(xs instanceof javax.xml.crypto.dom.DOMStructure)) { return false; } - Node onode = - ((javax.xml.crypto.dom.DOMStructure) oxs).getNode(); - Node node = - ((javax.xml.crypto.dom.DOMStructure) xs).getNode(); + Node onode = ((javax.xml.crypto.dom.DOMStructure)oxs).getNode(); + Node node = ((javax.xml.crypto.dom.DOMStructure)xs).getNode(); if (!DOMUtils.nodesEqual(node, onode)) { return false; } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java index 6c91e369f42..ebd41baae2a 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. @@ -29,7 +31,7 @@ * =========================================================================== */ /* - * $Id: DOMXMLSignature.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXMLSignature.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -40,7 +42,6 @@ import javax.xml.crypto.dsig.dom.DOMSignContext; import javax.xml.crypto.dsig.dom.DOMValidateContext; import javax.xml.crypto.dsig.keyinfo.KeyInfo; -import java.io.*; import java.security.InvalidKeyException; import java.security.Key; import java.security.Provider; @@ -48,8 +49,7 @@ import java.util.Collections; import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -67,11 +67,12 @@ import com.sun.org.apache.xml.internal.security.utils.Base64; public final class DOMXMLSignature extends DOMStructure implements XMLSignature { - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); private String id; private SignatureValue sv; private KeyInfo ki; - private List objects; + private List objects; private SignedInfo si; private Document ownerDoc = null; private Element localSigElem = null; @@ -79,7 +80,7 @@ public final class DOMXMLSignature extends DOMStructure private boolean validationStatus; private boolean validated = false; private KeySelectorResult ksr; - private HashMap signatureIdMap; + private HashMap signatureIdMap; static { com.sun.org.apache.xml.internal.security.Init.init(); @@ -98,8 +99,9 @@ public final class DOMXMLSignature extends DOMStructure * omit) * @throws NullPointerException if si is null */ - public DOMXMLSignature(SignedInfo si, KeyInfo ki, List objs, String id, - String signatureValueId) + public DOMXMLSignature(SignedInfo si, KeyInfo ki, + List objs, + String id, String signatureValueId) { if (si == null) { throw new NullPointerException("signedInfo cannot be null"); @@ -108,16 +110,16 @@ public final class DOMXMLSignature extends DOMStructure this.id = id; this.sv = new DOMSignatureValue(signatureValueId); if (objs == null) { - this.objects = Collections.EMPTY_LIST; + this.objects = Collections.emptyList(); } else { - List objsCopy = new ArrayList(objs); - for (int i = 0, size = objsCopy.size(); i < size; i++) { - if (!(objsCopy.get(i) instanceof XMLObject)) { + this.objects = + Collections.unmodifiableList(new ArrayList(objs)); + for (int i = 0, size = this.objects.size(); i < size; i++) { + if (!(this.objects.get(i) instanceof XMLObject)) { throw new ClassCastException ("objs["+i+"] is not an XMLObject"); } } - this.objects = Collections.unmodifiableList(objsCopy); } this.ki = ki; } @@ -129,7 +131,9 @@ public final class DOMXMLSignature extends DOMStructure * @throws MarshalException if XMLSignature cannot be unmarshalled */ public DOMXMLSignature(Element sigElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { localSigElem = sigElem; ownerDoc = localSigElem.getOwnerDocument(); @@ -142,7 +146,7 @@ public final class DOMXMLSignature extends DOMStructure // unmarshal SignatureValue Element sigValElem = DOMUtils.getNextSiblingElement(siElem); - sv = new DOMSignatureValue(sigValElem); + sv = new DOMSignatureValue(sigValElem, context); // unmarshal KeyInfo, if specified Element nextSibling = DOMUtils.getNextSiblingElement(sigValElem); @@ -153,12 +157,12 @@ public final class DOMXMLSignature extends DOMStructure // unmarshal Objects, if specified if (nextSibling == null) { - objects = Collections.EMPTY_LIST; + objects = Collections.emptyList(); } else { - List tempObjects = new ArrayList(); + List tempObjects = new ArrayList(); while (nextSibling != null) { - tempObjects.add - (new DOMXMLObject(nextSibling, context, provider)); + tempObjects.add(new DOMXMLObject(nextSibling, + context, provider)); nextSibling = DOMUtils.getNextSiblingElement(nextSibling); } objects = Collections.unmodifiableList(tempObjects); @@ -190,41 +194,42 @@ public final class DOMXMLSignature extends DOMStructure } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { marshal(parent, null, dsPrefix, context); } public void marshal(Node parent, Node nextSibling, String dsPrefix, - DOMCryptoContext context) throws MarshalException { + DOMCryptoContext context) + throws MarshalException + { ownerDoc = DOMUtils.getOwnerDocument(parent); - - sigElem = DOMUtils.createElement - (ownerDoc, "Signature", XMLSignature.XMLNS, dsPrefix); + sigElem = DOMUtils.createElement(ownerDoc, "Signature", + XMLSignature.XMLNS, dsPrefix); // append xmlns attribute if (dsPrefix == null || dsPrefix.length() == 0) { - sigElem.setAttributeNS - ("http://www.w3.org/2000/xmlns/", "xmlns", XMLSignature.XMLNS); + sigElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", + XMLSignature.XMLNS); } else { - sigElem.setAttributeNS - ("http://www.w3.org/2000/xmlns/", "xmlns:" + dsPrefix, - XMLSignature.XMLNS); + sigElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + + dsPrefix, XMLSignature.XMLNS); } // create and append SignedInfo element - ((DOMSignedInfo) si).marshal(sigElem, dsPrefix, context); + ((DOMSignedInfo)si).marshal(sigElem, dsPrefix, context); // create and append SignatureValue element - ((DOMSignatureValue) sv).marshal(sigElem, dsPrefix, context); + ((DOMSignatureValue)sv).marshal(sigElem, dsPrefix, context); // create and append KeyInfo element if necessary if (ki != null) { - ((DOMKeyInfo) ki).marshal(sigElem, null, dsPrefix, context); + ((DOMKeyInfo)ki).marshal(sigElem, null, dsPrefix, context); } // create and append Object elements if necessary for (int i = 0, size = objects.size(); i < size; i++) { - ((DOMXMLObject) objects.get(i)).marshal(sigElem, dsPrefix, context); + ((DOMXMLObject)objects.get(i)).marshal(sigElem, dsPrefix, context); } // append Id attribute @@ -234,8 +239,8 @@ public final class DOMXMLSignature extends DOMStructure } public boolean validate(XMLValidateContext vc) - throws XMLSignatureException { - + throws XMLSignatureException + { if (vc == null) { throw new NullPointerException("validateContext is null"); } @@ -258,20 +263,20 @@ public final class DOMXMLSignature extends DOMStructure } // validate all References - List refs = this.si.getReferences(); + @SuppressWarnings("unchecked") + List refs = this.si.getReferences(); boolean validateRefs = true; for (int i = 0, size = refs.size(); validateRefs && i < size; i++) { - Reference ref = (Reference) refs.get(i); + Reference ref = refs.get(i); boolean refValid = ref.validate(vc); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Reference[" + ref.getURI() + "] is valid: " - + refValid); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Reference[" + ref.getURI() + "] is valid: " + refValid); } validateRefs &= refValid; } if (!validateRefs) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Couldn't validate the References"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Couldn't validate the References"); } validationStatus = false; validated = true; @@ -281,27 +286,30 @@ public final class DOMXMLSignature extends DOMStructure // validate Manifests, if property set boolean validateMans = true; if (Boolean.TRUE.equals(vc.getProperty - ("org.jcp.xml.dsig.validateManifests"))) { - + ("org.jcp.xml.dsig.validateManifests"))) + { for (int i=0, size=objects.size(); validateMans && i < size; i++) { - XMLObject xo = (XMLObject) objects.get(i); - List content = xo.getContent(); + XMLObject xo = objects.get(i); + @SuppressWarnings("unchecked") + List content = xo.getContent(); int csize = content.size(); for (int j = 0; validateMans && j < csize; j++) { - XMLStructure xs = (XMLStructure) content.get(j); + XMLStructure xs = content.get(j); if (xs instanceof Manifest) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "validating manifest"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "validating manifest"); } - Manifest man = (Manifest) xs; - List manRefs = man.getReferences(); + Manifest man = (Manifest)xs; + @SuppressWarnings("unchecked") + List manRefs = man.getReferences(); int rsize = manRefs.size(); for (int k = 0; validateMans && k < rsize; k++) { - Reference ref = (Reference) manRefs.get(k); + Reference ref = manRefs.get(k); boolean refValid = ref.validate(vc); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Manifest ref[" - + ref.getURI() + "] is valid: " + refValid); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, + "Manifest ref[" + ref.getURI() + "] is valid: " + refValid + ); } validateMans &= refValid; } @@ -316,41 +324,39 @@ public final class DOMXMLSignature extends DOMStructure } public void sign(XMLSignContext signContext) - throws MarshalException, XMLSignatureException { + throws MarshalException, XMLSignatureException + { if (signContext == null) { throw new NullPointerException("signContext cannot be null"); } - DOMSignContext context = (DOMSignContext) signContext; - if (context != null) { - marshal(context.getParent(), context.getNextSibling(), + DOMSignContext context = (DOMSignContext)signContext; + marshal(context.getParent(), context.getNextSibling(), DOMUtils.getSignaturePrefix(context), context); - } // generate references and signature value - List allReferences = new ArrayList(); + List allReferences = new ArrayList(); // traverse the Signature and register all objects with IDs that // may contain References - signatureIdMap = new HashMap(); + signatureIdMap = new HashMap(); signatureIdMap.put(id, this); signatureIdMap.put(si.getId(), si); - List refs = si.getReferences(); - for (int i = 0, size = refs.size(); i < size; i++) { - Reference ref = (Reference) refs.get(i); + @SuppressWarnings("unchecked") + List refs = si.getReferences(); + for (Reference ref : refs) { signatureIdMap.put(ref.getId(), ref); } - for (int i = 0, size = objects.size(); i < size; i++) { - XMLObject obj = (XMLObject) objects.get(i); + for (XMLObject obj : objects) { signatureIdMap.put(obj.getId(), obj); - List content = obj.getContent(); - for (int j = 0, csize = content.size(); j < csize; j++) { - XMLStructure xs = (XMLStructure) content.get(j); + @SuppressWarnings("unchecked") + List content = obj.getContent(); + for (XMLStructure xs : content) { if (xs instanceof Manifest) { - Manifest man = (Manifest) xs; + Manifest man = (Manifest)xs; signatureIdMap.put(man.getId(), man); - List manRefs = man.getReferences(); - for (int k = 0, msize = manRefs.size(); k < msize; k++) { - Reference ref = (Reference) manRefs.get(k); + @SuppressWarnings("unchecked") + List manRefs = man.getReferences(); + for (Reference ref : manRefs) { allReferences.add(ref); signatureIdMap.put(ref.getId(), ref); } @@ -359,56 +365,51 @@ public final class DOMXMLSignature extends DOMStructure } // always add SignedInfo references after Manifest references so // that Manifest reference are digested first - allReferences.addAll(si.getReferences()); + allReferences.addAll(refs); // generate/digest each reference - for (int i = 0, size = allReferences.size(); i < size; i++) { - DOMReference ref = (DOMReference) allReferences.get(i); - digestReference(ref, signContext); + for (Reference ref : allReferences) { + digestReference((DOMReference)ref, signContext); } // do final sweep to digest any references that were skipped or missed - for (int i = 0, size = allReferences.size(); i < size; i++) { - DOMReference ref = (DOMReference) allReferences.get(i); - if (ref.isDigested()) { + for (Reference ref : allReferences) { + if (((DOMReference)ref).isDigested()) { continue; } - ref.digest(signContext); + ((DOMReference)ref).digest(signContext); } Key signingKey = null; KeySelectorResult ksr = null; try { - ksr = signContext.getKeySelector().select - (ki, KeySelector.Purpose.SIGN, - si.getSignatureMethod(), signContext); + ksr = signContext.getKeySelector().select(ki, + KeySelector.Purpose.SIGN, + si.getSignatureMethod(), + signContext); signingKey = ksr.getKey(); if (signingKey == null) { throw new XMLSignatureException("the keySelector did not " + - "find a signing key"); + "find a signing key"); } } catch (KeySelectorException kse) { throw new XMLSignatureException("cannot find signing key", kse); } // calculate signature value - byte[] val = null; try { - val = ((DOMSignatureMethod) si.getSignatureMethod()).sign - (signingKey, (DOMSignedInfo) si, signContext); + byte[] val = ((AbstractDOMSignatureMethod) + si.getSignatureMethod()).sign(signingKey, si, signContext); + ((DOMSignatureValue)sv).setValue(val); } catch (InvalidKeyException ike) { throw new XMLSignatureException(ike); } - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "SignatureValue = " + val); - } - ((DOMSignatureValue) sv).setValue(val); - this.localSigElem = sigElem; this.ksr = ksr; } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -417,22 +418,39 @@ public final class DOMXMLSignature extends DOMStructure if (!(o instanceof XMLSignature)) { return false; } - XMLSignature osig = (XMLSignature) o; + XMLSignature osig = (XMLSignature)o; boolean idEqual = (id == null ? osig.getId() == null : id.equals(osig.getId())); boolean keyInfoEqual = - (ki == null ? osig.getKeyInfo() == null : - ki.equals(osig.getKeyInfo())); + (ki == null ? osig.getKeyInfo() == null + : ki.equals(osig.getKeyInfo())); return (idEqual && keyInfoEqual && - sv.equals(osig.getSignatureValue()) && - si.equals(osig.getSignedInfo()) && - objects.equals(osig.getObjects())); + sv.equals(osig.getSignatureValue()) && + si.equals(osig.getSignedInfo()) && + objects.equals(osig.getObjects())); + } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + if (ki != null) { + result = 31 * result + ki.hashCode(); + } + result = 31 * result + sv.hashCode(); + result = 31 * result + si.hashCode(); + result = 31 * result + objects.hashCode(); + + return result; } private void digestReference(DOMReference ref, XMLSignContext signContext) - throws XMLSignatureException { + throws XMLSignatureException + { if (ref.isDigested()) { return; } @@ -441,15 +459,15 @@ public final class DOMXMLSignature extends DOMStructure if (Utils.sameDocumentURI(uri)) { String id = Utils.parseIdFromSameDocumentURI(uri); if (id != null && signatureIdMap.containsKey(id)) { - Object obj = signatureIdMap.get(id); - if (obj instanceof DOMReference) { - digestReference((DOMReference) obj, signContext); - } else if (obj instanceof Manifest) { - Manifest man = (Manifest) obj; + XMLStructure xs = signatureIdMap.get(id); + if (xs instanceof DOMReference) { + digestReference((DOMReference)xs, signContext); + } else if (xs instanceof Manifest) { + Manifest man = (Manifest)xs; List manRefs = man.getReferences(); for (int i = 0, size = manRefs.size(); i < size; i++) { - digestReference - ((DOMReference) manRefs.get(i), signContext); + digestReference((DOMReference)manRefs.get(i), + signContext); } } } @@ -457,9 +475,9 @@ public final class DOMXMLSignature extends DOMStructure // reference dependencies in the XPath Transform - so be on // the safe side, and skip and do at end in the final sweep if (uri.length() == 0) { - List transforms = ref.getTransforms(); - for (int i = 0, size = transforms.size(); i < size; i++) { - Transform transform = (Transform) transforms.get(i); + @SuppressWarnings("unchecked") + List transforms = ref.getTransforms(); + for (Transform transform : transforms) { String transformAlg = transform.getAlgorithm(); if (transformAlg.equals(Transform.XPATH) || transformAlg.equals(Transform.XPATH2)) { @@ -472,8 +490,8 @@ public final class DOMXMLSignature extends DOMStructure } public class DOMSignatureValue extends DOMStructure - implements SignatureValue { - + implements SignatureValue + { private String id; private byte[] value; private String valueBase64; @@ -485,7 +503,9 @@ public final class DOMXMLSignature extends DOMStructure this.id = id; } - DOMSignatureValue(Element sigValueElem) throws MarshalException { + DOMSignatureValue(Element sigValueElem, XMLCryptoContext context) + throws MarshalException + { try { // base64 decode signatureValue value = Base64.decode(sigValueElem); @@ -508,12 +528,12 @@ public final class DOMXMLSignature extends DOMStructure } public byte[] getValue() { - return (value == null) ? null : (byte[]) value.clone(); + return (value == null) ? null : (byte[])value.clone(); } public boolean validate(XMLValidateContext validateContext) - throws XMLSignatureException { - + throws XMLSignatureException + { if (validateContext == null) { throw new NullPointerException("context cannot be null"); } @@ -531,18 +551,18 @@ public final class DOMXMLSignature extends DOMStructure (ki, KeySelector.Purpose.VERIFY, sm, validateContext); validationKey = ksResult.getKey(); if (validationKey == null) { - throw new XMLSignatureException("the keyselector did " + - "not find a validation key"); + throw new XMLSignatureException("the keyselector did not " + + "find a validation key"); } } catch (KeySelectorException kse) { throw new XMLSignatureException("cannot find validation " + - "key", kse); + "key", kse); } // canonicalize SignedInfo and verify signature try { - validationStatus = ((DOMSignatureMethod) sm).verify - (validationKey, (DOMSignedInfo) si, value, validateContext); + validationStatus = ((AbstractDOMSignatureMethod)sm).verify + (validationKey, si, value, validateContext); } catch (Exception e) { throw new XMLSignatureException(e); } @@ -552,6 +572,7 @@ public final class DOMXMLSignature extends DOMStructure return validationStatus; } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -560,7 +581,7 @@ public final class DOMXMLSignature extends DOMStructure if (!(o instanceof SignatureValue)) { return false; } - SignatureValue osv = (SignatureValue) o; + SignatureValue osv = (SignatureValue)o; boolean idEqual = (id == null ? osv.getId() == null : id.equals(osv.getId())); @@ -569,12 +590,23 @@ public final class DOMXMLSignature extends DOMStructure return idEqual; } - public void marshal(Node parent, String dsPrefix, - DOMCryptoContext context) throws MarshalException { + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + return result; + } + + public void marshal(Node parent, String dsPrefix, + DOMCryptoContext context) + throws MarshalException + { // create SignatureValue element - sigValueElem = DOMUtils.createElement - (ownerDoc, "SignatureValue", XMLSignature.XMLNS, dsPrefix); + sigValueElem = DOMUtils.createElement(ownerDoc, "SignatureValue", + XMLSignature.XMLNS, dsPrefix); if (valueBase64 != null) { sigValueElem.appendChild(ownerDoc.createTextNode(valueBase64)); } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java index fb9664db0c1..b085a33f5e5 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java @@ -2,31 +2,34 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMXMLSignatureFactory.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXMLSignatureFactory.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import javax.xml.crypto.*; +import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.dom.DOMValidateContext; import javax.xml.crypto.dsig.keyinfo.*; @@ -34,7 +37,6 @@ import javax.xml.crypto.dsig.spec.*; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; -import java.security.spec.AlgorithmParameterSpec; import java.util.List; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -56,6 +58,7 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { return new DOMXMLSignature(si, ki, null, null, null); } + @SuppressWarnings("unchecked") public XMLSignature newXMLSignature(SignedInfo si, KeyInfo ki, List objects, String id, String signatureValueId) { return new DOMXMLSignature(si, ki, objects, id, signatureValueId); @@ -65,11 +68,13 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { return newReference(uri, dm, null, null, null); } + @SuppressWarnings("unchecked") public Reference newReference(String uri, DigestMethod dm, List transforms, String type, String id) { return new DOMReference(uri, type, dm, transforms, id, getProvider()); } + @SuppressWarnings("unchecked") public Reference newReference(String uri, DigestMethod dm, List appliedTransforms, Data result, List transforms, String type, String id) { @@ -86,6 +91,7 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { (uri, type, dm, appliedTransforms, result, transforms, id, getProvider()); } + @SuppressWarnings("unchecked") public Reference newReference(String uri, DigestMethod dm, List transforms, String type, String id, byte[] digestValue) { if (digestValue == null) { @@ -95,34 +101,41 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { (uri, type, dm, null, null, transforms, id, digestValue, getProvider()); } + @SuppressWarnings("unchecked") public SignedInfo newSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, List references) { return newSignedInfo(cm, sm, references, null); } + @SuppressWarnings("unchecked") public SignedInfo newSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, List references, String id) { return new DOMSignedInfo(cm, sm, references, id); } // Object factory methods + @SuppressWarnings("unchecked") public XMLObject newXMLObject(List content, String id, String mimeType, String encoding) { return new DOMXMLObject(content, id, mimeType, encoding); } + @SuppressWarnings("unchecked") public Manifest newManifest(List references) { return newManifest(references, null); } + @SuppressWarnings("unchecked") public Manifest newManifest(List references, String id) { return new DOMManifest(references, id); } + @SuppressWarnings("unchecked") public SignatureProperties newSignatureProperties(List props, String id) { return new DOMSignatureProperties(props, id); } + @SuppressWarnings("unchecked") public SignatureProperty newSignatureProperty (List info, String target, String id) { return new DOMSignatureProperty(info, target, id); @@ -143,12 +156,19 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { if (xmlStructure == null) { throw new NullPointerException("xmlStructure cannot be null"); } + if (!(xmlStructure instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("xmlStructure must be of type DOMStructure"); + } return unmarshal (((javax.xml.crypto.dom.DOMStructure) xmlStructure).getNode(), - null); + new UnmarshalContext()); } - private XMLSignature unmarshal(Node node, XMLValidateContext context) + private static class UnmarshalContext extends DOMCryptoContext { + UnmarshalContext() {} + } + + private XMLSignature unmarshal(Node node, XMLCryptoContext context) throws MarshalException { node.normalize(); @@ -221,12 +241,20 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { return new DOMSignatureMethod.SHA1withDSA(params); } else if (algorithm.equals(SignatureMethod.HMAC_SHA1)) { return new DOMHMACSignatureMethod.SHA1(params); - } else if (algorithm.equals(DOMSignatureMethod.HMAC_SHA256)) { + } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA256)) { return new DOMHMACSignatureMethod.SHA256(params); - } else if (algorithm.equals(DOMSignatureMethod.HMAC_SHA384)) { + } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA384)) { return new DOMHMACSignatureMethod.SHA384(params); - } else if (algorithm.equals(DOMSignatureMethod.HMAC_SHA512)) { + } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA512)) { return new DOMHMACSignatureMethod.SHA512(params); + } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA1)) { + return new DOMSignatureMethod.SHA1withECDSA(params); + } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA256)) { + return new DOMSignatureMethod.SHA256withECDSA(params); + } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA384)) { + return new DOMSignatureMethod.SHA384withECDSA(params); + } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA512)) { + return new DOMSignatureMethod.SHA512withECDSA(params); } else { throw new NoSuchAlgorithmException("unsupported algorithm"); } @@ -235,12 +263,18 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { public Transform newTransform(String algorithm, TransformParameterSpec params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { + TransformService spi; - try { + if (getProvider() == null) { spi = TransformService.getInstance(algorithm, "DOM"); - } catch (NoSuchAlgorithmException nsae) { - spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } else { + try { + spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(algorithm, "DOM"); + } } + spi.init(params); return new DOMTransform(spi); } @@ -249,11 +283,16 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { XMLStructure params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { TransformService spi; - try { + if (getProvider() == null) { spi = TransformService.getInstance(algorithm, "DOM"); - } catch (NoSuchAlgorithmException nsae) { - spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } else { + try { + spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(algorithm, "DOM"); + } } + if (params == null) { spi.init(null); } else { @@ -266,11 +305,16 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { C14NMethodParameterSpec params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { TransformService spi; - try { + if (getProvider() == null) { spi = TransformService.getInstance(algorithm, "DOM"); - } catch (NoSuchAlgorithmException nsae) { - spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } else { + try { + spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(algorithm, "DOM"); + } } + spi.init(params); return new DOMCanonicalizationMethod(spi); } @@ -279,16 +323,21 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { XMLStructure params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { TransformService spi; - try { + if (getProvider() == null) { spi = TransformService.getInstance(algorithm, "DOM"); - } catch (NoSuchAlgorithmException nsae) { - spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } else { + try { + spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(algorithm, "DOM"); + } } if (params == null) { spi.init(null); } else { spi.init(params, null); } + return new DOMCanonicalizationMethod(spi); } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java index 6da75e93b23..edabc988002 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * =========================================================================== @@ -29,7 +31,7 @@ * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMXPathFilter2Transform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXPathFilter2Transform.java 1203789 2011-11-18 18:46:07Z mullan $ */ package org.jcp.xml.dsig.internal.dom; @@ -40,10 +42,10 @@ import javax.xml.crypto.dsig.spec.XPathType; import javax.xml.crypto.dsig.spec.XPathFilter2ParameterSpec; import java.security.InvalidAlgorithmParameterException; import java.util.ArrayList; -import java.util.Iterator; +import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.HashMap; +import java.util.Set; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; @@ -57,7 +59,8 @@ import org.w3c.dom.NamedNodeMap; public final class DOMXPathFilter2Transform extends ApacheTransform { public void init(TransformParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params == null) { throw new InvalidAlgorithmParameterException("params are required"); } else if (!(params instanceof XPathFilter2ParameterSpec)) { @@ -68,23 +71,23 @@ public final class DOMXPathFilter2Transform extends ApacheTransform { } public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { - + throws InvalidAlgorithmParameterException + { super.init(parent, context); try { unmarshalParams(DOMUtils.getFirstChildElement(transformElem)); } catch (MarshalException me) { - throw (InvalidAlgorithmParameterException) - new InvalidAlgorithmParameterException().initCause(me); + throw new InvalidAlgorithmParameterException(me); } } - private void unmarshalParams(Element curXPathElem) throws MarshalException { - List list = new ArrayList(); + private void unmarshalParams(Element curXPathElem) throws MarshalException + { + List list = new ArrayList(); while (curXPathElem != null) { String xPath = curXPathElem.getFirstChild().getNodeValue(); - String filterVal = - DOMUtils.getAttributeValue(curXPathElem, "Filter"); + String filterVal = DOMUtils.getAttributeValue(curXPathElem, + "Filter"); if (filterVal == null) { throw new MarshalException("filter cannot be null"); } @@ -96,15 +99,16 @@ public final class DOMXPathFilter2Transform extends ApacheTransform { } else if (filterVal.equals("union")) { filter = XPathType.Filter.UNION; } else { - throw new MarshalException("Unknown XPathType filter type" - + filterVal); + throw new MarshalException("Unknown XPathType filter type" + + filterVal); } NamedNodeMap attributes = curXPathElem.getAttributes(); if (attributes != null) { int length = attributes.getLength(); - Map namespaceMap = new HashMap(length); + Map namespaceMap = + new HashMap(length); for (int i = 0; i < length; i++) { - Attr attr = (Attr) attributes.item(i); + Attr attr = (Attr)attributes.item(i); String prefix = attr.getPrefix(); if (prefix != null && prefix.equals("xmlns")) { namespaceMap.put(attr.getLocalName(), attr.getValue()); @@ -121,32 +125,34 @@ public final class DOMXPathFilter2Transform extends ApacheTransform { } public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { - + throws MarshalException + { super.marshalParams(parent, context); XPathFilter2ParameterSpec xp = - (XPathFilter2ParameterSpec) getParameterSpec(); + (XPathFilter2ParameterSpec)getParameterSpec(); String prefix = DOMUtils.getNSPrefix(context, Transform.XPATH2); String qname = (prefix == null || prefix.length() == 0) ? "xmlns" : "xmlns:" + prefix; - List list = xp.getXPathList(); - for (int i = 0, size = list.size(); i < size; i++) { - XPathType xpathType = (XPathType) list.get(i); - Element elem = DOMUtils.createElement - (ownerDoc, "XPath", Transform.XPATH2, prefix); + @SuppressWarnings("unchecked") + List xpathList = xp.getXPathList(); + for (XPathType xpathType : xpathList) { + Element elem = DOMUtils.createElement(ownerDoc, "XPath", + Transform.XPATH2, prefix); elem.appendChild (ownerDoc.createTextNode(xpathType.getExpression())); - DOMUtils.setAttribute - (elem, "Filter", xpathType.getFilter().toString()); + DOMUtils.setAttribute(elem, "Filter", + xpathType.getFilter().toString()); elem.setAttributeNS("http://www.w3.org/2000/xmlns/", qname, - Transform.XPATH2); + Transform.XPATH2); // add namespace attributes, if necessary - Iterator it = xpathType.getNamespaceMap().entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" - + (String) entry.getKey(), (String) entry.getValue()); + @SuppressWarnings("unchecked") + Set> entries = + xpathType.getNamespaceMap().entrySet(); + for (Map.Entry entry : entries) { + elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + + entry.getKey(), + entry.getValue()); } transformElem.appendChild(elem); diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathTransform.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathTransform.java index 6258561f10b..aaf8d22bc20 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathTransform.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathTransform.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMXPathTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXPathTransform.java 1203789 2011-11-18 18:46:07Z mullan $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,9 +33,9 @@ import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.spec.TransformParameterSpec; import javax.xml.crypto.dsig.spec.XPathFilterParameterSpec; import java.security.InvalidAlgorithmParameterException; -import java.util.Iterator; -import java.util.Map; import java.util.HashMap; +import java.util.Map; +import java.util.Set; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; @@ -47,7 +49,8 @@ import org.w3c.dom.NamedNodeMap; public final class DOMXPathTransform extends ApacheTransform { public void init(TransformParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params == null) { throw new InvalidAlgorithmParameterException("params are required"); } else if (!(params instanceof XPathFilterParameterSpec)) { @@ -58,8 +61,8 @@ public final class DOMXPathTransform extends ApacheTransform { } public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { - + throws InvalidAlgorithmParameterException + { super.init(parent, context); unmarshalParams(DOMUtils.getFirstChildElement(transformElem)); } @@ -70,9 +73,10 @@ public final class DOMXPathTransform extends ApacheTransform { NamedNodeMap attributes = paramsElem.getAttributes(); if (attributes != null) { int length = attributes.getLength(); - Map namespaceMap = new HashMap(length); + Map namespaceMap = + new HashMap(length); for (int i = 0; i < length; i++) { - Attr attr = (Attr) attributes.item(i); + Attr attr = (Attr)attributes.item(i); String prefix = attr.getPrefix(); if (prefix != null && prefix.equals("xmlns")) { namespaceMap.put(attr.getLocalName(), attr.getValue()); @@ -85,22 +89,23 @@ public final class DOMXPathTransform extends ApacheTransform { } public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { - + throws MarshalException + { super.marshalParams(parent, context); XPathFilterParameterSpec xp = - (XPathFilterParameterSpec) getParameterSpec(); - Element xpathElem = DOMUtils.createElement - (ownerDoc, "XPath", XMLSignature.XMLNS, - DOMUtils.getSignaturePrefix(context)); + (XPathFilterParameterSpec)getParameterSpec(); + Element xpathElem = DOMUtils.createElement(ownerDoc, "XPath", + XMLSignature.XMLNS, DOMUtils.getSignaturePrefix(context)); xpathElem.appendChild(ownerDoc.createTextNode(xp.getXPath())); // add namespace attributes, if necessary - Iterator i = xp.getNamespaceMap().entrySet().iterator(); - while (i.hasNext()) { - Map.Entry entry = (Map.Entry) i.next(); - xpathElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" - + (String) entry.getKey(), (String) entry.getValue()); + @SuppressWarnings("unchecked") + Set> entries = + xp.getNamespaceMap().entrySet(); + for (Map.Entry entry : entries) { + xpathElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + + entry.getKey(), + entry.getValue()); } transformElem.appendChild(xpathElem); diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXSLTTransform.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXSLTTransform.java index cc1362bcc0d..06bb624309d 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXSLTTransform.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXSLTTransform.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMXSLTTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXSLTTransform.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,7 +33,6 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import javax.xml.crypto.*; -import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.spec.TransformParameterSpec; import javax.xml.crypto.dsig.spec.XSLTTransformParameterSpec; diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java index 8f0e3526806..8c080609c6d 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: Utils.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: Utils.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -44,7 +46,8 @@ public final class Utils { private Utils() {} public static byte[] readBytesFromStream(InputStream is) - throws IOException { + throws IOException + { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; while (true) { @@ -67,10 +70,10 @@ public final class Utils { * @param i the Iterator * @return the Set of Nodes */ - static Set toNodeSet(Iterator i) { - Set nodeSet = new HashSet(); + static Set toNodeSet(Iterator i) { + Set nodeSet = new HashSet(); while (i.hasNext()) { - Node n = (Node) i.next(); + Node n = i.next(); nodeSet.add(n); // insert attributes nodes to comply with XPath if (n.getNodeType() == Node.ELEMENT_NODE) { diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java index c122cb176a7..2cc871485b3 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * =========================================================================== @@ -29,7 +31,7 @@ * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: XMLDSigRI.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: XMLDSigRI.java 1400021 2012-10-19 10:16:04Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -53,13 +55,15 @@ public final class XMLDSigRI extends Provider { static final long serialVersionUID = -5049765099299494554L; private static final String INFO = "XMLDSig " + - "(DOM XMLSignatureFactory; DOM KeyInfoFactory)"; + "(DOM XMLSignatureFactory; DOM KeyInfoFactory; " + + "C14N 1.0, C14N 1.1, Exclusive C14N, Base64, Enveloped, XPath, " + + "XPath2, XSLT TransformServices)"; public XMLDSigRI() { /* We are the XMLDSig provider */ - super("XMLDSig", 1.0, INFO); + super("XMLDSig", 1.8, INFO); - final Map map = new HashMap(); + final Map map = new HashMap(); map.put("XMLSignatureFactory.DOM", "org.jcp.xml.dsig.internal.dom.DOMXMLSignatureFactory"); map.put("KeyInfoFactory.DOM", @@ -67,94 +71,89 @@ public final class XMLDSigRI extends Provider { // Inclusive C14N - map.put((String)"TransformService." + CanonicalizationMethod.INCLUSIVE, + map.put("TransformService." + CanonicalizationMethod.INCLUSIVE, "org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod"); map.put("Alg.Alias.TransformService.INCLUSIVE", CanonicalizationMethod.INCLUSIVE); - map.put((String)"TransformService." + CanonicalizationMethod.INCLUSIVE + + map.put("TransformService." + CanonicalizationMethod.INCLUSIVE + " MechanismType", "DOM"); // InclusiveWithComments C14N - map.put((String) "TransformService." + + map.put("TransformService." + CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, "org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod"); map.put("Alg.Alias.TransformService.INCLUSIVE_WITH_COMMENTS", CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS); - map.put((String) "TransformService." + + map.put("TransformService." + CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS + " MechanismType", "DOM"); // Inclusive C14N 1.1 - map.put((String)"TransformService." + - "http://www.w3.org/2006/12/xml-c14n11", + map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11", "org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method"); - map.put((String)"TransformService." + - "http://www.w3.org/2006/12/xml-c14n11" + + map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11" + " MechanismType", "DOM"); // InclusiveWithComments C14N 1.1 - map.put((String)"TransformService." + - "http://www.w3.org/2006/12/xml-c14n11#WithComments", + map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11#WithComments", "org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method"); - map.put((String)"TransformService." + - "http://www.w3.org/2006/12/xml-c14n11#WithComments" + + map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11#WithComments" + " MechanismType", "DOM"); // Exclusive C14N - map.put((String) "TransformService." + CanonicalizationMethod.EXCLUSIVE, + map.put("TransformService." + CanonicalizationMethod.EXCLUSIVE, "org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod"); map.put("Alg.Alias.TransformService.EXCLUSIVE", CanonicalizationMethod.EXCLUSIVE); - map.put((String)"TransformService." + CanonicalizationMethod.EXCLUSIVE + + map.put("TransformService." + CanonicalizationMethod.EXCLUSIVE + " MechanismType", "DOM"); // ExclusiveWithComments C14N - map.put((String) "TransformService." + + map.put("TransformService." + CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, "org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod"); map.put("Alg.Alias.TransformService.EXCLUSIVE_WITH_COMMENTS", CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS); - map.put((String) "TransformService." + + map.put("TransformService." + CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS + " MechanismType", "DOM"); // Base64 Transform - map.put((String) "TransformService." + Transform.BASE64, + map.put("TransformService." + Transform.BASE64, "org.jcp.xml.dsig.internal.dom.DOMBase64Transform"); map.put("Alg.Alias.TransformService.BASE64", Transform.BASE64); - map.put((String) "TransformService." + Transform.BASE64 + + map.put("TransformService." + Transform.BASE64 + " MechanismType", "DOM"); // Enveloped Transform - map.put((String) "TransformService." + Transform.ENVELOPED, + map.put("TransformService." + Transform.ENVELOPED, "org.jcp.xml.dsig.internal.dom.DOMEnvelopedTransform"); map.put("Alg.Alias.TransformService.ENVELOPED", Transform.ENVELOPED); - map.put((String) "TransformService." + Transform.ENVELOPED + + map.put("TransformService." + Transform.ENVELOPED + " MechanismType", "DOM"); // XPath2 Transform - map.put((String) "TransformService." + Transform.XPATH2, + map.put("TransformService." + Transform.XPATH2, "org.jcp.xml.dsig.internal.dom.DOMXPathFilter2Transform"); map.put("Alg.Alias.TransformService.XPATH2", Transform.XPATH2); - map.put((String) "TransformService." + Transform.XPATH2 + + map.put("TransformService." + Transform.XPATH2 + " MechanismType", "DOM"); // XPath Transform - map.put((String) "TransformService." + Transform.XPATH, + map.put("TransformService." + Transform.XPATH, "org.jcp.xml.dsig.internal.dom.DOMXPathTransform"); map.put("Alg.Alias.TransformService.XPATH", Transform.XPATH); - map.put((String) "TransformService." + Transform.XPATH + + map.put("TransformService." + Transform.XPATH + " MechanismType", "DOM"); // XSLT Transform - map.put((String) "TransformService." + Transform.XSLT, + map.put("TransformService." + Transform.XSLT, "org.jcp.xml.dsig.internal.dom.DOMXSLTTransform"); map.put("Alg.Alias.TransformService.XSLT", Transform.XSLT); - map.put((String) "TransformService." + Transform.XSLT + - " MechanismType", "DOM"); + map.put("TransformService." + Transform.XSLT + " MechanismType", "DOM"); - AccessController.doPrivileged(new java.security.PrivilegedAction() { - public Object run() { + AccessController.doPrivileged(new PrivilegedAction() { + public Void run() { putAll(map); return null; } From 3c389933665d2ed341b78a254e5bc35c0c416966 Mon Sep 17 00:00:00 2001 From: Valerie Peng Date: Fri, 5 Jul 2013 13:53:37 -0700 Subject: [PATCH 028/123] 8012637: Adjust CipherInputStream class to work in AEAD/GCM mode Ensure the Cipher.doFinal() is called only once Reviewed-by: xuelei --- .../javax/crypto/CipherInputStream.java | 4 +- .../provider/Cipher/AES/TestCICOWithGCM.java | 94 +++++++++++++++++++ 2 files changed, 97 insertions(+), 1 deletion(-) create mode 100644 jdk/test/com/sun/crypto/provider/Cipher/AES/TestCICOWithGCM.java diff --git a/jdk/src/share/classes/javax/crypto/CipherInputStream.java b/jdk/src/share/classes/javax/crypto/CipherInputStream.java index a8b4152a5ae..0e80a6013d5 100644 --- a/jdk/src/share/classes/javax/crypto/CipherInputStream.java +++ b/jdk/src/share/classes/javax/crypto/CipherInputStream.java @@ -303,7 +303,9 @@ public class CipherInputStream extends FilterInputStream { input.close(); try { // throw away the unprocessed data - cipher.doFinal(); + if (!done) { + cipher.doFinal(); + } } catch (BadPaddingException | IllegalBlockSizeException ex) { } diff --git a/jdk/test/com/sun/crypto/provider/Cipher/AES/TestCICOWithGCM.java b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestCICOWithGCM.java new file mode 100644 index 00000000000..8fec041d0a9 --- /dev/null +++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestCICOWithGCM.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8012637 + * @library ../UTIL + * @build TestUtil + * @run main TestCICOWithGCM + * @summary Test CipherInputStream/OutputStream with AES GCM mode. + * @author Valerie Peng + */ + +import java.security.*; +import javax.crypto.*; +import javax.crypto.spec.*; +import java.math.*; +import java.io.*; +import com.sun.crypto.provider.*; + +import java.util.*; + +public class TestCICOWithGCM { + public static void main(String[] args) throws Exception { + //init Secret Key + KeyGenerator kg = KeyGenerator.getInstance("AES", "SunJCE"); + kg.init(128); + SecretKey key = kg.generateKey(); + + //do initialization of the plainText + byte[] plainText = new byte[800]; + Random rdm = new Random(); + rdm.nextBytes(plainText); + + //init ciphers + Cipher encCipher = Cipher.getInstance("AES/GCM/NoPadding", "SunJCE"); + encCipher.init(Cipher.ENCRYPT_MODE, key); + Cipher decCipher = Cipher.getInstance("AES/GCM/NoPadding", "SunJCE"); + decCipher.init(Cipher.DECRYPT_MODE, key, encCipher.getParameters()); + + //init cipher streams + ByteArrayInputStream baInput = new ByteArrayInputStream(plainText); + CipherInputStream ciInput = new CipherInputStream(baInput, encCipher); + ByteArrayOutputStream baOutput = new ByteArrayOutputStream(); + CipherOutputStream ciOutput = new CipherOutputStream(baOutput, decCipher); + + //do test + byte[] buffer = new byte[800]; + int len = ciInput.read(buffer); + System.out.println("read " + len + " bytes from input buffer"); + + while (len != -1) { + ciOutput.write(buffer, 0, len); + System.out.println("wite " + len + " bytes to output buffer"); + len = ciInput.read(buffer); + if (len != -1) { + System.out.println("read " + len + " bytes from input buffer"); + } else { + System.out.println("finished reading"); + } + } + + ciOutput.flush(); + ciInput.close(); + ciOutput.close(); + byte[] recovered = baOutput.toByteArray(); + System.out.println("recovered " + recovered.length + " bytes"); + if (!Arrays.equals(plainText, recovered)) { + throw new RuntimeException("diff check failed!"); + } else { + System.out.println("diff check passed"); + } + } +} From c4932212fc2a031412cd4ba113e2afe8a474b7f5 Mon Sep 17 00:00:00 2001 From: Valerie Peng Date: Fri, 5 Jul 2013 13:56:12 -0700 Subject: [PATCH 029/123] 7196805: DH Key interoperability testing between SunJCE and JsafeJCE not successful Check equality based on component values instead of encoding which may vary due to optional components Reviewed-by: weijun --- .../com/sun/crypto/provider/DHKeyFactory.java | 8 +-- .../crypto/provider/DHKeyPairGenerator.java | 9 ++-- .../com/sun/crypto/provider/DHPrivateKey.java | 53 +++++++------------ .../com/sun/crypto/provider/DHPublicKey.java | 46 +++++++--------- .../classes/sun/security/pkcs11/P11Key.java | 48 ++++++++++++++++- 5 files changed, 96 insertions(+), 68 deletions(-) diff --git a/jdk/src/share/classes/com/sun/crypto/provider/DHKeyFactory.java b/jdk/src/share/classes/com/sun/crypto/provider/DHKeyFactory.java index 38e7d36f3f2..273d49eb076 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/DHKeyFactory.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/DHKeyFactory.java @@ -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 @@ public final class DHKeyFactory extends KeyFactorySpi { } } catch (InvalidKeyException e) { throw new InvalidKeySpecException - ("Inappropriate key specification"); + ("Inappropriate key specification", e); } } @@ -118,7 +118,7 @@ public final class DHKeyFactory extends KeyFactorySpi { } } catch (InvalidKeyException e) { throw new InvalidKeySpecException - ("Inappropriate key specification"); + ("Inappropriate key specification", e); } } @@ -227,7 +227,7 @@ public final class DHKeyFactory extends KeyFactorySpi { } } catch (InvalidKeySpecException e) { - throw new InvalidKeyException("Cannot translate key"); + throw new InvalidKeyException("Cannot translate key", e); } } } diff --git a/jdk/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java b/jdk/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java index 6ae39e25e7e..c71d6ab3fa8 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java @@ -167,15 +167,16 @@ public final class DHKeyPairGenerator extends KeyPairGeneratorSpi { 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); diff --git a/jdk/src/share/classes/com/sun/crypto/provider/DHPrivateKey.java b/jdk/src/share/classes/com/sun/crypto/provider/DHPrivateKey.java index 1653a239960..e3254c4fc34 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/DHPrivateKey.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/DHPrivateKey.java @@ -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 @@ javax.crypto.interfaces.DHPrivateKey, Serializable { // 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 @@ javax.crypto.interfaces.DHPrivateKey, Serializable { 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 @@ javax.crypto.interfaces.DHPrivateKey, Serializable { 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 @@ javax.crypto.interfaces.DHPrivateKey, Serializable { * @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 @@ javax.crypto.interfaces.DHPrivateKey, Serializable { * 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)); } /** diff --git a/jdk/src/share/classes/com/sun/crypto/provider/DHPublicKey.java b/jdk/src/share/classes/com/sun/crypto/provider/DHPublicKey.java index a9062e50797..7293c945768 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/DHPublicKey.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/DHPublicKey.java @@ -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 @@ javax.crypto.interfaces.DHPublicKey, Serializable { // 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 @@ javax.crypto.interfaces.DHPublicKey, Serializable { } 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 @@ javax.crypto.interfaces.DHPublicKey, Serializable { 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 @@ javax.crypto.interfaces.DHPublicKey, Serializable { * @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 @@ javax.crypto.interfaces.DHPublicKey, Serializable { * 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)); } /** diff --git a/jdk/src/share/classes/sun/security/pkcs11/P11Key.java b/jdk/src/share/classes/sun/security/pkcs11/P11Key.java index dd0ec5f7ee1..ae9264779f5 100644 --- a/jdk/src/share/classes/sun/security/pkcs11/P11Key.java +++ b/jdk/src/share/classes/sun/security/pkcs11/P11Key.java @@ -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 @@ -881,6 +881,29 @@ abstract class P11Key implements Key, Length { return super.toString() + "\n x: " + x + "\n p: " + params.getP() + "\n g: " + params.getG(); } + public int hashCode() { + if (token.isValid() == false) { + return 0; + } + fetchValues(); + return Objects.hash(x, params.getP(), params.getG()); + } + public boolean equals(Object obj) { + if (this == obj) return true; + // equals() should never throw exceptions + if (token.isValid() == false) { + return false; + } + if (!(obj instanceof DHPrivateKey)) { + return false; + } + fetchValues(); + DHPrivateKey other = (DHPrivateKey) obj; + DHParameterSpec otherParams = other.getParams(); + return ((this.x.compareTo(other.getX()) == 0) && + (this.params.getP().compareTo(otherParams.getP()) == 0) && + (this.params.getG().compareTo(otherParams.getG()) == 0)); + } } private static final class P11DHPublicKey extends P11Key @@ -945,6 +968,29 @@ abstract class P11Key implements Key, Length { return super.toString() + "\n y: " + y + "\n p: " + params.getP() + "\n g: " + params.getG(); } + public int hashCode() { + if (token.isValid() == false) { + return 0; + } + fetchValues(); + return Objects.hash(y, params.getP(), params.getG()); + } + public boolean equals(Object obj) { + if (this == obj) return true; + // equals() should never throw exceptions + if (token.isValid() == false) { + return false; + } + if (!(obj instanceof DHPublicKey)) { + return false; + } + fetchValues(); + DHPublicKey other = (DHPublicKey) obj; + DHParameterSpec otherParams = other.getParams(); + return ((this.y.compareTo(other.getY()) == 0) && + (this.params.getP().compareTo(otherParams.getP()) == 0) && + (this.params.getG().compareTo(otherParams.getG()) == 0)); + } } private static final class P11ECPrivateKey extends P11Key From 2c7b97640d69fad5814d6e9fcd45ebd2ffc10300 Mon Sep 17 00:00:00 2001 From: Bradford Wetmore Date: Fri, 5 Jul 2013 18:22:58 -0700 Subject: [PATCH 030/123] 8019341: Update CookieHttpsClientTest to use the newer framework Reviewed-by: xuelei, smarks, michaelm --- .../CookieHttpsClientTest.java | 104 +++++++++++++----- .../ssl/templates/SSLEngineTemplate.java | 8 +- .../templates/SSLSocketSSLEngineTemplate.java | 15 ++- .../ssl/templates/SSLSocketTemplate.java | 61 ++++++---- 4 files changed, 132 insertions(+), 56 deletions(-) diff --git a/jdk/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/CookieHttpsClientTest.java b/jdk/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/CookieHttpsClientTest.java index cc20b42377c..21006f0803d 100644 --- a/jdk/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/CookieHttpsClientTest.java +++ b/jdk/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/CookieHttpsClientTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,15 +21,14 @@ * questions. */ +// SunJSSE does not support dynamic system properties, no way to re-use +// system properties in samevm/agentvm mode. + /* * @test * @bug 7129083 * @summary Cookiemanager does not store cookies if url is read * before setting cookiemanager - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * * @run main/othervm CookieHttpsClientTest */ @@ -186,10 +185,10 @@ public class CookieHttpsClientTest { public static void main(String args[]) throws Exception { String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + + System.getProperty("test.src", ".") + "/" + pathToStores + "/" + keyStoreFile; String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + + System.getProperty("test.src", ".") + "/" + pathToStores + "/" + trustStoreFile; System.setProperty("javax.net.ssl.keyStore", keyFilename); @@ -205,40 +204,83 @@ public class CookieHttpsClientTest { Thread clientThread = null; Thread serverThread = null; + /* * Primary constructor, used to drive remainder of the test. * * Fork off the other side, then do your work. */ CookieHttpsClientTest() throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); + Exception startException = null; + try { + if (separateServerThread) { + startServer(true); + startClient(false); + } else { + startClient(true); + startServer(false); + } + } catch (Exception e) { + startException = e; } /* * Wait for other side to close down. */ if (separateServerThread) { - serverThread.join(); + if (serverThread != null) { + serverThread.join(); + } } else { - clientThread.join(); + if (clientThread != null) { + clientThread.join(); + } } /* * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. + * Which side threw the error? */ - if (serverException != null) - throw serverException; - if (clientException != null) - throw clientException; + Exception local; + Exception remote; + + if (separateServerThread) { + remote = serverException; + local = clientException; + } else { + remote = clientException; + local = serverException; + } + + Exception exception = null; + + /* + * Check various exception conditions. + */ + if ((local != null) && (remote != null)) { + // If both failed, return the curthread's exception. + local.initCause(remote); + exception = local; + } else if (local != null) { + exception = local; + } else if (remote != null) { + exception = remote; + } else if (startException != null) { + exception = startException; + } + + /* + * If there was an exception *AND* a startException, + * output it. + */ + if (exception != null) { + if (exception != startException) { + exception.addSuppressed(startException); + } + throw exception; + } + + // Fall-through: no exception to throw! } void startServer(boolean newThread) throws Exception { @@ -261,7 +303,13 @@ public class CookieHttpsClientTest { }; serverThread.start(); } else { - doServerSide(); + try { + doServerSide(); + } catch (Exception e) { + serverException = e; + } finally { + serverReady = true; + } } } @@ -277,12 +325,16 @@ public class CookieHttpsClientTest { */ System.err.println("Client died..."); clientException = e; - } + } } }; clientThread.start(); } else { - doClientSide(); + try { + doClientSide(); + } catch (Exception e) { + clientException = e; + } } } } diff --git a/jdk/test/sun/security/ssl/templates/SSLEngineTemplate.java b/jdk/test/sun/security/ssl/templates/SSLEngineTemplate.java index 22fff98357b..0f87ee25b89 100644 --- a/jdk/test/sun/security/ssl/templates/SSLEngineTemplate.java +++ b/jdk/test/sun/security/ssl/templates/SSLEngineTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,14 +21,14 @@ * questions. */ +// SunJSSE does not support dynamic system properties, no way to re-use +// system properties in samevm/agentvm mode. + /* * @test * @bug 1234567 * @summary SSLEngine has not yet caused Solaris kernel to panic * @run main/othervm SSLEngineTemplate - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. */ /** diff --git a/jdk/test/sun/security/ssl/templates/SSLSocketSSLEngineTemplate.java b/jdk/test/sun/security/ssl/templates/SSLSocketSSLEngineTemplate.java index 7e4c02e58a5..7e97d8e0410 100644 --- a/jdk/test/sun/security/ssl/templates/SSLSocketSSLEngineTemplate.java +++ b/jdk/test/sun/security/ssl/templates/SSLSocketSSLEngineTemplate.java @@ -309,14 +309,25 @@ public class SSLSocketSSLEngineTemplate { } catch (Exception e) { serverException = e; } finally { - socket.close(); + if (socket != null) { + socket.close(); + } // Wait for the client to join up with us. - thread.join(); + if (thread != null) { + thread.join(); + } + if (serverException != null) { + if (clientException != null) { + serverException.initCause(clientException); + } throw serverException; } if (clientException != null) { + if (serverException != null) { + clientException.initCause(serverException); + } throw clientException; } } diff --git a/jdk/test/sun/security/ssl/templates/SSLSocketTemplate.java b/jdk/test/sun/security/ssl/templates/SSLSocketTemplate.java index a31be5d3340..e8bfe91db06 100644 --- a/jdk/test/sun/security/ssl/templates/SSLSocketTemplate.java +++ b/jdk/test/sun/security/ssl/templates/SSLSocketTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,14 +21,14 @@ * questions. */ +// SunJSSE does not support dynamic system properties, no way to re-use +// system properties in samevm/agentvm mode. + /* * @test * @bug 1234567 * @summary Use this template to help speed your client/server tests. * @run main/othervm SSLSocketTemplate - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. * @author Brad Wetmore */ @@ -180,6 +180,7 @@ public class SSLSocketTemplate { * Fork off the other side, then do your work. */ SSLSocketTemplate() throws Exception { + Exception startException = null; try { if (separateServerThread) { startServer(true); @@ -189,16 +190,20 @@ public class SSLSocketTemplate { startServer(false); } } catch (Exception e) { - // swallow for now. Show later + startException = e; } /* * Wait for other side to close down. */ if (separateServerThread) { - serverThread.join(); + if (serverThread != null) { + serverThread.join(); + } } else { - clientThread.join(); + if (clientThread != null) { + clientThread.join(); + } } /* @@ -207,36 +212,44 @@ public class SSLSocketTemplate { */ Exception local; Exception remote; - String whichRemote; if (separateServerThread) { remote = serverException; local = clientException; - whichRemote = "server"; } else { remote = clientException; local = serverException; - whichRemote = "client"; + } + + Exception exception = null; + + /* + * Check various exception conditions. + */ + if ((local != null) && (remote != null)) { + // If both failed, return the curthread's exception. + local.initCause(remote); + exception = local; + } else if (local != null) { + exception = local; + } else if (remote != null) { + exception = remote; + } else if (startException != null) { + exception = startException; } /* - * If both failed, return the curthread's exception, but also - * print the remote side Exception + * If there was an exception *AND* a startException, + * output it. */ - if ((local != null) && (remote != null)) { - System.out.println(whichRemote + " also threw:"); - remote.printStackTrace(); - System.out.println(); - throw local; + if (exception != null) { + if (exception != startException) { + exception.addSuppressed(startException); + } + throw exception; } - if (remote != null) { - throw remote; - } - - if (local != null) { - throw local; - } + // Fall-through: no exception to throw! } void startServer(boolean newThread) throws Exception { From 6085f712f86887e3b4f00dc6adb145131a7a5543 Mon Sep 17 00:00:00 2001 From: Erik Helin Date: Mon, 8 Jul 2013 11:30:44 +0200 Subject: [PATCH 031/123] 8010734: NPG: The test MemoryTest.java needs to be updated to support metaspace Reviewed-by: alanb --- jdk/test/ProblemList.txt | 4 ---- .../lang/management/MemoryMXBean/MemoryTest.java | 15 +++++++++------ 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index 8a6931cf110..8c98dbda37a 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -137,10 +137,6 @@ java/lang/Class/asSubclass/BasicUnit.java generic-all # 8015780 java/lang/reflect/Method/GenericStringTest.java generic-all -# 8019500 -java/lang/management/MemoryMXBean/MemoryTestAllGC.sh generic-all -java/lang/management/MemoryMXBean/MemoryTest.java generic-all - ############################################################################ # jdk_management diff --git a/jdk/test/java/lang/management/MemoryMXBean/MemoryTest.java b/jdk/test/java/lang/management/MemoryMXBean/MemoryTest.java index 65d2da8d957..f61333750e0 100644 --- a/jdk/test/java/lang/management/MemoryMXBean/MemoryTest.java +++ b/jdk/test/java/lang/management/MemoryMXBean/MemoryTest.java @@ -59,18 +59,21 @@ public class MemoryTest { // (or equivalent for other collectors) // Number of GC memory managers = 2 - // Hotspot VM 1.8+ after perm gen removal is expected to have only - // one non-heap memory pool - private static int[] expectedMinNumPools = {3, 1}; - private static int[] expectedMaxNumPools = {3, 1}; + // Hotspot VM 1.8+ after perm gen removal is expected to have two or + // three non-heap memory pools: + // - Code cache + // - Metaspace + // - Compressed Class Space (if compressed class pointers are used) + private static int[] expectedMinNumPools = {3, 2}; + private static int[] expectedMaxNumPools = {3, 3}; private static int expectedNumGCMgrs = 2; - private static int expectedNumMgrs = expectedNumGCMgrs + 1; + private static int expectedNumMgrs = expectedNumGCMgrs + 2; private static String[] types = { "heap", "non-heap" }; public static void main(String args[]) throws Exception { Integer value = new Integer(args[0]); expectedNumGCMgrs = value.intValue(); - expectedNumMgrs = expectedNumGCMgrs + 1; + expectedNumMgrs = expectedNumGCMgrs + 2; checkMemoryPools(); checkMemoryManagers(); From bc2fd2fe9c2beee847380406791e94d1a2883008 Mon Sep 17 00:00:00 2001 From: Anthony Scarpino Date: Mon, 8 Jul 2013 10:20:46 -0700 Subject: [PATCH 032/123] 6755701: SunJCE DES/DESede SecretKeyFactory.generateSecret throws InvalidKeySpecExc if passed SecretKeySpec Reviewed-by: valeriep, wetmore, xuelei --- .../sun/crypto/provider/DESKeyFactory.java | 21 ++++--- .../sun/crypto/provider/DESedeKeyFactory.java | 19 ++++--- .../provider/Cipher/DES/DESSecretKeySpec.java | 56 +++++++++++++++++++ 3 files changed, 78 insertions(+), 18 deletions(-) create mode 100644 jdk/test/com/sun/crypto/provider/Cipher/DES/DESSecretKeySpec.java diff --git a/jdk/src/share/classes/com/sun/crypto/provider/DESKeyFactory.java b/jdk/src/share/classes/com/sun/crypto/provider/DESKeyFactory.java index 47f0b26a27d..f51de29ba8b 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/DESKeyFactory.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/DESKeyFactory.java @@ -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 javax.crypto.spec.DESKeySpec; 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 @@ public final class DESKeyFactory extends SecretKeyFactorySpi { */ 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()); } - else { - DESKeySpec desKeySpec = (DESKeySpec)keySpec; - desKey = new DESKey(desKeySpec.getKey()); + + if (keySpec instanceof SecretKeySpec) { + return new DESKey(((SecretKeySpec)keySpec).getEncoded()); } + + throw new InvalidKeySpecException( + "Inappropriate key specification"); + } catch (InvalidKeyException e) { + throw new InvalidKeySpecException(e.getMessage()); } - return desKey; } /** diff --git a/jdk/src/share/classes/com/sun/crypto/provider/DESedeKeyFactory.java b/jdk/src/share/classes/com/sun/crypto/provider/DESedeKeyFactory.java index 9caabc3d80b..d2d2d7d47ea 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/DESedeKeyFactory.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/DESedeKeyFactory.java @@ -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 javax.crypto.spec.DESedeKeySpec; 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 @@ public final class DESedeKeyFactory extends SecretKeyFactorySpi { */ protected SecretKey engineGenerateSecret(KeySpec keySpec) throws InvalidKeySpecException { - DESedeKey desEdeKey = null; try { if (keySpec instanceof DESedeKeySpec) { - DESedeKeySpec desEdeKeySpec = (DESedeKeySpec)keySpec; - desEdeKey = new DESedeKey(desEdeKeySpec.getKey()); - - } else { - throw new InvalidKeySpecException - ("Inappropriate key specification"); + return new DESedeKey(((DESedeKeySpec)keySpec).getKey()); } + if (keySpec instanceof SecretKeySpec) { + return new DESedeKey(((SecretKeySpec)keySpec).getEncoded()); + + } + throw new InvalidKeySpecException + ("Inappropriate key specification"); } catch (InvalidKeyException e) { + throw new InvalidKeySpecException(e.getMessage()); } - return desEdeKey; } /** diff --git a/jdk/test/com/sun/crypto/provider/Cipher/DES/DESSecretKeySpec.java b/jdk/test/com/sun/crypto/provider/Cipher/DES/DESSecretKeySpec.java new file mode 100644 index 00000000000..e5ec14f18e5 --- /dev/null +++ b/jdk/test/com/sun/crypto/provider/Cipher/DES/DESSecretKeySpec.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6755701 + * @summary Change SecretKeyFactory.generateSecret to allow SecretKeySpec to + * be passed and used for creating a DES and DESede keys. This avoids the error + * of "InvalidKeySpecException: Inappropriate key specification" + * @author Anthony Scarpino + */ + +import javax.crypto.Cipher; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.SecretKeySpec; + +public class DESSecretKeySpec { + + public static void main(String arg[]) throws Exception { + Cipher c; + byte[] key = new byte[]{'1','2','3','4','5','6','7','8', + '1','2','3','4','5','6','7','8', + '1','2','3','4','5','6','7','8'}; + + + System.out.println("Testing DES key"); + SecretKeySpec skey = new SecretKeySpec(key, "DES"); + c = Cipher.getInstance("DES/CBC/PKCS5Padding", "SunJCE"); + SecretKeyFactory.getInstance("DES").generateSecret(skey); + + System.out.println("Testing DESede key"); + skey = new SecretKeySpec(key, "DESede"); + c = Cipher.getInstance("DESede/CBC/PKCS5Padding", "SunJCE"); + SecretKeyFactory.getInstance("TripleDES").generateSecret(skey); + } +} From dfb135dd14fa38848712130f945fc32d2318fa9d Mon Sep 17 00:00:00 2001 From: Jason Uh Date: Mon, 8 Jul 2013 19:24:22 -0700 Subject: [PATCH 033/123] 8020091: Fix HTML doclint issues in java.io Reviewed-by: darcy --- jdk/src/share/classes/java/io/DataInput.java | 18 +++++++++--------- .../share/classes/java/io/FileInputStream.java | 2 +- .../classes/java/io/FileOutputStream.java | 4 ++-- .../classes/java/io/InputStreamReader.java | 8 ++++---- .../classes/java/io/OutputStreamWriter.java | 10 +++++----- .../classes/java/io/PipedInputStream.java | 14 +++++++------- .../classes/java/io/RandomAccessFile.java | 12 ++++++------ 7 files changed, 34 insertions(+), 34 deletions(-) diff --git a/jdk/src/share/classes/java/io/DataInput.java b/jdk/src/share/classes/java/io/DataInput.java index 1480c9f0485..4dad59d55f3 100644 --- a/jdk/src/share/classes/java/io/DataInput.java +++ b/jdk/src/share/classes/java/io/DataInput.java @@ -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 @@ package java.io; * summary="Bit values and bytes"> *
  • * - * + * * * - * + * *

    Examples

    Examples
    Floating-point ValueHexadecimal String
    {@code 1.0} {@code 0x1.0p0}
    {@code -1.0} {@code -0x1.0p0}
    Bit ValuesBit Values
    Byte 1Byte 1 * * @@ -92,10 +92,10 @@ package java.io; * summary="Bit values and bytes"> * * - * + * * * - * + * *
    Bit ValuesBit Values
    Byte 1Byte 1 * * @@ -108,7 +108,7 @@ package java.io; * * * - * + * *
    Byte 2Byte 2 * * @@ -131,10 +131,10 @@ package java.io; * summary="Bit values and bytes"> * * - * + * * * - * + * *
    Bit ValuesBit Values
    Byte 1Byte 1 * * @@ -148,7 +148,7 @@ package java.io; * * * - * + * *
    Byte 2Byte 2 * * diff --git a/jdk/src/share/classes/java/io/FileInputStream.java b/jdk/src/share/classes/java/io/FileInputStream.java index 90d1ad5cc3e..3e67fb85515 100644 --- a/jdk/src/share/classes/java/io/FileInputStream.java +++ b/jdk/src/share/classes/java/io/FileInputStream.java @@ -331,7 +331,7 @@ class FileInputStream extends InputStream * object associated with this file input stream. * *

    The initial {@link java.nio.channels.FileChannel#position() - * position} 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 diff --git a/jdk/src/share/classes/java/io/FileOutputStream.java b/jdk/src/share/classes/java/io/FileOutputStream.java index 928e4f3cf15..44f472870ec 100644 --- a/jdk/src/share/classes/java/io/FileOutputStream.java +++ b/jdk/src/share/classes/java/io/FileOutputStream.java @@ -358,10 +358,10 @@ class FileOutputStream extends OutputStream /** * Returns the unique {@link java.nio.channels.FileChannel FileChannel} - * object associated with this file output stream.

    + * object associated with this file output stream. * *

    The initial {@link java.nio.channels.FileChannel#position() - * position} 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 diff --git a/jdk/src/share/classes/java/io/InputStreamReader.java b/jdk/src/share/classes/java/io/InputStreamReader.java index 1f6d5f6113b..e131dca304a 100644 --- a/jdk/src/share/classes/java/io/InputStreamReader.java +++ b/jdk/src/share/classes/java/io/InputStreamReader.java @@ -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 @@ import sun.nio.cs.StreamDecoder; /** * 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 charset}. 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 @@ public class InputStreamReader extends Reader { } /** - * Creates an InputStreamReader that uses the given charset.

    + * Creates an InputStreamReader that uses the given charset. * * @param in An InputStream * @param cs A charset @@ -117,7 +117,7 @@ public class InputStreamReader extends Reader { } /** - * Creates an InputStreamReader that uses the given charset decoder.

    + * Creates an InputStreamReader that uses the given charset decoder. * * @param in An InputStream * @param dec A charset decoder diff --git a/jdk/src/share/classes/java/io/OutputStreamWriter.java b/jdk/src/share/classes/java/io/OutputStreamWriter.java index b4e4b9e320b..5f7b9e34bca 100644 --- a/jdk/src/share/classes/java/io/OutputStreamWriter.java +++ b/jdk/src/share/classes/java/io/OutputStreamWriter.java @@ -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 @@ import sun.nio.cs.StreamEncoder; /** * 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 charset}. 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 @@ public class OutputStreamWriter extends Writer { * * @param charsetName * The name of a supported - * {@link java.nio.charset.Charset
    charset} + * {@link java.nio.charset.Charset charset} * * @exception UnsupportedEncodingException * If the named encoding is not supported @@ -115,7 +115,7 @@ public class OutputStreamWriter extends Writer { } /** - * Creates an OutputStreamWriter that uses the given charset.

    + * Creates an OutputStreamWriter that uses the given charset. * * @param out * An OutputStream @@ -134,7 +134,7 @@ public class OutputStreamWriter extends Writer { } /** - * Creates an OutputStreamWriter that uses the given charset encoder.

    + * Creates an OutputStreamWriter that uses the given charset encoder. * * @param out * An OutputStream diff --git a/jdk/src/share/classes/java/io/PipedInputStream.java b/jdk/src/share/classes/java/io/PipedInputStream.java index 4ad8fbd81d8..af07de5b4e6 100644 --- a/jdk/src/share/classes/java/io/PipedInputStream.java +++ b/jdk/src/share/classes/java/io/PipedInputStream.java @@ -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 @@ package java.io; * The piped input stream contains a buffer, * decoupling read operations from write operations, * within limits. - * A pipe is said to be broken if a + * A pipe is said to be broken if a * thread that was providing data bytes to the connected * piped output stream is no longer alive. * @@ -193,7 +193,7 @@ public class PipedInputStream extends InputStream { * 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 broken, + * @exception IOException If the pipe is broken, * {@link #connect(java.io.PipedOutputStream) unconnected}, * closed, or if an I/O error occurs. * @since JDK1.1 @@ -219,7 +219,7 @@ public class PipedInputStream extends InputStream { * @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 broken, + * @exception IOException If the pipe is broken, * {@link #connect(java.io.PipedOutputStream) unconnected}, * closed,or if an I/O error occurs. */ @@ -298,7 +298,7 @@ public class PipedInputStream extends InputStream { * stream is reached. * @exception IOException if the pipe is * {@link #connect(java.io.PipedOutputStream) unconnected}, - * broken, closed, + * broken, closed, * or if an I/O error occurs. */ public synchronized int read() throws IOException { @@ -361,7 +361,7 @@ public class PipedInputStream extends InputStream { * @exception IndexOutOfBoundsException If off is negative, * len is negative, or len is greater than * b.length - off - * @exception IOException if the pipe is broken, + * @exception IOException if the pipe is broken, * {@link #connect(java.io.PipedOutputStream) unconnected}, * closed, or if an I/O error occurs. */ @@ -419,7 +419,7 @@ public class PipedInputStream extends InputStream { * 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 - * broken. + * broken. * * @exception IOException if an I/O error occurs. * @since JDK1.0.2 diff --git a/jdk/src/share/classes/java/io/RandomAccessFile.java b/jdk/src/share/classes/java/io/RandomAccessFile.java index adccfbc757a..5e32ad5dba1 100644 --- a/jdk/src/share/classes/java/io/RandomAccessFile.java +++ b/jdk/src/share/classes/java/io/RandomAccessFile.java @@ -123,11 +123,11 @@ public class RandomAccessFile implements DataOutput, DataInput, Closeable { * write to, the file specified by the {@link File} argument. A new {@link * FileDescriptor} object is created to represent this file connection. * - *

    The mode argument specifies the access mode + *

    The mode argument specifies the access mode * in which the file is to be opened. The permitted values and their * meanings are: * - *

    + *
    * * * - *

    Value

    Meaning

    "r" Open for reading only. Invoking any of the write @@ -144,7 +144,7 @@ public class RandomAccessFile implements DataOutput, DataInput, Closeable { * Open for reading and writing, as with "rw", and also * require that every update to the file's content be written * synchronously to the underlying storage device.
    + *
    * * The "rws" and "rwd" modes work much like the {@link * java.nio.channels.FileChannel#force(boolean) force(boolean)} method of @@ -158,13 +158,13 @@ public class RandomAccessFile implements DataOutput, DataInput, Closeable { * event of a system crash. If the file does not reside on a local device * then no such guarantee is made. * - *

    The "rwd" mode can be used to reduce the number of I/O + *

    The "rwd" mode can be used to reduce the number of I/O * operations performed. Using "rwd" only requires updates to the * file's content to be written to storage; using "rws" 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. * - *

    If there is a security manager, its {@code checkRead} method is + *

    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 @@ public class RandomAccessFile implements DataOutput, DataInput, Closeable { /** * Returns the opaque file descriptor object associated with this - * stream.

    + * stream. * * @return the file descriptor object associated with this stream. * @exception IOException if an I/O error occurs. From 0fb5272229eef9d48eedc2d14b3f1a07e85a344a Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Mon, 8 Jul 2013 22:43:36 -0700 Subject: [PATCH 034/123] 8020095: Fix doclint warnings in java.util.regex Reviewed-by: mchung --- .../classes/java/util/regex/MatchResult.java | 4 +- .../classes/java/util/regex/Matcher.java | 15 +- .../classes/java/util/regex/Pattern.java | 192 +++++++++--------- 3 files changed, 102 insertions(+), 109 deletions(-) diff --git a/jdk/src/share/classes/java/util/regex/MatchResult.java b/jdk/src/share/classes/java/util/regex/MatchResult.java index 9767d286377..4f42eae970d 100644 --- a/jdk/src/share/classes/java/util/regex/MatchResult.java +++ b/jdk/src/share/classes/java/util/regex/MatchResult.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -77,7 +77,7 @@ public interface MatchResult { public int start(int group); /** - * Returns the offset after the last character matched.

    + * Returns the offset after the last character matched. * * @return The offset after the last character matched * diff --git a/jdk/src/share/classes/java/util/regex/Matcher.java b/jdk/src/share/classes/java/util/regex/Matcher.java index b01ec84262a..ebab02e3b82 100644 --- a/jdk/src/share/classes/java/util/regex/Matcher.java +++ b/jdk/src/share/classes/java/util/regex/Matcher.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,8 +28,8 @@ package java.util.regex; import java.util.Objects; /** - * An engine that performs match operations on a {@link java.lang.CharSequence - * character sequence} by interpreting a {@link Pattern}. + * An engine that performs match operations on a {@linkplain java.lang.CharSequence + * character sequence} by interpreting a {@link Pattern}. * *

    A matcher is created from a pattern by invoking the pattern's {@link * Pattern#matcher matcher} method. Once created, a matcher can be used to @@ -330,7 +330,7 @@ public final class Matcher implements MatchResult { } /** - * Returns the start index of the previous match.

    + * Returns the start index of the previous match. * * @return The index of the first character matched * @@ -402,7 +402,7 @@ public final class Matcher implements MatchResult { } /** - * Returns the offset after the last character matched.

    + * Returns the offset after the last character matched. * * @return The offset after the last character matched * @@ -647,6 +647,7 @@ public final class Matcher implements MatchResult { * invocations of the {@link #find()} method will start at the first * character not matched by this match.

    * + * @param start the index to start searching for a match * @throws IndexOutOfBoundsException * If start is less than zero or if start is greater than the * length of the input sequence. @@ -736,8 +737,8 @@ public final class Matcher implements MatchResult { * captured during the previous match: Each occurrence of * ${name} or $g * will be replaced by the result of evaluating the corresponding - * {@link #group(String) group(name)} or {@link #group(int) group(g)} - * respectively. For $g, + * {@link #group(String) group(name)} or {@link #group(int) group(g)} + * respectively. For $g, * the first number after the $ is always treated as part of * the group reference. Subsequent numbers are incorporated into g if * they would form a legal group reference. Only the numerals '0' diff --git a/jdk/src/share/classes/java/util/regex/Pattern.java b/jdk/src/share/classes/java/util/regex/Pattern.java index ae7468758c8..4d52151210b 100644 --- a/jdk/src/share/classes/java/util/regex/Pattern.java +++ b/jdk/src/share/classes/java/util/regex/Pattern.java @@ -45,8 +45,8 @@ import java.util.stream.StreamSupport; * *

    A regular expression, specified as a string, must first be compiled into * an instance of this class. The resulting pattern can then be used to create - * a {@link Matcher} object that can match arbitrary {@link - * java.lang.CharSequence character sequences} against the regular + * a {@link Matcher} object that can match arbitrary {@linkplain + * java.lang.CharSequence character sequences} against the regular * expression. All of the state involved in performing a match resides in the * matcher, so many matchers can share the same pattern. * @@ -73,15 +73,14 @@ import java.util.stream.StreamSupport; * such use. * * - * - *

    Summary of regular-expression constructs

    + *

    Summary of regular-expression constructs

    * * * * - * - * + * + * * * * @@ -128,24 +127,24 @@ import java.util.stream.StreamSupport; * * * - * - * - * - * - * - * - * - * - * - * - * - * - * - * + * + * + * + * + * + * + * + * + * + * + * + * + * + * * * * @@ -175,36 +174,36 @@ import java.util.stream.StreamSupport; * * * - * + * * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * * * * @@ -220,19 +219,19 @@ import java.util.stream.StreamSupport; * * * - * * + * * * - * + * * - * + * * - * + * * - * + * * - * + * * - * + * * * * @@ -376,8 +375,7 @@ import java.util.stream.StreamSupport; *
    * * - * - *

    Backslashes, escapes, and quoting

    + *

    Backslashes, escapes, and quoting

    * *

    The backslash character ('\') serves to introduce escaped * constructs, as defined in the table above, as well as to quote characters @@ -405,8 +403,7 @@ import java.util.stream.StreamSupport; * (hello) the string literal "\\(hello\\)" * must be used. * - * - *

    Character Classes

    + *

    Character Classes

    * *

    Character classes may appear within other character classes, and * may be composed by the union operator (implicit) and the intersection @@ -435,7 +432,7 @@ import java.util.stream.StreamSupport; *

    * * - * + * *
    ConstructMatchesConstructMatches
     
     
    Character classes
    [abc]a, b, or c (simple class)
    [^abc]Any character except a, b, or c (negation)
    [a-zA-Z]a through z - * or A through Z, inclusive (range)
    [a-d[m-p]]a through d, - * or m through p: [a-dm-p] (union)
    [a-z&&[def]]d, e, or f (intersection)
    [a-z&&[^bc]]a through z, - * except for b and c: [ad-z] (subtraction)
    [a-z&&[^m-p]]a through z, - * and not m through p: [a-lq-z](subtraction)
    {@code [abc]}{@code a}, {@code b}, or {@code c} (simple class)
    {@code [^abc]}Any character except {@code a}, {@code b}, or {@code c} (negation)
    {@code [a-zA-Z]}{@code a} through {@code z} + * or {@code A} through {@code Z}, inclusive (range)
    {@code [a-d[m-p]]}{@code a} through {@code d}, + * or {@code m} through {@code p}: {@code [a-dm-p]} (union)
    {@code [a-z&&[def]]}{@code d}, {@code e}, or {@code f} (intersection)
    {@code [a-z&&[^bc]]}{@code a} through {@code z}, + * except for {@code b} and {@code c}: {@code [ad-z]} (subtraction)
    {@code [a-z&&[^m-p]]}{@code a} through {@code z}, + * and not {@code m} through {@code p}: {@code [a-lq-z]}(subtraction)
     
    Predefined character classes
    \WA non-word character: [^\w]
     
    POSIX character classes (US-ASCII only)
    POSIX character classes (US-ASCII only)
    \p{Lower}A lower-case alphabetic character: [a-z]
    \p{Upper}An upper-case alphabetic character:[A-Z]
    \p{ASCII}All ASCII:[\x00-\x7F]
    \p{Alpha}An alphabetic character:[\p{Lower}\p{Upper}]
    \p{Digit}A decimal digit: [0-9]
    \p{Alnum}An alphanumeric character:[\p{Alpha}\p{Digit}]
    \p{Punct}Punctuation: One of !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
    \p{Graph}A visible character: [\p{Alnum}\p{Punct}]
    \p{Print}A printable character: [\p{Graph}\x20]
    \p{Blank}A space or a tab: [ \t]
    \p{Cntrl}A control character: [\x00-\x1F\x7F]
    \p{XDigit}A hexadecimal digit: [0-9a-fA-F]
    \p{Space}A whitespace character: [ \t\n\x0B\f\r]
    {@code \p{Lower}}A lower-case alphabetic character: {@code [a-z]}
    {@code \p{Upper}}An upper-case alphabetic character:{@code [A-Z]}
    {@code \p{ASCII}}All ASCII:{@code [\x00-\x7F]}
    {@code \p{Alpha}}An alphabetic character:{@code [\p{Lower}\p{Upper}]}
    {@code \p{Digit}}A decimal digit: {@code [0-9]}
    {@code \p{Alnum}}An alphanumeric character:{@code [\p{Alpha}\p{Digit}]}
    {@code \p{Punct}}Punctuation: One of {@code !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~}
    {@code \p{Graph}}A visible character: {@code [\p{Alnum}\p{Punct}]}
    {@code \p{Print}}A printable character: {@code [\p{Graph}\x20]}
    {@code \p{Blank}}A space or a tab: {@code [ \t]}
    {@code \p{Cntrl}}A control character: {@code [\x00-\x1F\x7F]}
    {@code \p{XDigit}}A hexadecimal digit: {@code [0-9a-fA-F]}
    {@code \p{Space}}A whitespace character: {@code [ \t\n\x0B\f\r]}
     
    java.lang.Character classes (simple java character type)
     
    Classes for Unicode scripts, blocks, categories and binary properties
    \p{IsLatin}
    {@code \p{IsLatin}}A Latin script character (script)
    \p{InGreek}
    {@code \p{InGreek}}A character in the Greek block (block)
    \p{Lu}
    {@code \p{Lu}}An uppercase letter (category)
    \p{IsAlphabetic}
    {@code \p{IsAlphabetic}}An alphabetic character (binary property)
    \p{Sc}
    {@code \p{Sc}}A currency symbol
    \P{InGreek}
    {@code \P{InGreek}}Any character except one in the Greek block (negation)
    [\p{L}&&[^\p{Lu}]] 
    {@code [\p{L}&&[^\p{Lu}]]}Any letter except an uppercase letter (subtraction)
     
    [a-e][i-u]
    5    Intersection[a-z&&[aeiou]]
    {@code [a-z&&[aeiou]]}
    * *

    Note that a different set of metacharacters are in effect inside @@ -444,8 +441,7 @@ import java.util.stream.StreamSupport; * character class, while the expression - becomes a range * forming metacharacter. * - * - *

    Line terminators

    + *

    Line terminators

    * *

    A line terminator is a one- or two-character sequence that marks * the end of a line of the input character sequence. The following are @@ -480,11 +476,9 @@ import java.util.stream.StreamSupport; * except at the end of input. When in {@link #MULTILINE} mode $ * matches just before a line terminator or the end of the input sequence. * - * - *

    Groups and capturing

    + *

    Groups and capturing

    * - * - *
    Group number
    + *

    Group number

    *

    Capturing groups are numbered by counting their opening parentheses from * left to right. In the expression ((A)(B(C))), for example, there * are four such groups:

    @@ -507,8 +501,7 @@ import java.util.stream.StreamSupport; * subsequence may be used later in the expression, via a back reference, and * may also be retrieved from the matcher once the match operation is complete. * - * - *
    Group name
    + *

    Group name

    *

    A capturing group can also be assigned a "name", a named-capturing group, * and then be back-referenced later by the "name". Group names are composed of * the following characters. The first character must be a letter. @@ -537,7 +530,7 @@ import java.util.stream.StreamSupport; * that do not capture text and do not count towards the group total, or * named-capturing group. * - *

    Unicode support

    + *

    Unicode support

    * *

    This class is in conformance with Level 1 of Unicode Technical @@ -568,18 +561,18 @@ import java.util.stream.StreamSupport; *

    * Scripts, blocks, categories and binary properties can be used both inside * and outside of a character class. - * + * *

    - * Scripts are specified either with the prefix {@code Is}, as in + * Scripts are specified either with the prefix {@code Is}, as in * {@code IsHiragana}, or by using the {@code script} keyword (or its short * form {@code sc})as in {@code script=Hiragana} or {@code sc=Hiragana}. *

    * The script names supported by Pattern are the valid script names * accepted and defined by * {@link java.lang.Character.UnicodeScript#forName(String) UnicodeScript.forName}. - * + * *

    - * Blocks are specified with the prefix {@code In}, as in + * Blocks are specified with the prefix {@code In}, as in * {@code InMongolian}, or by using the keyword {@code block} (or its short * form {@code blk}) as in {@code block=Mongolian} or {@code blk=Mongolian}. *

    @@ -587,8 +580,8 @@ import java.util.stream.StreamSupport; * accepted and defined by * {@link java.lang.Character.UnicodeBlock#forName(String) UnicodeBlock.forName}. *

    - * - * Categories may be specified with the optional prefix {@code Is}: + * + * Categories may be specified with the optional prefix {@code Is}: * Both {@code \p{L}} and {@code \p{IsL}} denote the category of Unicode * letters. Same as scripts and blocks, categories can also be specified * by using the keyword {@code general_category} (or its short form @@ -600,8 +593,8 @@ import java.util.stream.StreamSupport; * {@link java.lang.Character Character} class. The category names are those * defined in the Standard, both normative and informative. *

    - * - * Binary properties are specified with the prefix {@code Is}, as in + * + * Binary properties are specified with the prefix {@code Is}, as in * {@code IsAlphabetic}. The supported binary properties by Pattern * are *

    * * Below is a picture showing an example of a memory pool: *

    @@ -98,7 +96,7 @@ import sun.management.MemoryUsageCompositeData; * max * * - *

    MXBean Mapping

    + *

    MXBean Mapping

    * MemoryUsage is mapped to a {@link CompositeData CompositeData} * with attributes as specified in the {@link #from from} method. * @@ -254,7 +252,7 @@ public class MemoryUsage { * must contain the following attributes: *

    *

    - * + *
    * * * diff --git a/jdk/src/share/classes/java/lang/management/MonitorInfo.java b/jdk/src/share/classes/java/lang/management/MonitorInfo.java index 658be133fda..e97a3173b9e 100644 --- a/jdk/src/share/classes/java/lang/management/MonitorInfo.java +++ b/jdk/src/share/classes/java/lang/management/MonitorInfo.java @@ -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 @@ import sun.management.MonitorInfoCompositeData; * Information about an object monitor lock. An object monitor is locked * when entering a synchronization block or method on that object. * - *

    MXBean Mapping

    + *

    MXBean Mapping

    * MonitorInfo is mapped to a {@link CompositeData CompositeData} * with attributes as specified in * the {@link #from from} method. @@ -106,7 +106,7 @@ public class MonitorInfo extends LockInfo { * * mapped type for the {@link LockInfo} class: *
    - *
    Attribute NameType
    + *
    * * * diff --git a/jdk/src/share/classes/java/lang/management/RuntimeMXBean.java b/jdk/src/share/classes/java/lang/management/RuntimeMXBean.java index e4142d3e439..0e680fdf04e 100644 --- a/jdk/src/share/classes/java/lang/management/RuntimeMXBean.java +++ b/jdk/src/share/classes/java/lang/management/RuntimeMXBean.java @@ -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 @@ public interface RuntimeMXBean extends PlatformManagedObject { * *

    * MBeanServer access:
    - * The mapped type of List is String[]. + * The mapped type of {@code List} is String[]. * * @return a list of String objects; each element * is an argument passed to the Java virtual machine. @@ -312,7 +312,7 @@ public interface RuntimeMXBean extends PlatformManagedObject { * {@link javax.management.openmbean.TabularData TabularData} * with two items in each row as follows: *

    - *
    Attribute NameType
    + *
    * * * diff --git a/jdk/src/share/classes/java/lang/management/ThreadInfo.java b/jdk/src/share/classes/java/lang/management/ThreadInfo.java index 676b698f5a2..e6f80b2eb23 100644 --- a/jdk/src/share/classes/java/lang/management/ThreadInfo.java +++ b/jdk/src/share/classes/java/lang/management/ThreadInfo.java @@ -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 @@ import static java.lang.Thread.State.*; /** * Thread information. ThreadInfo contains the information * about a thread including: - *

    General thread information

    + *

    General thread information

    *
      *
    • Thread ID.
    • *
    • Name of the thread.
    • *
    * - *

    Execution information

    + *

    Execution information

    *
      *
    • Thread state.
    • *
    • The object upon which the thread is blocked due to: @@ -652,7 +652,7 @@ public class ThreadInfo { * The given CompositeData must contain the following attributes * unless otherwise specified below: *
      - *
    Item NameItem Type
    + *
    * * * @@ -722,7 +722,7 @@ public class ThreadInfo { * Each element is a CompositeData representing * StackTraceElement containing the following attributes: *
    - *
    Attribute NameType
    + *
    * * * diff --git a/jdk/src/share/classes/java/lang/management/ThreadMXBean.java b/jdk/src/share/classes/java/lang/management/ThreadMXBean.java index 30251d51f60..02a87dcf6d3 100644 --- a/jdk/src/share/classes/java/lang/management/ThreadMXBean.java +++ b/jdk/src/share/classes/java/lang/management/ThreadMXBean.java @@ -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 @@ import java.util.Map; * It can be obtained by calling the * {@link PlatformManagedObject#getObjectName} method. * - *

    Thread ID

    + *

    Thread ID

    * 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 @@ import java.util.Map; *

    Some methods in this interface take a thread ID or an array * of thread IDs as the input parameter and return per-thread information. * - *

    Thread CPU time

    + *

    Thread CPU time

    * 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 @@ import java.util.Map; * Enabling thread CPU measurement could be expensive in some * Java virtual machine implementations. * - *

    Thread Contention Monitoring

    + *

    Thread Contention Monitoring

    * 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 @@ import java.util.Map; * {@link #setThreadContentionMonitoringEnabled} method can be used to enable * thread contention monitoring. * - *

    Synchronization Information and Deadlock Detection

    + *

    Synchronization Information and Deadlock Detection

    * Some Java virtual machines may support monitoring of * {@linkplain #isObjectMonitorUsageSupported object monitor usage} and * {@linkplain #isSynchronizerUsageSupported ownable synchronizer usage}. From 4111a6d9e45ffc36a0b345ee7e20a0968ec18fa6 Mon Sep 17 00:00:00 2001 From: Jason Uh Date: Wed, 10 Jul 2013 18:01:22 -0700 Subject: [PATCH 047/123] 8020318: Fix doclint issues in java.net Reviewed-by: darcy, khazra --- jdk/src/share/classes/java/net/CookieStore.java | 4 +++- .../share/classes/java/net/HttpURLPermission.java | 14 ++++++++------ jdk/src/share/classes/java/net/Inet4Address.java | 4 ++-- jdk/src/share/classes/java/net/Inet6Address.java | 4 ++-- jdk/src/share/classes/java/net/InetAddress.java | 5 ++--- jdk/src/share/classes/java/net/ProtocolFamily.java | 4 +++- jdk/src/share/classes/java/net/SocketOption.java | 6 +++++- jdk/src/share/classes/java/net/URI.java | 14 +++++++------- 8 files changed, 32 insertions(+), 23 deletions(-) diff --git a/jdk/src/share/classes/java/net/CookieStore.java b/jdk/src/share/classes/java/net/CookieStore.java index a8232d2930c..89b9c41dd01 100644 --- a/jdk/src/share/classes/java/net/CookieStore.java +++ b/jdk/src/share/classes/java/net/CookieStore.java @@ -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 @@ public interface CookieStore { * @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 uri is null * * @see #add diff --git a/jdk/src/share/classes/java/net/HttpURLPermission.java b/jdk/src/share/classes/java/net/HttpURLPermission.java index 55d37fda8ca..4e038bc739e 100644 --- a/jdk/src/share/classes/java/net/HttpURLPermission.java +++ b/jdk/src/share/classes/java/net/HttpURLPermission.java @@ -47,6 +47,7 @@ import java.security.Permission; * in {@link java.io.FilePermission}. There are three different ways * as the following examples show: *
    Attribute NameType
    + * * * * @@ -57,7 +58,7 @@ import java.security.Permission; * which only differ in the final path component, represented by the '*'. * * - * *
    URL Examples
    Example urlDescription
    http://www.oracle.com/a/b/c.htmlA url which identifies a specific (single) resource
    http://www.oracle.com/a/b/- + *
    http://www.oracle.com/a/b/-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 @@ public final class HttpURLPermission extends Permission { * 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 @@ public final class HttpURLPermission extends Permission { *
  • 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 *
  • otherwise, return false
  • - * - *

    - * Some examples of how paths are matched are shown below: - *

    - * + * + *

    Some examples of how paths are matched are shown below: + *

    + * * * * diff --git a/jdk/src/share/classes/java/net/Inet4Address.java b/jdk/src/share/classes/java/net/Inet4Address.java index 529257fa90d..6c59a692f82 100644 --- a/jdk/src/share/classes/java/net/Inet4Address.java +++ b/jdk/src/share/classes/java/net/Inet4Address.java @@ -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 @@ import java.io.ObjectStreamException; * and RFC 2365: * Administratively Scoped IP Multicast * - *

    Textual representation of IP addresses

    + *

    Textual representation of IP addresses

    * * Textual representation of IPv4 address used as input to methods * takes one of the following forms: diff --git a/jdk/src/share/classes/java/net/Inet6Address.java b/jdk/src/share/classes/java/net/Inet6Address.java index 4a2d4e22473..169a180de11 100644 --- a/jdk/src/share/classes/java/net/Inet6Address.java +++ b/jdk/src/share/classes/java/net/Inet6Address.java @@ -35,7 +35,7 @@ import java.util.Enumeration; * Defined by * RFC 2373: IP Version 6 Addressing Architecture. * - *

    Textual representation of IP addresses

    + *

    Textual representation of IP addresses

    * * Textual representation of IPv6 address used as input to methods * takes one of the following forms: @@ -156,7 +156,7 @@ import java.util.Enumeration; * 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. - *

  • As a string. This must be the exact string that is returned by + *
  • As a string. 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 diff --git a/jdk/src/share/classes/java/net/InetAddress.java b/jdk/src/share/classes/java/net/InetAddress.java index 1154c9a80f4..aa5ef16705d 100644 --- a/jdk/src/share/classes/java/net/InetAddress.java +++ b/jdk/src/share/classes/java/net/InetAddress.java @@ -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 @@ import sun.net.spi.nameservice.*; * with a host name or whether it has already done reverse host name * resolution). * - *

    Address types

    + *

    Address types

    * *
  • Examples of Path Matching
    this's pathp's pathmatch
    /a/b/a/byes
    /a/b/*/a/b/cyes
    * @@ -165,7 +165,6 @@ import sun.net.spi.nameservice.*; *

    * A value of -1 indicates "cache forever". * - *

    *

    networkaddress.cache.negative.ttl (default: 10)
    *
    Indicates the caching policy for un-successful name lookups * from the name service. The value is specified as as integer to diff --git a/jdk/src/share/classes/java/net/ProtocolFamily.java b/jdk/src/share/classes/java/net/ProtocolFamily.java index c6aa95b1861..5d02326db18 100644 --- a/jdk/src/share/classes/java/net/ProtocolFamily.java +++ b/jdk/src/share/classes/java/net/ProtocolFamily.java @@ -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 @@ package java.net; public interface ProtocolFamily { /** * Returns the name of the protocol family. + * + * @return the name of the protocol family */ String name(); } diff --git a/jdk/src/share/classes/java/net/SocketOption.java b/jdk/src/share/classes/java/net/SocketOption.java index cfa4616bcef..2ccf57f5f33 100644 --- a/jdk/src/share/classes/java/net/SocketOption.java +++ b/jdk/src/share/classes/java/net/SocketOption.java @@ -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 @@ public interface SocketOption { /** * 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 type(); } diff --git a/jdk/src/share/classes/java/net/URI.java b/jdk/src/share/classes/java/net/URI.java index ed90f090c29..643c8af8a71 100644 --- a/jdk/src/share/classes/java/net/URI.java +++ b/jdk/src/share/classes/java/net/URI.java @@ -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 @@ import java.lang.NullPointerException; // for javadoc * and relativizing URI instances. Instances of this class are immutable. * * - *

    URI syntax and components

    + *

    URI syntax and components

    * * At the highest level a URI reference (hereinafter simply "URI") in string * form has the syntax * *
    - * [scheme:]scheme-specific-part[#fragment] + * [scheme:]scheme-specific-part[#fragment] *
    * * where square brackets [...] delineate optional components and the characters @@ -334,14 +334,14 @@ import java.lang.NullPointerException; // for javadoc * *
      * - *
    • The {@link #URI(java.lang.String) single-argument - * constructor} requires any illegal characters in its argument to be + *

    • 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 other characters that * are present.

    • * - *
    • The {@link + *

    • The {@linkplain * #URI(java.lang.String,java.lang.String,java.lang.String,int,java.lang.String,java.lang.String,java.lang.String) - * multi-argument constructors} quote illegal characters as + * multi-argument constructors} quote illegal characters as * required by the components in which they appear. The percent character * ('%') is always quoted by these constructors. Any other * characters are preserved.

    • From ad9738a0be7bedfe1ff9f07e84ce887f6c0ad70f Mon Sep 17 00:00:00 2001 From: Valerie Peng Date: Wed, 10 Jul 2013 18:14:35 -0700 Subject: [PATCH 048/123] 8020310: JDK-6356530 broke the old build Add serialVersionUID to AuthProvider and P11Key class. Reviewed-by: xuelei --- jdk/src/share/classes/java/security/AuthProvider.java | 2 ++ jdk/src/share/classes/sun/security/pkcs11/P11Key.java | 2 ++ 2 files changed, 4 insertions(+) diff --git a/jdk/src/share/classes/java/security/AuthProvider.java b/jdk/src/share/classes/java/security/AuthProvider.java index a5310aa9f42..571a1fe085f 100644 --- a/jdk/src/share/classes/java/security/AuthProvider.java +++ b/jdk/src/share/classes/java/security/AuthProvider.java @@ -41,6 +41,8 @@ import javax.security.auth.callback.CallbackHandler; */ public abstract class AuthProvider extends Provider { + private static final long serialVersionUID = 4197859053084546461L; + /** * Constructs a provider with the specified name, version number, * and information. diff --git a/jdk/src/share/classes/sun/security/pkcs11/P11Key.java b/jdk/src/share/classes/sun/security/pkcs11/P11Key.java index ae9264779f5..236a6acc410 100644 --- a/jdk/src/share/classes/sun/security/pkcs11/P11Key.java +++ b/jdk/src/share/classes/sun/security/pkcs11/P11Key.java @@ -65,6 +65,8 @@ import sun.security.util.ECUtil; */ abstract class P11Key implements Key, Length { + private static final long serialVersionUID = -2575874101938349339L; + private final static String PUBLIC = "public"; private final static String PRIVATE = "private"; private final static String SECRET = "secret"; From d7811f443c3821e9efe580a94c10cbb509d438a5 Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Thu, 11 Jul 2013 09:21:09 +0200 Subject: [PATCH 049/123] 8019826: Test com/sun/management/HotSpotDiagnosticMXBean/SetVMOption.java fails with NPE Reviewed-by: sjiang, dholmes, mchung --- .../HotSpotDiagnosticMXBean/SetVMOption.java | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/jdk/test/com/sun/management/HotSpotDiagnosticMXBean/SetVMOption.java b/jdk/test/com/sun/management/HotSpotDiagnosticMXBean/SetVMOption.java index b66f7c01190..e6cd26e3c9e 100644 --- a/jdk/test/com/sun/management/HotSpotDiagnosticMXBean/SetVMOption.java +++ b/jdk/test/com/sun/management/HotSpotDiagnosticMXBean/SetVMOption.java @@ -27,6 +27,7 @@ * @summary Basic Test for HotSpotDiagnosticMXBean.setVMOption() * and getDiagnosticOptions(). * @author Mandy Chung + * @author Jaroslav Bachorik * * @run main/othervm -XX:+PrintGCDetails SetVMOption */ @@ -36,7 +37,6 @@ import java.util.*; import com.sun.management.HotSpotDiagnosticMXBean; import com.sun.management.VMOption; import com.sun.management.VMOption.Origin; -import sun.misc.Version; public class SetVMOption { private static String PRINT_GC_DETAILS = "PrintGCDetails"; @@ -47,17 +47,8 @@ public class SetVMOption { private static HotSpotDiagnosticMXBean mbean; public static void main(String[] args) throws Exception { - List list = - ManagementFactory.getPlatformMXBeans(HotSpotDiagnosticMXBean.class); - - // The following test is transitional only and should be removed - // once build 52 is promoted. - int build = Version.jvmBuildNumber(); - if (build > 0 && build < 52) { - // JVM support is integrated in build 52 - // this test is skipped if running with VM earlier than 52 - return; - } + mbean = + ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class); VMOption option = findPrintGCDetailsOption(); if (!option.getValue().equalsIgnoreCase(EXPECTED_VALUE)) { From 841458107b37435efcabbc3be2e0f40d6398e901 Mon Sep 17 00:00:00 2001 From: Doug Lea Date: Thu, 11 Jul 2013 13:07:47 +0200 Subject: [PATCH 050/123] 8019484: Sync j.u.c.ConcurrentHashMap from 166 to tl Reviewed-by: martin --- .../util/concurrent/ConcurrentHashMap.java | 4684 +++++++++-------- .../java/util/concurrent/ConcurrentMap.java | 12 +- .../concurrent/ConcurrentNavigableMap.java | 2 +- 3 files changed, 2462 insertions(+), 2236 deletions(-) diff --git a/jdk/src/share/classes/java/util/concurrent/ConcurrentHashMap.java b/jdk/src/share/classes/java/util/concurrent/ConcurrentHashMap.java index e62ef35916e..08e2bd38239 100644 --- a/jdk/src/share/classes/java/util/concurrent/ConcurrentHashMap.java +++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentHashMap.java @@ -34,8 +34,9 @@ */ package java.util.concurrent; -import java.io.Serializable; + import java.io.ObjectStreamField; +import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.AbstractMap; @@ -54,8 +55,8 @@ import java.util.Spliterator; 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 @@ import java.util.stream.Stream; * @param the type of keys maintained by this map * @param the type of mapped values */ -@SuppressWarnings({"unchecked", "rawtypes", "serial"}) -public class ConcurrentHashMap extends AbstractMap - implements ConcurrentMap, Serializable { - +public class ConcurrentHashMap extends AbstractMap implements ConcurrentMap, Serializable { private static final long serialVersionUID = 7249069246763182397L; /* @@ -280,16 +278,21 @@ public class ConcurrentHashMap extends AbstractMap * 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 @@ public class ConcurrentHashMap extends AbstractMap * * 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 @@ public class ConcurrentHashMap extends AbstractMap * 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 @@ public class ConcurrentHashMap extends AbstractMap * 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 @@ public class ConcurrentHashMap extends AbstractMap * 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 @@ public class ConcurrentHashMap extends AbstractMap /** * 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 @@ public class ConcurrentHashMap extends AbstractMap /* * 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 @@ public class ConcurrentHashMap extends AbstractMap 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. */ - @sun.misc.Contended static final class Cell { - volatile long value; - Cell(long x) { value = x; } + static class Node implements Map.Entry { + final int hash; + final K key; + volatile V val; + volatile Node next; + + Node(int hash, K key, V val, Node 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 find(int h, Object k) { + Node 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. + */ + 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", 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 Node tabAt(Node[] tab, int i) { + return (Node)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE); + } + + static final boolean casTabAt(Node[] tab, int i, + Node c, Node v) { + return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v); + } + + static final void setTabAt(Node[] tab, int i, Node v) { + U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v); } /* ---------------- Fields -------------- */ @@ -569,682 +775,301 @@ public class ConcurrentHashMap extends AbstractMap 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 keySet; private transient ValuesView values; private transient EntrySetView 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. - */ - - static final Node tabAt(Node[] tab, int i) { - return (Node)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE); - } - - static final boolean casTabAt(Node[] tab, int i, - Node c, Node v) { - return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v); - } - - static final void setTabAt(Node[] tab, int i, Node v) { - U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v); - } - - /* ---------------- Nodes -------------- */ + /* ---------------- Public operations -------------- */ /** - * 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 the default initial table size (16). */ - static class Node implements Map.Entry { - final int hash; - final Object key; - volatile V val; - Node next; - - Node(int hash, Object key, V val, Node 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 ConcurrentHashMap() { } /** - * Exported Entry for EntryIterator + * 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 class MapEntry implements Map.Entry { - final K key; // non-null - V val; // non-null - final ConcurrentHashMap map; - MapEntry(K key, V val, ConcurrentHashMap 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; - } - } - - - /* ---------------- TreeBins -------------- */ - - /** - * Nodes for use in TreeBins - */ - static final class TreeNode extends Node { - TreeNode parent; // red-black tree links - TreeNode left; - TreeNode right; - TreeNode prev; // needed to unlink next upon deletion - boolean red; - - TreeNode(int hash, Object key, V val, Node next, - TreeNode parent) { - super(hash, key, val, next); - this.parent = parent; - } + 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; } /** - * Returns a Class for the given type of the form "class C - * implements Comparable", if one exists, else null. See below - * for explanation. + * Creates a new map with the same mappings as the given map. + * + * @param m the map */ - 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; - } + public ConcurrentHashMap(Map m) { + this.sizeCtl = DEFAULT_CAPACITY; + putAll(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; + } + + // 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} + */ + 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. + * + *

      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[] tab; Node 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; } /** - * A specialized form of red-black tree for use in bins - * whose size exceeds a threshold. + * Tests if the specified object is a key in this table. * - * 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. + * @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 */ - static final class TreeBin extends StampedLock { - private static final long serialVersionUID = 2249069246763182397L; - transient TreeNode root; // root of tree - transient TreeNode first; // head of next-pointer list - - /** From CLR */ - private void rotateLeft(TreeNode p) { - if (p != null) { - TreeNode 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; - } - } - - /** From CLR */ - private void rotateRight(TreeNode p) { - if (p != null) { - TreeNode 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 getTreeNode(int h, Object k, TreeNode 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)k).compareTo(pk)) == 0) { - TreeNode 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 r = null; - for (Node e = first; e != null; e = e.next) { - long s; - if ((s = tryReadLock()) != 0L) { - try { - r = getTreeNode(h, k, root, cc); - } finally { - unlockRead(s); - } - 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 - */ - final TreeNode putTreeNode(int h, Object k, V v) { - Class cc = comparableClassFor(k.getClass()); - TreeNode 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)k).compareTo(pk)) == 0) { - TreeNode 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; - } - - TreeNode f = first; - TreeNode x = first = new TreeNode(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 xp, xpp, xppl, xppr;;) { - if ((xp = x.parent) == null) { - (root = x).red = false; - break; - } - else if (!xp.red || (xpp = xp.parent) == null) { - TreeNode r = root; - if (r != null && r.red) - r.red = false; - break; - } - 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); - } - } - } - } - 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); - } - } - } - } - } - } - 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 p) { - TreeNode next = (TreeNode)p.next; - TreeNode 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 replacement; - TreeNode pl = p.left; - TreeNode pr = p.right; - if (pl != null && pr != null) { - TreeNode 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 sr = s.right; - TreeNode pp = p.parent; - if (s == pr) { // p was s's direct parent - p.parent = s; - s.right = p; - } - else { - TreeNode 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 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 x = replacement; x != null; ) { - TreeNode 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 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 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 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 r = root; - if (r == null) - return (first == null); - else - return (first != null) && checkTreeNode(r); - } - - /** - * Recursive invariant check - */ - final boolean checkTreeNode(TreeNode t) { - TreeNode tp = t.parent, tl = t.left, tr = t.right, - tb = t.prev, tn = (TreeNode)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; + public boolean containsKey(Object key) { + return get(key) != null; } /** - * Replaces a list bin with a tree bin if key is comparable. Call - * only when locked. + * 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 */ - private final void replaceWithTreeBin(Node[] tab, int index, Object key) { - if (tab != null && comparableClassFor(key.getClass()) != null) { - TreeBin t = new TreeBin(); - for (Node e = tabAt(tab, index); e != null; e = e.next) - t.putTreeNode(e.hash, e.key, e.val); - setTabAt(tab, index, new Node(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[] tab; Node 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)ek).getValue(h, k); - break; - } - else if (!(ek instanceof Node[]) || // try new table - (e = tabAt(tab = (Node[])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; + public boolean containsValue(Object value) { + if (value == null) + throw new NullPointerException(); + Node[] t; + if ((t = table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node p; (p = it.advance()) != null; ) { + V v; + if ((v = p.val) == value || (v != null && value.equals(v))) + return true; } } - return v; + return false; + } + + /** + * Maps the specified key to the specified value in this table. + * Neither the key nor the value can be null. + * + *

      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 putVal(key, value, false); + } + + /** 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[] tab = table;;) { + Node 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(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 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 pred = e; + if ((e = e.next) == null) { + pred.next = new Node(hash, key, + value, null); + break; + } + } + } + else if (f instanceof TreeBin) { + Node p; + binCount = 2; + if ((p = ((TreeBin)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; + } + + /** + * 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 m) { + tryPresize(m.size()); + for (Map.Entry 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); } /** @@ -1252,616 +1077,104 @@ public class ConcurrentHashMap extends AbstractMap * 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; + final V replaceNode(Object key, V value, Object cv) { + int hash = spread(key.hashCode()); for (Node[] tab = table;;) { - Node f; int i, fh; Object fk; - if (tab == null || - (f = tabAt(tab, i = (tab.length - 1) & h)) == null) + Node 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) < 0) { - if ((fk = f.key) instanceof TreeBin) { - TreeBin t = (TreeBin)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 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[])fk; - } + else if ((fh = f.hash) == MOVED) + tab = helpTransfer(tab, f); else { + V oldVal = null; boolean validated = false; - boolean deleted = false; synchronized (f) { if (tabAt(tab, i) == f) { - validated = true; - for (Node 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 en = e.next; - if (pred != null) - pred.next = en; + if (fh >= 0) { + validated = true; + for (Node 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, en); + setTabAt(tab, i, e.next); } + break; + } + pred = e; + if ((e = e.next) == null) + break; + } + } + else if (f instanceof TreeBin) { + validated = true; + TreeBin t = (TreeBin)f; + TreeNode 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)); } - 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[] tab = table;;) { - int i, fh; Node 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(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 t = (TreeBin)fk; - long stamp = t.writeLock(); - V oldVal = null; - try { - if (tabAt(tab, i) == f) { - len = 2; - TreeNode 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[])fk; - } - else { - V oldVal = null; - synchronized (f) { - if (tabAt(tab, i) == f) { - len = 1; - for (Node 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 last = e; - if ((e = e.next) == null) { - last.next = new Node(h, k, v, null); - if (len > TREE_THRESHOLD) - replaceWithTreeBin(tab, i, k); - break; - } - } - } - } - if (len != 0) { - if (oldVal != null) + if (oldVal != null) { + if (value == null) + addCount(-1L, -1); return oldVal; + } break; } } } - addCount(1L, len); return null; } - /** Implementation for computeIfAbsent */ - private final V internalComputeIfAbsent(K k, Function mf) { - if (k == null || mf == null) - throw new NullPointerException(); - int h = spread(k.hashCode()); - V val = null; - int len = 0; - for (Node[] tab = table;;) { - Node f; int i; Object fk; - if (tab == null) - tab = initTable(); - else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) { - Node node = new Node(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 t = (TreeBin)fk; - long stamp = t.writeLock(); - boolean added = false; - try { - if (tabAt(tab, i) == f) { - len = 2; - Class cc = comparableClassFor(k.getClass()); - TreeNode 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[])fk; - } - else { - boolean added = false; - synchronized (f) { - if (tabAt(tab, i) == f) { - len = 1; - for (Node e = f;; ++len) { - Object ek; V ev; - if (e.hash == h && - ((ek = e.key) == k || k.equals(ek))) { - val = e.val; - break; - } - Node last = e; - if ((e = e.next) == null) { - if ((val = mf.apply(k)) != null) { - added = true; - last.next = new Node(h, k, val, null); - if (len > TREE_THRESHOLD) - replaceWithTreeBin(tab, i, k); - } - break; - } - } - } - } - if (len != 0) { - if (!added) - return val; - break; - } - } - } - if (val != null) - addCount(1L, len); - return val; - } - - /** Implementation for compute */ - private final V internalCompute(K k, boolean onlyIfPresent, - BiFunction mf) { - if (k == null || mf == null) - throw new NullPointerException(); - int h = spread(k.hashCode()); - V val = null; - int delta = 0; - int len = 0; - for (Node[] tab = table;;) { - Node f; int i, fh; Object fk; - if (tab == null) - tab = initTable(); - else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) { - if (onlyIfPresent) - break; - Node node = new Node(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 t = (TreeBin)fk; - long stamp = t.writeLock(); - try { - if (tabAt(tab, i) == f) { - len = 2; - Class cc = comparableClassFor(k.getClass()); - TreeNode 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[])fk; - } - else { - synchronized (f) { - if (tabAt(tab, i) == f) { - len = 1; - for (Node 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 (val != null) - e.val = val; - else { - delta = -1; - Node en = e.next; - if (pred != null) - pred.next = en; - else - setTabAt(tab, i, en); - } - break; - } - pred = e; - if ((e = e.next) == null) { - if (!onlyIfPresent && - (val = mf.apply(k, null)) != null) { - pred.next = new Node(h, k, val, null); - delta = 1; - if (len > TREE_THRESHOLD) - replaceWithTreeBin(tab, i, k); - } - break; - } - } - } - } - if (len != 0) - break; - } - } - if (delta != 0) - addCount((long)delta, len); - return val; - } - - /** Implementation for merge */ - private final V internalMerge(K k, V v, - BiFunction mf) { - if (k == null || v == null || mf == null) - throw new NullPointerException(); - int h = spread(k.hashCode()); - V val = null; - int delta = 0; - int len = 0; - for (Node[] tab = table;;) { - int i; Node 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(h, k, v, null))) { - delta = 1; - val = v; - break; - } - } - else if (f.hash < 0) { - if ((fk = f.key) instanceof TreeBin) { - TreeBin t = (TreeBin)fk; - long stamp = t.writeLock(); - try { - if (tabAt(tab, i) == f) { - len = 2; - Class cc = comparableClassFor(k.getClass()); - TreeNode p = t.getTreeNode(h, k, t.root, cc); - val = (p == null) ? v : mf.apply(p.val, v); - if (val != 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[])fk; - } - else { - synchronized (f) { - if (tabAt(tab, i) == f) { - len = 1; - for (Node 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; - else { - delta = -1; - Node 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 = v; - pred.next = new Node(h, k, val, null); - if (len > TREE_THRESHOLD) - replaceWithTreeBin(tab, i, k); - break; - } - } - } - } - if (len != 0) - break; - } - } - if (delta != 0) - addCount((long)delta, len); - return val; - } - - /** Implementation for putAll */ - private final void internalPutAll(Map 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 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[] tab = table;;) { - int i; Node 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(h, k, v, null))) { - ++delta; - break; - } - } - else if ((fh = f.hash) < 0) { - if ((fk = f.key) instanceof TreeBin) { - TreeBin t = (TreeBin)fk; - long stamp = t.writeLock(); - boolean validated = false; - try { - if (tabAt(tab, i) == f) { - validated = true; - Class cc = comparableClassFor(k.getClass()); - TreeNode 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[])fk; - } - else { - int len = 0; - synchronized (f) { - if (tabAt(tab, i) == f) { - len = 1; - for (Node e = f;; ++len) { - Object ek; - if (e.hash == h && - ((ek = e.key) == k || k.equals(ek))) { - e.val = v; - break; - } - Node last = e; - if ((e = e.next) == null) { - ++delta; - last.next = new Node(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(); - } - /** - * Implementation for clear. Steps through each bin, removing all - * nodes. + * Removes all of the mappings from this map. */ - private final void internalClear() { + public void clear() { long delta = 0L; // negative number of deletions int i = 0; Node[] tab = table; while (tab != null && i < tab.length) { + int fh; Node f = tabAt(tab, i); if (f == null) ++i; - else if (f.hash < 0) { - Object fk; - if ((fk = f.key) instanceof TreeBin) { - TreeBin t = (TreeBin)fk; - long stamp = t.writeLock(); - try { - if (tabAt(tab, i) == f) { - for (Node p = t.first; p != null; p = p.next) - --delta; - t.first = null; - t.root = null; - ++i; - } - } finally { - t.unlockWrite(stamp); - } - } - else - tab = (Node[])fk; + else if ((fh = f.hash) == MOVED) { + tab = helpTransfer(tab, f); + i = 0; // restart } else { synchronized (f) { if (tabAt(tab, i) == f) { - for (Node e = f; e != null; e = e.next) + Node p = (fh >= 0 ? f : + (f instanceof TreeBin) ? + ((TreeBin)f).first : null); + while (p != null) { --delta; - setTabAt(tab, i, null); - ++i; + p = p.next; + } + setTabAt(tab, i++, null); } } } @@ -1870,35 +1183,1013 @@ public class ConcurrentHashMap extends AbstractMap addCount(delta, -1); } - /* ---------------- Table Initialization and Resizing -------------- */ + /** + * 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. + * + *

      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 keySet() { + KeySetView ks; + return (ks = keySet) != null ? ks : (keySet = new KeySetView(this, null)); + } /** - * Returns a power of two table size for the given desired capacity. - * See Hackers Delight, sec 3.2 + * 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. + * + *

      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 */ - 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; + public Collection values() { + ValuesView vs; + return (vs = values) != null ? vs : (values = new ValuesView(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. + * + *

      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> entrySet() { + EntrySetView es; + return (es = entrySet) != null ? es : (entrySet = new EntrySetView(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[] t; + if ((t = table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node 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[] t; + int f = (t = table) == null ? 0 : t.length; + Traverser it = new Traverser(t, f, 0, f); + StringBuilder sb = new StringBuilder(); + sb.append('{'); + Node 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[] t; + int f = (t = table) == null ? 0 : t.length; + Traverser it = new Traverser(t, f, 0, f); + for (Node 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 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[] segments = (Segment[]) + new Segment[DEFAULT_CONCURRENCY_LEVEL]; + for (int i = 0; i < segments.length; ++i) + segments[i] = new Segment(LOAD_FACTOR); + s.putFields().put("segments", segments); + s.putFields().put("segmentShift", segmentShift); + s.putFields().put("segmentMask", segmentMask); + s.writeFields(); + + Node[] t; + if ((t = table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node 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. + */ + sizeCtl = -1; // force exclusion for table construction + s.defaultReadObject(); + long size = 0L; + Node 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(spread(k.hashCode()), k, v, p); + ++size; + } + 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[] tab = (Node[])new Node[n]; + int mask = n - 1; + long added = 0L; + while (p != null) { + boolean insertAtFront; + Node 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 t = (TreeBin)first; + if (t.putTreeVal(h, k, p.val) == null) + ++added; + insertAtFront = false; + } + else { + int binCount = 0; + insertAtFront = true; + Node 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 hd = null, tl = null; + for (q = p; q != null; q = q.next) { + TreeNode t = new TreeNode + (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(hd)); + } + } + } + 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 action) { + if (action == null) throw new NullPointerException(); + Node[] t; + if ((t = table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node p; (p = it.advance()) != null; ) { + action.accept(p.key, p.val); + } + } + } + + public void replaceAll(BiFunction function) { + if (function == null) throw new NullPointerException(); + Node[] t; + if ((t = table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node 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 mappingFunction) { + if (key == null || mappingFunction == null) + throw new NullPointerException(); + int h = spread(key.hashCode()); + V val = null; + int binCount = 0; + for (Node[] tab = table;;) { + Node 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 r = new ReservationNode(); + synchronized (r) { + if (casTabAt(tab, i, null, r)) { + binCount = 1; + Node node = null; + try { + if ((val = mappingFunction.apply(key)) != null) + node = new Node(h, key, val, null); + } finally { + setTabAt(tab, i, node); + } + } + } + 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 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 pred = e; + if ((e = e.next) == null) { + if ((val = mappingFunction.apply(key)) != null) { + added = true; + pred.next = new Node(h, key, val, null); + } + break; + } + } + } + else if (f instanceof TreeBin) { + binCount = 2; + TreeBin t = (TreeBin)f; + TreeNode 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); + } + } + } + } + if (binCount != 0) { + if (binCount >= TREEIFY_THRESHOLD) + treeifyBin(tab, i); + if (!added) + return val; + break; + } + } + } + if (val != null) + addCount(1L, binCount); + return val; + } + + /** + * 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 remappingFunction) { + if (key == null || remappingFunction == null) + throw new NullPointerException(); + int h = spread(key.hashCode()); + V val = null; + int delta = 0; + int binCount = 0; + for (Node[] tab = table;;) { + Node f; int n, i, fh; + if (tab == null || (n = tab.length) == 0) + tab = initTable(); + 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) { + if (fh >= 0) { + binCount = 1; + for (Node 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 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 t = (TreeBin)f; + TreeNode r, p; + if ((r = t.root) != null && + (p = r.findTreeNode(h, key, null)) != null) { + val = remappingFunction.apply(key, p.val); + if (val != null) + p.val = val; + else { + delta = -1; + if (t.removeTreeNode(p)) + setTabAt(tab, i, untreeify(t.first)); + } + } + } + } + } + if (binCount != 0) + break; + } + } + if (delta != 0) + addCount((long)delta, binCount); + return val; + } + + /** + * 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 remappingFunction) { + if (key == null || remappingFunction == null) + throw new NullPointerException(); + int h = spread(key.hashCode()); + V val = null; + int delta = 0; + int binCount = 0; + for (Node[] tab = table;;) { + Node 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 r = new ReservationNode(); + synchronized (r) { + if (casTabAt(tab, i, null, r)) { + binCount = 1; + Node node = null; + try { + if ((val = remappingFunction.apply(key, null)) != null) { + delta = 1; + node = new Node(h, key, val, null); + } + } finally { + setTabAt(tab, i, node); + } + } + } + if (binCount != 0) + break; + } + 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 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 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(h, key, val, null); + } + break; + } + } + } + else if (f instanceof TreeBin) { + binCount = 1; + TreeBin t = (TreeBin)f; + TreeNode 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.putTreeVal(h, key, val); + } + } + else if (p != null) { + delta = -1; + if (t.removeTreeNode(p)) + setTabAt(tab, i, untreeify(t.first)); + } + } + } + } + if (binCount != 0) { + if (binCount >= TREEIFY_THRESHOLD) + treeifyBin(tab, i); + break; + } + } + } + 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 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[] tab = table;;) { + Node 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(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) { + if (fh >= 0) { + binCount = 1; + for (Node 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 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(h, key, val, null); + break; + } + } + } + else if (f instanceof TreeBin) { + binCount = 2; + TreeBin t = (TreeBin)f; + TreeNode r = t.root; + TreeNode 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; + t.putTreeVal(h, key, val); + } + } + else if (p != null) { + delta = -1; + if (t.removeTreeNode(p)) + setTabAt(tab, i, untreeify(t.first)); + } + } + } + } + if (binCount != 0) { + if (binCount >= TREEIFY_THRESHOLD) + treeifyBin(tab, i); + break; + } + } + } + if (delta != 0) + addCount((long)delta, binCount); + return val; + } + + // 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 keys() { + Node[] t; + int f = (t = table) == null ? 0 : t.length; + return new KeyIterator(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 elements() { + Node[] t; + int f = (t = table) == null ? 0 : t.length; + return new ValueIterator(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 KeySetView newKeySet() { + return new KeySetView + (new ConcurrentHashMap(), 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 KeySetView newKeySet(int initialCapacity) { + return new KeySetView + (new ConcurrentHashMap(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 + */ + public KeySetView keySet(V mappedValue) { + if (mappedValue == null) + throw new NullPointerException(); + return new KeySetView(this, mappedValue); + } + + /* ---------------- Special Nodes -------------- */ + + /** + * A node inserted at head of bins during transfer operations. + */ + static final class ForwardingNode extends Node { + final Node[] nextTable; + ForwardingNode(Node[] tab) { + super(MOVED, null, null, null); + this.nextTable = tab; + } + + Node find(int h, Object k) { + // loop to avoid arbitrarily deep recursion on forwarding nodes + outer: for (Node[] tab = nextTable;;) { + Node 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)e).nextTable; + continue outer; + } + else + return e.find(h, k); + } + if ((e = e.next) == null) + return null; + } + } + } + } + + /** + * A place-holder node used in computeIfAbsent and compute + */ + static final class ReservationNode extends Node { + ReservationNode() { + super(RESERVED, null, null, null); + } + + Node find(int h, Object k) { + return null; + } + } + + /* ---------------- Table Initialization and Resizing -------------- */ + /** * Initializes table, using the size recorded in sizeCtl. */ private final Node[] initTable() { Node[] 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[])new Node[n]; + @SuppressWarnings({"rawtypes","unchecked"}) + Node[] nt = (Node[])new Node[n]; + table = tab = nt; sc = n - (n >>> 2); } } finally { @@ -1921,10 +2212,10 @@ public class ConcurrentHashMap extends AbstractMap * @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 || @@ -1955,6 +2246,22 @@ public class ConcurrentHashMap extends AbstractMap } } + /** + * Helps transfer if a resize is in progress. + */ + final Node[] helpTransfer(Node[] tab, Node f) { + Node[] nextTab; int sc; + if ((f instanceof ForwardingNode) && + (nextTab = ((ForwardingNode)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. * @@ -1971,7 +2278,9 @@ public class ConcurrentHashMap extends AbstractMap if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { try { if (table == tab) { - table = (Node[])new Node[n]; + @SuppressWarnings({"rawtypes","unchecked"}) + Node[] nt = (Node[])new Node[n]; + table = nt; sc = n - (n >>> 2); } } finally { @@ -1997,7 +2306,9 @@ public class ConcurrentHashMap extends AbstractMap stride = MIN_TRANSFER_STRIDE; // subdivide range if (nextTab == null) { // initiating try { - nextTab = (Node[])new Node[n << 1]; + @SuppressWarnings({"rawtypes","unchecked"}) + Node[] nt = (Node[])new Node[n << 1]; + nextTab = nt; } catch (Throwable ex) { // try to cope with OOME sizeCtl = Integer.MAX_VALUE; return; @@ -2005,7 +2316,7 @@ public class ConcurrentHashMap extends AbstractMap nextTable = nextTab; transferOrigin = n; transferIndex = n; - Node rev = new Node(MOVED, tab, null, null); + ForwardingNode rev = new ForwardingNode(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 @@ public class ConcurrentHashMap extends AbstractMap } } int nextn = nextTab.length; - Node fwd = new Node(MOVED, nextTab, null, null); + ForwardingNode fwd = new ForwardingNode(nextTab); boolean advance = true; + boolean finishing = false; // to ensure sweep before committing nextTab for (int i = 0, bound = 0;;) { - int nextIndex, nextBound; Node f; Object fk; + int nextIndex, nextBound, fh; Node f; while (advance) { - if (--i >= bound) + if (--i >= bound || finishing) advance = false; else if ((nextIndex = transferIndex) <= transferOrigin) { i = -1; @@ -2037,14 +2349,19 @@ public class ConcurrentHashMap extends AbstractMap } } 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 @@ public class ConcurrentHashMap extends AbstractMap 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 lastRun = f, lo = null, hi = null; - for (Node p = f.next; p != null; p = p.next) { - int b = p.hash & n; - if (b != runBit) { - runBit = b; - lastRun = p; + Node ln, hn; + if (fh >= 0) { + int runBit = fh & n; + Node lastRun = f; + for (Node p = f.next; p != null; p = p.next) { + int b = p.hash & n; + if (b != runBit) { + runBit = b; + lastRun = p; + } } - } - if (runBit == 0) - lo = lastRun; - else - hi = lastRun; - for (Node 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(ph, pk, pv, lo); - else - hi = new Node(ph, pk, pv, hi); - } - setTabAt(nextTab, i, lo); - setTabAt(nextTab, i + n, hi); - setTabAt(tab, i, fwd); - advance = true; - } - } - } - else if ((fk = f.key) instanceof TreeBin) { - TreeBin t = (TreeBin)fk; - long stamp = t.writeLock(); - try { - if (tabAt(tab, i) == f) { - TreeNode root; - Node ln = null, hn = null; - if ((root = t.root) != null) { - Node e, p; TreeNode lr, rr; int lh; - TreeBin 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; + if (runBit == 0) { + ln = lastRun; + hn = null; } else { - lt = new TreeBin(); - ht = new TreeBin(); - 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); - } + hn = lastRun; + ln = null; + } + for (Node 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(ph, pk, pv, ln); + else + hn = new Node(ph, pk, pv, hn); + } + setTabAt(nextTab, i, ln); + setTabAt(nextTab, i + n, hn); + setTabAt(tab, i, fwd); + advance = true; + } + else if (f instanceof TreeBin) { + TreeBin t = (TreeBin)f; + TreeNode lo = null, loTail = null; + TreeNode hi = null, hiTail = null; + int lc = 0, hc = 0; + for (Node e = t.first; e != null; e = e.next) { + int h = e.hash; + TreeNode p = new TreeNode + (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; } - if (lc < TREE_THRESHOLD) { // throw away - for (p = lt.first; p != null; p = p.next) - ln = new Node(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(p.hash, p.key, - p.val, hn); - ht = null; + else { + if ((p.prev = hiTail) == null) + hi = p; + else + hiTail.next = p; + hiTail = p; + ++hc; } } - if (ln == null && lt != null) - ln = new Node(MOVED, lt, null, null); - if (hn == null && ht != null) - hn = new Node(MOVED, ht, null, null); + ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) : + (hc != 0) ? new TreeBin(lo) : t; + hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) : + (lc != 0) ? new TreeBin(hi) : t; + setTabAt(nextTab, i, ln); + setTabAt(nextTab, i + n, hn); + setTabAt(tab, i, fwd); + advance = true; } - 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 @@ public class ConcurrentHashMap extends AbstractMap } 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 @@ public class ConcurrentHashMap extends AbstractMap 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 @@ public class ConcurrentHashMap extends AbstractMap 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 @@ public class ConcurrentHashMap extends AbstractMap } } + /* ---------------- 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[] tab, int index) { + Node 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 hd = null, tl = null; + for (Node e = b; e != null; e = e.next) { + TreeNode p = + new TreeNode(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(hd)); + } + } + } + } + } + + /** + * Returns a list on non-TreeNodes replacing those in given list. + */ + static Node untreeify(Node b) { + Node hd = null, tl = null; + for (Node q = b; q != null; q = q.next) { + Node p = new Node(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 extends Node { + TreeNode parent; // red-black tree links + TreeNode left; + TreeNode right; + TreeNode prev; // needed to unlink next upon deletion + boolean red; + + TreeNode(int hash, K key, V val, Node next, + TreeNode parent) { + super(hash, key, val, next); + this.parent = parent; + } + + Node 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 findTreeNode(int h, Object k, Class kc) { + if (k != null) { + TreeNode p = this; + do { + int ph, dir; K pk; TreeNode q; + TreeNode 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 extends Node { + TreeNode root; + volatile TreeNode 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 b) { + super(TREEBIN, null, null, null); + this.first = b; + TreeNode r = null; + for (TreeNode x = b, next; x != null; x = next) { + next = (TreeNode)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 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 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 find(int h, Object k) { + if (k != null) { + for (Node 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 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 putTreeVal(int h, K k, V v) { + Class kc = null; + for (TreeNode p = root;;) { + int dir, ph; K pk; TreeNode q, pr; + if (p == null) { + first = root = new TreeNode(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 xp = p; + if ((p = (dir < 0) ? p.left : p.right) == null) { + TreeNode x, f = first; + first = x = new TreeNode(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 p) { + TreeNode next = (TreeNode)p.next; + TreeNode pred = p.prev; // unlink traversal pointers + TreeNode 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 replacement; + TreeNode pl = p.left; + TreeNode pr = p.right; + if (pl != null && pr != null) { + TreeNode 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 sr = s.right; + TreeNode pp = p.parent; + if (s == pr) { // p was s's direct parent + p.parent = s; + s.right = p; + } + else { + TreeNode 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 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 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 TreeNode rotateLeft(TreeNode root, + TreeNode p) { + TreeNode 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 TreeNode rotateRight(TreeNode root, + TreeNode p) { + TreeNode 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 TreeNode balanceInsertion(TreeNode root, + TreeNode x) { + x.red = true; + for (TreeNode 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 TreeNode balanceDeletion(TreeNode root, + TreeNode x) { + for (TreeNode 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 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 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 boolean checkInvariants(TreeNode t) { + TreeNode tp = t.parent, tl = t.left, tr = t.right, + tb = t.prev, tn = (TreeNode)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 @@ public class ConcurrentHashMap extends AbstractMap if ((e = next) != null) e = e.next; for (;;) { - Node[] t; int i, n; Object ek; // must use locals in checks + Node[] 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)ek).first; - else { - tab = (Node[])ek; + if (e instanceof ForwardingNode) { + tab = ((ForwardingNode)e).nextTable; e = null; continue; } + else if (e instanceof TreeBin) + e = ((TreeBin)e).first; + else + e = null; } if ((index += baseSize) >= n) index = ++baseIndex; // visit upper slots if present @@ -2317,7 +3258,7 @@ public class ConcurrentHashMap extends AbstractMap /** * Base of key, value, and entry Iterators. Adds fields to - * Traverser to support iterator.remove + * Traverser to support iterator.remove. */ static class BaseIterator extends Traverser { final ConcurrentHashMap map; @@ -2337,7 +3278,7 @@ public class ConcurrentHashMap extends AbstractMap 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 @@ public class ConcurrentHashMap extends AbstractMap Node 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 @@ public class ConcurrentHashMap extends AbstractMap Node 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 @@ public class ConcurrentHashMap extends AbstractMap } } + /** + * Exported Entry for EntryIterator + */ + static final class MapEntry implements Map.Entry { + final K key; // non-null + V val; // non-null + final ConcurrentHashMap map; + MapEntry(K key, V val, ConcurrentHashMap 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 extends Traverser implements Spliterator { long est; // size estimate @@ -2419,7 +3403,7 @@ public class ConcurrentHashMap extends AbstractMap public void forEachRemaining(Consumer action) { if (action == null) throw new NullPointerException(); for (Node p; (p = advance()) != null;) - action.accept((K)p.key); + action.accept(p.key); } public boolean tryAdvance(Consumer action) { @@ -2427,7 +3411,7 @@ public class ConcurrentHashMap extends AbstractMap Node p; if ((p = advance()) == null) return false; - action.accept((K)p.key); + action.accept(p.key); return true; } @@ -2498,7 +3482,7 @@ public class ConcurrentHashMap extends AbstractMap public void forEachRemaining(Consumer> action) { if (action == null) throw new NullPointerException(); for (Node p; (p = advance()) != null; ) - action.accept(new MapEntry((K)p.key, p.val, map)); + action.accept(new MapEntry(p.key, p.val, map)); } public boolean tryAdvance(Consumer> action) { @@ -2506,7 +3490,7 @@ public class ConcurrentHashMap extends AbstractMap Node p; if ((p = advance()) == null) return false; - action.accept(new MapEntry((K)p.key, p.val, map)); + action.accept(new MapEntry(p.key, p.val, map)); return true; } @@ -2518,798 +3502,6 @@ public class ConcurrentHashMap extends AbstractMap } } - - /* ---------------- 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 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 KeySetView newKeySet() { - return new KeySetView - (new ConcurrentHashMap(), 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 KeySetView newKeySet(int initialCapacity) { - return new KeySetView - (new ConcurrentHashMap(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. - * - *

      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[] t; - if ((t = table) != null) { - Traverser it = new Traverser(t, t.length, 0, t.length); - for (Node 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. - * - *

      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 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 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 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 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 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. - * - *

      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 keySet() { - KeySetView ks = keySet; - return (ks != null) ? ks : (keySet = new KeySetView(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 keySet(V mappedValue) { - if (mappedValue == null) - throw new NullPointerException(); - return new KeySetView(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. - * - *

      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 values() { - ValuesView vs = values; - return (vs != null) ? vs : (values = new ValuesView(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. - * - *

      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> entrySet() { - EntrySetView es = entrySet; - return (es != null) ? es : (entrySet = new EntrySetView(this)); - } - - /** - * Returns an enumeration of the keys in this table. - * - * @return an enumeration of the keys in this table - * @see #keySet() - */ - public Enumeration keys() { - Node[] t; - int f = (t = table) == null ? 0 : t.length; - return new KeyIterator(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 elements() { - Node[] t; - int f = (t = table) == null ? 0 : t.length; - return new ValueIterator(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[] t; - if ((t = table) != null) { - Traverser it = new Traverser(t, t.length, 0, t.length); - for (Node 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[] t; - int f = (t = table) == null ? 0 : t.length; - Traverser it = new Traverser(t, f, 0, f); - StringBuilder sb = new StringBuilder(); - sb.append('{'); - Node 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[] t; - int f = (t = table) == null ? 0 : t.length; - Traverser it = new Traverser(t, f, 0, f); - for (Node 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 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[] segments = (Segment[]) - new Segment[DEFAULT_CONCURRENCY_LEVEL]; - for (int i = 0; i < segments.length; ++i) - segments[i] = new Segment(LOAD_FACTOR); - s.putFields().put("segments", segments); - s.putFields().put("segmentShift", segmentShift); - s.putFields().put("segmentMask", segmentMask); - s.writeFields(); - - Node[] t; - if ((t = table) != null) { - Traverser it = new Traverser(t, t.length, 0, t.length); - for (Node 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 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(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[] tab = (Node[])new Node[n]; - int mask = n - 1; - while (p != null) { - int j = p.hash & mask; - Node next = p.next; - Node 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[] tab = table; - for (int i = 0; i < tab.length; ++i) { - int c = 0; - for (Node 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 action) { - if (action == null) throw new NullPointerException(); - Node[] t; - if ((t = table) != null) { - Traverser it = new Traverser(t, t.length, 0, t.length); - for (Node p; (p = it.advance()) != null; ) { - action.accept((K)p.key, p.val); - } - } - } - - public void replaceAll(BiFunction function) { - if (function == null) throw new NullPointerException(); - Node[] t; - if ((t = table) != null) { - Traverser it = new Traverser(t, t.length, 0, t.length); - for (Node 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 @@ public class ConcurrentHashMap extends AbstractMap * of all (key, value) pairs * @since 1.8 */ - public double reduceToDoubleIn(long parallelismThreshold, - ToDoubleBiFunction transformer, - double basis, - DoubleBinaryOperator reducer) { + public double reduceToDouble(long parallelismThreshold, + ToDoubleBiFunction transformer, + double basis, + DoubleBinaryOperator reducer) { if (transformer == null || reducer == null) throw new NullPointerException(); return new MapReduceMappingsToDoubleTask @@ -4104,6 +4296,7 @@ public class ConcurrentHashMap extends AbstractMap return (i == n) ? r : Arrays.copyOf(r, i); } + @SuppressWarnings("unchecked") public final T[] toArray(T[] a) { long sz = map.mappingCount(); if (sz > MAX_ARRAY_SIZE) @@ -4202,6 +4395,7 @@ public class ConcurrentHashMap extends AbstractMap * {@link #keySet(Object) keySet(V)}, * {@link #newKeySet() newKeySet()}, * {@link #newKeySet(int) newKeySet(int)}. + * * @since 1.8 */ public static class KeySetView extends CollectionView @@ -4263,7 +4457,7 @@ public class ConcurrentHashMap extends AbstractMap 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 @@ public class ConcurrentHashMap extends AbstractMap 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 @@ public class ConcurrentHashMap extends AbstractMap if ((t = map.table) != null) { Traverser it = new Traverser(t, t.length, 0, t.length); for (Node p; (p = it.advance()) != null; ) - action.accept((K)p.key); + action.accept(p.key); } } } @@ -4418,7 +4612,7 @@ public class ConcurrentHashMap extends AbstractMap } public boolean add(Entry e) { - return map.internalPut(e.getKey(), e.getValue(), false) == null; + return map.putVal(e.getKey(), e.getValue(), false) == null; } public boolean addAll(Collection> c) { @@ -4463,7 +4657,7 @@ public class ConcurrentHashMap extends AbstractMap if ((t = map.table) != null) { Traverser it = new Traverser(t, t.length, 0, t.length); for (Node p; (p = it.advance()) != null; ) - action.accept(new MapEntry((K)p.key, p.val, map)); + action.accept(new MapEntry(p.key, p.val, map)); } } @@ -4506,23 +4700,25 @@ public class ConcurrentHashMap extends AbstractMap if ((e = next) != null) e = e.next; for (;;) { - Node[] t; int i, n; Object ek; + Node[] 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)ek).first; - else { - tab = (Node[])ek; + if (e instanceof ForwardingNode) { + tab = ((ForwardingNode)e).nextTable; e = null; continue; } + else if (e instanceof TreeBin) + e = ((TreeBin)e).first; + else + e = null; } if ((index += baseSize) >= n) - index = ++baseIndex; + index = ++baseIndex; // visit upper slots if present } } } @@ -4534,7 +4730,7 @@ public class ConcurrentHashMap extends AbstractMap * 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 extends BulkTask { final Consumer action; @@ -4555,12 +4751,13 @@ public class ConcurrentHashMap extends AbstractMap action).fork(); } for (Node p; (p = advance()) != null;) - action.accept((K)p.key); + action.accept(p.key); propagateCompletion(); } } } + @SuppressWarnings("serial") static final class ForEachValueTask extends BulkTask { final Consumer action; @@ -4587,6 +4784,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class ForEachEntryTask extends BulkTask { final Consumer> action; @@ -4613,6 +4811,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class ForEachMappingTask extends BulkTask { final BiConsumer action; @@ -4633,12 +4832,13 @@ public class ConcurrentHashMap extends AbstractMap action).fork(); } for (Node p; (p = advance()) != null; ) - action.accept((K)p.key, p.val); + action.accept(p.key, p.val); propagateCompletion(); } } } + @SuppressWarnings("serial") static final class ForEachTransformedKeyTask extends BulkTask { final Function transformer; @@ -4663,7 +4863,7 @@ public class ConcurrentHashMap extends AbstractMap } for (Node 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 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class ForEachTransformedValueTask extends BulkTask { final Function transformer; @@ -4703,6 +4904,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class ForEachTransformedEntryTask extends BulkTask { final Function, ? extends U> transformer; @@ -4735,6 +4937,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class ForEachTransformedMappingTask extends BulkTask { final BiFunction transformer; @@ -4760,7 +4963,7 @@ public class ConcurrentHashMap extends AbstractMap } for (Node 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 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class SearchKeysTask extends BulkTask { final Function searchFunction; @@ -4801,7 +5005,7 @@ public class ConcurrentHashMap extends AbstractMap 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 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class SearchValuesTask extends BulkTask { final Function searchFunction; @@ -4854,6 +5059,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class SearchEntriesTask extends BulkTask { final Function, ? extends U> searchFunction; @@ -4897,6 +5103,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class SearchMappingsTask extends BulkTask { final BiFunction searchFunction; @@ -4930,7 +5137,7 @@ public class ConcurrentHashMap extends AbstractMap 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 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class ReduceKeysTask extends BulkTask { final BiFunction reducer; @@ -4965,13 +5173,13 @@ public class ConcurrentHashMap extends AbstractMap } K r = null; for (Node 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 + @SuppressWarnings("unchecked") ReduceKeysTask t = (ReduceKeysTask)c, s = t.rights; while (s != null) { @@ -4986,6 +5194,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class ReduceValuesTask extends BulkTask { final BiFunction reducer; @@ -5017,7 +5226,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - ReduceValuesTask + @SuppressWarnings("unchecked") ReduceValuesTask t = (ReduceValuesTask)c, s = t.rights; while (s != null) { @@ -5032,6 +5241,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class ReduceEntriesTask extends BulkTask> { final BiFunction, Map.Entry, ? extends Map.Entry> reducer; @@ -5061,7 +5271,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - ReduceEntriesTask + @SuppressWarnings("unchecked") ReduceEntriesTask t = (ReduceEntriesTask)c, s = t.rights; while (s != null) { @@ -5076,6 +5286,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceKeysTask extends BulkTask { final Function transformer; @@ -5107,13 +5318,13 @@ public class ConcurrentHashMap extends AbstractMap U r = null; for (Node 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 + @SuppressWarnings("unchecked") MapReduceKeysTask t = (MapReduceKeysTask)c, s = t.rights; while (s != null) { @@ -5128,6 +5339,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceValuesTask extends BulkTask { final Function transformer; @@ -5165,7 +5377,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceValuesTask + @SuppressWarnings("unchecked") MapReduceValuesTask t = (MapReduceValuesTask)c, s = t.rights; while (s != null) { @@ -5180,6 +5392,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceEntriesTask extends BulkTask { final Function, ? extends U> transformer; @@ -5217,7 +5430,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceEntriesTask + @SuppressWarnings("unchecked") MapReduceEntriesTask t = (MapReduceEntriesTask)c, s = t.rights; while (s != null) { @@ -5232,6 +5445,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceMappingsTask extends BulkTask { final BiFunction transformer; @@ -5263,13 +5477,13 @@ public class ConcurrentHashMap extends AbstractMap U r = null; for (Node 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 + @SuppressWarnings("unchecked") MapReduceMappingsTask t = (MapReduceMappingsTask)c, s = t.rights; while (s != null) { @@ -5284,6 +5498,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask extends BulkTask { final ToDoubleFunction transformer; @@ -5316,11 +5531,11 @@ public class ConcurrentHashMap extends AbstractMap rights, transformer, r, reducer)).fork(); } for (Node 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 + @SuppressWarnings("unchecked") MapReduceKeysToDoubleTask t = (MapReduceKeysToDoubleTask)c, s = t.rights; while (s != null) { @@ -5332,6 +5547,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask extends BulkTask { final ToDoubleFunction transformer; @@ -5368,7 +5584,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceValuesToDoubleTask + @SuppressWarnings("unchecked") MapReduceValuesToDoubleTask t = (MapReduceValuesToDoubleTask)c, s = t.rights; while (s != null) { @@ -5380,6 +5596,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask extends BulkTask { final ToDoubleFunction> transformer; @@ -5416,7 +5633,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceEntriesToDoubleTask + @SuppressWarnings("unchecked") MapReduceEntriesToDoubleTask t = (MapReduceEntriesToDoubleTask)c, s = t.rights; while (s != null) { @@ -5428,6 +5645,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask extends BulkTask { final ToDoubleBiFunction transformer; @@ -5460,11 +5678,11 @@ public class ConcurrentHashMap extends AbstractMap rights, transformer, r, reducer)).fork(); } for (Node 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 + @SuppressWarnings("unchecked") MapReduceMappingsToDoubleTask t = (MapReduceMappingsToDoubleTask)c, s = t.rights; while (s != null) { @@ -5476,6 +5694,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceKeysToLongTask extends BulkTask { final ToLongFunction transformer; @@ -5508,11 +5727,11 @@ public class ConcurrentHashMap extends AbstractMap rights, transformer, r, reducer)).fork(); } for (Node 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 + @SuppressWarnings("unchecked") MapReduceKeysToLongTask t = (MapReduceKeysToLongTask)c, s = t.rights; while (s != null) { @@ -5524,6 +5743,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceValuesToLongTask extends BulkTask { final ToLongFunction transformer; @@ -5560,7 +5780,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceValuesToLongTask + @SuppressWarnings("unchecked") MapReduceValuesToLongTask t = (MapReduceValuesToLongTask)c, s = t.rights; while (s != null) { @@ -5572,6 +5792,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask extends BulkTask { final ToLongFunction> transformer; @@ -5608,7 +5829,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceEntriesToLongTask + @SuppressWarnings("unchecked") MapReduceEntriesToLongTask t = (MapReduceEntriesToLongTask)c, s = t.rights; while (s != null) { @@ -5620,6 +5841,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask extends BulkTask { final ToLongBiFunction transformer; @@ -5652,11 +5874,11 @@ public class ConcurrentHashMap extends AbstractMap rights, transformer, r, reducer)).fork(); } for (Node 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 + @SuppressWarnings("unchecked") MapReduceMappingsToLongTask t = (MapReduceMappingsToLongTask)c, s = t.rights; while (s != null) { @@ -5668,6 +5890,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceKeysToIntTask extends BulkTask { final ToIntFunction transformer; @@ -5700,11 +5923,11 @@ public class ConcurrentHashMap extends AbstractMap rights, transformer, r, reducer)).fork(); } for (Node 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 + @SuppressWarnings("unchecked") MapReduceKeysToIntTask t = (MapReduceKeysToIntTask)c, s = t.rights; while (s != null) { @@ -5716,6 +5939,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceValuesToIntTask extends BulkTask { final ToIntFunction transformer; @@ -5752,7 +5976,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceValuesToIntTask + @SuppressWarnings("unchecked") MapReduceValuesToIntTask t = (MapReduceValuesToIntTask)c, s = t.rights; while (s != null) { @@ -5764,6 +5988,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask extends BulkTask { final ToIntFunction> transformer; @@ -5800,7 +6025,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceEntriesToIntTask + @SuppressWarnings("unchecked") MapReduceEntriesToIntTask t = (MapReduceEntriesToIntTask)c, s = t.rights; while (s != null) { @@ -5812,6 +6037,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask extends BulkTask { final ToIntBiFunction transformer; @@ -5844,11 +6070,11 @@ public class ConcurrentHashMap extends AbstractMap rights, transformer, r, reducer)).fork(); } for (Node 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 + @SuppressWarnings("unchecked") MapReduceMappingsToIntTask t = (MapReduceMappingsToIntTask)c, s = t.rights; while (s != null) { @@ -5885,12 +6111,12 @@ public class ConcurrentHashMap extends AbstractMap (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); diff --git a/jdk/src/share/classes/java/util/concurrent/ConcurrentMap.java b/jdk/src/share/classes/java/util/concurrent/ConcurrentMap.java index f0c42bb321a..6c902fa6868 100644 --- a/jdk/src/share/classes/java/util/concurrent/ConcurrentMap.java +++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentMap.java @@ -39,8 +39,8 @@ import java.util.Objects; 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. * *

      Memory consistency effects: As with other concurrent * collections, actions in a thread prior to placing an object into a @@ -89,11 +89,11 @@ public interface ConcurrentMap extends Map { * @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 - * null if there was no mapping for the key. - * (A null return can also indicate that the map - * previously associated null 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 put 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 diff --git a/jdk/src/share/classes/java/util/concurrent/ConcurrentNavigableMap.java b/jdk/src/share/classes/java/util/concurrent/ConcurrentNavigableMap.java index 1d096f0c52d..7f54eab7b4e 100644 --- a/jdk/src/share/classes/java/util/concurrent/ConcurrentNavigableMap.java +++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentNavigableMap.java @@ -101,7 +101,7 @@ public interface ConcurrentNavigableMap * reflected in the descending map, and vice-versa. * *

      The returned map has an ordering equivalent to - * {@link Collections#reverseOrder(Comparator) Collections.reverseOrder}(comparator()). + * {@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}. * From 5a354fd6c7480b0edda3db85b4ea4c9c9e95d380 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Thu, 11 Jul 2013 18:50:25 +0530 Subject: [PATCH 051/123] 7187144: JavaDoc for ScriptEngineFactory.getProgram() contains an error Reviewed-by: mcimadamore, jlaskey, hannesw, attila --- .../share/classes/javax/script/ScriptEngineFactory.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/jdk/src/share/classes/javax/script/ScriptEngineFactory.java b/jdk/src/share/classes/javax/script/ScriptEngineFactory.java index 298b4ad7b41..e2596f0da1a 100644 --- a/jdk/src/share/classes/javax/script/ScriptEngineFactory.java +++ b/jdk/src/share/classes/javax/script/ScriptEngineFactory.java @@ -196,18 +196,17 @@ public interface ScriptEngineFactory { /** - * Returns A valid scripting language executable progam with given statements. + * Returns a valid scripting language executable progam with given statements. * For instance an implementation for a PHP engine might be: *

      *

      {@code
            * public String getProgram(String... statements) {
      -     *      $retval = "";
      -     *
      +     *      return retval += "?>";
            * }
            * }
      * From a4223b53c16aa70cc7894f3ecb9732f4346ebd12 Mon Sep 17 00:00:00 2001 From: Valerie Peng Date: Thu, 11 Jul 2013 11:43:23 -0700 Subject: [PATCH 052/123] 8020321: Problem in PKCS11 regression test TestRSAKeyLength Corrected the "isValidKeyLength" array Reviewed-by: xuelei --- .../sun/security/pkcs11/Signature/TestRSAKeyLength.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/jdk/test/sun/security/pkcs11/Signature/TestRSAKeyLength.java b/jdk/test/sun/security/pkcs11/Signature/TestRSAKeyLength.java index 81309213b35..9d6f62a8a1c 100644 --- a/jdk/test/sun/security/pkcs11/Signature/TestRSAKeyLength.java +++ b/jdk/test/sun/security/pkcs11/Signature/TestRSAKeyLength.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,7 +36,7 @@ public class TestRSAKeyLength extends PKCS11Test { main(new TestRSAKeyLength()); } public void main(Provider p) throws Exception { - boolean isValidKeyLength[] = { true, true, false, false }; + boolean isValidKeyLength[] = { true, true, true, false, false }; String algos[] = { "SHA1withRSA", "SHA224withRSA", "SHA256withRSA", "SHA384withRSA", "SHA512withRSA" }; KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", p); @@ -45,6 +45,10 @@ public class TestRSAKeyLength extends PKCS11Test { PrivateKey privKey = kp.getPrivate(); PublicKey pubKey = kp.getPublic(); + if (algos.length != isValidKeyLength.length) { + throw new Exception("Internal Error: number of test algos" + + " and results length mismatch!"); + } for (int i = 0; i < algos.length; i++) { Signature sig = Signature.getInstance(algos[i], p); System.out.println("Testing RSA signature " + algos[i]); From ec6cb721e1ff4e4d43bc89f87986ab52ffe0284d Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Thu, 11 Jul 2013 21:11:03 +0200 Subject: [PATCH 053/123] 8010285: Enforce the requirement of Management Interfaces being public Reviewed-by: sjiang, dfuchs, mchung --- .../com/sun/jmx/mbeanserver/Introspector.java | 52 +++-- .../sun/jmx/mbeanserver/MBeanAnalyzer.java | 7 +- .../share/classes/javax/management/JMX.java | 42 ++-- .../MBeanServerInvocationHandler.java | 2 +- .../classes/javax/management/MXBean.java | 8 +- .../classes/javax/management/package.html | 4 +- .../management/ManagementFactoryHelper.java | 26 +-- .../MBeanServer/MBeanFallbackTest.java | 94 +++++++++ .../management/MBeanServer/MBeanTest.java | 158 +++++++++++++++ .../management/mxbean/MXBeanFallbackTest.java | 85 ++++++++ .../javax/management/mxbean/MXBeanTest.java | 54 ++++- .../proxy/JMXProxyFallbackTest.java | 100 +++++++++ .../javax/management/proxy/JMXProxyTest.java | 191 ++++++++++++++++++ 13 files changed, 768 insertions(+), 55 deletions(-) create mode 100644 jdk/test/javax/management/MBeanServer/MBeanFallbackTest.java create mode 100644 jdk/test/javax/management/MBeanServer/MBeanTest.java create mode 100644 jdk/test/javax/management/mxbean/MXBeanFallbackTest.java create mode 100644 jdk/test/javax/management/proxy/JMXProxyFallbackTest.java create mode 100644 jdk/test/javax/management/proxy/JMXProxyTest.java diff --git a/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java b/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java index 732c280f7dd..0e08177d7f2 100644 --- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java +++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java @@ -52,6 +52,7 @@ import javax.management.NotCompliantMBeanException; 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 @@ import sun.reflect.misc.ReflectUtil; * @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 @@ public class Introspector { 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 @@ public class Introspector { * not a JMX compliant Standard MBean. */ public static Class getStandardMBeanInterface(Class baseClass) - throws NotCompliantMBeanException { - Class current = baseClass; - Class 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 current = baseClass; + Class 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 @@ public class Introspector { } 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; diff --git a/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java b/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java index 5e5375d0974..d7d06a04a73 100644 --- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java +++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java @@ -28,6 +28,8 @@ package com.sun.jmx.mbeanserver; 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 @@ import javax.management.NotCompliantMBeanException; * @since 1.6 */ class MBeanAnalyzer { - static interface MBeanVisitor { public void visitAttribute(String attributeName, M getter, @@ -107,6 +108,10 @@ class MBeanAnalyzer { 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 { diff --git a/jdk/src/share/classes/javax/management/JMX.java b/jdk/src/share/classes/javax/management/JMX.java index 7f8cc411964..fe5d9093ac2 100644 --- a/jdk/src/share/classes/javax/management/JMX.java +++ b/jdk/src/share/classes/javax/management/JMX.java @@ -160,6 +160,10 @@ public class JMX { * example, then the return type is {@code MyMBean}. * * @return the new proxy instance. + * + * @throws IllegalArgumentException if {@code interfaceClass} is not + * a compliant MBean + * interface */ public static T newMBeanProxy(MBeanServerConnection connection, ObjectName objectName, @@ -200,6 +204,10 @@ public class JMX { * example, then the return type is {@code MyMBean}. * * @return the new proxy instance. + * + * @throws IllegalArgumentException if {@code interfaceClass} is not + * a compliant MBean + * interface */ public static T newMBeanProxy(MBeanServerConnection connection, ObjectName objectName, @@ -298,6 +306,9 @@ public class JMX { * example, then the return type is {@code MyMXBean}. * * @return the new proxy instance. + * + * @throws IllegalArgumentException if {@code interfaceClass} is not + * a {@link javax.management.MXBean compliant MXBean interface} */ public static T newMXBeanProxy(MBeanServerConnection connection, ObjectName objectName, @@ -338,6 +349,9 @@ public class JMX { * example, then the return type is {@code MyMXBean}. * * @return the new proxy instance. + * + * @throws IllegalArgumentException if {@code interfaceClass} is not + * a {@link javax.management.MXBean compliant MXBean interface} */ public static T newMXBeanProxy(MBeanServerConnection connection, ObjectName objectName, @@ -348,21 +362,25 @@ public class JMX { /** *

      Test whether an interface is an MXBean interface. - * An interface is an MXBean interface if it is annotated - * {@link MXBean @MXBean} or {@code @MXBean(true)} + * An interface is an MXBean interface if it is public, + * annotated {@link MXBean @MXBean} or {@code @MXBean(true)} * or if it does not have an {@code @MXBean} annotation * and its name ends with "{@code MXBean}".

      * * @param interfaceClass The candidate interface. * - * @return true if {@code interfaceClass} is an interface and - * meets the conditions described. + * @return true if {@code interfaceClass} is a + * {@link javax.management.MXBean compliant MXBean interface} * * @throws NullPointerException if {@code interfaceClass} is null. */ public static boolean isMXBeanInterface(Class interfaceClass) { if (!interfaceClass.isInterface()) return false; + if (!Modifier.isPublic(interfaceClass.getModifiers()) && + !Introspector.ALLOW_NONPUBLIC_MBEAN) { + return false; + } MXBean a = interfaceClass.getAnnotation(MXBean.class); if (a != null) return a.value(); @@ -389,9 +407,6 @@ public class JMX { boolean notificationEmitter, boolean isMXBean) { - if (System.getSecurityManager() != null) { - checkProxyInterface(interfaceClass); - } try { if (isMXBean) { // Check interface for MXBean compliance @@ -419,17 +434,4 @@ public class JMX { handler); return interfaceClass.cast(proxy); } - - /** - * Checks for the M(X)Bean proxy interface being public and not restricted - * @param interfaceClass MBean proxy interface - * @throws SecurityException when the proxy interface comes from a restricted - * package or is not public - */ - private static void checkProxyInterface(Class interfaceClass) { - if (!Modifier.isPublic(interfaceClass.getModifiers())) { - throw new SecurityException("mbean proxy interface non-public"); - } - ReflectUtil.checkPackageAccess(interfaceClass); - } } diff --git a/jdk/src/share/classes/javax/management/MBeanServerInvocationHandler.java b/jdk/src/share/classes/javax/management/MBeanServerInvocationHandler.java index bc174fb303f..485dec8b59c 100644 --- a/jdk/src/share/classes/javax/management/MBeanServerInvocationHandler.java +++ b/jdk/src/share/classes/javax/management/MBeanServerInvocationHandler.java @@ -225,7 +225,7 @@ public class MBeanServerInvocationHandler implements InvocationHandler { * * @return the new proxy instance. * - * @see JMX#newMBeanProxy(MBeanServerConnection, ObjectName, Class) + * @see JMX#newMBeanProxy(MBeanServerConnection, ObjectName, Class, boolean) */ public static T newProxyInstance(MBeanServerConnection connection, ObjectName objectName, diff --git a/jdk/src/share/classes/javax/management/MXBean.java b/jdk/src/share/classes/javax/management/MXBean.java index 4ff10d360af..e4c920651bc 100644 --- a/jdk/src/share/classes/javax/management/MXBean.java +++ b/jdk/src/share/classes/javax/management/MXBean.java @@ -54,9 +54,9 @@ import javax.management.openmbean.TabularType; /**

      Annotation to mark an interface explicitly as being an MXBean interface, or as not being an MXBean interface. By default, an - interface is an MXBean interface if its name ends with {@code - MXBean}, as in {@code SomethingMXBean}. The following interfaces - are MXBean interfaces:

      + interface is an MXBean interface if it is public and its name ends + with {@code MXBean}, as in {@code SomethingMXBean}. The following + interfaces are MXBean interfaces:

           public interface WhatsitMXBean {}
      @@ -71,6 +71,8 @@ import javax.management.openmbean.TabularType;
           

      The following interfaces are not MXBean interfaces:

      +    interface NonPublicInterfaceNotMXBean{}
      +
           public interface Whatsit3Interface{}
       
           @MXBean(false)
      diff --git a/jdk/src/share/classes/javax/management/package.html b/jdk/src/share/classes/javax/management/package.html
      index 4c9b012cf22..9cd9ef81766 100644
      --- a/jdk/src/share/classes/javax/management/package.html
      +++ b/jdk/src/share/classes/javax/management/package.html
      @@ -53,8 +53,8 @@ questions.
       
               

      The fundamental notion of the JMX API is the MBean. An MBean is a named managed object representing a - resource. It has a management interface consisting - of:

      + resource. It has a management interface + which must be public and consist of:

      • named and typed attributes that can be read and/or diff --git a/jdk/src/share/classes/sun/management/ManagementFactoryHelper.java b/jdk/src/share/classes/sun/management/ManagementFactoryHelper.java index 6e875a27914..43079e986d6 100644 --- a/jdk/src/share/classes/sun/management/ManagementFactoryHelper.java +++ b/jdk/src/share/classes/sun/management/ManagementFactoryHelper.java @@ -147,18 +147,20 @@ public class ManagementFactoryHelper { } } - // The logging MXBean object is an instance of - // PlatformLoggingMXBean and java.util.logging.LoggingMXBean - // but it can't directly implement two MXBean interfaces - // as a compliant MXBean implements exactly one MXBean interface, - // or if it implements one interface that is a subinterface of - // all the others; otherwise, it is a non-compliant MXBean - // and MBeanServer will throw NotCompliantMBeanException. - // See the Definition of an MXBean section in javax.management.MXBean spec. - // - // To create a compliant logging MXBean, define a LoggingMXBean interface - // that extend PlatformLoggingMXBean and j.u.l.LoggingMXBean - interface LoggingMXBean + /** + * The logging MXBean object is an instance of + * PlatformLoggingMXBean and java.util.logging.LoggingMXBean + * but it can't directly implement two MXBean interfaces + * as a compliant MXBean implements exactly one MXBean interface, + * or if it implements one interface that is a subinterface of + * all the others; otherwise, it is a non-compliant MXBean + * and MBeanServer will throw NotCompliantMBeanException. + * See the Definition of an MXBean section in javax.management.MXBean spec. + * + * To create a compliant logging MXBean, define a LoggingMXBean interface + * that extend PlatformLoggingMXBean and j.u.l.LoggingMXBean + */ + public interface LoggingMXBean extends PlatformLoggingMXBean, java.util.logging.LoggingMXBean { } diff --git a/jdk/test/javax/management/MBeanServer/MBeanFallbackTest.java b/jdk/test/javax/management/MBeanServer/MBeanFallbackTest.java new file mode 100644 index 00000000000..dcb5e1803a4 --- /dev/null +++ b/jdk/test/javax/management/MBeanServer/MBeanFallbackTest.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.management.MBeanServer; +import javax.management.MBeanServerFactory; +import javax.management.NotCompliantMBeanException; +import javax.management.ObjectName; + +/* + * @test + * @bug 8010285 + * @summary Test fallback for private MBean interfaces. + * It needs to be a separate class because the "jdk.jmx.mbeans.allowNonPublic" + * system property must be set before c.s.j.m.MBeanAnalyzer has been loaded. + * @author Jaroslav Bachorik + * @run clean MBeanFallbackTest + * @run build MBeanFallbackTest + * @run main MBeanFallbackTest + */ +public class MBeanFallbackTest { + private static interface PrivateMBean { + public int[] getInts(); + } + + public static class Private implements PrivateMBean { + public int[] getInts() { + return new int[]{1,2,3}; + } + } + + private static int failures = 0; + + public static void main(String[] args) throws Exception { + System.setProperty("jdk.jmx.mbeans.allowNonPublic", "true"); + testPrivate(PrivateMBean.class, new Private()); + + if (failures == 0) + System.out.println("Test passed"); + else + throw new Exception("TEST FAILURES: " + failures); + } + + private static void fail(String msg) { + failures++; + System.out.println("FAIL: " + msg); + } + + private static void success(String msg) { + System.out.println("OK: " + msg); + } + + private static void testPrivate(Class iface, Object bean) throws Exception { + try { + System.out.println("Registering a private MBean " + + iface.getName() + " ..."); + + MBeanServer mbs = MBeanServerFactory.newMBeanServer(); + ObjectName on = new ObjectName("test:type=Compliant"); + + mbs.registerMBean(bean, on); + success("Registered a private MBean - " + iface.getName()); + } catch (Exception e) { + Throwable t = e; + while (t != null && !(t instanceof NotCompliantMBeanException)) { + t = t.getCause(); + } + if (t != null) { + fail("MBean not registered"); + } else { + throw e; + } + } + } +} diff --git a/jdk/test/javax/management/MBeanServer/MBeanTest.java b/jdk/test/javax/management/MBeanServer/MBeanTest.java new file mode 100644 index 00000000000..1ac50573e5f --- /dev/null +++ b/jdk/test/javax/management/MBeanServer/MBeanTest.java @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.management.MBeanServer; +import javax.management.MBeanServerFactory; +import javax.management.NotCompliantMBeanException; +import javax.management.ObjectName; + +/* + * @test + * @bug 8010285 + * @summary General MBean test. + * @author Jaroslav Bachorik + * @run clean MBeanTest + * @run build MBeanTest + * @run main MBeanTest + */ +public class MBeanTest { + private static interface PrivateMBean { + public int[] getInts(); + } + + public static class Private implements PrivateMBean { + public int[] getInts() { + return new int[]{1,2,3}; + } + } + + public static interface NonCompliantMBean { + public boolean getInt(); + public boolean isInt(); + public void setInt(int a); + public void setInt(long b); + } + + public static class NonCompliant implements NonCompliantMBean { + public boolean getInt() { + return false; + } + + public boolean isInt() { + return true; + } + + public void setInt(int a) { + } + + public void setInt(long b) { + } + } + + public static interface CompliantMBean { + public boolean isFlag(); + public int getInt(); + public void setInt(int value); + } + + public static class Compliant implements CompliantMBean { + public boolean isFlag() { + return false; + } + + public int getInt() { + return 1; + } + + public void setInt(int value) { + } + } + + private static int failures = 0; + + public static void main(String[] args) throws Exception { + testCompliant(CompliantMBean.class, new Compliant()); + testNonCompliant(PrivateMBean.class, new Private()); + testNonCompliant(NonCompliantMBean.class, new NonCompliant()); + + if (failures == 0) + System.out.println("Test passed"); + else + throw new Exception("TEST FAILURES: " + failures); + } + + private static void fail(String msg) { + failures++; + System.out.println("FAIL: " + msg); + } + + private static void success(String msg) { + System.out.println("OK: " + msg); + } + + private static void testNonCompliant(Class iface, Object bean) throws Exception { + try { + System.out.println("Registering a non-compliant MBean " + + iface.getName() + " ..."); + + MBeanServer mbs = MBeanServerFactory.newMBeanServer(); + ObjectName on = new ObjectName("test:type=NonCompliant"); + + mbs.registerMBean(bean, on); + + fail("Registered a non-compliant MBean - " + iface.getName()); + } catch (Exception e) { + Throwable t = e; + while (t != null && !(t instanceof NotCompliantMBeanException)) { + t = t.getCause(); + } + if (t != null) { + success("MBean not registered"); + } else { + throw e; + } + } + } + private static void testCompliant(Class iface, Object bean) throws Exception { + try { + System.out.println("Registering a compliant MBean " + + iface.getName() + " ..."); + + MBeanServer mbs = MBeanServerFactory.newMBeanServer(); + ObjectName on = new ObjectName("test:type=Compliant"); + + mbs.registerMBean(bean, on); + success("Registered a compliant MBean - " + iface.getName()); + } catch (Exception e) { + Throwable t = e; + while (t != null && !(t instanceof NotCompliantMBeanException)) { + t = t.getCause(); + } + if (t != null) { + fail("MBean not registered"); + } else { + throw e; + } + } + } +} diff --git a/jdk/test/javax/management/mxbean/MXBeanFallbackTest.java b/jdk/test/javax/management/mxbean/MXBeanFallbackTest.java new file mode 100644 index 00000000000..388ffc9373d --- /dev/null +++ b/jdk/test/javax/management/mxbean/MXBeanFallbackTest.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8010285 + * @summary Test for the private MXBean interface fallback. + * It needs to be a separate class because the "jdk.jmx.mbeans.allowNonPublic" + * system property must be set before c.s.j.m.MBeanAnalyzer has been loaded. + * @author Jaroslav Bachorik + * @run clean MXBeanFallbackTest + * @run build MXBeanFallbackTest + * @run main MXBeanFallbackTest + */ + +import javax.management.MBeanServer; +import javax.management.MBeanServerFactory; +import javax.management.NotCompliantMBeanException; +import javax.management.ObjectName; + +public class MXBeanFallbackTest { + public static void main(String[] args) throws Exception { + System.setProperty("jdk.jmx.mbeans.allowNonPublic", "true"); + testPrivateMXBean("Private", new Private()); + + if (failures == 0) + System.out.println("Test passed"); + else + throw new Exception("TEST FAILURES: " + failures); + } + + private static int failures = 0; + + private static interface PrivateMXBean { + public int[] getInts(); + } + + public static class Private implements PrivateMXBean { + public int[] getInts() { + return new int[]{1,2,3}; + } + } + + private static void testPrivateMXBean(String type, Object bean) throws Exception { + System.out.println(type + " MXBean test..."); + MBeanServer mbs = MBeanServerFactory.newMBeanServer(); + ObjectName on = new ObjectName("test:type=" + type); + try { + mbs.registerMBean(bean, on); + success("Private MXBean registered"); + } catch (NotCompliantMBeanException e) { + failure("Failed to register the private MXBean - " + + bean.getClass().getInterfaces()[0].getName()); + } + } + + private static void success(String what) { + System.out.println("OK: " + what); + } + + private static void failure(String what) { + System.out.println("FAILED: " + what); + failures++; + } +} diff --git a/jdk/test/javax/management/mxbean/MXBeanTest.java b/jdk/test/javax/management/mxbean/MXBeanTest.java index 7d1c79c9597..ecafe49adbb 100644 --- a/jdk/test/javax/management/mxbean/MXBeanTest.java +++ b/jdk/test/javax/management/mxbean/MXBeanTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,9 +23,10 @@ /* * @test - * @bug 6175517 6278707 6318827 6305746 6392303 6600709 + * @bug 6175517 6278707 6318827 6305746 6392303 6600709 8010285 * @summary General MXBean test. * @author Eamonn McManus + * @author Jaroslav Bachorik * @run clean MXBeanTest MerlinMXBean TigerMXBean * @run build MXBeanTest MerlinMXBean TigerMXBean * @run main MXBeanTest @@ -51,6 +52,7 @@ import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.MBeanServerFactory; import javax.management.MBeanServerInvocationHandler; +import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import javax.management.StandardMBean; import javax.management.openmbean.ArrayType; @@ -75,6 +77,8 @@ public class MXBeanTest { testExplicitMXBean(); testSubclassMXBean(); testIndirectMXBean(); + testNonCompliantMXBean("Private", new Private()); + testNonCompliantMXBean("NonCompliant", new NonCompliant()); if (failures == 0) System.out.println("Test passed"); @@ -84,6 +88,39 @@ public class MXBeanTest { private static int failures = 0; + private static interface PrivateMXBean { + public int[] getInts(); + } + + public static class Private implements PrivateMXBean { + public int[] getInts() { + return new int[]{1,2,3}; + } + } + + public static interface NonCompliantMXBean { + public boolean getInt(); + public boolean isInt(); + public void setInt(int a); + public void setInt(long b); + } + + public static class NonCompliant implements NonCompliantMXBean { + public boolean getInt() { + return false; + } + + public boolean isInt() { + return true; + } + + public void setInt(int a) { + } + + public void setInt(long b) { + } + } + public static interface ExplicitMXBean { public int[] getInts(); } @@ -110,6 +147,19 @@ public class MXBeanTest { } } + private static void testNonCompliantMXBean(String type, Object bean) throws Exception { + System.out.println(type + " MXBean test..."); + MBeanServer mbs = MBeanServerFactory.newMBeanServer(); + ObjectName on = new ObjectName("test:type=" + type); + try { + mbs.registerMBean(bean, on); + failure(bean.getClass().getInterfaces()[0].getName() + " is not a compliant " + + "MXBean interface"); + } catch (NotCompliantMBeanException e) { + success("Non-compliant MXBean not registered"); + } + } + private static void testExplicitMXBean() throws Exception { System.out.println("Explicit MXBean test..."); MBeanServer mbs = MBeanServerFactory.newMBeanServer(); diff --git a/jdk/test/javax/management/proxy/JMXProxyFallbackTest.java b/jdk/test/javax/management/proxy/JMXProxyFallbackTest.java new file mode 100644 index 00000000000..d1243593c11 --- /dev/null +++ b/jdk/test/javax/management/proxy/JMXProxyFallbackTest.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.management.JMX; +import javax.management.MBeanServer; +import javax.management.MBeanServerFactory; +import javax.management.NotCompliantMBeanException; +import javax.management.ObjectName; + +/* + * @test + * @bug 8010285 + * @summary Tests the fallback for creating JMX proxies for private interfaces + * It needs to be a separate class because the "jdk.jmx.mbeans.allowNonPublic" + * system property must be set before c.s.j.m.MBeanAnalyzer has been loaded. + * @author Jaroslav Bachorik + * @run clean JMXProxyFallbackTest + * @run build JMXProxyFallbackTest + * @run main JMXProxyFallbackTest + */ +public class JMXProxyFallbackTest { + private static interface PrivateMBean { + public int[] getInts(); + } + + private static interface PrivateMXBean { + public int[] getInts(); + } + + public static class Private implements PrivateMXBean, PrivateMBean { + public int[] getInts() { + return new int[]{1,2,3}; + } + } + + private static int failures = 0; + + public static void main(String[] args) throws Exception { + System.setProperty("jdk.jmx.mbeans.allowNonPublic", "true"); + testPrivate(PrivateMBean.class); + testPrivate(PrivateMXBean.class); + + if (failures == 0) + System.out.println("Test passed"); + else + throw new Exception("TEST FAILURES: " + failures); + } + + private static void fail(String msg) { + failures++; + System.out.println("FAIL: " + msg); + } + + private static void success(String msg) { + System.out.println("OK: " + msg); + } + + private static void testPrivate(Class iface) throws Exception { + try { + System.out.println("Creating a proxy for private M(X)Bean " + + iface.getName() + " ..."); + + MBeanServer mbs = MBeanServerFactory.newMBeanServer(); + ObjectName on = new ObjectName("test:type=Proxy"); + + JMX.newMBeanProxy(mbs, on, iface); + success("Created a proxy for private M(X)Bean - " + iface.getName()); + } catch (Exception e) { + Throwable t = e; + while (t != null && !(t instanceof NotCompliantMBeanException)) { + t = t.getCause(); + } + if (t != null) { + fail("Proxy not created"); + } else { + throw e; + } + } + } +} diff --git a/jdk/test/javax/management/proxy/JMXProxyTest.java b/jdk/test/javax/management/proxy/JMXProxyTest.java new file mode 100644 index 00000000000..0eb53cdebdb --- /dev/null +++ b/jdk/test/javax/management/proxy/JMXProxyTest.java @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.management.JMX; +import javax.management.MBeanServer; +import javax.management.MBeanServerFactory; +import javax.management.NotCompliantMBeanException; +import javax.management.ObjectName; + +/* + * @test + * @bug 8010285 + * @summary Tests that javax.management.JMX creates proxies only for the + * compliant MBeans/MXBeans + * @author Jaroslav Bachorik + * @run clean JMXProxyTest + * @run build JMXProxyTest + * @run main JMXProxyTest + */ +public class JMXProxyTest { + private static interface PrivateMBean { + public int[] getInts(); + } + + private static interface PrivateMXBean { + public int[] getInts(); + } + + public static class Private implements PrivateMXBean, PrivateMBean { + public int[] getInts() { + return new int[]{1,2,3}; + } + } + + public static interface NonCompliantMBean { + public boolean getInt(); + public boolean isInt(); + public void setInt(int a); + public void setInt(long b); + } + + public static interface NonCompliantMXBean { + public boolean getInt(); + public boolean isInt(); + public void setInt(int a); + public void setInt(long b); + } + + public static class NonCompliant implements NonCompliantMXBean, NonCompliantMBean { + public boolean getInt() { + return false; + } + + public boolean isInt() { + return true; + } + + public void setInt(int a) { + } + + public void setInt(long b) { + } + } + + public static interface CompliantMBean { + public boolean isFlag(); + public int getInt(); + public void setInt(int value); + } + + public static interface CompliantMXBean { + public boolean isFlag(); + public int getInt(); + public void setInt(int value); + } + + public static class Compliant implements CompliantMXBean, CompliantMBean { + public boolean isFlag() { + return false; + } + + public int getInt() { + return 1; + } + + public void setInt(int value) { + } + } + + private static int failures = 0; + + public static void main(String[] args) throws Exception { + testCompliant(CompliantMBean.class, false); + testCompliant(CompliantMXBean.class, true); + testNonCompliant(PrivateMBean.class, false); + testNonCompliant(PrivateMXBean.class, true); + testNonCompliant(NonCompliantMBean.class, false); + testNonCompliant(NonCompliantMXBean.class, true); + + if (failures == 0) + System.out.println("Test passed"); + else + throw new Exception("TEST FAILURES: " + failures); + } + + private static void fail(String msg) { + failures++; + System.out.println("FAIL: " + msg); + } + + private static void success(String msg) { + System.out.println("OK: " + msg); + } + + private static void testNonCompliant(Class iface, boolean isMx) throws Exception { + try { + System.out.println("Creating a proxy for non-compliant " + + (isMx ? "MXBean" : "MBean") + " " + + iface.getName() + " ..."); + + MBeanServer mbs = MBeanServerFactory.newMBeanServer(); + ObjectName on = new ObjectName("test:type=Proxy"); + + if (isMx) { + JMX.newMXBeanProxy(mbs, on, iface); + } else { + JMX.newMBeanProxy(mbs, on, iface); + } + fail("Created a proxy for non-compliant " + + (isMx ? "MXBean" : "MBean") + " - " + iface.getName()); + } catch (Exception e) { + Throwable t = e; + while (t != null && !(t instanceof NotCompliantMBeanException)) { + t = t.getCause(); + } + if (t != null) { + success("Proxy not created"); + } else { + throw e; + } + } + } + private static void testCompliant(Class iface, boolean isMx) throws Exception { + try { + System.out.println("Creating a proxy for compliant " + + (isMx ? "MXBean" : "MBean") + " " + + iface.getName() + " ..."); + + MBeanServer mbs = MBeanServerFactory.newMBeanServer(); + ObjectName on = new ObjectName("test:type=Proxy"); + + if (isMx) { + JMX.newMXBeanProxy(mbs, on, iface); + } else { + JMX.newMBeanProxy(mbs, on, iface); + } + success("Created a proxy for compliant " + + (isMx ? "MXBean" : "MBean") + " - " + iface.getName()); + } catch (Exception e) { + Throwable t = e; + while (t != null && !(t instanceof NotCompliantMBeanException)) { + t = t.getCause(); + } + if (t != null) { + fail("Proxy not created"); + } else { + throw e; + } + } + } +} From 20c1572bcd04a677506514457c46ca1ce51c0e75 Mon Sep 17 00:00:00 2001 From: Kumar Srinivasan Date: Thu, 11 Jul 2013 11:14:06 -0700 Subject: [PATCH 054/123] 8019799: api/java_util/jar/Pack200 test failed with compactX profiles Reviewed-by: dholmes --- .../share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java b/jdk/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java index 5bfe096893c..9044d92b86f 100644 --- a/jdk/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java +++ b/jdk/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java @@ -134,7 +134,7 @@ public class UnpackerImpl extends TLGlobals implements Pack200.Unpacker { } else { try { (new NativeUnpack(this)).run(in0, out); - } catch (UnsatisfiedLinkError ule) { + } catch (UnsatisfiedLinkError | NoClassDefFoundError ex) { // failover to java implementation (new DoUnpack()).run(in0, out); } From 94e1bc3172d7622970ddb49a18b54722bf7f61f8 Mon Sep 17 00:00:00 2001 From: Dan Xu Date: Thu, 11 Jul 2013 13:40:25 -0700 Subject: [PATCH 055/123] 8017212: File.createTempFile requires unnecessary "read" permission Directly call FileSystem method to check a file existence. Also reviewed by tom.hawtin@oracle.com Reviewed-by: alanb --- jdk/src/share/classes/java/io/File.java | 33 +- jdk/test/java/io/File/CheckPermission.java | 379 ++++++++++++++++++ jdk/test/java/io/File/NulFile.java | 7 +- .../File/createTempFile/SpecialTempFile.java | 14 +- 4 files changed, 417 insertions(+), 16 deletions(-) create mode 100644 jdk/test/java/io/File/CheckPermission.java diff --git a/jdk/src/share/classes/java/io/File.java b/jdk/src/share/classes/java/io/File.java index 4bc75fe5099..6bab9bb21fe 100644 --- a/jdk/src/share/classes/java/io/File.java +++ b/jdk/src/share/classes/java/io/File.java @@ -1910,7 +1910,7 @@ public class File } 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 @@ public class File 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; } diff --git a/jdk/test/java/io/File/CheckPermission.java b/jdk/test/java/io/File/CheckPermission.java new file mode 100644 index 00000000000..33fffddd283 --- /dev/null +++ b/jdk/test/java/io/File/CheckPermission.java @@ -0,0 +1,379 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 8017212 + * @summary Examine methods in File.java that access the file system do the + * right permission check when a security manager exists. + * @author Dan Xu + */ + +import java.io.File; +import java.io.FilenameFilter; +import java.io.FileFilter; +import java.io.IOException; +import java.security.Permission; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class CheckPermission { + + private static final String CHECK_PERMISSION_TEST = "CheckPermissionTest"; + + public enum FileOperation { + READ, WRITE, DELETE, EXEC + } + + static class Checks { + private List permissionsChecked = new ArrayList<>(); + private Set propertiesChecked = new HashSet<>(); + + private Map> fileOperationChecked = + new EnumMap<>(FileOperation.class); + + List permissionsChecked() { + return permissionsChecked; + } + + Set propertiesChecked() { + return propertiesChecked; + } + + List fileOperationChecked(FileOperation op) { + return fileOperationChecked.get(op); + } + + void addFileOperation(FileOperation op, String file) { + List opList = fileOperationChecked.get(op); + if (opList == null) { + opList = new ArrayList<>(); + fileOperationChecked.put(op, opList); + } + opList.add(file); + } + } + + static ThreadLocal myChecks = new ThreadLocal<>(); + + static void prepare() { + myChecks.set(new Checks()); + } + + static class LoggingSecurityManager extends SecurityManager { + static void install() { + System.setSecurityManager(new LoggingSecurityManager()); + } + + private void checkFileOperation(FileOperation op, String file) { + Checks checks = myChecks.get(); + if (checks != null) + checks.addFileOperation(op, file); + } + + @Override + public void checkRead(String file) { + checkFileOperation(FileOperation.READ, file); + } + + @Override + public void checkWrite(String file) { + checkFileOperation(FileOperation.WRITE, file); + } + + @Override + public void checkDelete(String file) { + checkFileOperation(FileOperation.DELETE, file); + } + + @Override + public void checkExec(String file) { + checkFileOperation(FileOperation.EXEC, file); + } + + @Override + public void checkPermission(Permission perm) { + Checks checks = myChecks.get(); + if (checks != null) + checks.permissionsChecked().add(perm); + } + + @Override + public void checkPropertyAccess(String key) { + Checks checks = myChecks.get(); + if (checks != null) + checks.propertiesChecked().add(key); + } + } + + static void assertCheckPermission(Class type, + String name) + { + for (Permission perm : myChecks.get().permissionsChecked()) { + if (type.isInstance(perm) && perm.getName().equals(name)) + return; + } + throw new RuntimeException(type.getName() + "(\"" + name + + "\") not checked"); + } + + static void assertCheckPropertyAccess(String key) { + if (!myChecks.get().propertiesChecked().contains(key)) + throw new RuntimeException("Property " + key + " not checked"); + } + + static void assertChecked(File file, List list) { + if (list != null && !list.isEmpty()) { + for (String path : list) { + if (path.equals(file.getPath())) + return; + } + } + throw new RuntimeException("Access not checked"); + } + + static void assertNotChecked(File file, List list) { + if (list != null && !list.isEmpty()) { + for (String path : list) { + if (path.equals(file.getPath())) + throw new RuntimeException("Access checked"); + } + } + } + + static void assertCheckOperation(File file, Set ops) { + for (FileOperation op : ops) + assertChecked(file, myChecks.get().fileOperationChecked(op)); + } + + static void assertNotCheckOperation(File file, Set ops) { + for (FileOperation op : ops) + assertNotChecked(file, myChecks.get().fileOperationChecked(op)); + } + + static void assertOnlyCheckOperation(File file, + EnumSet ops) + { + assertCheckOperation(file, ops); + assertNotCheckOperation(file, EnumSet.complementOf(ops)); + } + + static File testFile, another; + + static void setup() { + testFile = new File(CHECK_PERMISSION_TEST + System.currentTimeMillis()); + if (testFile.exists()) { + testFile.delete(); + } + + another = new File(CHECK_PERMISSION_TEST + "Another" + + System.currentTimeMillis()); + if (another.exists()) { + another.delete(); + } + + LoggingSecurityManager.install(); + } + + public static void main(String[] args) throws IOException { + setup(); + + prepare(); + testFile.canRead(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.canWrite(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.exists(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.isDirectory(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.isFile(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.isHidden(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.lastModified(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.length(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.createNewFile(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.list(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.list(new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return false; + } + }); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.listFiles(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.listFiles(new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return false; + } + }); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.listFiles(new FileFilter() { + @Override + public boolean accept(File file) { + return false; + } + }); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.mkdir(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + if (testFile.exists()) { + prepare(); + testFile.mkdirs(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + } + + if (!another.exists()) { + prepare(); + another.mkdirs(); + assertOnlyCheckOperation(another, + EnumSet.of(FileOperation.READ, FileOperation.WRITE)); + } + + prepare(); + another.delete(); + assertOnlyCheckOperation(another, EnumSet.of(FileOperation.DELETE)); + + prepare(); + boolean renRst = testFile.renameTo(another); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + assertOnlyCheckOperation(another, EnumSet.of(FileOperation.WRITE)); + + if (renRst) { + if (testFile.exists()) + throw new RuntimeException(testFile + " is already renamed to " + + another); + testFile = another; + } + + prepare(); + testFile.setLastModified(0); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.setReadOnly(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.setWritable(true, true); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.setWritable(true); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.setReadable(true, true); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.setReadable(true); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.setExecutable(true, true); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.setExecutable(true); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.canExecute(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.EXEC)); + + prepare(); + testFile.getTotalSpace(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + assertCheckPermission(RuntimePermission.class, + "getFileSystemAttributes"); + + prepare(); + testFile.getFreeSpace(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + assertCheckPermission(RuntimePermission.class, + "getFileSystemAttributes"); + + prepare(); + testFile.getUsableSpace(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + assertCheckPermission(RuntimePermission.class, + "getFileSystemAttributes"); + + prepare(); + File tmpFile = File.createTempFile(CHECK_PERMISSION_TEST, null); + assertOnlyCheckOperation(tmpFile, EnumSet.of(FileOperation.WRITE)); + tmpFile.delete(); + assertCheckOperation(tmpFile, EnumSet.of(FileOperation.DELETE)); + + prepare(); + tmpFile = File.createTempFile(CHECK_PERMISSION_TEST, null, null); + assertOnlyCheckOperation(tmpFile, EnumSet.of(FileOperation.WRITE)); + tmpFile.delete(); + assertCheckOperation(tmpFile, EnumSet.of(FileOperation.DELETE)); + + prepare(); + testFile.deleteOnExit(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.DELETE)); + } +} diff --git a/jdk/test/java/io/File/NulFile.java b/jdk/test/java/io/File/NulFile.java index c7cff6aa81d..4b83d64791e 100644 --- a/jdk/test/java/io/File/NulFile.java +++ b/jdk/test/java/io/File/NulFile.java @@ -612,8 +612,13 @@ public class NulFile { try { File.createTempFile(prefix, suffix, directory); } catch (IOException ex) { - if (ExceptionMsg.equals(ex.getMessage())) + String err = "Unable to create temporary file"; + if (err.equals(ex.getMessage())) exceptionThrown = true; + else { + throw new RuntimeException("Get IOException with message, " + + ex.getMessage() + ", expect message, "+ err); + } } } if (!exceptionThrown) { diff --git a/jdk/test/java/io/File/createTempFile/SpecialTempFile.java b/jdk/test/java/io/File/createTempFile/SpecialTempFile.java index 20d6ed8cd82..9a4cc01c5ff 100644 --- a/jdk/test/java/io/File/createTempFile/SpecialTempFile.java +++ b/jdk/test/java/io/File/createTempFile/SpecialTempFile.java @@ -23,9 +23,8 @@ /* * @test - * @bug 8013827 8011950 + * @bug 8013827 8011950 8017212 * @summary Check whether File.createTempFile can handle special parameters - * on Windows platforms * @author Dan Xu */ @@ -64,6 +63,17 @@ public class SpecialTempFile { } public static void main(String[] args) throws Exception { + // Common test + final String name = "SpecialTempFile"; + File f = new File(System.getProperty("java.io.tmpdir"), name); + if (!f.exists()) { + f.createNewFile(); + } + String[] nulPre = { name + "\u0000" }; + String[] nulSuf = { ".test" }; + test("NulName", nulPre, nulSuf); + + // Windows tests if (!System.getProperty("os.name").startsWith("Windows")) return; From b2aec6eda349cb03471fadd911d7959d00353243 Mon Sep 17 00:00:00 2001 From: Thomas Schatzl Date: Mon, 8 Jul 2013 14:05:59 +0200 Subject: [PATCH 056/123] 8014890: (ref) Reference queues may return more entries than expected When enqueuing references check whether the j.l.r.Reference has already been enqeued or removed in the lock. Do not enqueue them again. This occurs because multiple threads may try to enqueue the same j.l.r.Reference at the same time. Reviewed-by: mchung, dholmes, plevart, shade --- .../classes/java/lang/ref/Reference.java | 6 +- .../classes/java/lang/ref/ReferenceQueue.java | 32 ++++---- jdk/test/java/lang/ref/EnqueuePollRace.java | 73 +++++++++++++++++++ 3 files changed, 93 insertions(+), 18 deletions(-) create mode 100644 jdk/test/java/lang/ref/EnqueuePollRace.java diff --git a/jdk/src/share/classes/java/lang/ref/Reference.java b/jdk/src/share/classes/java/lang/ref/Reference.java index bc24e9df026..1cdeefd992b 100644 --- a/jdk/src/share/classes/java/lang/ref/Reference.java +++ b/jdk/src/share/classes/java/lang/ref/Reference.java @@ -89,7 +89,7 @@ public abstract class Reference { private T referent; /* Treated specially by GC */ - ReferenceQueue queue; + volatile ReferenceQueue queue; /* When active: NULL * pending: this @@ -225,9 +225,7 @@ public abstract class Reference { * been enqueued */ public boolean isEnqueued() { - synchronized (this) { - return (this.next != null && this.queue == ReferenceQueue.ENQUEUED); - } + return (this.queue == ReferenceQueue.ENQUEUED); } /** diff --git a/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java b/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java index 00ca9b3e0ed..a2fad1cbce3 100644 --- a/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java +++ b/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java @@ -55,25 +55,29 @@ public class ReferenceQueue { private long queueLength = 0; boolean enqueue(Reference 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 reallyPoll() { /* Must hold lock */ - if (head != null) { - Reference r = head; + Reference r = head; + if (r != null) { head = (r.next == r) ? null : r.next; r.queue = NULL; r.next = r; diff --git a/jdk/test/java/lang/ref/EnqueuePollRace.java b/jdk/test/java/lang/ref/EnqueuePollRace.java new file mode 100644 index 00000000000..c19a366715d --- /dev/null +++ b/jdk/test/java/lang/ref/EnqueuePollRace.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 8014890 + * @summary Verify that a race between ReferenceQueue.enqueue() and poll() does not occur. + * @author thomas.schatzl@oracle.com + * @run main/othervm -XX:+UseSerialGC -Xmx10M EnqueuePollRace + */ + +import java.lang.ref.*; + +public class EnqueuePollRace { + + public static void main(String args[]) throws Exception { + new WeakRef().run(); + System.out.println("Test passed."); + } + + static class WeakRef { + ReferenceQueue queue = new ReferenceQueue(); + final int numReferences = 100; + final Reference refs[] = new Reference[numReferences]; + final int iterations = 1000; + + void run() throws InterruptedException { + for (int i = 0; i < iterations; i++) { + queue = new ReferenceQueue(); + + for (int j = 0; j < refs.length; j++) { + refs[j] = new WeakReference(new Object(), queue); + } + + System.gc(); // enqueues references into the list of discovered references + + // now manually enqueue all of them + for (int j = 0; j < refs.length; j++) { + refs[j].enqueue(); + } + // and get them back. There should be exactly numReferences + // entries in the queue now. + int foundReferences = 0; + while (queue.poll() != null) { + foundReferences++; + } + + if (foundReferences != refs.length) { + throw new RuntimeException("Got " + foundReferences + " references in the queue, but expected " + refs.length); + } + } + } + } +} From c14b02d7078c9ef084e7cb7e612f363e33128176 Mon Sep 17 00:00:00 2001 From: Mike Duigou Date: Fri, 12 Jul 2013 11:11:30 -0700 Subject: [PATCH 057/123] 7129185: Add Collections.{checked|empty|unmodifiable}Navigable{Map|Set} Reviewed-by: dmocek, martin, smarks --- .../share/classes/java/util/AbstractMap.java | 2 + .../share/classes/java/util/Collections.java | 1033 ++++++++++++++--- .../share/classes/java/util/NavigableSet.java | 2 +- jdk/test/java/util/Collection/MOAT.java | 24 + .../util/Collections/CheckedIdentityMap.java | 47 +- .../java/util/Collections/CheckedMapBash.java | 159 +-- .../java/util/Collections/CheckedSetBash.java | 154 ++- .../EmptyCollectionSerialization.java | 59 +- .../util/Collections/EmptyNavigableMap.java | 373 ++++++ .../util/Collections/EmptyNavigableSet.java | 410 +++++++ .../java/util/Collections/EmptySortedSet.java | 351 ------ jdk/test/java/util/Map/LockStep.java | 9 +- jdk/test/java/util/NavigableMap/LockStep.java | 45 +- 13 files changed, 1973 insertions(+), 695 deletions(-) create mode 100644 jdk/test/java/util/Collections/EmptyNavigableMap.java create mode 100644 jdk/test/java/util/Collections/EmptyNavigableSet.java delete mode 100644 jdk/test/java/util/Collections/EmptySortedSet.java diff --git a/jdk/src/share/classes/java/util/AbstractMap.java b/jdk/src/share/classes/java/util/AbstractMap.java index fdca2aa7993..7c5153fc3bb 100644 --- a/jdk/src/share/classes/java/util/AbstractMap.java +++ b/jdk/src/share/classes/java/util/AbstractMap.java @@ -543,6 +543,8 @@ public abstract class AbstractMap implements Map { /** * 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); diff --git a/jdk/src/share/classes/java/util/Collections.java b/jdk/src/share/classes/java/util/Collections.java index 56f16f6809b..bbb987ec58f 100644 --- a/jdk/src/share/classes/java/util/Collections.java +++ b/jdk/src/share/classes/java/util/Collections.java @@ -27,6 +27,7 @@ package java.util; 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; @@ -138,7 +139,7 @@ public class Collections { * *

        The implementation was adapted from Tim Peters's list sort for Python * ( - * TimSort). It uses techiques from Peter McIlroy's "Optimistic + * TimSort). 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. @@ -199,7 +200,7 @@ public class Collections { * *

        The implementation was adapted from Tim Peters's list sort for Python * ( - * TimSort). It uses techiques from Peter McIlroy's "Optimistic + * TimSort). 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. @@ -1213,6 +1214,94 @@ public class Collections { public E last() {return ss.last();} } + /** + * 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}.

        + * + * The returned navigable set will be serializable if the specified + * navigable set is serializable. + * + * @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 NavigableSet unmodifiableNavigableSet(NavigableSet s) { + return new UnmodifiableNavigableSet<>(s); + } + + /** + * Wraps a navigable set and disables all of the mutative operations. + * + * @param type of elements + * @serial include + */ + static class UnmodifiableNavigableSet + extends UnmodifiableSortedSet + implements NavigableSet, Serializable { + + private static final long serialVersionUID = -6027448201786391929L; + + /** + * A singleton empty unmodifiable navigable set used for + * {@link #emptyNavigableSet()}. + * + * @param type of elements, if there were any, and bounds + */ + private static class EmptyNavigableSet extends UnmodifiableNavigableSet + implements Serializable { + private static final long serialVersionUID = -6291252904449939134L; + + public EmptyNavigableSet() { + super(new TreeSet()); + } + + 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 ns; + + UnmodifiableNavigableSet(NavigableSet 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 descendingSet() + { return new UnmodifiableNavigableSet<>(ns.descendingSet()); } + public Iterator descendingIterator() + { return descendingSet().iterator(); } + + public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + return new UnmodifiableNavigableSet<>( + ns.subSet(fromElement, fromInclusive, toElement, toInclusive)); + } + + public NavigableSet headSet(E toElement, boolean inclusive) { + return new UnmodifiableNavigableSet<>( + ns.headSet(toElement, inclusive)); + } + + public NavigableSet 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 @@ -1240,6 +1329,7 @@ public class Collections { static class UnmodifiableList extends UnmodifiableCollection implements List { private static final long serialVersionUID = -283967356065247728L; + final List list; UnmodifiableList(List list) { @@ -1682,7 +1772,8 @@ public class Collections { private static class UnmodifiableEntry implements Map.Entry { private Map.Entry e; - UnmodifiableEntry(Map.Entry e) {this.e = e;} + UnmodifiableEntry(Map.Entry e) + {this.e = Objects.requireNonNull(e);} public K getKey() {return e.getKey();} public V getValue() {return e.getValue();} @@ -1734,24 +1825,151 @@ public class Collections { private final SortedMap sm; - UnmodifiableSortedMap(SortedMap m) {super(m); sm = m;} - - public Comparator comparator() {return sm.comparator();} - - public SortedMap subMap(K fromKey, K toKey) { - return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey)); - } - public SortedMap headMap(K toKey) { - return new UnmodifiableSortedMap<>(sm.headMap(toKey)); - } - public SortedMap tailMap(K fromKey) { - return new UnmodifiableSortedMap<>(sm.tailMap(fromKey)); - } - - public K firstKey() {return sm.firstKey();} - public K lastKey() {return sm.lastKey();} + UnmodifiableSortedMap(SortedMap m) {super(m); sm = m; } + public Comparator comparator() { return sm.comparator(); } + public SortedMap subMap(K fromKey, K toKey) + { return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey)); } + public SortedMap headMap(K toKey) + { return new UnmodifiableSortedMap<>(sm.headMap(toKey)); } + public SortedMap 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}.

        + * + * The returned navigable map will be serializable if the specified + * navigable map is serializable. + * + * @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 NavigableMap unmodifiableNavigableMap(NavigableMap m) { + return new UnmodifiableNavigableMap<>(m); + } + + /** + * @serial include + */ + static class UnmodifiableNavigableMap + extends UnmodifiableSortedMap + implements NavigableMap, Serializable { + private static final long serialVersionUID = -4858195264774772197L; + + /** + * A class for the {@link EMPTY_NAVIGABLE_MAP} which needs readResolve + * to preserve singleton property. + * + * @param type of keys, if there were any, and of bounds + * @param type of values, if there were any + */ + private static class EmptyNavigableMap extends UnmodifiableNavigableMap + implements Serializable { + + private static final long serialVersionUID = -2239321462712562324L; + + EmptyNavigableMap() { super(new TreeMap()); } + + @Override + public NavigableSet 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 nm; + + UnmodifiableNavigableMap(NavigableMap 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 lowerEntry(K key) { + Entry lower = (Entry) nm.lowerEntry(key); + return (null != lower) + ? new UnmodifiableEntrySet.UnmodifiableEntry(lower) + : null; + } + + public Entry floorEntry(K key) { + Entry floor = (Entry) nm.floorEntry(key); + return (null != floor) + ? new UnmodifiableEntrySet.UnmodifiableEntry(floor) + : null; + } + + public Entry ceilingEntry(K key) { + Entry ceiling = (Entry) nm.ceilingEntry(key); + return (null != ceiling) + ? new UnmodifiableEntrySet.UnmodifiableEntry(ceiling) + : null; + } + + + public Entry higherEntry(K key) { + Entry higher = (Entry) nm.higherEntry(key); + return (null != higher) + ? new UnmodifiableEntrySet.UnmodifiableEntry(higher) + : null; + } + + public Entry firstEntry() { + Entry first = (Entry) nm.firstEntry(); + return (null != first) + ? new UnmodifiableEntrySet.UnmodifiableEntry(first) + : null; + } + + public Entry lastEntry() { + Entry last = (Entry) nm.lastEntry(); + return (null != last) + ? new UnmodifiableEntrySet.UnmodifiableEntry(last) + : null; + } + + public Entry pollFirstEntry() + { throw new UnsupportedOperationException(); } + public Entry pollLastEntry() + { throw new UnsupportedOperationException(); } + public NavigableMap descendingMap() + { return unmodifiableNavigableMap(nm.descendingMap()); } + public NavigableSet navigableKeySet() + { return unmodifiableNavigableSet(nm.navigableKeySet()); } + public NavigableSet descendingKeySet() + { return unmodifiableNavigableSet(nm.descendingKeySet()); } + + public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { + return unmodifiableNavigableMap( + nm.subMap(fromKey, fromInclusive, toKey, toInclusive)); + } + + public NavigableMap headMap(K toKey, boolean inclusive) + { return unmodifiableNavigableMap(nm.headMap(toKey, inclusive)); } + public NavigableMap tailMap(K fromKey, boolean inclusive) + { return unmodifiableNavigableMap(nm.tailMap(fromKey, inclusive)); } + } // Synch Wrappers @@ -1805,14 +2023,13 @@ public class Collections { final Object mutex; // Object on which to synchronize SynchronizedCollection(Collection c) { - if (c==null) - throw new NullPointerException(); - this.c = c; + this.c = Objects.requireNonNull(c); mutex = this; } + SynchronizedCollection(Collection c, Object mutex) { - this.c = c; - this.mutex = mutex; + this.c = Objects.requireNonNull(c); + this.mutex = Objects.requireNonNull(mutex); } public int size() { @@ -2026,6 +2243,120 @@ public class Collections { } } + /** + * Returns a synchronized (thread-safe) navigable set backed by the + * specified navigable set. In order to guarantee serial access, it is + * critical that all access to the backing navigable set is + * accomplished through the returned navigable set (or its views).

        + * + * 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. + *

        +     *  NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet());
        +     *      ...
        +     *  synchronized (s) {
        +     *      Iterator i = s.iterator(); // Must be in the synchronized block
        +     *      while (i.hasNext())
        +     *          foo(i.next());
        +     *  }
        +     * 
        + * or: + *
        +     *  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());
        +     *  }
        +     * 
        + * Failure to follow this advice may result in non-deterministic behavior. + * + *

        The returned navigable set will be serializable if the specified + * navigable set is serializable. + * + * @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 NavigableSet synchronizedNavigableSet(NavigableSet s) { + return new SynchronizedNavigableSet<>(s); + } + + /** + * @serial include + */ + static class SynchronizedNavigableSet + extends SynchronizedSortedSet + implements NavigableSet + { + private static final long serialVersionUID = -5505529816273629798L; + + private final NavigableSet ns; + + SynchronizedNavigableSet(NavigableSet s) { + super(s); + ns = s; + } + + SynchronizedNavigableSet(NavigableSet 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 descendingSet() { + synchronized (mutex) { + return new SynchronizedNavigableSet<>(ns.descendingSet(), mutex); + } + } + + public Iterator descendingIterator() + { synchronized (mutex) { return descendingSet().iterator(); } } + + public NavigableSet subSet(E fromElement, E toElement) { + synchronized (mutex) { + return new SynchronizedNavigableSet<>(ns.subSet(fromElement, true, toElement, false), mutex); + } + } + public NavigableSet headSet(E toElement) { + synchronized (mutex) { + return new SynchronizedNavigableSet<>(ns.headSet(toElement, false), mutex); + } + } + public NavigableSet tailSet(E fromElement) { + synchronized (mutex) { + return new SynchronizedNavigableSet(ns.tailSet(fromElement, true), mutex); + } + } + + public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + synchronized (mutex) { + return new SynchronizedNavigableSet<>(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), mutex); + } + } + + public NavigableSet headSet(E toElement, boolean inclusive) { + synchronized (mutex) { + return new SynchronizedNavigableSet<>(ns.headSet(toElement, inclusive), mutex); + } + } + + public NavigableSet 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 @@ -2235,9 +2566,7 @@ public class Collections { final Object mutex; // Object on which to synchronize SynchronizedMap(Map m) { - if (m==null) - throw new NullPointerException(); - this.m = m; + this.m = Objects.requireNonNull(m); mutex = this; } @@ -2416,7 +2745,6 @@ public class Collections { return new SynchronizedSortedMap<>(m); } - /** * @serial include */ @@ -2466,6 +2794,164 @@ public class Collections { } } + /** + * Returns a synchronized (thread-safe) navigable map backed by the + * specified navigable map. In order to guarantee serial access, it is + * critical that all access to the backing navigable map is + * accomplished through the returned navigable map (or its views).

        + * + * 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. + *

        +     *  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());
        +     *  }
        +     * 
        + * or: + *
        +     *  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());
        +     *  }
        +     * 
        + * Failure to follow this advice may result in non-deterministic behavior. + * + *

        The returned navigable map will be serializable if the specified + * navigable map is serializable. + * + * @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 NavigableMap synchronizedNavigableMap(NavigableMap m) { + return new SynchronizedNavigableMap<>(m); + } + + /** + * A synchronized NavigableMap. + * + * @serial include + */ + static class SynchronizedNavigableMap + extends SynchronizedSortedMap + implements NavigableMap + { + private static final long serialVersionUID = 699392247599746807L; + + private final NavigableMap nm; + + SynchronizedNavigableMap(NavigableMap m) { + super(m); + nm = m; + } + SynchronizedNavigableMap(NavigableMap m, Object mutex) { + super(m, mutex); + nm = m; + } + + public Entry lowerEntry(K key) + { synchronized (mutex) { return nm.lowerEntry(key); } } + public K lowerKey(K key) + { synchronized (mutex) { return nm.lowerKey(key); } } + public Entry floorEntry(K key) + { synchronized (mutex) { return nm.floorEntry(key); } } + public K floorKey(K key) + { synchronized (mutex) { return nm.floorKey(key); } } + public Entry ceilingEntry(K key) + { synchronized (mutex) { return nm.ceilingEntry(key); } } + public K ceilingKey(K key) + { synchronized (mutex) { return nm.ceilingKey(key); } } + public Entry higherEntry(K key) + { synchronized (mutex) { return nm.higherEntry(key); } } + public K higherKey(K key) + { synchronized (mutex) { return nm.higherKey(key); } } + public Entry firstEntry() + { synchronized (mutex) { return nm.firstEntry(); } } + public Entry lastEntry() + { synchronized (mutex) { return nm.lastEntry(); } } + public Entry pollFirstEntry() + { synchronized (mutex) { return nm.pollFirstEntry(); } } + public Entry pollLastEntry() + { synchronized (mutex) { return nm.pollLastEntry(); } } + + public NavigableMap descendingMap() { + synchronized (mutex) { + return + new SynchronizedNavigableMap(nm.descendingMap(), mutex); + } + } + + public NavigableSet keySet() { + return navigableKeySet(); + } + + public NavigableSet navigableKeySet() { + synchronized (mutex) { + return new SynchronizedNavigableSet(nm.navigableKeySet(), mutex); + } + } + + public NavigableSet descendingKeySet() { + synchronized (mutex) { + return new SynchronizedNavigableSet(nm.descendingKeySet(), mutex); + } + } + + + public SortedMap subMap(K fromKey, K toKey) { + synchronized (mutex) { + return new SynchronizedNavigableMap<>( + nm.subMap(fromKey, true, toKey, false), mutex); + } + } + public SortedMap headMap(K toKey) { + synchronized (mutex) { + return new SynchronizedNavigableMap<>(nm.headMap(toKey, false), mutex); + } + } + public SortedMap tailMap(K fromKey) { + synchronized (mutex) { + return new SynchronizedNavigableMap<>(nm.tailMap(fromKey, true),mutex); + } + } + + public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { + synchronized (mutex) { + return new SynchronizedNavigableMap( + nm.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); + } + } + + public NavigableMap headMap(K toKey, boolean inclusive) { + synchronized (mutex) { + return new SynchronizedNavigableMap( + nm.headMap(toKey, inclusive), mutex); + } + } + + public NavigableMap tailMap(K fromKey, boolean inclusive) { + synchronized (mutex) { + return new SynchronizedNavigableMap( + nm.tailMap(fromKey, inclusive), mutex); + } + } + } + // Dynamically typesafe collection wrappers /** @@ -2497,12 +2983,12 @@ public class Collections { * program to wrap the collection with a dynamically typesafe view. * For example, this declaration: *

         {@code
        -     *     Collection c = new HashSet();
        +     *     Collection c = new HashSet<>();
              * }
        * may be replaced temporarily by this one: *
         {@code
              *     Collection c = Collections.checkedCollection(
        -     *         new HashSet(), String.class);
        +     *         new HashSet<>(), String.class);
              * }
        * Running the program again will cause it to fail at the point where * an incorrectly typed element is inserted into the collection, clearly @@ -2788,6 +3274,7 @@ public class Collections { implements SortedSet, Serializable { private static final long serialVersionUID = 1599911165492914959L; + private final SortedSet ss; CheckedSortedSet(SortedSet s, Class type) { @@ -2810,6 +3297,87 @@ public class Collections { } } +/** + * 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 + * guaranteed that the navigable set cannot contain an incorrectly + * typed element. + * + *

        A discussion of the use of dynamically typesafe views may be + * found in the documentation for the {@link #checkedCollection + * checkedCollection} method. + * + *

        The returned navigable set will be serializable if the specified + * navigable set is serializable. + * + *

        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 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 NavigableSet checkedNavigableSet(NavigableSet s, + Class type) { + return new CheckedNavigableSet<>(s, type); + } + + /** + * @serial include + */ + static class CheckedNavigableSet extends CheckedSortedSet + implements NavigableSet, Serializable + { + private static final long serialVersionUID = -5429120189805438922L; + + private final NavigableSet ns; + + CheckedNavigableSet(NavigableSet s, Class 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 descendingSet() + { return checkedNavigableSet(ns.descendingSet(), type); } + public Iterator descendingIterator() + {return checkedNavigableSet(ns.descendingSet(), type).iterator(); } + + public NavigableSet subSet(E fromElement, E toElement) { + return checkedNavigableSet(ns.subSet(fromElement, true, toElement, false), type); + } + public NavigableSet headSet(E toElement) { + return checkedNavigableSet(ns.headSet(toElement, false), type); + } + public NavigableSet tailSet(E fromElement) { + return checkedNavigableSet(ns.tailSet(fromElement, true), type); + } + + public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + return checkedNavigableSet(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), type); + } + + public NavigableSet headSet(E toElement, boolean inclusive) { + return checkedNavigableSet(ns.headSet(toElement, inclusive), type); + } + + public NavigableSet 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 @@ -3022,11 +3590,9 @@ public class Collections { } CheckedMap(Map m, Class keyType, Class 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(); } @@ -3303,8 +3869,8 @@ public class Collections { private final Class valueType; CheckedEntry(Map.Entry e, Class valueType) { - this.e = e; - this.valueType = valueType; + this.e = Objects.requireNonNull(e); + this.valueType = Objects.requireNonNull(valueType); } public K getKey() { return e.getKey(); } @@ -3407,6 +3973,177 @@ public class Collections { } } + /** + * 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. + * + *

        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 guaranteed that the + * map cannot contain an incorrectly typed key or value. + * + *

        A discussion of the use of dynamically typesafe views may be + * found in the documentation for the {@link #checkedCollection + * checkedCollection} method. + * + *

        The returned map will be serializable if the specified map is + * serializable. + * + *

        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 type of map keys + * @param 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 NavigableMap checkedNavigableMap(NavigableMap m, + Class keyType, + Class valueType) { + return new CheckedNavigableMap<>(m, keyType, valueType); + } + + /** + * @serial include + */ + static class CheckedNavigableMap extends CheckedSortedMap + implements NavigableMap, Serializable + { + private static final long serialVersionUID = -4852462692372534096L; + + private final NavigableMap nm; + + CheckedNavigableMap(NavigableMap m, + Class keyType, Class valueType) { + super(m, keyType, valueType); + nm = m; + } + + public Comparator comparator() { return nm.comparator(); } + public K firstKey() { return nm.firstKey(); } + public K lastKey() { return nm.lastKey(); } + + public Entry lowerEntry(K key) { + Entry 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 floorEntry(K key) { + Entry 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 ceilingEntry(K key) { + Entry 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 higherEntry(K key) { + Entry 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 firstEntry() { + Entry first = nm.firstEntry(); + return (null != first) + ? new CheckedMap.CheckedEntrySet.CheckedEntry(first, valueType) + : null; + } + + public Entry lastEntry() { + Entry last = nm.lastEntry(); + return (null != last) + ? new CheckedMap.CheckedEntrySet.CheckedEntry(last, valueType) + : null; + } + + public Entry pollFirstEntry() { + Entry entry = nm.pollFirstEntry(); + return (null == entry) + ? null + : new CheckedMap.CheckedEntrySet.CheckedEntry(entry, valueType); + } + + public Entry pollLastEntry() { + Entry entry = nm.pollLastEntry(); + return (null == entry) + ? null + : new CheckedMap.CheckedEntrySet.CheckedEntry(entry, valueType); + } + + public NavigableMap descendingMap() { + return checkedNavigableMap(nm.descendingMap(), keyType, valueType); + } + + public NavigableSet keySet() { + return navigableKeySet(); + } + + public NavigableSet navigableKeySet() { + return checkedNavigableSet(nm.navigableKeySet(), keyType); + } + + public NavigableSet descendingKeySet() { + return checkedNavigableSet(nm.descendingKeySet(), keyType); + } + + @Override + public NavigableMap subMap(K fromKey, K toKey) { + return checkedNavigableMap(nm.subMap(fromKey, true, toKey, false), + keyType, valueType); + } + + @Override + public NavigableMap headMap(K toKey) { + return checkedNavigableMap(nm.headMap(toKey, false), keyType, valueType); + } + + @Override + public NavigableMap tailMap(K fromKey) { + return checkedNavigableMap(nm.tailMap(fromKey, true), keyType, valueType); + } + + public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { + return checkedNavigableMap(nm.subMap(fromKey, fromInclusive, toKey, toInclusive), keyType, valueType); + } + + public NavigableMap headMap(K toKey, boolean inclusive) { + return checkedNavigableMap(nm.headMap(toKey, inclusive), keyType, valueType); + } + + public NavigableMap tailMap(K fromKey, boolean inclusive) { + return checkedNavigableMap(nm.tailMap(fromKey, inclusive), keyType, valueType); + } + } + // Empty collections /** @@ -3428,6 +4165,7 @@ public class Collections { *

        Implementations of this method are permitted, but not * required, to return the same object from multiple invocations. * + * @param type of elements, if there were any, in the iterator * @return an empty iterator * @since 1.7 */ @@ -3478,6 +4216,7 @@ public class Collections { *

        Implementations of this method are permitted, but not * required, to return the same object from multiple invocations. * + * @param type of elements, if there were any, in the iterator * @return an empty list iterator * @since 1.7 */ @@ -3542,17 +4281,19 @@ public class Collections { 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. * *

        This example illustrates the type-safe way to obtain an empty set: *

              *     Set<String> s = Collections.emptySet();
              * 
        - * Implementation note: Implementations of this method need not - * create a separate 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.) + * @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.) + * + * @return the empty set * * @see #EMPTY_SET * @since 1.5 @@ -3607,121 +4348,45 @@ public class Collections { } /** - * Returns the empty sorted set (immutable). This set is serializable. + * Returns an empty sorted set (immutable). This set is serializable. * - *

        This example illustrates the type-safe way to obtain an empty sorted - * set: - *

        -     *     SortedSet<String> s = Collections.emptySortedSet();
        -     * 
        - * Implementation note: Implementations of this method need not - * create a separate SortedSet object for each call. + *

        This example illustrates the type-safe way to obtain an empty + * sorted set: + *

         {@code
        +     *     SortedSet s = Collections.emptySortedSet();
        +     * }
        * + * @implNote Implementations of this method need not create a separate + * {@code SortedSet} object for each call. + * + * @param type of elements, if there were any, in the set + * @return the empty sorted set * @since 1.8 */ @SuppressWarnings("unchecked") - public static final SortedSet emptySortedSet() { - return (SortedSet) new EmptySortedSet<>(); + public static SortedSet emptySortedSet() { + return (SortedSet) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET; } /** - * @serial include + * Returns an empty navigable set (immutable). This set is serializable. + * + *

        This example illustrates the type-safe way to obtain an empty + * navigable set: + *

         {@code
        +     *     NavigableSet s = Collections.emptyNavigableSet();
        +     * }
        + * + * @implNote Implementations of this method need not + * create a separate {@code NavigableSet} object for each call. + * + * @param type of elements, if there were any, in the set + * @return the empty navigable set + * @since 1.8 */ - private static class EmptySortedSet - extends AbstractSet - implements SortedSet, Serializable - { - private static final long serialVersionUID = 6316515401502265487L; - public Iterator 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[] toArray(E[] a) { - if (a.length > 0) - a[0] = null; - return a; - } - - // Preserves singleton property - private Object readResolve() { - return new EmptySortedSet<>(); - } - - @Override - public Comparator comparator() { - return null; - } - - @Override - @SuppressWarnings("unchecked") - public SortedSet 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 headSet(Object toElement) { - Objects.requireNonNull(toElement); - - if (!(toElement instanceof Comparable)) { - throw new ClassCastException(); - } - - return emptySortedSet(); - } - - @Override - public SortedSet 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 action) { - Objects.requireNonNull(action); - } - - @Override - public boolean removeIf(Predicate filter) { - Objects.requireNonNull(filter); - return false; - } - - @Override - public Spliterator spliterator() { return Spliterators.emptySpliterator(); } + @SuppressWarnings("unchecked") + public static NavigableSet emptyNavigableSet() { + return (NavigableSet) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET; } /** @@ -3733,7 +4398,7 @@ public class Collections { 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. * *

        This example illustrates the type-safe way to obtain an empty list: *

        @@ -3744,6 +4409,9 @@ public class Collections {
              * method is likely to have comparable cost to using the like-named
              * field.  (Unlike this method, the field does not provide type safety.)
              *
        +     * @param  type of elements, if there were any, in the list
        +     * @return an empty immutable list
        +     *
              * @see #EMPTY_LIST
              * @since 1.5
              */
        @@ -3830,17 +4498,18 @@ public class Collections {
             public static final Map EMPTY_MAP = new EmptyMap<>();
         
             /**
        -     * Returns the empty map (immutable).  This map is serializable.
        +     * Returns an empty map (immutable).  This map is serializable.
              *
        -     * 

        This example illustrates the type-safe way to obtain an empty set: + *

        This example illustrates the type-safe way to obtain an empty map: *

              *     Map<String, Date> s = Collections.emptyMap();
              * 
        - * Implementation note: Implementations of this method need not - * create a separate 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.) + * @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.) * + * @return an empty map * @see #EMPTY_MAP * @since 1.5 */ @@ -3849,6 +4518,44 @@ public class Collections { return (Map) EMPTY_MAP; } + /** + * Returns an empty sorted map (immutable). This map is serializable. + * + *

        This example illustrates the type-safe way to obtain an empty map: + *

         {@code
        +     *     SortedMap s = Collections.emptySortedMap();
        +     * }
        + * + * @implNote Implementations of this method need not create a separate + * {@code SortedMap} object for each call. + * + * @return an empty sorted map + * @since 1.8 + */ + @SuppressWarnings("unchecked") + public static final SortedMap emptySortedMap() { + return (SortedMap) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP; + } + + /** + * Returns an empty navigable map (immutable). This map is serializable. + * + *

        This example illustrates the type-safe way to obtain an empty map: + *

         {@code
        +     *     NavigableMap s = Collections.emptyNavigableMap();
        +     * }
        + * + * @implNote Implementations of this method need not create a separate + * {@code NavigableMap} object for each call. + * + * @return an empty navigable map + * @since 1.8 + */ + @SuppressWarnings("unchecked") + public static final NavigableMap emptyNavigableMap() { + return (NavigableMap) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP; + } + /** * @serial include */ @@ -4153,15 +4860,11 @@ public class Collections { 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 keySet = null; private transient Set> entrySet = null; @@ -4508,6 +5211,8 @@ public class Collections { /** * 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); diff --git a/jdk/src/share/classes/java/util/NavigableSet.java b/jdk/src/share/classes/java/util/NavigableSet.java index 26fcd3a7c35..4dbb1c1cc45 100644 --- a/jdk/src/share/classes/java/util/NavigableSet.java +++ b/jdk/src/share/classes/java/util/NavigableSet.java @@ -303,7 +303,7 @@ public interface NavigableSet extends SortedSet { * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} -na */ + */ SortedSet headSet(E toElement); /** diff --git a/jdk/test/java/util/Collection/MOAT.java b/jdk/test/java/util/Collection/MOAT.java index 7abc669d4b9..a5b2c42e47b 100644 --- a/jdk/test/java/util/Collection/MOAT.java +++ b/jdk/test/java/util/Collection/MOAT.java @@ -71,6 +71,14 @@ public class MOAT { testCollection(new LinkedList()); testCollection(new LinkedList().subList(0,0)); testCollection(new TreeSet()); + testCollection(Collections.checkedList(new ArrayList(), Integer.class)); + testCollection(Collections.synchronizedList(new ArrayList())); + testCollection(Collections.checkedSet(new HashSet(), Integer.class)); + testCollection(Collections.checkedSortedSet(new TreeSet(), Integer.class)); + testCollection(Collections.checkedNavigableSet(new TreeSet(), Integer.class)); + testCollection(Collections.synchronizedSet(new HashSet())); + testCollection(Collections.synchronizedSortedSet(new TreeSet())); + testCollection(Collections.synchronizedNavigableSet(new TreeSet())); testCollection(new CopyOnWriteArrayList()); testCollection(new CopyOnWriteArrayList().subList(0,0)); @@ -98,6 +106,12 @@ public class MOAT { testMap(new Hashtable()); testMap(new ConcurrentHashMap(10, 0.5f)); testMap(new ConcurrentSkipListMap()); + testMap(Collections.checkedMap(new HashMap(), Integer.class, Integer.class)); + testMap(Collections.checkedSortedMap(new TreeMap(), Integer.class, Integer.class)); + testMap(Collections.checkedNavigableMap(new TreeMap(), Integer.class, Integer.class)); + testMap(Collections.synchronizedMap(new HashMap())); + testMap(Collections.synchronizedSortedMap(new TreeMap())); + testMap(Collections.synchronizedNavigableMap(new TreeMap())); // Empty collections final List emptyArray = Arrays.asList(new Integer[]{}); @@ -117,19 +131,29 @@ public class MOAT { testCollection(emptySet); testEmptySet(emptySet); testEmptySet(EMPTY_SET); + testEmptySet(Collections.emptySet()); + testEmptySet(Collections.emptySortedSet()); + testEmptySet(Collections.emptyNavigableSet()); testImmutableSet(emptySet); List emptyList = emptyList(); testCollection(emptyList); testEmptyList(emptyList); testEmptyList(EMPTY_LIST); + testEmptyList(Collections.emptyList()); testImmutableList(emptyList); Map emptyMap = emptyMap(); testMap(emptyMap); testEmptyMap(emptyMap); testEmptyMap(EMPTY_MAP); + testEmptyMap(Collections.emptyMap()); + testEmptyMap(Collections.emptySortedMap()); + testEmptyMap(Collections.emptyNavigableMap()); testImmutableMap(emptyMap); + testImmutableMap(Collections.emptyMap()); + testImmutableMap(Collections.emptySortedMap()); + testImmutableMap(Collections.emptyNavigableMap()); // Singleton collections Set singletonSet = singleton(1); diff --git a/jdk/test/java/util/Collections/CheckedIdentityMap.java b/jdk/test/java/util/Collections/CheckedIdentityMap.java index befbd23b81a..4c2e9d2bf5e 100644 --- a/jdk/test/java/util/Collections/CheckedIdentityMap.java +++ b/jdk/test/java/util/Collections/CheckedIdentityMap.java @@ -24,59 +24,42 @@ /* * @test * @bug 6585904 + * @run testng CheckedIdentityMap * @summary Checked collections with underlying maps with identity comparisons */ import java.util.*; import static java.util.Collections.*; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotEquals; + +import org.testng.annotations.Test; + public class CheckedIdentityMap { - void test(String[] args) throws Throwable { + + @Test + public void testHashCode() { Map m1 = checkedMap( new IdentityHashMap(), Integer.class, Integer.class); Map m2 = checkedMap( new IdentityHashMap(), Integer.class, Integer.class); + // NB: these are unique instances. Compare vs. Integer.valueOf(1) m1.put(new Integer(1), new Integer(1)); m2.put(new Integer(1), new Integer(1)); Map.Entry e1 = m1.entrySet().iterator().next(); Map.Entry e2 = m2.entrySet().iterator().next(); - check(! e1.equals(e2)); - check(e1.hashCode() == hashCode(e1)); - check(e2.hashCode() == hashCode(e2)); + + assertNotEquals(e1, e2); + assertEquals(e1.hashCode(), hashCode(e1)); + assertEquals(e2.hashCode(), hashCode(e2)); } - int hashCode(Map.Entry e) { + static int hashCode(Map.Entry e) { return (System.identityHashCode(e.getKey()) ^ System.identityHashCode(e.getValue())); } - - //--------------------- Infrastructure --------------------------- - volatile int passed = 0, failed = 0; - void pass() {passed++;} - void fail() {failed++; Thread.dumpStack();} - void fail(String msg) {System.err.println(msg); fail();} - void unexpected(Throwable t) {failed++; t.printStackTrace();} - void check(boolean cond) {if (cond) pass(); else fail();} - void equal(Object x, Object y) { - if (x == null ? y == null : x.equals(y)) pass(); - else fail(x + " not equal to " + y);} - public static void main(String[] args) throws Throwable { - new CheckedIdentityMap().instanceMain(args);} - void instanceMain(String[] args) throws Throwable { - try {test(args);} catch (Throwable t) {unexpected(t);} - System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed); - if (failed > 0) throw new AssertionError("Some tests failed");} - abstract class F {abstract void f() throws Throwable;} - void THROWS(Class k, F... fs) { - for (F f : fs) - try {f.f(); fail("Expected " + k.getName() + " not thrown");} - catch (Throwable t) { - if (k.isAssignableFrom(t.getClass())) pass(); - else unexpected(t);}} - Thread checkedThread(final Runnable r) { - return new Thread() {public void run() { - try {r.run();} catch (Throwable t) {unexpected(t);}}};} } diff --git a/jdk/test/java/util/Collections/CheckedMapBash.java b/jdk/test/java/util/Collections/CheckedMapBash.java index 61c7dd09cfe..880d35b5646 100644 --- a/jdk/test/java/util/Collections/CheckedMapBash.java +++ b/jdk/test/java/util/Collections/CheckedMapBash.java @@ -23,76 +23,83 @@ /* * @test - * @bug 4904067 5023830 + * @bug 4904067 5023830 7129185 * @summary Unit test for Collections.checkedMap * @author Josh Bloch + * @run testng CheckedMapBash */ import java.util.*; +import java.util.function.Supplier; +import org.testng.annotations.Test; +import org.testng.annotations.DataProvider; + +import static org.testng.Assert.fail; +import static org.testng.Assert.assertTrue; public class CheckedMapBash { - static Random rnd = new Random(); - static Object nil = new Integer(0); + static final Random rnd = new Random(); + static final Object nil = new Integer(0); + static final int numItr = 100; + static final int mapSize = 100; - public static void main(String[] args) { - int numItr = 100; - int mapSize = 100; + @Test(dataProvider = "Bash.Supplier>") + public static void testCheckedMap(String description, Supplier> supplier) { + Map m = supplier.get(); + Object head = nil; - // Linked List test - for (int i=0; i> supplier) { + Map m = supplier.get(); for (int i=0; i bashNavigableMapProvider() { + ArrayList iters = new ArrayList<>(makeCheckedMaps()); + iters.ensureCapacity(numItr * iters.size()); + for(int each=1; each < numItr; each++) { + iters.addAll( makeCheckedMaps()); + } + return iters.iterator(); } - static void fail(String s) { - throw new RuntimeException(s); + @DataProvider(name = "Supplier>", parallel = true) + public static Iterator navigableMapProvider() { + return makeCheckedMaps().iterator(); + } + + public static Collection makeCheckedMaps() { + return Arrays.asList( + new Object[]{"Collections.checkedMap(HashMap)", + (Supplier) () -> {return Collections.checkedMap(new HashMap(), Integer.class, Integer.class);}}, + new Object[]{"Collections.checkedMap(TreeSet(reverseOrder)", + (Supplier) () -> {return Collections.checkedMap(new TreeMap(Collections.reverseOrder()), Integer.class, Integer.class);}}, + new Object[]{"Collections.checkedMap(TreeSet).descendingSet()", + (Supplier) () -> {return Collections.checkedMap(new TreeMap().descendingMap(), Integer.class, Integer.class);}}, + new Object[]{"Collections.checkedNavigableMap(TreeSet)", + (Supplier) () -> {return Collections.checkedNavigableMap(new TreeMap(), Integer.class, Integer.class);}}, + new Object[]{"Collections.checkedNavigableMap(TreeSet(reverseOrder)", + (Supplier) () -> {return Collections.checkedNavigableMap(new TreeMap(Collections.reverseOrder()), Integer.class, Integer.class);}}, + new Object[]{"Collections.checkedNavigableMap().descendingSet()", + (Supplier) () -> {return Collections.checkedNavigableMap(new TreeMap().descendingMap(), Integer.class, Integer.class);}} + ); } } diff --git a/jdk/test/java/util/Collections/CheckedSetBash.java b/jdk/test/java/util/Collections/CheckedSetBash.java index 714fcae896a..0d87cb15953 100644 --- a/jdk/test/java/util/Collections/CheckedSetBash.java +++ b/jdk/test/java/util/Collections/CheckedSetBash.java @@ -23,82 +23,93 @@ /* * @test - * @bug 4904067 + * @bug 4904067 7129185 * @summary Unit test for Collections.checkedSet * @author Josh Bloch + * @run testng CheckedSetBash */ import java.util.*; +import java.util.function.Supplier; +import org.testng.annotations.Test; +import org.testng.annotations.DataProvider; + +import static org.testng.Assert.fail; +import static org.testng.Assert.assertTrue; public class CheckedSetBash { - static Random rnd = new Random(); + static final int numItr = 100; + static final int setSize = 100; + static final Random rnd = new Random(); - public static void main(String[] args) { - int numItr = 100; - int setSize = 100; + @Test(dataProvider = "Supplier>") + public static void testCheckedSet(String description, Supplier> supplier) { - for (int i=0; i s1 = supplier.get(); + assertTrue(s1.isEmpty()); - Set s2 = newSet(); - AddRandoms(s2, setSize); + AddRandoms(s1, setSize); - Set intersection = clone(s1); - intersection.retainAll(s2); - Set diff1 = clone(s1); diff1.removeAll(s2); - Set diff2 = clone(s2); diff2.removeAll(s1); - Set union = clone(s1); union.addAll(s2); + Set s2 = supplier.get(); - if (diff1.removeAll(diff2)) - fail("Set algebra identity 2 failed"); - if (diff1.removeAll(intersection)) - fail("Set algebra identity 3 failed"); - if (diff2.removeAll(diff1)) - fail("Set algebra identity 4 failed"); - if (diff2.removeAll(intersection)) - fail("Set algebra identity 5 failed"); - if (intersection.removeAll(diff1)) - fail("Set algebra identity 6 failed"); - if (intersection.removeAll(diff1)) - fail("Set algebra identity 7 failed"); + assertTrue(s2.isEmpty()); - intersection.addAll(diff1); intersection.addAll(diff2); - if (!intersection.equals(union)) - fail("Set algebra identity 1 failed"); + AddRandoms(s2, setSize); - if (new HashSet(union).hashCode() != union.hashCode()) - fail("Incorrect hashCode computation."); + Set intersection = clone(s1, supplier); + intersection.retainAll(s2); + Set diff1 = clone(s1, supplier); diff1.removeAll(s2); + Set diff2 = clone(s2, supplier); diff2.removeAll(s1); + Set union = clone(s1, supplier); union.addAll(s2); - Iterator e = union.iterator(); - while (e.hasNext()) - if (!intersection.remove(e.next())) - fail("Couldn't remove element from copy."); - if (!intersection.isEmpty()) - fail("Copy nonempty after deleting all elements."); + if (diff1.removeAll(diff2)) + fail("Set algebra identity 2 failed"); + if (diff1.removeAll(intersection)) + fail("Set algebra identity 3 failed"); + if (diff2.removeAll(diff1)) + fail("Set algebra identity 4 failed"); + if (diff2.removeAll(intersection)) + fail("Set algebra identity 5 failed"); + if (intersection.removeAll(diff1)) + fail("Set algebra identity 6 failed"); + if (intersection.removeAll(diff1)) + fail("Set algebra identity 7 failed"); - e = union.iterator(); - while (e.hasNext()) { - Object o = e.next(); - if (!union.contains(o)) - fail("Set doesn't contain one of its elements."); - e.remove(); - if (union.contains(o)) - fail("Set contains element after deletion."); - } - if (!union.isEmpty()) - fail("Set nonempty after deleting all elements."); + intersection.addAll(diff1); intersection.addAll(diff2); + if (!intersection.equals(union)) + fail("Set algebra identity 1 failed"); - s1.clear(); - if (!s1.isEmpty()) - fail("Set nonempty after clear."); + if (new HashSet(union).hashCode() != union.hashCode()) + fail("Incorrect hashCode computation."); + + Iterator e = union.iterator(); + while (e.hasNext()) + if (!intersection.remove(e.next())) + fail("Couldn't remove element from copy."); + if (!intersection.isEmpty()) + fail("Copy nonempty after deleting all elements."); + + e = union.iterator(); + while (e.hasNext()) { + Object o = e.next(); + if (!union.contains(o)) + fail("Set doesn't contain one of its elements."); + e.remove(); + if (union.contains(o)) + fail("Set contains element after deletion."); } + if (!union.isEmpty()) + fail("Set nonempty after deleting all elements."); + + s1.clear(); + if (!s1.isEmpty()) + fail("Set nonempty after clear."); } // Done inefficiently so as to exercise toArray - static Set clone(Set s) { - Set clone = newSet(); - List arrayList = Arrays.asList(s.toArray()); + static Set clone(Set s, Supplier> supplier) { + Set clone = supplier.get(); + List arrayList = Arrays.asList((T[]) s.toArray()); clone.addAll(arrayList); if (!s.equals(clone)) fail("Set not equal to copy."); @@ -109,13 +120,6 @@ public class CheckedSetBash { return clone; } - static Set newSet() { - Set s = Collections.checkedSet(new HashSet(), Integer.class); - if (!s.isEmpty()) - fail("New instance non empty."); - return s; - } - static void AddRandoms(Set s, int n) { for (int i=0; i navigableSetsProvider() { + ArrayList iters = new ArrayList<>(makeCheckedSets()); + iters.ensureCapacity(numItr * iters.size()); + for(int each=1; each < numItr; each++) { + iters.addAll( makeCheckedSets()); + } + return iters.iterator(); + } + public static Collection makeCheckedSets() { + return Arrays.asList( + new Object[]{"Collections.checkedSet(HashSet)", + (Supplier) () -> {return Collections.checkedSet(new HashSet(), Integer.class);}}, + new Object[]{"Collections.checkedSet(TreeSet(reverseOrder)", + (Supplier) () -> {return Collections.checkedSet(new TreeSet(Collections.reverseOrder()), Integer.class);}}, + new Object[]{"Collections.checkedSet(TreeSet).descendingSet()", + (Supplier) () -> {return Collections.checkedSet(new TreeSet().descendingSet(), Integer.class);}}, + new Object[]{"Collections.checkedNavigableSet(TreeSet)", + (Supplier) () -> {return Collections.checkedNavigableSet(new TreeSet(), Integer.class);}}, + new Object[]{"Collections.checkedNavigableSet(TreeSet(reverseOrder)", + (Supplier) () -> {return Collections.checkedNavigableSet(new TreeSet(Collections.reverseOrder()), Integer.class);}}, + new Object[]{"Collections.checkedNavigableSet().descendingSet()", + (Supplier) () -> {return Collections.checkedNavigableSet(new TreeSet().descendingSet(), Integer.class);}} + ); } } diff --git a/jdk/test/java/util/Collections/EmptyCollectionSerialization.java b/jdk/test/java/util/Collections/EmptyCollectionSerialization.java index 7bbe0bf14d0..1369663ffc5 100644 --- a/jdk/test/java/util/Collections/EmptyCollectionSerialization.java +++ b/jdk/test/java/util/Collections/EmptyCollectionSerialization.java @@ -23,13 +23,20 @@ /* * @test - * @bug 4684279 + * @bug 4684279 7129185 * @summary Empty utility collections should be singletons * @author Josh Bloch + * @run testng EmptyCollectionSerialization */ import java.util.*; +import java.util.function.Supplier; import java.io.*; +import org.testng.annotations.Test; +import org.testng.annotations.DataProvider; + +import static org.testng.Assert.fail; +import static org.testng.Assert.assertSame; public class EmptyCollectionSerialization { private static Object patheticDeepCopy(Object o) throws Exception { @@ -45,16 +52,48 @@ public class EmptyCollectionSerialization { return ois.readObject(); } - private static boolean isSingleton(Object o) throws Exception { - return patheticDeepCopy(o) == o; + @Test(dataProvider="SerializableSingletons") + public static void serializableSingletons(String description, Supplier o) { + try { + Object singleton = o.get(); + assertSame(o.get(), singleton, description + ": broken Supplier not returning singleton"); + Object copy = patheticDeepCopy(singleton); + assertSame( copy, singleton, description + ": " + + copy.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(copy)) + + " is not the singleton " + + singleton.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(singleton))); + } catch(Exception all) { + fail(description + ": Unexpected Exception", all); + } } - public static void main(String[] args) throws Exception { - if (!isSingleton(Collections.EMPTY_SET)) - throw new Exception("EMPTY_SET"); - if (!isSingleton(Collections.EMPTY_LIST)) - throw new Exception("EMPTY_LIST"); - if (!isSingleton(Collections.EMPTY_MAP)) - throw new Exception("EMPTY_MAP"); + @DataProvider(name = "SerializableSingletons", parallel = true) + public static Iterator navigableMapProvider() { + return makeSingletons().iterator(); + } + + public static Collection makeSingletons() { + return Arrays.asList( + new Object[]{"Collections.EMPTY_LIST", + (Supplier) () -> {return Collections.EMPTY_LIST;}}, + new Object[]{"Collections.EMPTY_MAP", + (Supplier) () -> {return Collections.EMPTY_MAP;}}, + new Object[]{"Collections.EMPTY_SET", + (Supplier) () -> {return Collections.EMPTY_SET;}}, + new Object[]{"Collections.singletonMap()", + (Supplier) () -> {return Collections.emptyList();}}, + new Object[]{"Collections.emptyMap()", + (Supplier) () -> {return Collections.emptyMap();}}, + new Object[]{"Collections.emptySet()", + (Supplier) () -> {return Collections.emptySet();}}, + new Object[]{"Collections.emptySortedSet()", + (Supplier) () -> {return Collections.emptySortedSet();}}, + new Object[]{"Collections.emptySortedMap()", + (Supplier) () -> {return Collections.emptySortedMap();}}, + new Object[]{"Collections.emptyNavigableSet()", + (Supplier) () -> {return Collections.emptyNavigableSet();}}, + new Object[]{"Collections.emptyNavigableMap()", + (Supplier) () -> {return Collections.emptyNavigableMap();}} + ); } } diff --git a/jdk/test/java/util/Collections/EmptyNavigableMap.java b/jdk/test/java/util/Collections/EmptyNavigableMap.java new file mode 100644 index 00000000000..ba8e67b42a4 --- /dev/null +++ b/jdk/test/java/util/Collections/EmptyNavigableMap.java @@ -0,0 +1,373 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4533691 7129185 + * @summary Unit test for Collections.emptyNavigableMap + * @run testng EmptyNavigableMap + */ +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.NavigableMap; +import java.util.SortedMap; +import java.util.TreeMap; +import org.testng.annotations.Test; +import org.testng.annotations.DataProvider; + +import static org.testng.Assert.fail; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertSame; + +public class EmptyNavigableMap { + + public static void assertInstance(T actual, Class expected) { + assertInstance(expected.isInstance(actual), null); + } + + public static void assertInstance(T actual, Class expected, String message) { + assertTrue(expected.isInstance(actual), ((null != message) ? message : "") + + " " + (actual == null ? "" : actual.getClass().getSimpleName()) + " != " + expected.getSimpleName() + ". "); + } + + public static void assertEmptyNavigableMap(Object obj) { + assertInstance(obj, NavigableMap.class); + assertTrue(((NavigableMap)obj).isEmpty() && (((NavigableMap)obj).size() == 0)); + } + + public static void assertEmptyNavigableMap(Object obj, String message) { + assertInstance(obj, NavigableMap.class, message); + assertTrue(((NavigableMap)obj).isEmpty() && (((NavigableMap)obj).size() == 0), + ((null != message) ? message : "") + " Not empty. "); + } + + public interface Thrower { + + public void run() throws T; + } + + public static void assertThrows(Thrower thrower, Class throwable) { + assertThrows(thrower, throwable, null); + } + + public static void assertThrows(Thrower thrower, Class throwable, String message) { + Throwable result; + try { + thrower.run(); + fail(((null != message) ? message : "") + "Failed to throw " + throwable.getCanonicalName() + ". "); + return; + } catch (Throwable caught) { + result = caught; + } + + assertInstance(result, throwable, ((null != message) ? message : "") + "Failed to throw " + throwable.getCanonicalName() + ". "); + } + + public static final boolean isDescending(SortedMap set) { + if (null == set.comparator()) { + // natural order + return false; + } + + if (Collections.reverseOrder() == set.comparator()) { + // reverse natural order. + return true; + } + + if (set.comparator().equals(Collections.reverseOrder(Collections.reverseOrder(set.comparator())))) { + // it's a Collections.reverseOrder(Comparator). + return true; + } + + throw new IllegalStateException("can't determine ordering for " + set); + } + + /** + * Tests that the comparator is {@code null}. + */ + @Test(dataProvider = "NavigableMap", dataProviderClass = EmptyNavigableMap.class) + public void testComparatorIsNull(String description, NavigableMap navigableMap) { + Comparator comparator = navigableMap.comparator(); + + assertTrue(comparator == null || comparator == Collections.reverseOrder(), description + ": Comparator (" + comparator + ") is not null."); + } + + /** + * Tests that contains requires Comparable + */ + @Test(dataProvider = "NavigableMap", dataProviderClass = EmptyNavigableMap.class) + public void testContainsRequiresComparable(String description, NavigableMap navigableMap) { + assertThrows(() -> { + navigableMap.containsKey(new Object()); + }, + ClassCastException.class, + description + ": Compareable should be required"); + } + + /** + * Tests that the contains method returns {@code false}. + */ + @Test(dataProvider = "NavigableMap", dataProviderClass = EmptyNavigableMap.class) + public void testContains(String description, NavigableMap navigableMap) { + assertFalse(navigableMap.containsKey(new Integer(1)), + description + ": Should not contain any elements."); + assertFalse(navigableMap.containsValue(new Integer(1)), + description + ": Should not contain any elements."); + } + + /** + * Tests that the containsAll method returns {@code false}. + */ + @Test(dataProvider = "NavigableMap", dataProviderClass = EmptyNavigableMap.class) + public void testContainsAll(String description, NavigableMap navigableMap) { + TreeMap treeMap = new TreeMap(); + treeMap.put("1", 1); + treeMap.put("2", 2); + treeMap.put("3", 3); + + assertFalse(navigableMap.equals(treeMap), "Should not contain any elements."); + } + + /** + * Tests that the iterator is empty. + */ + @Test(dataProvider = "NavigableMap", dataProviderClass = EmptyNavigableMap.class) + public void testEmptyIterator(String description, NavigableMap navigableMap) { + assertFalse(navigableMap.keySet().iterator().hasNext(), "The iterator is not empty."); + assertFalse(navigableMap.values().iterator().hasNext(), "The iterator is not empty."); + assertFalse(navigableMap.entrySet().iterator().hasNext(), "The iterator is not empty."); + } + + /** + * Tests that the set is empty. + */ + @Test(dataProvider = "NavigableMap", dataProviderClass = EmptyNavigableMap.class) + public void testIsEmpty(String description, NavigableMap navigableMap) { + assertTrue(navigableMap.isEmpty(), "The set is not empty."); + } + + /** + * Tests the headMap() method. + */ + @Test(dataProvider = "NavigableMap", dataProviderClass = EmptyNavigableMap.class) + public void testHeadMap(String description, NavigableMap navigableMap) { + assertThrows( + () -> { NavigableMap ss = navigableMap.headMap(null, false); }, + NullPointerException.class, + description + ": Must throw NullPointerException for null element"); + + assertThrows( + () -> { NavigableMap ss = navigableMap.headMap(new Object(), true); }, + ClassCastException.class, + description + ": Must throw ClassCastException for non-Comparable element"); + + NavigableMap ss = navigableMap.headMap("1", false); + + assertEmptyNavigableMap(ss, description + ": Returned value is not empty navigable set."); + } + + /** + * Tests that the size is 0. + */ + @Test(dataProvider = "NavigableMap", dataProviderClass = EmptyNavigableMap.class) + public void testSizeIsZero(String description, NavigableMap navigableMap) { + assertTrue(0 == navigableMap.size(), "The size of the set is not 0."); + } + + /** + * Tests the subMap() method. + */ + @Test(dataProvider = "NavigableMap", dataProviderClass = EmptyNavigableMap.class) + public void testSubMap(String description, NavigableMap navigableMap) { + assertThrows( + () -> { + SortedMap ss = navigableMap.subMap(null, BigInteger.TEN); + }, + NullPointerException.class, + description + ": Must throw NullPointerException for null element"); + + assertThrows( + () -> { + SortedMap ss = navigableMap.subMap(BigInteger.ZERO, null); + }, + NullPointerException.class, + description + ": Must throw NullPointerException for null element"); + + assertThrows( + () -> { + SortedMap ss = navigableMap.subMap(null, null); + }, + NullPointerException.class, + description + ": Must throw NullPointerException for null element"); + + Object obj1 = new Object(); + Object obj2 = new Object(); + + assertThrows( + () -> { + SortedMap ss = navigableMap.subMap(obj1, BigInteger.TEN); + }, + ClassCastException.class, description + + ": Must throw ClassCastException for parameter which is not Comparable."); + + assertThrows( + () -> { + SortedMap ss = navigableMap.subMap(BigInteger.ZERO, obj2); + }, + ClassCastException.class, description + + ": Must throw ClassCastException for parameter which is not Comparable."); + + assertThrows( + () -> { + SortedMap ss = navigableMap.subMap(obj1, obj2); + }, + ClassCastException.class, description + + ": Must throw ClassCastException for parameter which is not Comparable."); + + // minimal range + navigableMap.subMap(BigInteger.ZERO, false, BigInteger.ZERO, false); + navigableMap.subMap(BigInteger.ZERO, false, BigInteger.ZERO, true); + navigableMap.subMap(BigInteger.ZERO, true, BigInteger.ZERO, false); + navigableMap.subMap(BigInteger.ZERO, true, BigInteger.ZERO, true); + + Object first = isDescending(navigableMap) ? BigInteger.TEN : BigInteger.ZERO; + Object last = (BigInteger.ZERO == first) ? BigInteger.TEN : BigInteger.ZERO; + + assertThrows( + () -> { + navigableMap.subMap(last, true, first, false); + }, + IllegalArgumentException.class, description + + ": Must throw IllegalArgumentException when fromElement is not less then then toElement."); + + navigableMap.subMap(first, true, last, false); + } + + @Test(dataProvider = "NavigableMap", dataProviderClass = EmptyNavigableMap.class) + public void testSubMapRanges(String description, NavigableMap navigableMap) { + Object first = isDescending(navigableMap) ? BigInteger.TEN : BigInteger.ZERO; + Object last = (BigInteger.ZERO == first) ? BigInteger.TEN : BigInteger.ZERO; + + NavigableMap subMap = navigableMap.subMap(first, true, last, true); + + // same subset + subMap.subMap(first, true, last, true); + + // slightly smaller + NavigableMap ns = subMap.subMap(first, false, last, false); + // slight exapansion + assertThrows(() -> { + ns.subMap(first, true, last, true); + }, + IllegalArgumentException.class, + description + ": Expansion should not be allowed"); + + // much smaller + subMap.subMap(first, false, BigInteger.ONE, false); + } + + @Test(dataProvider = "NavigableMap", dataProviderClass = EmptyNavigableMap.class) + public void testheadMapRanges(String description, NavigableMap navigableMap) { + NavigableMap subMap = navigableMap.headMap(BigInteger.ONE, true); + + // same subset + subMap.headMap(BigInteger.ONE, true); + + // slightly smaller + NavigableMap ns = subMap.headMap(BigInteger.ONE, false); + + // slight exapansion + assertThrows(() -> { + ns.headMap(BigInteger.ONE, true); + }, + IllegalArgumentException.class, + description + ": Expansion should not be allowed"); + + // much smaller + subMap.headMap(isDescending(subMap) ? BigInteger.TEN : BigInteger.ZERO, true); + } + + @Test(dataProvider = "NavigableMap", dataProviderClass = EmptyNavigableMap.class) + public void testTailMapRanges(String description, NavigableMap navigableMap) { + NavigableMap subMap = navigableMap.tailMap(BigInteger.ONE, true); + + // same subset + subMap.tailMap(BigInteger.ONE, true); + + // slightly smaller + NavigableMap ns = subMap.tailMap(BigInteger.ONE, false); + + // slight exapansion + assertThrows(() -> { + ns.tailMap(BigInteger.ONE, true); + }, + IllegalArgumentException.class, + description + ": Expansion should not be allowed"); + + // much smaller + subMap.tailMap(isDescending(subMap) ? BigInteger.ZERO : BigInteger.TEN, false); + } + + /** + * Tests the tailMap() method. + */ + @Test(dataProvider = "NavigableMap", dataProviderClass = EmptyNavigableMap.class) + public void testTailMap(String description, NavigableMap navigableMap) { + assertThrows(() -> { + navigableMap.tailMap(null); + }, + NullPointerException.class, + description + ": Must throw NullPointerException for null element"); + + assertThrows(() -> { + navigableMap.tailMap(new Object()); + }, ClassCastException.class); + + NavigableMap ss = navigableMap.tailMap("1", true); + + assertEmptyNavigableMap(ss, description + ": Returned value is not empty navigable set."); + } + + @DataProvider(name = "NavigableMap", parallel = true) + public static Iterator navigableMapsProvider() { + return makeNavigableMaps().iterator(); + } + + public static Collection makeNavigableMaps() { + return Arrays.asList( + new Object[]{"UnmodifiableNavigableMap(TreeMap)", Collections.unmodifiableNavigableMap(new TreeMap())}, + new Object[]{"UnmodifiableNavigableMap(TreeMap.descendingMap()", Collections.unmodifiableNavigableMap(new TreeMap().descendingMap())}, + new Object[]{"UnmodifiableNavigableMap(TreeMap.descendingMap().descendingMap()", Collections.unmodifiableNavigableMap(new TreeMap().descendingMap().descendingMap())}, + new Object[]{"emptyNavigableMap()", Collections.emptyNavigableMap()}, + new Object[]{"emptyNavigableMap().descendingMap()", Collections.emptyNavigableMap().descendingMap()}, + new Object[]{"emptyNavigableMap().descendingMap().descendingMap()", Collections.emptyNavigableMap().descendingMap().descendingMap()} + ); + } +} diff --git a/jdk/test/java/util/Collections/EmptyNavigableSet.java b/jdk/test/java/util/Collections/EmptyNavigableSet.java new file mode 100644 index 00000000000..7c4811bdfe8 --- /dev/null +++ b/jdk/test/java/util/Collections/EmptyNavigableSet.java @@ -0,0 +1,410 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4533691 7129185 + * @summary Unit test for Collections.emptyNavigableSet + * @run testng EmptyNavigableSet + */ +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.NavigableSet; +import java.util.SortedSet; +import java.util.TreeSet; +import org.testng.annotations.Test; +import org.testng.annotations.DataProvider; + +import static org.testng.Assert.fail; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertSame; + +public class EmptyNavigableSet { + + public static void assertInstance(T actual, Class expected) { + assertInstance(expected.isInstance(actual), null); + } + + public static void assertInstance(T actual, Class expected, String message) { + assertTrue(expected.isInstance(actual), ((null != message) ? message : "") + + " " + (actual == null ? "" : actual.getClass().getSimpleName()) + " != " + expected.getSimpleName() + ". "); + } + + public static void assertEmptyNavigableSet(Object obj) { + assertInstance(obj, NavigableSet.class); + assertTrue(((NavigableSet)obj).isEmpty() && (((NavigableSet)obj).size() == 0)); + } + + public static void assertEmptyNavigableSet(Object obj, String message) { + assertInstance(obj, NavigableSet.class, message); + assertTrue(((NavigableSet)obj).isEmpty() && (((NavigableSet)obj).size() == 0), + ((null != message) ? message : "") + " Not empty. "); + } + + public interface Thrower { + + public void run() throws T; + } + + public static void assertThrows(Thrower thrower, Class throwable) { + assertThrows(thrower, throwable, null); + } + + public static void assertThrows(Thrower thrower, Class throwable, String message) { + Throwable result; + try { + thrower.run(); + fail(((null != message) ? message : "") + "Failed to throw " + throwable.getCanonicalName() + ". "); + return; + } catch (Throwable caught) { + result = caught; + } + + assertInstance(result, throwable, ((null != message) ? message : "") + "Failed to throw " + throwable.getCanonicalName() + ". "); + } + + public static final boolean isDescending(SortedSet set) { + if (null == set.comparator()) { + // natural order + return false; + } + + if (Collections.reverseOrder() == set.comparator()) { + // reverse natural order. + return true; + } + + if (set.comparator().equals(Collections.reverseOrder(Collections.reverseOrder(set.comparator())))) { + // it's a Collections.reverseOrder(Comparator). + return true; + } + + throw new IllegalStateException("can't determine ordering for " + set); + } + + /** + * Tests that the comparator is {@code null}. + */ + @Test(dataProvider = "NavigableSet", dataProviderClass = EmptyNavigableSet.class) + public void testComparatorIsNull(String description, NavigableSet navigableSet) { + Comparator comparator = navigableSet.comparator(); + + assertTrue(comparator == null || comparator == Collections.reverseOrder(), description + ": Comparator (" + comparator + ") is not null."); + } + + /** + * Tests that contains requires Comparable + */ + @Test(dataProvider = "NavigableSet", dataProviderClass = EmptyNavigableSet.class) + public void testContainsRequiresComparable(String description, NavigableSet navigableSet) { + assertThrows(() -> { + navigableSet.contains(new Object()); + }, + ClassCastException.class, + description + ": Compareable should be required"); + } + + /** + * Tests that the contains method returns {@code false}. + */ + @Test(dataProvider = "NavigableSet", dataProviderClass = EmptyNavigableSet.class) + public void testContains(String description, NavigableSet navigableSet) { + assertFalse(navigableSet.contains(new Integer(1)), + description + ": Should not contain any elements."); + } + + /** + * Tests that the containsAll method returns {@code false}. + */ + @Test(dataProvider = "NavigableSet", dataProviderClass = EmptyNavigableSet.class) + public void testContainsAll(String description, NavigableSet navigableSet) { + TreeSet treeSet = new TreeSet(); + treeSet.add("1"); + treeSet.add("2"); + treeSet.add("3"); + + assertFalse(navigableSet.containsAll(treeSet), "Should not contain any elements."); + } + + /** + * Tests that the iterator is empty. + */ + @Test(dataProvider = "NavigableSet", dataProviderClass = EmptyNavigableSet.class) + public void testEmptyIterator(String description, NavigableSet navigableSet) { + Iterator emptyIterator = navigableSet.iterator(); + + assertFalse((emptyIterator != null) && (emptyIterator.hasNext()), + "The iterator is not empty."); + } + + /** + * Tests that the set is empty. + */ + @Test(dataProvider = "NavigableSet", dataProviderClass = EmptyNavigableSet.class) + public void testIsEmpty(String description, NavigableSet navigableSet) { + assertTrue(navigableSet.isEmpty(), "The set is not empty."); + } + + /** + * Tests that the first() method throws NoSuchElementException + */ + @Test(dataProvider = "NavigableSet", dataProviderClass = EmptyNavigableSet.class) + public void testFirst(String description, NavigableSet navigableSet) { + assertThrows(() -> { + navigableSet.first(); + }, NoSuchElementException.class, description); + } + + /** + * Tests the headSet() method. + */ + @Test(dataProvider = "NavigableSet", dataProviderClass = EmptyNavigableSet.class) + public void testHeadSet(String description, NavigableSet navigableSet) { + assertThrows( + () -> { NavigableSet ns = navigableSet.headSet(null, false); }, + NullPointerException.class, + description + ": Must throw NullPointerException for null element"); + + assertThrows( + () -> { NavigableSet ns = navigableSet.headSet(new Object(), true); }, + ClassCastException.class, + description + ": Must throw ClassCastException for non-Comparable element"); + + NavigableSet ns = navigableSet.headSet("1", false); + + assertEmptyNavigableSet(ns, description + ": Returned value is not empty navigable set."); + } + + /** + * Tests that the last() method throws NoSuchElementException + */ + @Test(dataProvider = "NavigableSet", dataProviderClass = EmptyNavigableSet.class) + public void testLast(String description, NavigableSet navigableSet) { + assertThrows(() -> { + navigableSet.last(); + }, NoSuchElementException.class, description); + } + + /** + * Tests that the size is 0. + */ + @Test(dataProvider = "NavigableSet", dataProviderClass = EmptyNavigableSet.class) + public void testSizeIsZero(String description, NavigableSet navigableSet) { + assertTrue(0 == navigableSet.size(), "The size of the set is not 0."); + } + + /** + * Tests the subSet() method. + */ + @Test(dataProvider = "NavigableSet", dataProviderClass = EmptyNavigableSet.class) + public void testSubSet(String description, NavigableSet navigableSet) { + assertThrows( + () -> { + SortedSet ss = navigableSet.subSet(null, BigInteger.TEN); + }, + NullPointerException.class, + description + ": Must throw NullPointerException for null element"); + + assertThrows( + () -> { + SortedSet ss = navigableSet.subSet(BigInteger.ZERO, null); + }, + NullPointerException.class, + description + ": Must throw NullPointerException for null element"); + + assertThrows( + () -> { + SortedSet ss = navigableSet.subSet(null, null); + }, + NullPointerException.class, + description + ": Must throw NullPointerException for null element"); + + Object obj1 = new Object(); + Object obj2 = new Object(); + + assertThrows( + () -> { + SortedSet ss = navigableSet.subSet(obj1, BigInteger.TEN); + }, + ClassCastException.class, description + + ": Must throw ClassCastException for parameter which is not Comparable."); + + assertThrows( + () -> { + SortedSet ss = navigableSet.subSet(BigInteger.ZERO, obj2); + }, + ClassCastException.class, description + + ": Must throw ClassCastException for parameter which is not Comparable."); + + assertThrows( + () -> { + SortedSet ss = navigableSet.subSet(obj1, obj2); + }, + ClassCastException.class, description + + ": Must throw ClassCastException for parameter which is not Comparable."); + + // minimal range + navigableSet.subSet(BigInteger.ZERO, false, BigInteger.ZERO, false); + navigableSet.subSet(BigInteger.ZERO, false, BigInteger.ZERO, true); + navigableSet.subSet(BigInteger.ZERO, true, BigInteger.ZERO, false); + navigableSet.subSet(BigInteger.ZERO, true, BigInteger.ZERO, true); + + Object first = isDescending(navigableSet) ? BigInteger.TEN : BigInteger.ZERO; + Object last = (BigInteger.ZERO == first) ? BigInteger.TEN : BigInteger.ZERO; + + assertThrows( + () -> { + navigableSet.subSet(last, true, first, false); + }, + IllegalArgumentException.class, description + + ": Must throw IllegalArgumentException when fromElement is not less then then toElement."); + + navigableSet.subSet(first, true, last, false); + } + + @Test(dataProvider = "NavigableSet", dataProviderClass = EmptyNavigableSet.class) + public void testSubSetRanges(String description, NavigableSet navigableSet) { + Object first = isDescending(navigableSet) ? BigInteger.TEN : BigInteger.ZERO; + Object last = (BigInteger.ZERO == first) ? BigInteger.TEN : BigInteger.ZERO; + + NavigableSet subSet = navigableSet.subSet(first, true, last, true); + + // same subset + subSet.subSet(first, true, last, true); + + // slightly smaller + NavigableSet ns = subSet.subSet(first, false, last, false); + // slight exapansion + assertThrows(() -> { + ns.subSet(first, true, last, true); + }, + IllegalArgumentException.class, + description + ": Expansion should not be allowed"); + + // much smaller + subSet.subSet(first, false, BigInteger.ONE, false); + } + + @Test(dataProvider = "NavigableSet", dataProviderClass = EmptyNavigableSet.class) + public void testheadSetRanges(String description, NavigableSet navigableSet) { + NavigableSet subSet = navigableSet.headSet(BigInteger.ONE, true); + + // same subset + subSet.headSet(BigInteger.ONE, true); + + // slightly smaller + NavigableSet ns = subSet.headSet(BigInteger.ONE, false); + + // slight exapansion + assertThrows(() -> { + ns.headSet(BigInteger.ONE, true); + }, + IllegalArgumentException.class, + description + ": Expansion should not be allowed"); + + // much smaller + subSet.headSet(isDescending(subSet) ? BigInteger.TEN : BigInteger.ZERO, true); + } + + @Test(dataProvider = "NavigableSet", dataProviderClass = EmptyNavigableSet.class) + public void testTailSetRanges(String description, NavigableSet navigableSet) { + NavigableSet subSet = navigableSet.tailSet(BigInteger.ONE, true); + + // same subset + subSet.tailSet(BigInteger.ONE, true); + + // slightly smaller + NavigableSet ns = subSet.tailSet(BigInteger.ONE, false); + + // slight exapansion + assertThrows(() -> { + ns.tailSet(BigInteger.ONE, true); + }, + IllegalArgumentException.class, + description + ": Expansion should not be allowed"); + + // much smaller + subSet.tailSet(isDescending(subSet) ? BigInteger.ZERO : BigInteger.TEN, false); + } + + /** + * Tests the tailSet() method. + */ + @Test(dataProvider = "NavigableSet", dataProviderClass = EmptyNavigableSet.class) + public void testTailSet(String description, NavigableSet navigableSet) { + assertThrows(() -> { + navigableSet.tailSet(null); + }, + NullPointerException.class, + description + ": Must throw NullPointerException for null element"); + + assertThrows(() -> { + navigableSet.tailSet(new Object()); + }, ClassCastException.class); + + NavigableSet ss = navigableSet.tailSet("1", true); + + assertEmptyNavigableSet(ss, description + ": Returned value is not empty navigable set."); + } + + /** + * Tests that the array has a size of 0. + */ + @Test(dataProvider = "NavigableSet", dataProviderClass = EmptyNavigableSet.class) + public void testToArray(String description, NavigableSet navigableSet) { + Object[] emptyNavigableSetArray = navigableSet.toArray(); + + assertTrue(emptyNavigableSetArray.length == 0, "Returned non-empty Array."); + + emptyNavigableSetArray = new Object[20]; + + Object[] result = navigableSet.toArray(emptyNavigableSetArray); + + assertSame(emptyNavigableSetArray, result); + + assertTrue(result[0] == null); + } + + @DataProvider(name = "NavigableSet", parallel = true) + public static Iterator navigableSetsProvider() { + return makeNavigableSets().iterator(); + } + + public static Collection makeNavigableSets() { + return Arrays.asList( + new Object[]{"UnmodifiableNavigableSet(TreeSet)", Collections.unmodifiableNavigableSet(new TreeSet())}, + new Object[]{"UnmodifiableNavigableSet(TreeSet.descendingSet()", Collections.unmodifiableNavigableSet(new TreeSet().descendingSet())}, + new Object[]{"UnmodifiableNavigableSet(TreeSet.descendingSet().descendingSet()", Collections.unmodifiableNavigableSet(new TreeSet().descendingSet().descendingSet())}, + new Object[]{"emptyNavigableSet()", Collections.emptyNavigableSet()}, + new Object[]{"emptyNavigableSet().descendingSet()", Collections.emptyNavigableSet().descendingSet()}, + new Object[]{"emptyNavigableSet().descendingSet().descendingSet()", Collections.emptyNavigableSet().descendingSet().descendingSet()} + ); + } +} diff --git a/jdk/test/java/util/Collections/EmptySortedSet.java b/jdk/test/java/util/Collections/EmptySortedSet.java deleted file mode 100644 index 224400ec7a8..00000000000 --- a/jdk/test/java/util/Collections/EmptySortedSet.java +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4533691 - * @summary Unit test for Collections.emptySortedSet - */ - -import java.lang.reflect.Method; -import java.math.BigInteger; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.SortedSet; -import java.util.TreeSet; - -public class EmptySortedSet { - static int status = 0; - private static final String FAILED = " failed. "; - private static final String PERIOD = "."; - private final String thisClassName = this.getClass().getName(); - - public static void main(String[] args) throws Exception { - new EmptySortedSet(); - } - - public EmptySortedSet() throws Exception { - run(); - } - - /** - * Returns {@code true} if the {@link Object} passed in is an empty - * {@link SortedSet}. - * - * @param obj the object to test - * @return {@code true} if the {@link Object} is an empty {@link SortedSet} - * otherwise {@code false}. - */ - private boolean isEmptySortedSet(Object obj) { - boolean isEmptySortedSet = false; - - // We determine if the object is an empty sorted set by testing if it's - // an instance of SortedSet, and if so, if it's empty. Currently the - // testing doesn't include checks of the other methods. - if (obj instanceof SortedSet) { - SortedSet ss = (SortedSet) obj; - - if ((ss.isEmpty()) && (ss.size() == 0)) { - isEmptySortedSet = true; - } - } - - return isEmptySortedSet; - } - - private void run() throws Exception { - Method[] methods = this.getClass().getDeclaredMethods(); - - for (int i = 0; i < methods.length; i++) { - Method method = methods[i]; - String methodName = method.getName(); - - if (methodName.startsWith("test")) { - try { - Object obj = method.invoke(this, new Object[0]); - } catch(Exception e) { - throw new Exception(this.getClass().getName() + "." + - methodName + " test failed, test exception " - + "follows\n" + e.getCause()); - } - } - } - } - - private void throwException(String methodName, String reason) - throws Exception - { - StringBuilder sb = new StringBuilder(thisClassName); - sb.append(PERIOD); - sb.append(methodName); - sb.append(FAILED); - sb.append(reason); - throw new Exception(sb.toString()); - } - - /** - * - */ - private void test00() throws Exception { - //throwException("test00", "This test has not been implemented yet."); - } - - /** - * Tests that the comparator is {@code null}. - */ - private void testComparatorIsNull() throws Exception { - SortedSet sortedSet = Collections.emptySortedSet(); - Comparator comparator = sortedSet.comparator(); - - if (comparator != null) { - throwException("testComparatorIsNull", "Comparator is not null."); - } - } - - /** - * Tests that the contains method returns {@code false}. - */ - private void testContains() throws Exception { - SortedSet sortedSet = Collections.emptySortedSet(); - - if (sortedSet.contains(new Object())) { - throwException("testContains", "Should not contain any elements."); - } - } - - /** - * Tests that the containsAll method returns {@code false}. - */ - private void testContainsAll() throws Exception { - SortedSet sortedSet = Collections.emptySortedSet(); - TreeSet treeSet = new TreeSet(); - treeSet.add("1"); - treeSet.add("2"); - treeSet.add("3"); - - if (sortedSet.containsAll(treeSet)) { - throwException("testContainsAll", - "Should not contain any elements."); - } - } - - /** - * Tests that the iterator is empty. - */ - private void testEmptyIterator() throws Exception { - SortedSet sortedSet = Collections.emptySortedSet(); - Iterator emptyIterator = sortedSet.iterator(); - - if ((emptyIterator != null) && (emptyIterator.hasNext())) { - throwException("testEmptyIterator", "The iterator is not empty."); - } - } - - /** - * Tests that the set is empty. - */ - private void testIsEmpty() throws Exception { - SortedSet sortedSet = Collections.emptySortedSet(); - - if ((sortedSet != null) && (!sortedSet.isEmpty())) { - throwException("testSizeIsZero", "The set is not empty."); - } - } - - /** - * Tests that the first() method throws NoSuchElementException - */ - private void testFirst() throws Exception { - SortedSet sortedSet = Collections.emptySortedSet(); - - try { - sortedSet.first(); - throwException("testFirst", - "NoSuchElemenException was not thrown."); - } catch(NoSuchElementException nsee) { - // Do nothing - } - } - - /** - * Tests the headSet() method. - */ - private void testHeadSet() throws Exception { - SortedSet sortedSet = Collections.emptySortedSet(); - SortedSet ss; - - try { - ss = sortedSet.headSet(null); - throwException("testHeadSet", - "Must throw NullPointerException for null element"); - } catch(NullPointerException npe) { - // Do nothing - } - - try { - ss = sortedSet.headSet(new Object()); - throwException("testHeadSet", - "Must throw ClassCastException for non-Comparable element"); - } catch(ClassCastException cce) { - // Do nothing. - } - - ss = sortedSet.headSet("1"); - - if ((ss == null) || !isEmptySortedSet(ss)) { - throwException("testHeadSet", - "Returned value is null or not an EmptySortedSet."); - } - } - - /** - * Tests that the last() method throws NoSuchElementException - */ - private void testLast() throws Exception { - SortedSet sortedSet = Collections.emptySortedSet(); - - try { - sortedSet.last(); - throwException("testLast", - "NoSuchElemenException was not thrown."); - } catch(NoSuchElementException nsee) { - // Do nothing - } - } - - /** - * Tests that the size is 0. - */ - private void testSizeIsZero() throws Exception { - SortedSet sortedSet = Collections.emptySortedSet(); - int size = sortedSet.size(); - - if (size > 0) { - throwException("testSizeIsZero", - "The size of the set is greater then 0."); - } - } - - /** - * Tests the subSet() method. - */ - private void testSubSet() throws Exception { - SortedSet sortedSet = Collections.emptySortedSet(); - SortedSet ss = sortedSet.headSet("1"); - - try { - ss = sortedSet.subSet(null, BigInteger.TEN); - ss = sortedSet.subSet(BigInteger.ZERO, null); - ss = sortedSet.subSet(null, null); - throwException("testSubSet", - "Must throw NullPointerException for null element"); - } catch(NullPointerException npe) { - // Do nothing - } - - try { - Object obj1 = new Object(); - Object obj2 = new Object(); - ss = sortedSet.subSet(obj1, BigInteger.TEN); - ss = sortedSet.subSet(BigInteger.ZERO, obj2); - ss = sortedSet.subSet(obj1, obj2); - throwException("testSubSet", - "Must throw ClassCastException for parameter which is " - + "not Comparable."); - } catch(ClassCastException cce) { - // Do nothing. - } - - try { - ss = sortedSet.subSet(BigInteger.ZERO, BigInteger.ZERO); - ss = sortedSet.subSet(BigInteger.TEN, BigInteger.ZERO); - throwException("testSubSet", - "Must throw IllegalArgumentException when fromElement is " - + "not less then then toElement."); - } catch(IllegalArgumentException iae) { - // Do nothing. - } - - ss = sortedSet.subSet(BigInteger.ZERO, BigInteger.TEN); - - if (!isEmptySortedSet(ss)) { - throw new Exception("Returned value is not empty sorted set."); - } - } - - /** - * Tests the tailSet() method. - */ - private void testTailSet() throws Exception { - SortedSet sortedSet = Collections.emptySortedSet(); - SortedSet ss; - - try { - ss = sortedSet.tailSet(null); - throwException("testTailSet", - "Must throw NullPointerException for null element"); - } catch(NullPointerException npe) { - // Do nothing - } - - try { - SortedSet ss2 = sortedSet.tailSet(new Object()); - throwException("testTailSet", - "Must throw ClassCastException for non-Comparable element"); - } catch(ClassCastException cce) { - // Do nothing. - } - - ss = sortedSet.tailSet("1"); - - if ((ss == null) || !isEmptySortedSet(ss)) { - throwException("testTailSet", - "Returned value is null or not an EmptySortedSet."); - } - } - - /** - * Tests that the array has a size of 0. - */ - private void testToArray() throws Exception { - SortedSet sortedSet = Collections.emptySortedSet(); - Object[] emptySortedSetArray = sortedSet.toArray(); - - if ((emptySortedSetArray == null) || (emptySortedSetArray.length > 0)) { - throwException("testToArray", - "Returned null array or array with length > 0."); - } - - String[] strings = new String[2]; - strings[0] = "1"; - strings[1] = "2"; - emptySortedSetArray = sortedSet.toArray(strings); - - if ((emptySortedSetArray == null) || (emptySortedSetArray[0] != null)) { - throwException("testToArray", - "Returned null array or array with length > 0."); - } - } -} diff --git a/jdk/test/java/util/Map/LockStep.java b/jdk/test/java/util/Map/LockStep.java index 553644782ce..2903c5a5f50 100644 --- a/jdk/test/java/util/Map/LockStep.java +++ b/jdk/test/java/util/Map/LockStep.java @@ -100,7 +100,14 @@ public class LockStep { new Hashtable(16), new TreeMap(), new ConcurrentHashMap(16), - new ConcurrentSkipListMap() }); + new ConcurrentSkipListMap(), + Collections.checkedMap(new HashMap(16), Integer.class, Integer.class), + Collections.checkedSortedMap(new TreeMap(), Integer.class, Integer.class), + Collections.checkedNavigableMap(new TreeMap(), Integer.class, Integer.class), + Collections.synchronizedMap(new HashMap(16)), + Collections.synchronizedSortedMap(new TreeMap()), + Collections.synchronizedNavigableMap(new TreeMap()) + }); for (int j = 0; j < 10; j++) put(maps, r.nextInt(100), r.nextInt(100)); diff --git a/jdk/test/java/util/NavigableMap/LockStep.java b/jdk/test/java/util/NavigableMap/LockStep.java index 64f9bdf7683..0b43d0a0744 100644 --- a/jdk/test/java/util/NavigableMap/LockStep.java +++ b/jdk/test/java/util/NavigableMap/LockStep.java @@ -55,11 +55,19 @@ public class LockStep { lockSteps(new TreeMap(), new ConcurrentSkipListMap()); + lockSteps(new TreeMap(), + Collections.checkedNavigableMap(new TreeMap(), Integer.class, Integer.class)); + lockSteps(new TreeMap(), + Collections.synchronizedNavigableMap(new TreeMap())); lockSteps(new TreeMap(reverseOrder()), new ConcurrentSkipListMap(reverseOrder())); lockSteps(new TreeSet(), new ConcurrentSkipListSet()); + lockSteps(new TreeSet(), + Collections.checkedNavigableSet(new TreeSet(), Integer.class)); + lockSteps(new TreeSet(), + Collections.synchronizedNavigableSet(new TreeSet())); lockSteps(new TreeSet(reverseOrder()), new ConcurrentSkipListSet(reverseOrder())); } @@ -181,7 +189,15 @@ public class LockStep { testEmptyCollection(m.values()); } - static final Random rnd = new Random(); + static final Random rnd; + + static { + // sufficiently random for this test + long seed = System.nanoTime(); + System.out.println(LockStep.class.getCanonicalName() + ": Trial random seed: " + seed ); + + rnd = new Random(seed); + } static void equalNext(final Iterator it, Object expected) { if (maybe(2)) @@ -208,8 +224,15 @@ public class LockStep { check(s.descendingSet().descendingSet().comparator() == null); equal(s.isEmpty(), s.size() == 0); equal2(s, s.descendingSet()); - if (maybe(4) && s instanceof Serializable) - equal2(s, serialClone(s)); + if (maybe(4) && s instanceof Serializable) { + try { + equal2(s, serialClone(s)); + } catch(RuntimeException uhoh) { + if(!(uhoh.getCause() instanceof NotSerializableException)) { + throw uhoh; + } + } + } Comparator cmp = comparator(s); if (s.isEmpty()) { THROWS(NoSuchElementException.class, @@ -276,6 +299,15 @@ public class LockStep { check(! it2.hasNext()); } + static void equalSetsLeaf(final Set s1, final Set s2) { + equal2(s1, s2); + equal( s1.size(), s2.size()); + equal( s1.isEmpty(), s2.isEmpty()); + equal( s1.hashCode(), s2.hashCode()); + equal( s1.toString(), s2.toString()); + equal( s1.containsAll(s2), s2.containsAll(s1)); + } + static void equalNavigableSetsLeaf(final NavigableSet s1, final NavigableSet s2) { equal2(s1, s2); @@ -448,8 +480,7 @@ public class LockStep { static void equalNavigableMaps(NavigableMap m1, NavigableMap m2) { equalNavigableMapsLeaf(m1, m2); - equalNavigableSetsLeaf((NavigableSet) m1.keySet(), - (NavigableSet) m2.keySet()); + equalSetsLeaf(m1.keySet(), m2.keySet()); equalNavigableSets(m1.navigableKeySet(), m2.navigableKeySet()); equalNavigableSets(m1.descendingKeySet(), @@ -836,5 +867,7 @@ public class LockStep { @SuppressWarnings("unchecked") static T serialClone(T obj) { try { return (T) readObject(serializedForm(obj)); } - catch (Exception e) { throw new RuntimeException(e); }} + catch (Error|RuntimeException e) { throw e; } + catch (Throwable e) { throw new RuntimeException(e); } + } } From 53edbe01cb589ca959e7cd6bf4055b13d749c788 Mon Sep 17 00:00:00 2001 From: Brian Goetz Date: Fri, 12 Jul 2013 11:12:16 -0700 Subject: [PATCH 058/123] 8015317: Optional.filter, map, and flatMap Co-authored-by: Henry Jen Reviewed-by: psandoz, mduigou --- jdk/src/share/classes/java/util/Optional.java | 105 +++++++++++- .../classes/java/util/OptionalDouble.java | 10 +- .../share/classes/java/util/OptionalInt.java | 8 +- .../share/classes/java/util/OptionalLong.java | 10 +- jdk/test/java/util/Optional/Basic.java | 154 +++++++++++++++--- 5 files changed, 250 insertions(+), 37 deletions(-) diff --git a/jdk/src/share/classes/java/util/Optional.java b/jdk/src/share/classes/java/util/Optional.java index b51a4d26122..4e95e18684b 100644 --- a/jdk/src/share/classes/java/util/Optional.java +++ b/jdk/src/share/classes/java/util/Optional.java @@ -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 @@ public final class Optional { 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 @@ public final class Optional { } /** - * 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 @@ public final class Optional { } /** - * 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 @@ -98,6 +100,18 @@ public final class Optional { return new Optional<>(value); } + /** + * 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 Optional 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 @@ public final class Optional { } /** - * 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 @@ -136,6 +150,89 @@ public final class Optional { consumer.accept(value); } + /** + * 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 filter(Predicate 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}: + * + *
        {@code
        +     *     Optional fis =
        +     *         names.stream().filter(name -> !isProcessedYet(name))
        +     *                       .findFirst()
        +     *                       .map(name -> new FileInputStream(name));
        +     * }
        + * + * Here, {@code findFirst} returns an {@code Optional}, and then + * {@code map} returns an {@code Optional} for the desired + * file if one exists. + * + * @param 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 Optional map(Function 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 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 Optional flatMap(Function> mapper) { + Objects.requireNonNull(mapper); + if (!isPresent()) + return empty(); + else { + return Objects.requireNonNull(mapper.apply(value)); + } + } + /** * Return the value if present, otherwise return {@code other}. * diff --git a/jdk/src/share/classes/java/util/OptionalDouble.java b/jdk/src/share/classes/java/util/OptionalDouble.java index 118a4b8d017..eda306cf7d4 100644 --- a/jdk/src/share/classes/java/util/OptionalDouble.java +++ b/jdk/src/share/classes/java/util/OptionalDouble.java @@ -186,10 +186,10 @@ public final class OptionalDouble { } /** - * 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: *
          - *
        • it is also an {@code OptionalInt} and; + *
        • it is also an {@code OptionalDouble} and; *
        • both instances have no value present or; *
        • the present values are "equal to" each other via {@code Double.compare() == 0}. *
        @@ -226,12 +226,14 @@ public final class OptionalDouble { } /** - * 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 diff --git a/jdk/src/share/classes/java/util/OptionalInt.java b/jdk/src/share/classes/java/util/OptionalInt.java index 755c2870b73..66478ce4713 100644 --- a/jdk/src/share/classes/java/util/OptionalInt.java +++ b/jdk/src/share/classes/java/util/OptionalInt.java @@ -186,7 +186,7 @@ public final class OptionalInt { } /** - * 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: *
          *
        • it is also an {@code OptionalInt} and; @@ -226,12 +226,14 @@ public final class OptionalInt { } /** - * 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 diff --git a/jdk/src/share/classes/java/util/OptionalLong.java b/jdk/src/share/classes/java/util/OptionalLong.java index fbb1661cc25..f07cc0d3d3a 100644 --- a/jdk/src/share/classes/java/util/OptionalLong.java +++ b/jdk/src/share/classes/java/util/OptionalLong.java @@ -186,10 +186,10 @@ public final class OptionalLong { } /** - * 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: *
            - *
          • it is also an {@code OptionalInt} and; + *
          • it is also an {@code OptionalLong} and; *
          • both instances have no value present or; *
          • the present values are "equal to" each other via {@code ==}. *
          @@ -226,12 +226,14 @@ public final class OptionalLong { } /** - * 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 diff --git a/jdk/test/java/util/Optional/Basic.java b/jdk/test/java/util/Optional/Basic.java index 099e0455985..dc05ff97a78 100644 --- a/jdk/test/java/util/Optional/Basic.java +++ b/jdk/test/java/util/Optional/Basic.java @@ -58,36 +58,36 @@ public class Basic { assertSame(Boolean.FALSE, empty.orElseGet(()-> Boolean.FALSE)); } - @Test(expectedExceptions=NoSuchElementException.class) - public void testEmptyGet() { - Optional empty = Optional.empty(); + @Test(expectedExceptions=NoSuchElementException.class) + public void testEmptyGet() { + Optional empty = Optional.empty(); - Boolean got = empty.get(); - } + Boolean got = empty.get(); + } - @Test(expectedExceptions=NullPointerException.class) - public void testEmptyOrElseGetNull() { - Optional empty = Optional.empty(); + @Test(expectedExceptions=NullPointerException.class) + public void testEmptyOrElseGetNull() { + Optional empty = Optional.empty(); - Boolean got = empty.orElseGet(null); - } + Boolean got = empty.orElseGet(null); + } - @Test(expectedExceptions=NullPointerException.class) - public void testEmptyOrElseThrowNull() throws Throwable { - Optional empty = Optional.empty(); + @Test(expectedExceptions=NullPointerException.class) + public void testEmptyOrElseThrowNull() throws Throwable { + Optional empty = Optional.empty(); - Boolean got = empty.orElseThrow(null); - } + Boolean got = empty.orElseThrow(null); + } - @Test(expectedExceptions=ObscureException.class) - public void testEmptyOrElseThrow() throws Exception { - Optional empty = Optional.empty(); + @Test(expectedExceptions=ObscureException.class) + public void testEmptyOrElseThrow() throws Exception { + Optional empty = Optional.empty(); - Boolean got = empty.orElseThrow(ObscureException::new); - } + Boolean got = empty.orElseThrow(ObscureException::new); + } - @Test(groups = "unit") - public void testPresent() { + @Test(groups = "unit") + public void testPresent() { Optional empty = Optional.empty(); Optional presentEmptyString = Optional.of(""); Optional present = Optional.of(Boolean.TRUE); @@ -116,6 +116,116 @@ public class Basic { assertSame(Boolean.TRUE, present.orElseThrow(ObscureException::new)); } + @Test(groups = "unit") + public void testOfNullable() { + Optional instance = Optional.ofNullable(null); + assertFalse(instance.isPresent()); + + instance = Optional.ofNullable("Duke"); + assertTrue(instance.isPresent()); + assertEquals(instance.get(), "Duke"); + } + + @Test(groups = "unit") + public void testFilter() { + // Null mapper function + Optional empty = Optional.empty(); + Optional duke = Optional.of("Duke"); + + try { + Optional result = empty.filter(null); + fail("Should throw NPE on null mapping function"); + } catch (NullPointerException npe) { + // expected + } + + Optional result = empty.filter(String::isEmpty); + assertFalse(result.isPresent()); + + result = duke.filter(String::isEmpty); + assertFalse(result.isPresent()); + result = duke.filter(s -> s.startsWith("D")); + assertTrue(result.isPresent()); + assertEquals(result.get(), "Duke"); + + Optional emptyString = Optional.of(""); + result = emptyString.filter(String::isEmpty); + assertTrue(result.isPresent()); + assertEquals(result.get(), ""); + } + + @Test(groups = "unit") + public void testMap() { + Optional empty = Optional.empty(); + Optional duke = Optional.of("Duke"); + + // Null mapper function + try { + Optional b = empty.map(null); + fail("Should throw NPE on null mapping function"); + } catch (NullPointerException npe) { + // expected + } + + // Map an empty value + Optional b = empty.map(String::isEmpty); + assertFalse(b.isPresent()); + + // Map into null + b = empty.map(n -> null); + assertFalse(b.isPresent()); + b = duke.map(s -> null); + assertFalse(b.isPresent()); + + // Map to value + Optional l = duke.map(String::length); + assertEquals(l.get().intValue(), 4); + } + + @Test(groups = "unit") + public void testFlatMap() { + Optional empty = Optional.empty(); + Optional duke = Optional.of("Duke"); + + // Null mapper function + try { + Optional b = empty.flatMap(null); + fail("Should throw NPE on null mapping function"); + } catch (NullPointerException npe) { + // expected + } + + // Map into null + try { + Optional b = duke.flatMap(s -> null); + fail("Should throw NPE when mapper return null"); + } catch (NullPointerException npe) { + // expected + } + + // Empty won't invoke mapper function + try { + Optional b = empty.flatMap(s -> null); + assertFalse(b.isPresent()); + } catch (NullPointerException npe) { + fail("Mapper function should not be invoked"); + } + + // Map an empty value + Optional l = empty.flatMap(s -> Optional.of(s.length())); + assertFalse(l.isPresent()); + + // Map to value + Optional fixture = Optional.of(Integer.MAX_VALUE); + l = duke.flatMap(s -> Optional.of(s.length())); + assertTrue(l.isPresent()); + assertEquals(l.get().intValue(), 4); + + // Verify same instance + l = duke.flatMap(s -> fixture); + assertSame(l, fixture); + } + private static class ObscureException extends RuntimeException { } From 593f3c74ba781d5bc278b347902bdb2614dbc918 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Fri, 12 Jul 2013 11:14:53 -0700 Subject: [PATCH 059/123] 8020430: NullPointerException in xml sqe nightly result on 2013-07-12 Reviewed-by: chegar, lancea --- .../jaxp/common/8020430/JAXP15RegTest.java | 63 ++++++++++++ .../xml/jaxp/common/8020430/TestBase.java | 95 +++++++++++++++++++ 2 files changed, 158 insertions(+) create mode 100644 jdk/test/javax/xml/jaxp/common/8020430/JAXP15RegTest.java create mode 100644 jdk/test/javax/xml/jaxp/common/8020430/TestBase.java diff --git a/jdk/test/javax/xml/jaxp/common/8020430/JAXP15RegTest.java b/jdk/test/javax/xml/jaxp/common/8020430/JAXP15RegTest.java new file mode 100644 index 00000000000..890fba45058 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/common/8020430/JAXP15RegTest.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8020430 + * @summary test that setProperty for XMLOutputFactory works properly + * @run main/othervm JAXP15RegTest + */ +import java.security.Policy; +import javax.xml.stream.XMLOutputFactory; + +/** + * @author huizhe.wang@oracle.com + */ +public class JAXP15RegTest extends TestBase { + + public JAXP15RegTest(String name) { + super(name); + } + + private boolean hasSM; + private Policy _orig; + + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + JAXP15RegTest test = new JAXP15RegTest("JAXP 1.5 regression"); + test.setUp(); + test.testXMLOutputFactory(); + test.tearDown(); + } + + + public void testXMLOutputFactory() { + XMLOutputFactory factory = XMLOutputFactory.newInstance(); + factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true); + success("testXMLOutputFactory passed"); + } + +} diff --git a/jdk/test/javax/xml/jaxp/common/8020430/TestBase.java b/jdk/test/javax/xml/jaxp/common/8020430/TestBase.java new file mode 100644 index 00000000000..c96a60aeb60 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/common/8020430/TestBase.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.security.Policy; + +/** + * + * + * @author huizhe.wang@oracle.com + */ +public class TestBase { + String filePath; + boolean hasSM; + String curDir; + Policy origPolicy; + + String testName; + static String errMessage; + + int passed = 0, failed = 0; + + /** + * Creates a new instance of StreamReader + */ + public TestBase(String name) { + testName = name; + } + + //junit @Override + protected void setUp() { + if (System.getSecurityManager() != null) { + hasSM = true; + System.setSecurityManager(null); + } + + filePath = System.getProperty("test.src"); + if (filePath == null) { + //current directory + filePath = System.getProperty("user.dir"); + } + origPolicy = Policy.getPolicy(); + + } + + //junit @Override + public void tearDown() { + // turn off security manager and restore policy + System.setSecurityManager(null); + Policy.setPolicy(origPolicy); + if (hasSM) { + System.setSecurityManager(new SecurityManager()); + } + System.out.println("\nNumber of tests passed: " + passed); + System.out.println("Number of tests failed: " + failed + "\n"); + + if (errMessage != null ) { + throw new RuntimeException(errMessage); + } + } + + void fail(String errMsg) { + if (errMessage == null) { + errMessage = errMsg; + } else { + errMessage = errMessage + "\n" + errMsg; + } + failed++; + } + + void success(String msg) { + passed++; + System.out.println(msg); + } + +} From 25154dcc20bdf11177bcfd17d2f9a8c6068f14b0 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Fri, 12 Jul 2013 11:48:23 -0700 Subject: [PATCH 060/123] 8010679: Clarify "present" and annotation ordering in Core Reflection for Annotations Reviewed-by: abuckley, jfranck --- .../java/lang/reflect/AnnotatedElement.java | 168 ++++++++++++------ 1 file changed, 112 insertions(+), 56 deletions(-) diff --git a/jdk/src/share/classes/java/lang/reflect/AnnotatedElement.java b/jdk/src/share/classes/java/lang/reflect/AnnotatedElement.java index 6bc894efaba..50a7e6af904 100644 --- a/jdk/src/share/classes/java/lang/reflect/AnnotatedElement.java +++ b/jdk/src/share/classes/java/lang/reflect/AnnotatedElement.java @@ -32,49 +32,101 @@ import java.lang.annotation.AnnotationFormatError; * 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. * *

          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. * - *

          The terms directly present and present are used - * throughout this interface to describe precisely which annotations are - * returned by methods: + *

          The terms directly present, indirectly present, + * present, and associated are used throughout this + * interface to describe precisely which annotations are returned by + * methods: * *

            - *
          • An annotation A is directly present on an element E if E is - * associated with a RuntimeVisibleAnnotations or - * RuntimeVisibleParameterAnnotations attribute, and: + * + *
          • An annotation A is directly present on an + * element E if E has a {@code + * RuntimeVisibleAnnotations} or {@code + * RuntimeVisibleParameterAnnotations} or {@code + * RuntimeVisibleTypeAnnotations} attribute, and the attribute + * contains A. + * + *
          • An annotation A is indirectly present on an + * element E if E has a {@code RuntimeVisibleAnnotations} or + * {@code RuntimeVisibleParameterAnnotations} or {@code RuntimeVisibleTypeAnnotations} + * attribute, and A 's type is repeatable, and the attribute contains + * exactly one annotation whose value element contains A and whose + * type is the containing annotation type of A 's type. + * + *
          • An annotation A is present on an element E if either: * *
              - *
            • for an invocation of {@code get[Declared]Annotation(Class)} or - * {@code get[Declared]Annotations()}, the attribute contains A. * - *
            • for an invocation of {@code get[Declared]AnnotationsByType(Class)}, 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). + *
            • A is directly present on E; or + * + *
            • No annotation of A 's type is directly present on + * E, and E is a class, and A 's type is + * inheritable, and A is present on the superclass of E. + * *
            * - *

            - *

          • An annotation A is present on an element E if either: + *
          • An annotation A is associated with an element E + * if either: * *
              - *
            • A is directly present on E; or * - *
            • A is not directly present on E, and E is a class, and A's type - * is inheritable (JLS 9.6.3.3), and A is present on the superclass of - * E. + *
            • A is directly or indirectly present on E; or + * + *
            • No annotation of A 's type is directly or indirectly + * present on E, and E is a class, and A's type + * is inheritable, and A is associated with the superclass of + * E. + * *
            * *
          * + *

          The table below summarizes which kind of annotation presence + * different methods in this interface examine. + * + *

    unicast
    + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Overview of kind of presence detected by different AnnotatedElement methods
    Kind of Presence
    MethodDirectly PresentIndirectly PresentPresentAssociated
    {@code T}{@link #getAnnotation(Class) getAnnotation(Class<T>)} + * X
    {@code Annotation[]}{@link #getAnnotations getAnnotations()} + * X
    {@code T[]}{@link #getAnnotationsByType(Class) getAnnotationsByType(Class<T>)} + * X
    {@code T}{@link #getDeclaredAnnotation(Class) getDeclaredAnnotation(Class<T>)} + * X
    {@code Annotation[]}{@link #getDeclaredAnnotations getDeclaredAnnotations()} + * X
    {@code T[]}{@link #getDeclaredAnnotationsByType(Class) getDeclaredAnnotationsByType(Class<T>)} + * XX
    + * + *

    For an invocation of {@code get[Declared]AnnotationsByType( Class < + * T >)}, the order of annotations which are directly or indirectly + * present on an element E is computed as if indirectly present + * annotations on E are directly present on E in place + * of their container annotation, in the order in which they appear in + * the value element of the container annotation. + *

    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 @@ import java.lang.annotation.AnnotationFormatError; * a {@link EnumConstantNotPresentException} if the enum constant in the * annotation is no longer present in the enum type. * - *

    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}. + *

    If an annotation type T is (meta-)annotated with an + * {@code @Repeatable} annotation whose value element indicates a type + * TC, but TC does not declare a {@code value()} method + * with a return type of T{@code []}, then an exception of type + * {@link java.lang.annotation.AnnotationFormatError} is thrown. * *

    Finally, attempting to read a member whose definition has evolved * incompatibly will result in a {@link @@ -106,7 +159,7 @@ import java.lang.annotation.AnnotationFormatError; public interface AnnotatedElement { /** * Returns true if an annotation for the specified type - * is present on this element, else false. This method + * is present on this element, else false. This method * is designed primarily for convenient access to marker annotations. * *

    The truth value returned by this method is equivalent to: @@ -128,7 +181,7 @@ public interface AnnotatedElement { /** * Returns this element's annotation for the specified type if - * such an annotation is present, else null. + * such an annotation is present, else null. * * @param the type of the annotation to query for and return if present * @param annotationClass the Class object corresponding to the @@ -146,6 +199,20 @@ public interface AnnotatedElement { * If there are no annotations present 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 associated with this element. + * + * If there are no annotations associated 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 repeatable * annotation type (JLS 9.6), and if so, attempts to find one or @@ -159,65 +226,54 @@ public interface AnnotatedElement { * @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[] getAnnotationsByType(Class annotationClass); - /** - * Returns annotations that are present on this element. - * - * If there are no annotations present 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 directly present, else null. * * This method ignores inherited annotations. (Returns null if no * annotations are directly present on this element.) * - * @param the type of the annotation to query for and return if present + * @param 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 getDeclaredAnnotation(Class annotationClass); /** - * Returns annotations that are directly present on this element. - * This method ignores inherited annotations. + * Returns this element's annotation(s) for the specified type if + * such annotations are either directly present or + * indirectly present. This method ignores inherited + * annotations. * - * If there are no annotations directly present 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 repeatable annotation type (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 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 */ From 4e416d4714b9668f5f5f3a812db8af29cb4ab1cf Mon Sep 17 00:00:00 2001 From: Brian Goetz Date: Fri, 12 Jul 2013 12:15:22 -0700 Subject: [PATCH 061/123] 8015315: Stream.concat methods Co-authored-by: Henry Jen Reviewed-by: psandoz, mduigou --- .../java/util/stream/DoubleStream.java | 22 ++ .../classes/java/util/stream/IntStream.java | 22 ++ .../classes/java/util/stream/LongStream.java | 34 ++- .../classes/java/util/stream/Stream.java | 25 ++ .../classes/java/util/stream/Streams.java | 145 ++++++++++- .../java/util/stream/LambdaTestHelpers.java | 39 ++- .../tests/java/util/stream/ConcatOpTest.java | 49 ++++ .../tests/java/util/stream/ConcatTest.java | 229 ++++++++++++++++++ .../tests/java/util/stream/RangeTest.java | 222 +++++++++-------- 9 files changed, 642 insertions(+), 145 deletions(-) create mode 100644 jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/ConcatOpTest.java create mode 100644 jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/ConcatTest.java diff --git a/jdk/src/share/classes/java/util/stream/DoubleStream.java b/jdk/src/share/classes/java/util/stream/DoubleStream.java index 55d244fc4c3..1b058abdf8b 100644 --- a/jdk/src/share/classes/java/util/stream/DoubleStream.java +++ b/jdk/src/share/classes/java/util/stream/DoubleStream.java @@ -746,4 +746,26 @@ public interface DoubleStream extends BaseStream { return StreamSupport.doubleStream( new StreamSpliterators.InfiniteSupplyingSpliterator.OfDouble(Long.MAX_VALUE, s)); } + + /** + * Creates a lazy concatenated {@code DoubleStream} whose elements are all the + * elements of a first {@code DoubleStream} succeeded by all the elements of the + * second {@code DoubleStream}. The resulting stream is ordered if both + * of the input streams are ordered, and parallel if either of the input + * streams is parallel. + * + * @param a the first stream + * @param b the second stream to concatenate on to end of the first stream + * @return the concatenation of the two streams + */ + public static DoubleStream concat(DoubleStream a, DoubleStream b) { + Objects.requireNonNull(a); + Objects.requireNonNull(b); + + Spliterator.OfDouble split = new Streams.ConcatSpliterator.OfDouble( + a.spliterator(), b.spliterator()); + return (a.isParallel() || b.isParallel()) + ? StreamSupport.doubleParallelStream(split) + : StreamSupport.doubleStream(split); + } } diff --git a/jdk/src/share/classes/java/util/stream/IntStream.java b/jdk/src/share/classes/java/util/stream/IntStream.java index 3eb4409c4e5..39e0713f1cf 100644 --- a/jdk/src/share/classes/java/util/stream/IntStream.java +++ b/jdk/src/share/classes/java/util/stream/IntStream.java @@ -800,4 +800,26 @@ public interface IntStream extends BaseStream { new Streams.RangeIntSpliterator(startInclusive, endInclusive, true)); } } + + /** + * Creates a lazy concatenated {@code IntStream} whose elements are all the + * elements of a first {@code IntStream} succeeded by all the elements of the + * second {@code IntStream}. The resulting stream is ordered if both + * of the input streams are ordered, and parallel if either of the input + * streams is parallel. + * + * @param a the first stream + * @param b the second stream to concatenate on to end of the first stream + * @return the concatenation of the two streams + */ + public static IntStream concat(IntStream a, IntStream b) { + Objects.requireNonNull(a); + Objects.requireNonNull(b); + + Spliterator.OfInt split = new Streams.ConcatSpliterator.OfInt( + a.spliterator(), b.spliterator()); + return (a.isParallel() || b.isParallel()) + ? StreamSupport.intParallelStream(split) + : StreamSupport.intStream(split); + } } diff --git a/jdk/src/share/classes/java/util/stream/LongStream.java b/jdk/src/share/classes/java/util/stream/LongStream.java index 3bc0f76a494..6e3bc688923 100644 --- a/jdk/src/share/classes/java/util/stream/LongStream.java +++ b/jdk/src/share/classes/java/util/stream/LongStream.java @@ -765,10 +765,8 @@ public interface LongStream extends BaseStream { // Split the range in two and concatenate // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE) then // the lower range, [Long.MIN_VALUE, 0) will be further split in two -// long m = startInclusive + Long.divideUnsigned(endExclusive - startInclusive, 2) + 1; -// return Streams.concat(range(startInclusive, m), range(m, endExclusive)); - // This is temporary until Streams.concat is supported - throw new UnsupportedOperationException(); + long m = startInclusive + Long.divideUnsigned(endExclusive - startInclusive, 2) + 1; + return concat(range(startInclusive, m), range(m, endExclusive)); } else { return StreamSupport.longStream( new Streams.RangeLongSpliterator(startInclusive, endExclusive, false)); @@ -801,13 +799,33 @@ public interface LongStream extends BaseStream { // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE] then // the lower range, [Long.MIN_VALUE, 0), and upper range, // [0, Long.MAX_VALUE], will both be further split in two -// long m = startInclusive + Long.divideUnsigned(endInclusive - startInclusive, 2) + 1; -// return Streams.concat(range(startInclusive, m), rangeClosed(m, endInclusive)); - // This is temporary until Streams.concat is supported - throw new UnsupportedOperationException(); + long m = startInclusive + Long.divideUnsigned(endInclusive - startInclusive, 2) + 1; + return concat(range(startInclusive, m), rangeClosed(m, endInclusive)); } else { return StreamSupport.longStream( new Streams.RangeLongSpliterator(startInclusive, endInclusive, true)); } } + + /** + * Creates a lazy concatenated {@code LongStream} whose elements are all the + * elements of a first {@code LongStream} succeeded by all the elements of the + * second {@code LongStream}. The resulting stream is ordered if both + * of the input streams are ordered, and parallel if either of the input + * streams is parallel. + * + * @param a the first stream + * @param b the second stream to concatenate on to end of the first stream + * @return the concatenation of the two streams + */ + public static LongStream concat(LongStream a, LongStream b) { + Objects.requireNonNull(a); + Objects.requireNonNull(b); + + Spliterator.OfLong split = new Streams.ConcatSpliterator.OfLong( + a.spliterator(), b.spliterator()); + return (a.isParallel() || b.isParallel()) + ? StreamSupport.longParallelStream(split) + : StreamSupport.longStream(split); + } } diff --git a/jdk/src/share/classes/java/util/stream/Stream.java b/jdk/src/share/classes/java/util/stream/Stream.java index 32b3585fdbf..78264e407ec 100644 --- a/jdk/src/share/classes/java/util/stream/Stream.java +++ b/jdk/src/share/classes/java/util/stream/Stream.java @@ -883,4 +883,29 @@ public interface Stream extends BaseStream> { return StreamSupport.stream( new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s)); } + + /** + * Creates a lazy concatenated {@code Stream} whose elements are all the + * elements of a first {@code Stream} succeeded by all the elements of the + * second {@code Stream}. The resulting stream is ordered if both + * of the input streams are ordered, and parallel if either of the input + * streams is parallel. + * + * @param The type of stream elements + * @param a the first stream + * @param b the second stream to concatenate on to end of the first + * stream + * @return the concatenation of the two input streams + */ + public static Stream concat(Stream a, Stream b) { + Objects.requireNonNull(a); + Objects.requireNonNull(b); + + @SuppressWarnings("unchecked") + Spliterator split = new Streams.ConcatSpliterator.OfRef<>( + (Spliterator) a.spliterator(), (Spliterator) b.spliterator()); + return (a.isParallel() || b.isParallel()) + ? StreamSupport.parallelStream(split) + : StreamSupport.stream(split); + } } diff --git a/jdk/src/share/classes/java/util/stream/Streams.java b/jdk/src/share/classes/java/util/stream/Streams.java index 11dbbe3d7ca..1d49997fe22 100644 --- a/jdk/src/share/classes/java/util/stream/Streams.java +++ b/jdk/src/share/classes/java/util/stream/Streams.java @@ -43,7 +43,7 @@ import java.util.function.LongConsumer; * * @since 1.8 */ -class Streams { +final class Streams { private Streams() { throw new Error("no instances"); @@ -670,4 +670,147 @@ class Streams { } } } + + abstract static class ConcatSpliterator> + implements Spliterator { + protected final T_SPLITR aSpliterator; + protected final T_SPLITR bSpliterator; + // True when no split has occurred, otherwise false + boolean beforeSplit; + // Never read after splitting + final boolean unsized; + + public ConcatSpliterator(T_SPLITR aSpliterator, T_SPLITR bSpliterator) { + this.aSpliterator = aSpliterator; + this.bSpliterator = bSpliterator; + beforeSplit = true; + // The spliterator is unsized before splitting if a and b are + // sized and the sum of the estimates overflows + unsized = aSpliterator.hasCharacteristics(SIZED) + && aSpliterator.hasCharacteristics(SIZED) + && aSpliterator.estimateSize() + bSpliterator.estimateSize() < 0; + } + + @Override + public T_SPLITR trySplit() { + T_SPLITR ret = beforeSplit ? aSpliterator : (T_SPLITR) bSpliterator.trySplit(); + beforeSplit = false; + return ret; + } + + @Override + public boolean tryAdvance(Consumer consumer) { + boolean hasNext; + if (beforeSplit) { + hasNext = aSpliterator.tryAdvance(consumer); + if (!hasNext) { + beforeSplit = false; + hasNext = bSpliterator.tryAdvance(consumer); + } + } + else + hasNext = bSpliterator.tryAdvance(consumer); + return hasNext; + } + + @Override + public void forEachRemaining(Consumer consumer) { + if (beforeSplit) + aSpliterator.forEachRemaining(consumer); + bSpliterator.forEachRemaining(consumer); + } + + @Override + public long estimateSize() { + if (beforeSplit) { + // If one or both estimates are Long.MAX_VALUE then the sum + // will either be Long.MAX_VALUE or overflow to a negative value + long size = aSpliterator.estimateSize() + bSpliterator.estimateSize(); + return (size >= 0) ? size : Long.MAX_VALUE; + } + else { + return bSpliterator.estimateSize(); + } + } + + @Override + public int characteristics() { + if (beforeSplit) { + // Concatenation loses DISTINCT and SORTED characteristics + return aSpliterator.characteristics() & bSpliterator.characteristics() + & ~(Spliterator.DISTINCT | Spliterator.SORTED + | (unsized ? Spliterator.SIZED | Spliterator.SUBSIZED : 0)); + } + else { + return bSpliterator.characteristics(); + } + } + + @Override + public Comparator getComparator() { + if (beforeSplit) + throw new IllegalStateException(); + return bSpliterator.getComparator(); + } + + static class OfRef extends ConcatSpliterator> { + OfRef(Spliterator aSpliterator, Spliterator bSpliterator) { + super(aSpliterator, bSpliterator); + } + } + + private static abstract class OfPrimitive> + extends ConcatSpliterator + implements Spliterator.OfPrimitive { + private OfPrimitive(T_SPLITR aSpliterator, T_SPLITR bSpliterator) { + super(aSpliterator, bSpliterator); + } + + @Override + public boolean tryAdvance(T_CONS action) { + boolean hasNext; + if (beforeSplit) { + hasNext = aSpliterator.tryAdvance(action); + if (!hasNext) { + beforeSplit = false; + hasNext = bSpliterator.tryAdvance(action); + } + } + else + hasNext = bSpliterator.tryAdvance(action); + return hasNext; + } + + @Override + public void forEachRemaining(T_CONS action) { + if (beforeSplit) + aSpliterator.forEachRemaining(action); + bSpliterator.forEachRemaining(action); + } + } + + static class OfInt + extends ConcatSpliterator.OfPrimitive + implements Spliterator.OfInt { + OfInt(Spliterator.OfInt aSpliterator, Spliterator.OfInt bSpliterator) { + super(aSpliterator, bSpliterator); + } + } + + static class OfLong + extends ConcatSpliterator.OfPrimitive + implements Spliterator.OfLong { + OfLong(Spliterator.OfLong aSpliterator, Spliterator.OfLong bSpliterator) { + super(aSpliterator, bSpliterator); + } + } + + static class OfDouble + extends ConcatSpliterator.OfPrimitive + implements Spliterator.OfDouble { + OfDouble(Spliterator.OfDouble aSpliterator, Spliterator.OfDouble bSpliterator) { + super(aSpliterator, bSpliterator); + } + } + } } diff --git a/jdk/test/java/util/stream/bootlib/java/util/stream/LambdaTestHelpers.java b/jdk/test/java/util/stream/bootlib/java/util/stream/LambdaTestHelpers.java index 225cbf147f6..cec872aa484 100644 --- a/jdk/test/java/util/stream/bootlib/java/util/stream/LambdaTestHelpers.java +++ b/jdk/test/java/util/stream/bootlib/java/util/stream/LambdaTestHelpers.java @@ -360,35 +360,26 @@ public class LambdaTestHelpers { private static Map toBoxedMultiset(Iterator it) { Map result = new HashMap<>(); - it.forEachRemaining(new OmnivorousConsumer() { - @Override - public void accept(T t) { - add(t); - } - - @Override - public void accept(int value) { - add(value); - } - - @Override - public void accept(long value) { - add(value); - } - - @Override - public void accept(double value) { - add(value); - } - - void add(Object o) { + it.forEachRemaining(toBoxingConsumer(o -> { if (result.containsKey(o)) result.put(o, result.get(o) + 1); else result.put(o, 1); - } + })); - }); + return (Map) result; + } + + @SuppressWarnings("unchecked") + public static Map toBoxedMultiset(Spliterator it) { + Map result = new HashMap<>(); + + it.forEachRemaining(toBoxingConsumer(o -> { + if (result.containsKey(o)) + result.put(o, result.get(o) + 1); + else + result.put(o, 1); + })); return (Map) result; } diff --git a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/ConcatOpTest.java b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/ConcatOpTest.java new file mode 100644 index 00000000000..1b3c4b65bf2 --- /dev/null +++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/ConcatOpTest.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.openjdk.tests.java.util.stream; + +import java.util.stream.OpTestCase; +import java.util.stream.StreamTestDataProvider; + +import org.testng.annotations.Test; + +import java.util.stream.Stream; +import java.util.stream.IntStream; +import java.util.stream.LongStream; +import java.util.stream.DoubleStream; +import java.util.stream.TestData; + +import static java.util.stream.LambdaTestHelpers.*; + +public class ConcatOpTest extends OpTestCase { + + // Sanity to make sure all type of stream source works + @Test(dataProvider = "StreamTestData", dataProviderClass = StreamTestDataProvider.class) + public void testOpsSequential(String name, TestData.OfRef data) { + exerciseOpsInt(data, + s -> Stream.concat(s, data.stream()), + s -> IntStream.concat(s, data.stream().mapToInt(Integer::intValue)), + s -> LongStream.concat(s, data.stream().mapToLong(Integer::longValue)), + s -> DoubleStream.concat(s, data.stream().mapToDouble(Integer::doubleValue))); + } +} diff --git a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/ConcatTest.java b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/ConcatTest.java new file mode 100644 index 00000000000..4ce9c9645b6 --- /dev/null +++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/ConcatTest.java @@ -0,0 +1,229 @@ +/* + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.openjdk.tests.java.util.stream; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Spliterator; +import java.util.TreeSet; +import java.util.stream.DoubleStream; +import java.util.stream.IntStream; +import java.util.stream.LongStream; +import java.util.stream.Stream; + +import static java.util.stream.LambdaTestHelpers.*; +import static org.testng.Assert.*; + +@Test +public class ConcatTest { + private static Object[][] cases; + + static { + List part1 = Arrays.asList(5, 3, 4, 1, 2, 6, 2, 4); + List part2 = Arrays.asList(8, 8, 6, 6, 9, 7, 10, 9); + List p1p2 = Arrays.asList(5, 3, 4, 1, 2, 6, 2, 4, 8, 8, 6, 6, 9, 7, 10, 9); + List p2p1 = Arrays.asList(8, 8, 6, 6, 9, 7, 10, 9, 5, 3, 4, 1, 2, 6, 2, 4); + List empty = new LinkedList<>(); // To be ordered + assertTrue(empty.isEmpty()); + LinkedHashSet distinctP1 = new LinkedHashSet<>(part1); + LinkedHashSet distinctP2 = new LinkedHashSet<>(part2); + TreeSet sortedP1 = new TreeSet<>(part1); + TreeSet sortedP2 = new TreeSet<>(part2); + + cases = new Object[][] { + { "regular", part1, part2, p1p2 }, + { "reverse regular", part2, part1, p2p1 }, + { "front distinct", distinctP1, part2, Arrays.asList(5, 3, 4, 1, 2, 6, 8, 8, 6, 6, 9, 7, 10, 9) }, + { "back distinct", part1, distinctP2, Arrays.asList(5, 3, 4, 1, 2, 6, 2, 4, 8, 6, 9, 7, 10) }, + { "both distinct", distinctP1, distinctP2, Arrays.asList(5, 3, 4, 1, 2, 6, 8, 6, 9, 7, 10) }, + { "front sorted", sortedP1, part2, Arrays.asList(1, 2, 3, 4, 5, 6, 8, 8, 6, 6, 9, 7, 10, 9) }, + { "back sorted", part1, sortedP2, Arrays.asList(5, 3, 4, 1, 2, 6, 2, 4, 6, 7, 8, 9, 10) }, + { "both sorted", sortedP1, sortedP2, Arrays.asList(1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10) }, + { "reverse both sorted", sortedP2, sortedP1, Arrays.asList(6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6) }, + { "empty something", empty, part1, part1 }, + { "something empty", part1, empty, part1 }, + { "empty empty", empty, empty, empty } + }; + } + + @DataProvider(name = "cases") + private static Object[][] getCases() { + return cases; + } + + @Factory(dataProvider = "cases") + public static Object[] createTests(String scenario, Collection c1, Collection c2, Collection expected) { + return new Object[] { + new ConcatTest(scenario, c1, c2, expected) + }; + } + + protected final String scenario; + protected final Collection c1; + protected final Collection c2; + protected final Collection expected; + + public ConcatTest(String scenario, Collection c1, Collection c2, Collection expected) { + this.scenario = scenario; + this.c1 = c1; + this.c2 = c2; + this.expected = expected; + + // verify prerequisite + Stream s1s = c1.stream(); + Stream s2s = c2.stream(); + Stream s1p = c1.parallelStream(); + Stream s2p = c2.parallelStream(); + assertTrue(s1p.isParallel()); + assertTrue(s2p.isParallel()); + assertFalse(s1s.isParallel()); + assertFalse(s2s.isParallel()); + + assertTrue(s1s.spliterator().hasCharacteristics(Spliterator.ORDERED)); + assertTrue(s1p.spliterator().hasCharacteristics(Spliterator.ORDERED)); + assertTrue(s2s.spliterator().hasCharacteristics(Spliterator.ORDERED)); + assertTrue(s2p.spliterator().hasCharacteristics(Spliterator.ORDERED)); + } + + private void assertConcatContent(Spliterator sp, boolean ordered, Spliterator expected) { + // concat stream cannot guarantee uniqueness + assertFalse(sp.hasCharacteristics(Spliterator.DISTINCT), scenario); + // concat stream cannot guarantee sorted + assertFalse(sp.hasCharacteristics(Spliterator.SORTED), scenario); + // concat stream is ordered if both are ordered + assertEquals(sp.hasCharacteristics(Spliterator.ORDERED), ordered, scenario); + + // Verify elements + if (ordered) { + assertEquals(toBoxedList(sp), + toBoxedList(expected), + scenario); + } else { + assertEquals(toBoxedMultiset(sp), + toBoxedMultiset(expected), + scenario); + } + } + + private void assertRefConcat(Stream s1, Stream s2, boolean parallel, boolean ordered) { + Stream result = Stream.concat(s1, s2); + assertEquals(result.isParallel(), parallel); + assertConcatContent(result.spliterator(), ordered, expected.spliterator()); + } + + private void assertIntConcat(Stream s1, Stream s2, boolean parallel, boolean ordered) { + IntStream result = IntStream.concat(s1.mapToInt(Integer::intValue), + s2.mapToInt(Integer::intValue)); + assertEquals(result.isParallel(), parallel); + assertConcatContent(result.spliterator(), ordered, + expected.stream().mapToInt(Integer::intValue).spliterator()); + } + + private void assertLongConcat(Stream s1, Stream s2, boolean parallel, boolean ordered) { + LongStream result = LongStream.concat(s1.mapToLong(Integer::longValue), + s2.mapToLong(Integer::longValue)); + assertEquals(result.isParallel(), parallel); + assertConcatContent(result.spliterator(), ordered, + expected.stream().mapToLong(Integer::longValue).spliterator()); + } + + private void assertDoubleConcat(Stream s1, Stream s2, boolean parallel, boolean ordered) { + DoubleStream result = DoubleStream.concat(s1.mapToDouble(Integer::doubleValue), + s2.mapToDouble(Integer::doubleValue)); + assertEquals(result.isParallel(), parallel); + assertConcatContent(result.spliterator(), ordered, + expected.stream().mapToDouble(Integer::doubleValue).spliterator()); + } + + public void testRefConcat() { + // sequential + sequential -> sequential + assertRefConcat(c1.stream(), c2.stream(), false, true); + // parallel + parallel -> parallel + assertRefConcat(c1.parallelStream(), c2.parallelStream(), true, true); + // sequential + parallel -> parallel + assertRefConcat(c1.stream(), c2.parallelStream(), true, true); + // parallel + sequential -> parallel + assertRefConcat(c1.parallelStream(), c2.stream(), true, true); + + // not ordered + assertRefConcat(c1.stream().unordered(), c2.stream(), false, false); + assertRefConcat(c1.stream(), c2.stream().unordered(), false, false); + assertRefConcat(c1.parallelStream().unordered(), c2.stream().unordered(), true, false); + } + + public void testIntConcat() { + // sequential + sequential -> sequential + assertIntConcat(c1.stream(), c2.stream(), false, true); + // parallel + parallel -> parallel + assertIntConcat(c1.parallelStream(), c2.parallelStream(), true, true); + // sequential + parallel -> parallel + assertIntConcat(c1.stream(), c2.parallelStream(), true, true); + // parallel + sequential -> parallel + assertIntConcat(c1.parallelStream(), c2.stream(), true, true); + + // not ordered + assertIntConcat(c1.stream().unordered(), c2.stream(), false, false); + assertIntConcat(c1.stream(), c2.stream().unordered(), false, false); + assertIntConcat(c1.parallelStream().unordered(), c2.stream().unordered(), true, false); + } + + public void testLongConcat() { + // sequential + sequential -> sequential + assertLongConcat(c1.stream(), c2.stream(), false, true); + // parallel + parallel -> parallel + assertLongConcat(c1.parallelStream(), c2.parallelStream(), true, true); + // sequential + parallel -> parallel + assertLongConcat(c1.stream(), c2.parallelStream(), true, true); + // parallel + sequential -> parallel + assertLongConcat(c1.parallelStream(), c2.stream(), true, true); + + // not ordered + assertLongConcat(c1.stream().unordered(), c2.stream(), false, false); + assertLongConcat(c1.stream(), c2.stream().unordered(), false, false); + assertLongConcat(c1.parallelStream().unordered(), c2.stream().unordered(), true, false); + } + + public void testDoubleConcat() { + // sequential + sequential -> sequential + assertDoubleConcat(c1.stream(), c2.stream(), false, true); + // parallel + parallel -> parallel + assertDoubleConcat(c1.parallelStream(), c2.parallelStream(), true, true); + // sequential + parallel -> parallel + assertDoubleConcat(c1.stream(), c2.parallelStream(), true, true); + // parallel + sequential -> parallel + assertDoubleConcat(c1.parallelStream(), c2.stream(), true, true); + + // not ordered + assertDoubleConcat(c1.stream().unordered(), c2.stream(), false, false); + assertDoubleConcat(c1.stream(), c2.stream().unordered(), false, false); + assertDoubleConcat(c1.parallelStream().unordered(), c2.stream().unordered(), true, false); + } +} diff --git a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/RangeTest.java b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/RangeTest.java index 1e6b343fc60..20ae203bb63 100644 --- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/RangeTest.java +++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/RangeTest.java @@ -226,116 +226,114 @@ public class RangeTest extends OpTestCase { assertEquals(first, LongStream.iterate(0, i -> i + 1).parallel().filter(i -> i > 10000).findFirst().getAsLong()); } - // Enable when Stream.concat is present and range implementations are - // updated to use that -// private static void assertSizedAndSubSized(Spliterator s) { -// assertTrue(s.hasCharacteristics(Spliterator.SIZED | Spliterator.SUBSIZED)); -// } -// -// private static void assertNotSizedAndSubSized(Spliterator s) { -// assertFalse(s.hasCharacteristics(Spliterator.SIZED | Spliterator.SUBSIZED)); -// } -// -// public void testLongLongRange() { -// // Test [Long.MIN_VALUE, Long.MAX_VALUE) -// // This will concatenate streams of three ranges -// // [Long.MIN_VALUE, x) [x, 0) [0, Long.MAX_VALUE) -// // where x = Long.divideUnsigned(0 - Long.MIN_VALUE, 2) + 1 -// { -// Spliterator.OfLong s = LongStream.range(Long.MIN_VALUE, Long.MAX_VALUE).spliterator(); -// -// assertEquals(s.estimateSize(), Long.MAX_VALUE); -// assertNotSizedAndSubSized(s); -// -// Spliterator.OfLong s1 = s.trySplit(); -// assertNotSizedAndSubSized(s1); -// assertSizedAndSubSized(s); -// -// Spliterator.OfLong s2 = s1.trySplit(); -// assertSizedAndSubSized(s1); -// assertSizedAndSubSized(s2); -// -// assertTrue(s.estimateSize() == Long.MAX_VALUE); -// assertTrue(s1.estimateSize() < Long.MAX_VALUE); -// assertTrue(s2.estimateSize() < Long.MAX_VALUE); -// -// assertEquals(s.estimateSize() + s1.estimateSize() + s2.estimateSize(), -// Long.MAX_VALUE - Long.MIN_VALUE); -// } -// -// long[][] ranges = { {Long.MIN_VALUE, 0}, {-1, Long.MAX_VALUE} }; -// for (int i = 0; i < ranges.length; i++) { -// long start = ranges[i][0]; -// long end = ranges[i][1]; -// -// Spliterator.OfLong s = LongStream.range(start, end).spliterator(); -// -// assertEquals(s.estimateSize(), Long.MAX_VALUE); -// assertNotSizedAndSubSized(s); -// -// Spliterator.OfLong s1 = s.trySplit(); -// assertSizedAndSubSized(s1); -// assertSizedAndSubSized(s); -// -// assertTrue(s.estimateSize() < Long.MAX_VALUE); -// assertTrue(s1.estimateSize() < Long.MAX_VALUE); -// -// assertEquals(s.estimateSize() + s1.estimateSize(), end - start); -// } -// } -// -// public void testLongLongRangeClosed() { -// // Test [Long.MIN_VALUE, Long.MAX_VALUE] -// // This will concatenate streams of four ranges -// // [Long.MIN_VALUE, x) [x, 0) [0, y) [y, Long.MAX_VALUE] -// // where x = Long.divideUnsigned(0 - Long.MIN_VALUE, 2) + 1 -// // y = Long.divideUnsigned(Long.MAX_VALUE, 2) + 1 -// -// { -// Spliterator.OfLong s = LongStream.rangeClosed(Long.MIN_VALUE, Long.MAX_VALUE).spliterator(); -// -// assertEquals(s.estimateSize(), Long.MAX_VALUE); -// assertNotSizedAndSubSized(s); -// -// Spliterator.OfLong s1 = s.trySplit(); -// assertNotSizedAndSubSized(s1); -// assertNotSizedAndSubSized(s); -// -// Spliterator.OfLong s2 = s1.trySplit(); -// assertSizedAndSubSized(s1); -// assertSizedAndSubSized(s2); -// -// Spliterator.OfLong s3 = s.trySplit(); -// assertSizedAndSubSized(s3); -// assertSizedAndSubSized(s); -// -// assertTrue(s.estimateSize() < Long.MAX_VALUE); -// assertTrue(s3.estimateSize() < Long.MAX_VALUE); -// assertTrue(s1.estimateSize() < Long.MAX_VALUE); -// assertTrue(s2.estimateSize() < Long.MAX_VALUE); -// -// assertEquals(s.estimateSize() + s3.estimateSize() + s1.estimateSize() + s2.estimateSize(), -// Long.MAX_VALUE - Long.MIN_VALUE + 1); -// } -// -// long[][] ranges = { {Long.MIN_VALUE, 0}, {-1, Long.MAX_VALUE} }; -// for (int i = 0; i < ranges.length; i++) { -// long start = ranges[i][0]; -// long end = ranges[i][1]; -// -// Spliterator.OfLong s = LongStream.rangeClosed(start, end).spliterator(); -// -// assertEquals(s.estimateSize(), Long.MAX_VALUE); -// assertNotSizedAndSubSized(s); -// -// Spliterator.OfLong s1 = s.trySplit(); -// assertSizedAndSubSized(s1); -// assertSizedAndSubSized(s); -// -// assertTrue(s.estimateSize() < Long.MAX_VALUE); -// assertTrue(s1.estimateSize() < Long.MAX_VALUE); -// -// assertEquals(s.estimateSize() + s1.estimateSize(), end - start + 1); -// } -// } + private static void assertSizedAndSubSized(Spliterator s) { + assertTrue(s.hasCharacteristics(Spliterator.SIZED | Spliterator.SUBSIZED)); + } + + private static void assertNotSizedAndSubSized(Spliterator s) { + assertFalse(s.hasCharacteristics(Spliterator.SIZED | Spliterator.SUBSIZED)); + } + + public void testLongLongRange() { + // Test [Long.MIN_VALUE, Long.MAX_VALUE) + // This will concatenate streams of three ranges + // [Long.MIN_VALUE, x) [x, 0) [0, Long.MAX_VALUE) + // where x = Long.divideUnsigned(0 - Long.MIN_VALUE, 2) + 1 + { + Spliterator.OfLong s = LongStream.range(Long.MIN_VALUE, Long.MAX_VALUE).spliterator(); + + assertEquals(s.estimateSize(), Long.MAX_VALUE); + assertNotSizedAndSubSized(s); + + Spliterator.OfLong s1 = s.trySplit(); + assertNotSizedAndSubSized(s1); + assertSizedAndSubSized(s); + + Spliterator.OfLong s2 = s1.trySplit(); + assertSizedAndSubSized(s1); + assertSizedAndSubSized(s2); + + assertTrue(s.estimateSize() == Long.MAX_VALUE); + assertTrue(s1.estimateSize() < Long.MAX_VALUE); + assertTrue(s2.estimateSize() < Long.MAX_VALUE); + + assertEquals(s.estimateSize() + s1.estimateSize() + s2.estimateSize(), + Long.MAX_VALUE - Long.MIN_VALUE); + } + + long[][] ranges = { {Long.MIN_VALUE, 0}, {-1, Long.MAX_VALUE} }; + for (int i = 0; i < ranges.length; i++) { + long start = ranges[i][0]; + long end = ranges[i][1]; + + Spliterator.OfLong s = LongStream.range(start, end).spliterator(); + + assertEquals(s.estimateSize(), Long.MAX_VALUE); + assertNotSizedAndSubSized(s); + + Spliterator.OfLong s1 = s.trySplit(); + assertSizedAndSubSized(s1); + assertSizedAndSubSized(s); + + assertTrue(s.estimateSize() < Long.MAX_VALUE); + assertTrue(s1.estimateSize() < Long.MAX_VALUE); + + assertEquals(s.estimateSize() + s1.estimateSize(), end - start); + } + } + + public void testLongLongRangeClosed() { + // Test [Long.MIN_VALUE, Long.MAX_VALUE] + // This will concatenate streams of four ranges + // [Long.MIN_VALUE, x) [x, 0) [0, y) [y, Long.MAX_VALUE] + // where x = Long.divideUnsigned(0 - Long.MIN_VALUE, 2) + 1 + // y = Long.divideUnsigned(Long.MAX_VALUE, 2) + 1 + + { + Spliterator.OfLong s = LongStream.rangeClosed(Long.MIN_VALUE, Long.MAX_VALUE).spliterator(); + + assertEquals(s.estimateSize(), Long.MAX_VALUE); + assertNotSizedAndSubSized(s); + + Spliterator.OfLong s1 = s.trySplit(); + assertNotSizedAndSubSized(s1); + assertNotSizedAndSubSized(s); + + Spliterator.OfLong s2 = s1.trySplit(); + assertSizedAndSubSized(s1); + assertSizedAndSubSized(s2); + + Spliterator.OfLong s3 = s.trySplit(); + assertSizedAndSubSized(s3); + assertSizedAndSubSized(s); + + assertTrue(s.estimateSize() < Long.MAX_VALUE); + assertTrue(s3.estimateSize() < Long.MAX_VALUE); + assertTrue(s1.estimateSize() < Long.MAX_VALUE); + assertTrue(s2.estimateSize() < Long.MAX_VALUE); + + assertEquals(s.estimateSize() + s3.estimateSize() + s1.estimateSize() + s2.estimateSize(), + Long.MAX_VALUE - Long.MIN_VALUE + 1); + } + + long[][] ranges = { {Long.MIN_VALUE, 0}, {-1, Long.MAX_VALUE} }; + for (int i = 0; i < ranges.length; i++) { + long start = ranges[i][0]; + long end = ranges[i][1]; + + Spliterator.OfLong s = LongStream.rangeClosed(start, end).spliterator(); + + assertEquals(s.estimateSize(), Long.MAX_VALUE); + assertNotSizedAndSubSized(s); + + Spliterator.OfLong s1 = s.trySplit(); + assertSizedAndSubSized(s1); + assertSizedAndSubSized(s); + + assertTrue(s.estimateSize() < Long.MAX_VALUE); + assertTrue(s1.estimateSize() < Long.MAX_VALUE); + + assertEquals(s.estimateSize() + s1.estimateSize(), end - start + 1); + } + } } From c5fcef26c96de5eada2f0dfbe4fd052768cf42aa Mon Sep 17 00:00:00 2001 From: Paul Sandoz Date: Wed, 3 Jul 2013 21:43:49 +0200 Subject: [PATCH 062/123] 8019395: Consolidate StreamSupport.{stream,parallelStream} into a single method Reviewed-by: henryjen, briangoetz --- .../share/classes/java/io/BufferedReader.java | 2 +- .../share/classes/java/lang/CharSequence.java | 6 +- .../classes/java/nio/X-Buffer.java.template | 2 +- .../share/classes/java/nio/file/Files.java | 27 +- jdk/src/share/classes/java/util/Arrays.java | 8 +- jdk/src/share/classes/java/util/BitSet.java | 3 +- .../share/classes/java/util/Collection.java | 4 +- .../share/classes/java/util/Collections.java | 4 +- .../share/classes/java/util/jar/JarFile.java | 2 +- .../classes/java/util/regex/Pattern.java | 2 +- .../java/util/stream/DoubleStream.java | 12 +- .../classes/java/util/stream/IntStream.java | 16 +- .../classes/java/util/stream/LongStream.java | 16 +- .../classes/java/util/stream/Stream.java | 12 +- .../java/util/stream/StreamSupport.java | 456 +++++------------- .../classes/java/util/stream/Streams.java | 11 +- .../share/classes/java/util/zip/ZipFile.java | 2 +- .../util/stream/DoubleStreamTestScenario.java | 6 +- .../util/stream/IntStreamTestScenario.java | 7 +- .../util/stream/LongStreamTestScenario.java | 6 +- .../java/util/stream/StreamTestScenario.java | 6 +- .../bootlib/java/util/stream/TestData.java | 32 +- .../java/util/stream/DistinctOpTest.java | 4 +- .../stream/InfiniteStreamWithLimitOpTest.java | 2 +- .../tests/java/util/stream/MatchOpTest.java | 8 +- .../tests/java/util/stream/SliceOpTest.java | 2 +- .../tests/java/util/stream/SortedOpTest.java | 8 +- .../util/stream/StreamSpliteratorTest.java | 24 +- 28 files changed, 246 insertions(+), 444 deletions(-) diff --git a/jdk/src/share/classes/java/io/BufferedReader.java b/jdk/src/share/classes/java/io/BufferedReader.java index ebf398078bf..98fe47c7a59 100644 --- a/jdk/src/share/classes/java/io/BufferedReader.java +++ b/jdk/src/share/classes/java/io/BufferedReader.java @@ -587,6 +587,6 @@ public class BufferedReader extends Reader { } } }; - return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iter, Spliterator.ORDERED)); + return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iter, Spliterator.ORDERED), false); } } diff --git a/jdk/src/share/classes/java/lang/CharSequence.java b/jdk/src/share/classes/java/lang/CharSequence.java index 3ee0b9ac1dd..ac80b22f066 100644 --- a/jdk/src/share/classes/java/lang/CharSequence.java +++ b/jdk/src/share/classes/java/lang/CharSequence.java @@ -156,7 +156,8 @@ public interface CharSequence { new CharIterator(), length(), Spliterator.ORDERED), - Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED); + Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED, + false); } /** @@ -227,6 +228,7 @@ public interface CharSequence { Spliterators.spliteratorUnknownSize( new CodePointIterator(), Spliterator.ORDERED), - Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED); + Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED, + false); } } diff --git a/jdk/src/share/classes/java/nio/X-Buffer.java.template b/jdk/src/share/classes/java/nio/X-Buffer.java.template index 03a7255c16a..60f0733c9ab 100644 --- a/jdk/src/share/classes/java/nio/X-Buffer.java.template +++ b/jdk/src/share/classes/java/nio/X-Buffer.java.template @@ -1495,7 +1495,7 @@ public abstract class $Type$Buffer #end[char] public $Streamtype$Stream $type$s() { return StreamSupport.$streamtype$Stream(() -> new $Type$BufferSpliterator(this), - Buffer.SPLITERATOR_CHARACTERISTICS); + Buffer.SPLITERATOR_CHARACTERISTICS, false); } #end[streamableType] diff --git a/jdk/src/share/classes/java/nio/file/Files.java b/jdk/src/share/classes/java/nio/file/Files.java index ca0263d0660..586859f17dc 100644 --- a/jdk/src/share/classes/java/nio/file/Files.java +++ b/jdk/src/share/classes/java/nio/file/Files.java @@ -3269,9 +3269,10 @@ public final class Files { } }; - return new DelegatingCloseableStream<>(ds, - StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, - Spliterator.DISTINCT))); + Stream s = StreamSupport.stream( + Spliterators.spliteratorUnknownSize(it, Spliterator.DISTINCT), + false); + return new DelegatingCloseableStream<>(ds, s); } /** @@ -3358,9 +3359,12 @@ public final class Files { 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 s = StreamSupport.stream( + Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT), + false). + map(entry -> entry.file()); + return new DelegatingCloseableStream<>(iterator, s); } /** @@ -3455,10 +3459,13 @@ public final class Files { 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 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); } /** diff --git a/jdk/src/share/classes/java/util/Arrays.java b/jdk/src/share/classes/java/util/Arrays.java index 196a31e5767..3e81c11b8f1 100644 --- a/jdk/src/share/classes/java/util/Arrays.java +++ b/jdk/src/share/classes/java/util/Arrays.java @@ -4966,7 +4966,7 @@ public class Arrays { * @since 1.8 */ public static Stream stream(T[] array, int startInclusive, int endExclusive) { - return StreamSupport.stream(spliterator(array, startInclusive, endExclusive)); + return StreamSupport.stream(spliterator(array, startInclusive, endExclusive), false); } /** @@ -4996,7 +4996,7 @@ public class Arrays { * @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 +5026,7 @@ public class Arrays { * @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 +5056,6 @@ public class Arrays { * @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); } } diff --git a/jdk/src/share/classes/java/util/BitSet.java b/jdk/src/share/classes/java/util/BitSet.java index 56faccc66fb..35ecf70ea25 100644 --- a/jdk/src/share/classes/java/util/BitSet.java +++ b/jdk/src/share/classes/java/util/BitSet.java @@ -1231,6 +1231,7 @@ public class BitSet implements Cloneable, java.io.Serializable { 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); } } diff --git a/jdk/src/share/classes/java/util/Collection.java b/jdk/src/share/classes/java/util/Collection.java index 249be10f0ea..d42ba3e8a6e 100644 --- a/jdk/src/share/classes/java/util/Collection.java +++ b/jdk/src/share/classes/java/util/Collection.java @@ -557,7 +557,7 @@ public interface Collection extends Iterable { * @since 1.8 */ default Stream stream() { - return StreamSupport.stream(spliterator()); + return StreamSupport.stream(spliterator(), false); } /** @@ -578,6 +578,6 @@ public interface Collection extends Iterable { * @since 1.8 */ default Stream parallelStream() { - return StreamSupport.parallelStream(spliterator()); + return StreamSupport.stream(spliterator(), true); } } diff --git a/jdk/src/share/classes/java/util/Collections.java b/jdk/src/share/classes/java/util/Collections.java index bbb987ec58f..f56af07fd1b 100644 --- a/jdk/src/share/classes/java/util/Collections.java +++ b/jdk/src/share/classes/java/util/Collections.java @@ -1674,12 +1674,12 @@ public class Collections { @Override public Stream> stream() { - return StreamSupport.stream(spliterator()); + return StreamSupport.stream(spliterator(), false); } @Override public Stream> parallelStream() { - return StreamSupport.parallelStream(spliterator()); + return StreamSupport.stream(spliterator(), true); } public Iterator> iterator() { diff --git a/jdk/src/share/classes/java/util/jar/JarFile.java b/jdk/src/share/classes/java/util/jar/JarFile.java index a70be7a6e2d..f8deb7643ac 100644 --- a/jdk/src/share/classes/java/util/jar/JarFile.java +++ b/jdk/src/share/classes/java/util/jar/JarFile.java @@ -272,7 +272,7 @@ class JarFile extends ZipFile { return StreamSupport.stream(Spliterators.spliterator( new JarEntryIterator(), size(), Spliterator.ORDERED | Spliterator.DISTINCT | - Spliterator.IMMUTABLE | Spliterator.NONNULL)); + Spliterator.IMMUTABLE | Spliterator.NONNULL), false); } private class JarFileEntry extends JarEntry { diff --git a/jdk/src/share/classes/java/util/regex/Pattern.java b/jdk/src/share/classes/java/util/regex/Pattern.java index 4d52151210b..d7b800e3258 100644 --- a/jdk/src/share/classes/java/util/regex/Pattern.java +++ b/jdk/src/share/classes/java/util/regex/Pattern.java @@ -5815,6 +5815,6 @@ NEXT: while (i <= last) { } } return StreamSupport.stream(Spliterators.spliteratorUnknownSize( - new MatcherIterator(), Spliterator.ORDERED | Spliterator.NONNULL)); + new MatcherIterator(), Spliterator.ORDERED | Spliterator.NONNULL), false); } } diff --git a/jdk/src/share/classes/java/util/stream/DoubleStream.java b/jdk/src/share/classes/java/util/stream/DoubleStream.java index 1b058abdf8b..225de5e03b6 100644 --- a/jdk/src/share/classes/java/util/stream/DoubleStream.java +++ b/jdk/src/share/classes/java/util/stream/DoubleStream.java @@ -672,7 +672,7 @@ public interface DoubleStream extends BaseStream { * @return an empty sequential stream */ public static DoubleStream empty() { - return StreamSupport.doubleStream(Spliterators.emptyDoubleSpliterator()); + return StreamSupport.doubleStream(Spliterators.emptyDoubleSpliterator(), false); } /** @@ -682,7 +682,7 @@ public interface DoubleStream extends BaseStream { * @return a singleton sequential stream */ public static DoubleStream of(double t) { - return StreamSupport.doubleStream(new Streams.DoubleStreamBuilderImpl(t)); + return StreamSupport.doubleStream(new Streams.DoubleStreamBuilderImpl(t), false); } /** @@ -730,7 +730,7 @@ public interface DoubleStream extends BaseStream { }; return StreamSupport.doubleStream(Spliterators.spliteratorUnknownSize( iterator, - Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL)); + Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false); } /** @@ -744,7 +744,7 @@ public interface DoubleStream extends BaseStream { public static DoubleStream generate(DoubleSupplier s) { Objects.requireNonNull(s); return StreamSupport.doubleStream( - new StreamSpliterators.InfiniteSupplyingSpliterator.OfDouble(Long.MAX_VALUE, s)); + new StreamSpliterators.InfiniteSupplyingSpliterator.OfDouble(Long.MAX_VALUE, s), false); } /** @@ -764,8 +764,6 @@ public interface DoubleStream extends BaseStream { Spliterator.OfDouble split = new Streams.ConcatSpliterator.OfDouble( a.spliterator(), b.spliterator()); - return (a.isParallel() || b.isParallel()) - ? StreamSupport.doubleParallelStream(split) - : StreamSupport.doubleStream(split); + return StreamSupport.doubleStream(split, a.isParallel() || b.isParallel()); } } diff --git a/jdk/src/share/classes/java/util/stream/IntStream.java b/jdk/src/share/classes/java/util/stream/IntStream.java index 39e0713f1cf..2ef55e15f9c 100644 --- a/jdk/src/share/classes/java/util/stream/IntStream.java +++ b/jdk/src/share/classes/java/util/stream/IntStream.java @@ -674,7 +674,7 @@ public interface IntStream extends BaseStream { * @return an empty sequential stream */ public static IntStream empty() { - return StreamSupport.intStream(Spliterators.emptyIntSpliterator()); + return StreamSupport.intStream(Spliterators.emptyIntSpliterator(), false); } /** @@ -684,7 +684,7 @@ public interface IntStream extends BaseStream { * @return a singleton sequential stream */ public static IntStream of(int t) { - return StreamSupport.intStream(new Streams.IntStreamBuilderImpl(t)); + return StreamSupport.intStream(new Streams.IntStreamBuilderImpl(t), false); } /** @@ -732,7 +732,7 @@ public interface IntStream extends BaseStream { }; return StreamSupport.intStream(Spliterators.spliteratorUnknownSize( iterator, - Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL)); + Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false); } /** @@ -746,7 +746,7 @@ public interface IntStream extends BaseStream { public static IntStream generate(IntSupplier s) { Objects.requireNonNull(s); return StreamSupport.intStream( - new StreamSpliterators.InfiniteSupplyingSpliterator.OfInt(Long.MAX_VALUE, s)); + new StreamSpliterators.InfiniteSupplyingSpliterator.OfInt(Long.MAX_VALUE, s), false); } /** @@ -771,7 +771,7 @@ public interface IntStream extends BaseStream { return empty(); } else { return StreamSupport.intStream( - new Streams.RangeIntSpliterator(startInclusive, endExclusive, false)); + new Streams.RangeIntSpliterator(startInclusive, endExclusive, false), false); } } @@ -797,7 +797,7 @@ public interface IntStream extends BaseStream { return empty(); } else { return StreamSupport.intStream( - new Streams.RangeIntSpliterator(startInclusive, endInclusive, true)); + new Streams.RangeIntSpliterator(startInclusive, endInclusive, true), false); } } @@ -818,8 +818,6 @@ public interface IntStream extends BaseStream { Spliterator.OfInt split = new Streams.ConcatSpliterator.OfInt( a.spliterator(), b.spliterator()); - return (a.isParallel() || b.isParallel()) - ? StreamSupport.intParallelStream(split) - : StreamSupport.intStream(split); + return StreamSupport.intStream(split, a.isParallel() || b.isParallel()); } } diff --git a/jdk/src/share/classes/java/util/stream/LongStream.java b/jdk/src/share/classes/java/util/stream/LongStream.java index 6e3bc688923..8d1c7eae8fd 100644 --- a/jdk/src/share/classes/java/util/stream/LongStream.java +++ b/jdk/src/share/classes/java/util/stream/LongStream.java @@ -665,7 +665,7 @@ public interface LongStream extends BaseStream { * @return an empty sequential stream */ public static LongStream empty() { - return StreamSupport.longStream(Spliterators.emptyLongSpliterator()); + return StreamSupport.longStream(Spliterators.emptyLongSpliterator(), false); } /** @@ -675,7 +675,7 @@ public interface LongStream extends BaseStream { * @return a singleton sequential stream */ public static LongStream of(long t) { - return StreamSupport.longStream(new Streams.LongStreamBuilderImpl(t)); + return StreamSupport.longStream(new Streams.LongStreamBuilderImpl(t), false); } /** @@ -723,7 +723,7 @@ public interface LongStream extends BaseStream { }; return StreamSupport.longStream(Spliterators.spliteratorUnknownSize( iterator, - Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL)); + Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false); } /** @@ -737,7 +737,7 @@ public interface LongStream extends BaseStream { public static LongStream generate(LongSupplier s) { Objects.requireNonNull(s); return StreamSupport.longStream( - new StreamSpliterators.InfiniteSupplyingSpliterator.OfLong(Long.MAX_VALUE, s)); + new StreamSpliterators.InfiniteSupplyingSpliterator.OfLong(Long.MAX_VALUE, s), false); } /** @@ -769,7 +769,7 @@ public interface LongStream extends BaseStream { return concat(range(startInclusive, m), range(m, endExclusive)); } else { return StreamSupport.longStream( - new Streams.RangeLongSpliterator(startInclusive, endExclusive, false)); + new Streams.RangeLongSpliterator(startInclusive, endExclusive, false), false); } } @@ -803,7 +803,7 @@ public interface LongStream extends BaseStream { return concat(range(startInclusive, m), rangeClosed(m, endInclusive)); } else { return StreamSupport.longStream( - new Streams.RangeLongSpliterator(startInclusive, endInclusive, true)); + new Streams.RangeLongSpliterator(startInclusive, endInclusive, true), false); } } @@ -824,8 +824,6 @@ public interface LongStream extends BaseStream { Spliterator.OfLong split = new Streams.ConcatSpliterator.OfLong( a.spliterator(), b.spliterator()); - return (a.isParallel() || b.isParallel()) - ? StreamSupport.longParallelStream(split) - : StreamSupport.longStream(split); + return StreamSupport.longStream(split, a.isParallel() || b.isParallel()); } } diff --git a/jdk/src/share/classes/java/util/stream/Stream.java b/jdk/src/share/classes/java/util/stream/Stream.java index 78264e407ec..ea166bdca36 100644 --- a/jdk/src/share/classes/java/util/stream/Stream.java +++ b/jdk/src/share/classes/java/util/stream/Stream.java @@ -805,7 +805,7 @@ public interface Stream extends BaseStream> { * @return an empty sequential stream */ public static Stream empty() { - return StreamSupport.stream(Spliterators.emptySpliterator()); + return StreamSupport.stream(Spliterators.emptySpliterator(), false); } /** @@ -816,7 +816,7 @@ public interface Stream extends BaseStream> { * @return a singleton sequential stream */ public static Stream of(T t) { - return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t)); + return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false); } /** @@ -866,7 +866,7 @@ public interface Stream extends BaseStream> { }; return StreamSupport.stream(Spliterators.spliteratorUnknownSize( iterator, - Spliterator.ORDERED | Spliterator.IMMUTABLE)); + Spliterator.ORDERED | Spliterator.IMMUTABLE), false); } /** @@ -881,7 +881,7 @@ public interface Stream extends BaseStream> { public static Stream generate(Supplier s) { Objects.requireNonNull(s); return StreamSupport.stream( - new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s)); + new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s), false); } /** @@ -904,8 +904,6 @@ public interface Stream extends BaseStream> { @SuppressWarnings("unchecked") Spliterator split = new Streams.ConcatSpliterator.OfRef<>( (Spliterator) a.spliterator(), (Spliterator) b.spliterator()); - return (a.isParallel() || b.isParallel()) - ? StreamSupport.parallelStream(split) - : StreamSupport.stream(split); + return StreamSupport.stream(split, a.isParallel() || b.isParallel()); } } diff --git a/jdk/src/share/classes/java/util/stream/StreamSupport.java b/jdk/src/share/classes/java/util/stream/StreamSupport.java index 2b3cbfaeb76..0d9a5c36e82 100644 --- a/jdk/src/share/classes/java/util/stream/StreamSupport.java +++ b/jdk/src/share/classes/java/util/stream/StreamSupport.java @@ -47,59 +47,38 @@ public final class StreamSupport { private StreamSupport() {} /** - * Creates a new sequential {@code Stream} from a {@code Spliterator}. - * - *

    The spliterator is only traversed, split, or queried for estimated - * size after the terminal operation of the stream pipeline commences. - * - *

    It is strongly recommended the spliterator report a characteristic of - * {@code IMMUTABLE} or {@code CONCURRENT}, or be - * late-binding. Otherwise, - * {@link #stream(Supplier, int)} should be used to - * reduce the scope of potential interference with the source. See - * Non-Interference for - * more details. - * - * @param the type of stream elements - * @param spliterator a {@code Spliterator} describing the stream elements - * @return a new sequential {@code Stream} - */ - public static Stream stream(Spliterator spliterator) { - Objects.requireNonNull(spliterator); - return new ReferencePipeline.Head<>(spliterator, - StreamOpFlag.fromCharacteristics(spliterator), - false); - } - - /** - * Creates a new parallel {@code Stream} from a {@code Spliterator}. - * - *

    The spliterator is only traversed, split, or queried for estimated - * size after the terminal operation of the stream pipeline commences. - * - *

    It is strongly recommended the spliterator report a characteristic of - * {@code IMMUTABLE} or {@code CONCURRENT}, or be - * late-binding. Otherwise, - * {@link #stream(Supplier, int)} should be used to - * reduce the scope of potential interference with the source. See - * Non-Interference for - * more details. - * - * @param the type of stream elements - * @param spliterator a {@code Spliterator} describing the stream elements - * @return a new parallel {@code Stream} - */ - public static Stream parallelStream(Spliterator spliterator) { - Objects.requireNonNull(spliterator); - return new ReferencePipeline.Head<>(spliterator, - StreamOpFlag.fromCharacteristics(spliterator), - true); - } - - /** - * Creates a new sequential {@code Stream} from a {@code Supplier} of + * Creates a new sequential or parallel {@code Stream} from a * {@code Spliterator}. * + *

    The spliterator is only traversed, split, or queried for estimated + * size after the terminal operation of the stream pipeline commences. + * + *

    It is strongly recommended the spliterator report a characteristic of + * {@code IMMUTABLE} or {@code CONCURRENT}, or be + * late-binding. Otherwise, + * {@link #stream(java.util.function.Supplier, int, boolean)} should be used + * to reduce the scope of potential interference with the source. See + * Non-Interference for + * more details. + * + * @param the type of stream elements + * @param spliterator a {@code Spliterator} describing the stream elements + * @param parallel if {@code true} then the returned stream is a parallel + * stream; if {@code false} the returned stream is a sequential + * stream. + * @return a new sequential or parallel {@code Stream} + */ + public static Stream stream(Spliterator spliterator, boolean parallel) { + Objects.requireNonNull(spliterator); + return new ReferencePipeline.Head<>(spliterator, + StreamOpFlag.fromCharacteristics(spliterator), + parallel); + } + + /** + * Creates a new sequential or parallel {@code Stream} from a + * {@code Supplier} of {@code Spliterator}. + * *

    The {@link Supplier#get()} method will be invoked on the supplier no * more than once, and after the terminal operation of the stream pipeline * commences. @@ -107,7 +86,8 @@ public final class StreamSupport { *

    For spliterators that report a characteristic of {@code IMMUTABLE} * or {@code CONCURRENT}, or that are * late-binding, it is likely - * more efficient to use {@link #stream(java.util.Spliterator)} instead. + * more efficient to use {@link #stream(java.util.Spliterator, boolean)} + * instead. * The use of a {@code Supplier} in this form provides a level of * indirection that reduces the scope of potential interference with the * source. Since the supplier is only invoked after the terminal operation @@ -116,60 +96,28 @@ public final class StreamSupport { * Non-Interference for * more details. * - * @param the type of stream elements * @param supplier a {@code Supplier} of a {@code Spliterator} * @param characteristics Spliterator characteristics of the supplied * {@code Spliterator}. The characteristics must be equal to - * {@code source.get().getCharacteristics()}. - * @return a new sequential {@code Stream} - * @see #stream(Spliterator) + * {@code supplier.get().characteristics()}. + * @param parallel if {@code true} then the returned stream is a parallel + * stream; if {@code false} the returned stream is a sequential + * stream. + * @return a new sequential or parallel {@code Stream} + * @see #stream(java.util.Spliterator, boolean) */ public static Stream stream(Supplier> supplier, - int characteristics) { + int characteristics, + boolean parallel) { Objects.requireNonNull(supplier); return new ReferencePipeline.Head<>(supplier, StreamOpFlag.fromCharacteristics(characteristics), - false); + parallel); } /** - * Creates a new parallel {@code Stream} from a {@code Supplier} of - * {@code Spliterator}. - * - *

    The {@link Supplier#get()} method will be invoked on the supplier no - * more than once, and after the terminal operation of the stream pipeline - * commences. - * - *

    For spliterators that report a characteristic of {@code IMMUTABLE} - * or {@code CONCURRENT}, or that are - * late-binding, it is likely - * more efficient to use {@link #stream(Spliterator)} instead. - * The use of a {@code Supplier} in this form provides a level of - * indirection that reduces the scope of potential interference with the - * source. Since the supplier is only invoked after the terminal operation - * commences, any modifications to the source up to the start of the - * terminal operation are reflected in the stream result. See - * Non-Interference for - * more details. - * - * @param the type of stream elements - * @param supplier a {@code Supplier} of a {@code Spliterator} - * @param characteristics Spliterator characteristics of the supplied - * {@code Spliterator}. The characteristics must be equal to - * {@code source.get().getCharacteristics()} - * @return a new parallel {@code Stream} - * @see #parallelStream(Spliterator) - */ - public static Stream parallelStream(Supplier> supplier, - int characteristics) { - Objects.requireNonNull(supplier); - return new ReferencePipeline.Head<>(supplier, - StreamOpFlag.fromCharacteristics(characteristics), - true); - } - - /** - * Creates a new sequential {@code IntStream} from a {@code Spliterator.OfInt}. + * Creates a new sequential or parallel {@code IntStream} from a + * {@code Spliterator.OfInt}. * *

    The spliterator is only traversed, split, or queried for estimated size * after the terminal operation of the stream pipeline commences. @@ -177,46 +125,26 @@ public final class StreamSupport { *

    It is strongly recommended the spliterator report a characteristic of * {@code IMMUTABLE} or {@code CONCURRENT}, or be * late-binding. Otherwise, - * {@link #stream(Supplier, int)}} should be used to - * reduce the scope of potential interference with the source. See + * {@link #intStream(java.util.function.Supplier, int, boolean)} should be + * used to reduce the scope of potential interference with the source. See * Non-Interference for * more details. * * @param spliterator a {@code Spliterator.OfInt} describing the stream elements - * @return a new sequential {@code IntStream} + * @param parallel if {@code true} then the returned stream is a parallel + * stream; if {@code false} the returned stream is a sequential + * stream. + * @return a new sequential or parallel {@code IntStream} */ - public static IntStream intStream(Spliterator.OfInt spliterator) { + public static IntStream intStream(Spliterator.OfInt spliterator, boolean parallel) { return new IntPipeline.Head<>(spliterator, StreamOpFlag.fromCharacteristics(spliterator), - false); + parallel); } /** - * Creates a new parallel {@code IntStream} from a {@code Spliterator.OfInt}. - * - *

    he spliterator is only traversed, split, or queried for estimated size - * after the terminal operation of the stream pipeline commences. - * - *

    It is strongly recommended the spliterator report a characteristic of - * {@code IMMUTABLE} or {@code CONCURRENT}, or be - * late-binding. Otherwise, - * {@link #stream(Supplier, int)}} should be used to - * reduce the scope of potential interference with the source. See - * Non-Interference for - * more details. - * - * @param spliterator a {@code Spliterator.OfInt} describing the stream elements - * @return a new parallel {@code IntStream} - */ - public static IntStream intParallelStream(Spliterator.OfInt spliterator) { - return new IntPipeline.Head<>(spliterator, - StreamOpFlag.fromCharacteristics(spliterator), - true); - } - - /** - * Creates a new sequential {@code IntStream} from a {@code Supplier} of - * {@code Spliterator.OfInt}. + * Creates a new sequential or parallel {@code IntStream} from a + * {@code Supplier} of {@code Spliterator.OfInt}. * *

    The {@link Supplier#get()} method will be invoked on the supplier no * more than once, and after the terminal operation of the stream pipeline @@ -225,7 +153,8 @@ public final class StreamSupport { *

    For spliterators that report a characteristic of {@code IMMUTABLE} * or {@code CONCURRENT}, or that are * late-binding, it is likely - * more efficient to use {@link #intStream(Spliterator.OfInt)} instead. + * more efficient to use {@link #intStream(java.util.Spliterator.OfInt, boolean)} + * instead. * The use of a {@code Supplier} in this form provides a level of * indirection that reduces the scope of potential interference with the * source. Since the supplier is only invoked after the terminal operation @@ -237,53 +166,24 @@ public final class StreamSupport { * @param supplier a {@code Supplier} of a {@code Spliterator.OfInt} * @param characteristics Spliterator characteristics of the supplied * {@code Spliterator.OfInt}. The characteristics must be equal to - * {@code source.get().getCharacteristics()} - * @return a new sequential {@code IntStream} - * @see #intStream(Spliterator.OfInt) + * {@code supplier.get().characteristics()} + * @param parallel if {@code true} then the returned stream is a parallel + * stream; if {@code false} the returned stream is a sequential + * stream. + * @return a new sequential or parallel {@code IntStream} + * @see #intStream(java.util.Spliterator.OfInt, boolean) */ public static IntStream intStream(Supplier supplier, - int characteristics) { + int characteristics, + boolean parallel) { return new IntPipeline.Head<>(supplier, StreamOpFlag.fromCharacteristics(characteristics), - false); + parallel); } /** - * Creates a new parallel {@code IntStream} from a {@code Supplier} of - * {@code Spliterator.OfInt}. - * - *

    The {@link Supplier#get()} method will be invoked on the supplier no - * more than once, and after the terminal operation of the stream pipeline - * commences. - * - *

    For spliterators that report a characteristic of {@code IMMUTABLE} - * or {@code CONCURRENT}, or that are - * late-binding, it is likely - * more efficient to use {@link #intStream(Spliterator.OfInt)} instead. - * The use of a {@code Supplier} in this form provides a level of - * indirection that reduces the scope of potential interference with the - * source. Since the supplier is only invoked after the terminal operation - * commences, any modifications to the source up to the start of the - * terminal operation are reflected in the stream result. See - * Non-Interference for - * more details. - * - * @param supplier a {@code Supplier} of a {@code Spliterator.OfInt} - * @param characteristics Spliterator characteristics of the supplied - * {@code Spliterator.OfInt}. The characteristics must be equal to - * {@code source.get().getCharacteristics()} - * @return a new parallel {@code IntStream} - * @see #intParallelStream(Spliterator.OfInt) - */ - public static IntStream intParallelStream(Supplier supplier, - int characteristics) { - return new IntPipeline.Head<>(supplier, - StreamOpFlag.fromCharacteristics(characteristics), - true); - } - - /** - * Creates a new sequential {@code LongStream} from a {@code Spliterator.OfLong}. + * Creates a new sequential or parallel {@code LongStream} from a + * {@code Spliterator.OfLong}. * *

    The spliterator is only traversed, split, or queried for estimated * size after the terminal operation of the stream pipeline commences. @@ -291,47 +191,27 @@ public final class StreamSupport { *

    It is strongly recommended the spliterator report a characteristic of * {@code IMMUTABLE} or {@code CONCURRENT}, or be * late-binding. Otherwise, - * {@link #stream(Supplier, int)} should be used to - * reduce the scope of potential interference with the source. See - * Non-Interference for - * more details. - * - * @param spliterator a {@code Spliterator.OfLong} describing the stream - * elements - * @return a new sequential {@code LongStream} - */ - public static LongStream longStream(Spliterator.OfLong spliterator) { - return new LongPipeline.Head<>(spliterator, - StreamOpFlag.fromCharacteristics(spliterator), - false); - } - - /** - * Creates a new parallel {@code LongStream} from a {@code Spliterator.OfLong}. - * - *

    The spliterator is only traversed, split, or queried for estimated - * size after the terminal operation of the stream pipeline commences. - * - *

    It is strongly recommended the spliterator report a characteristic of - * {@code IMMUTABLE} or {@code CONCURRENT}, or be - * late-binding. Otherwise, - * {@link #stream(Supplier, int)} should be used to - * reduce the scope of potential interference with the source. See + * {@link #longStream(java.util.function.Supplier, int, boolean)} should be + * used to reduce the scope of potential interference with the source. See * Non-Interference for * more details. * * @param spliterator a {@code Spliterator.OfLong} describing the stream elements - * @return a new parallel {@code LongStream} + * @param parallel if {@code true} then the returned stream is a parallel + * stream; if {@code false} the returned stream is a sequential + * stream. + * @return a new sequential or parallel {@code LongStream} */ - public static LongStream longParallelStream(Spliterator.OfLong spliterator) { + public static LongStream longStream(Spliterator.OfLong spliterator, + boolean parallel) { return new LongPipeline.Head<>(spliterator, StreamOpFlag.fromCharacteristics(spliterator), - true); + parallel); } /** - * Creates a new sequential {@code LongStream} from a {@code Supplier} of - * {@code Spliterator.OfLong}. + * Creates a new sequential or parallel {@code LongStream} from a + * {@code Supplier} of {@code Spliterator.OfLong}. * *

    The {@link Supplier#get()} method will be invoked on the supplier no * more than once, and after the terminal operation of the stream pipeline @@ -340,7 +220,8 @@ public final class StreamSupport { *

    For spliterators that report a characteristic of {@code IMMUTABLE} * or {@code CONCURRENT}, or that are * late-binding, it is likely - * more efficient to use {@link #longStream(Spliterator.OfLong)} instead. + * more efficient to use {@link #longStream(java.util.Spliterator.OfLong, boolean)} + * instead. * The use of a {@code Supplier} in this form provides a level of * indirection that reduces the scope of potential interference with the * source. Since the supplier is only invoked after the terminal operation @@ -352,20 +233,52 @@ public final class StreamSupport { * @param supplier a {@code Supplier} of a {@code Spliterator.OfLong} * @param characteristics Spliterator characteristics of the supplied * {@code Spliterator.OfLong}. The characteristics must be equal to - * {@code source.get().getCharacteristics()} - * @return a new sequential {@code LongStream} - * @see #longStream(Spliterator.OfLong) + * {@code supplier.get().characteristics()} + * @param parallel if {@code true} then the returned stream is a parallel + * stream; if {@code false} the returned stream is a sequential + * stream. + * @return a new sequential or parallel {@code LongStream} + * @see #longStream(java.util.Spliterator.OfLong, boolean) */ public static LongStream longStream(Supplier supplier, - int characteristics) { + int characteristics, + boolean parallel) { return new LongPipeline.Head<>(supplier, StreamOpFlag.fromCharacteristics(characteristics), - false); + parallel); } /** - * Creates a new parallel {@code LongStream} from a {@code Supplier} of - * {@code Spliterator.OfLong}. + * Creates a new sequential or parallel {@code DoubleStream} from a + * {@code Spliterator.OfDouble}. + * + *

    The spliterator is only traversed, split, or queried for estimated size + * after the terminal operation of the stream pipeline commences. + * + *

    It is strongly recommended the spliterator report a characteristic of + * {@code IMMUTABLE} or {@code CONCURRENT}, or be + * late-binding. Otherwise, + * {@link #doubleStream(java.util.function.Supplier, int, boolean)} should + * be used to reduce the scope of potential interference with the source. See + * Non-Interference for + * more details. + * + * @param spliterator A {@code Spliterator.OfDouble} describing the stream elements + * @param parallel if {@code true} then the returned stream is a parallel + * stream; if {@code false} the returned stream is a sequential + * stream. + * @return a new sequential or parallel {@code DoubleStream} + */ + public static DoubleStream doubleStream(Spliterator.OfDouble spliterator, + boolean parallel) { + return new DoublePipeline.Head<>(spliterator, + StreamOpFlag.fromCharacteristics(spliterator), + parallel); + } + + /** + * Creates a new sequential or parallel {@code DoubleStream} from a + * {@code Supplier} of {@code Spliterator.OfDouble}. * *

    The {@link Supplier#get()} method will be invoked on the supplier no * more than once, and after the terminal operation of the stream pipeline @@ -374,89 +287,8 @@ public final class StreamSupport { *

    For spliterators that report a characteristic of {@code IMMUTABLE} * or {@code CONCURRENT}, or that are * late-binding, it is likely - * more efficient to use {@link #longStream(Spliterator.OfLong)} instead. - * The use of a {@code Supplier} in this form provides a level of - * indirection that reduces the scope of potential interference with the - * source. Since the supplier is only invoked after the terminal operation - * commences, any modifications to the source up to the start of the - * terminal operation are reflected in the stream result. See - * Non-Interference for - * more details. - * - * @param supplier A {@code Supplier} of a {@code Spliterator.OfLong} - * @param characteristics Spliterator characteristics of the supplied - * {@code Spliterator.OfLong}. The characteristics must be equal to - * {@code source.get().getCharacteristics()} - * @return A new parallel {@code LongStream} - * @see #longParallelStream(Spliterator.OfLong) - */ - public static LongStream longParallelStream(Supplier supplier, - int characteristics) { - return new LongPipeline.Head<>(supplier, - StreamOpFlag.fromCharacteristics(characteristics), - true); - } - - /** - * Creates a new sequential {@code DoubleStream} from a - * {@code Spliterator.OfDouble}. - * - *

    The spliterator is only traversed, split, or queried for estimated size - * after the terminal operation of the stream pipeline commences. - * - *

    It is strongly recommended the spliterator report a characteristic of - * {@code IMMUTABLE} or {@code CONCURRENT}, or be - * late-binding. Otherwise, - * {@link #stream(Supplier, int)} should be used to - * reduce the scope of potential interference with the source. See - * Non-Interference for - * more details. - * - * @param spliterator A {@code Spliterator.OfDouble} describing the stream elements - * @return A new sequential {@code DoubleStream} - */ - public static DoubleStream doubleStream(Spliterator.OfDouble spliterator) { - return new DoublePipeline.Head<>(spliterator, - StreamOpFlag.fromCharacteristics(spliterator), - false); - } - - /** - * Creates a new parallel {@code DoubleStream} from a - * {@code Spliterator.OfDouble}. - * - *

    The spliterator is only traversed, split, or queried for estimated size - * after the terminal operation of the stream pipeline commences. - * - *

    It is strongly recommended the spliterator report a characteristic of - * {@code IMMUTABLE} or {@code CONCURRENT}, or be - * late-binding. Otherwise, - * {@link #stream(Supplier, int)} should be used to - * reduce the scope of potential interference with the source. See - * Non-Interference for - * more details. - * - * @param spliterator A {@code Spliterator.OfDouble} describing the stream elements - * @return A new parallel {@code DoubleStream} - */ - public static DoubleStream doubleParallelStream(Spliterator.OfDouble spliterator) { - return new DoublePipeline.Head<>(spliterator, - StreamOpFlag.fromCharacteristics(spliterator), - true); - } - - /** - * Creates a new sequential {@code DoubleStream} from a {@code Supplier} of - * {@code Spliterator.OfDouble}. - *

    - * The {@link Supplier#get()} method will be invoked on the supplier no - * more than once, and after the terminal operation of the stream pipeline - * commences. - *

    - * For spliterators that report a characteristic of {@code IMMUTABLE} - * or {@code CONCURRENT}, or that are - * late-binding, it is likely - * more efficient to use {@link #doubleStream(Spliterator.OfDouble)} instead. + * more efficient to use {@link #doubleStream(java.util.Spliterator.OfDouble, boolean)} + * instead. * The use of a {@code Supplier} in this form provides a level of * indirection that reduces the scope of potential interference with the * source. Since the supplier is only invoked after the terminal operation @@ -468,48 +300,18 @@ public final class StreamSupport { * @param supplier A {@code Supplier} of a {@code Spliterator.OfDouble} * @param characteristics Spliterator characteristics of the supplied * {@code Spliterator.OfDouble}. The characteristics must be equal to - * {@code source.get().getCharacteristics()} - * @return A new sequential {@code DoubleStream} - * @see #doubleStream(Spliterator.OfDouble) + * {@code supplier.get().characteristics()} + * @param parallel if {@code true} then the returned stream is a parallel + * stream; if {@code false} the returned stream is a sequential + * stream. + * @return a new sequential or parallel {@code DoubleStream} + * @see #doubleStream(java.util.Spliterator.OfDouble, boolean) */ public static DoubleStream doubleStream(Supplier supplier, - int characteristics) { + int characteristics, + boolean parallel) { return new DoublePipeline.Head<>(supplier, StreamOpFlag.fromCharacteristics(characteristics), - false); - } - - /** - * Creates a new parallel {@code DoubleStream} from a {@code Supplier} of - * {@code Spliterator.OfDouble}. - * - *

    The {@link Supplier#get()} method will be invoked on the supplier no - * more than once, and after the terminal operation of the stream pipeline - * commences. - * - *

    For spliterators that report a characteristic of {@code IMMUTABLE} - * or {@code CONCURRENT}, or that are - * late-binding, it is likely - * more efficient to use {@link #doubleStream(Spliterator.OfDouble)} instead. - * The use of a {@code Supplier} in this form provides a level of - * indirection that reduces the scope of potential interference with the - * source. Since the supplier is only invoked after the terminal operation - * commences, any modifications to the source up to the start of the - * terminal operation are reflected in the stream result. See - * Non-Interference for - * more details. - * - * @param supplier a {@code Supplier} of a {@code Spliterator.OfDouble} - * @param characteristics Spliterator characteristics of the supplied - * {@code Spliterator.OfDouble}. The characteristics must be equal to - * {@code source.get().getCharacteristics()} - * @return a new parallel {@code DoubleStream} - * @see #doubleParallelStream(Spliterator.OfDouble) - */ - public static DoubleStream doubleParallelStream(Supplier supplier, - int characteristics) { - return new DoublePipeline.Head<>(supplier, - StreamOpFlag.fromCharacteristics(characteristics), - true); + parallel); } } diff --git a/jdk/src/share/classes/java/util/stream/Streams.java b/jdk/src/share/classes/java/util/stream/Streams.java index 1d49997fe22..21fe2706280 100644 --- a/jdk/src/share/classes/java/util/stream/Streams.java +++ b/jdk/src/share/classes/java/util/stream/Streams.java @@ -25,10 +25,7 @@ package java.util.stream; import java.util.Comparator; -import java.util.Objects; import java.util.Spliterator; -import java.util.Spliterators; -import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.DoubleConsumer; import java.util.function.IntConsumer; @@ -379,7 +376,7 @@ final class Streams { count = -count - 1; // Use this spliterator if 0 or 1 elements, otherwise use // the spliterator of the spined buffer - return (c < 2) ? StreamSupport.stream(this) : StreamSupport.stream(buffer.spliterator()); + return (c < 2) ? StreamSupport.stream(this, false) : StreamSupport.stream(buffer.spliterator(), false); } throw new IllegalStateException(); @@ -466,7 +463,7 @@ final class Streams { count = -count - 1; // Use this spliterator if 0 or 1 elements, otherwise use // the spliterator of the spined buffer - return (c < 2) ? StreamSupport.intStream(this) : StreamSupport.intStream(buffer.spliterator()); + return (c < 2) ? StreamSupport.intStream(this, false) : StreamSupport.intStream(buffer.spliterator(), false); } throw new IllegalStateException(); @@ -553,7 +550,7 @@ final class Streams { count = -count - 1; // Use this spliterator if 0 or 1 elements, otherwise use // the spliterator of the spined buffer - return (c < 2) ? StreamSupport.longStream(this) : StreamSupport.longStream(buffer.spliterator()); + return (c < 2) ? StreamSupport.longStream(this, false) : StreamSupport.longStream(buffer.spliterator(), false); } throw new IllegalStateException(); @@ -640,7 +637,7 @@ final class Streams { count = -count - 1; // Use this spliterator if 0 or 1 elements, otherwise use // the spliterator of the spined buffer - return (c < 2) ? StreamSupport.doubleStream(this) : StreamSupport.doubleStream(buffer.spliterator()); + return (c < 2) ? StreamSupport.doubleStream(this, false) : StreamSupport.doubleStream(buffer.spliterator(), false); } throw new IllegalStateException(); diff --git a/jdk/src/share/classes/java/util/zip/ZipFile.java b/jdk/src/share/classes/java/util/zip/ZipFile.java index 97d415c4a51..6a023f81355 100644 --- a/jdk/src/share/classes/java/util/zip/ZipFile.java +++ b/jdk/src/share/classes/java/util/zip/ZipFile.java @@ -551,7 +551,7 @@ class ZipFile implements ZipConstants, Closeable { return StreamSupport.stream(Spliterators.spliterator( new ZipEntryIterator(), size(), Spliterator.ORDERED | Spliterator.DISTINCT | - Spliterator.IMMUTABLE | Spliterator.NONNULL)); + Spliterator.IMMUTABLE | Spliterator.NONNULL), false); } private ZipEntry getZipEntry(String name, long jzentry) { diff --git a/jdk/test/java/util/stream/bootlib/java/util/stream/DoubleStreamTestScenario.java b/jdk/test/java/util/stream/bootlib/java/util/stream/DoubleStreamTestScenario.java index 5e431b1325e..d4459cf0c9b 100644 --- a/jdk/test/java/util/stream/bootlib/java/util/stream/DoubleStreamTestScenario.java +++ b/jdk/test/java/util/stream/bootlib/java/util/stream/DoubleStreamTestScenario.java @@ -140,9 +140,9 @@ public enum DoubleStreamTestScenario implements OpTestCase.BaseStreamTestScenari void _run(TestData data, DoubleConsumer b, Function m) { DoubleStream s = m.apply(data.parallelStream()); Spliterator.OfDouble sp = s.spliterator(); - DoubleStream ss = StreamSupport.doubleParallelStream(() -> sp, - StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s)) - | (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED)); + DoubleStream ss = StreamSupport.doubleStream(() -> sp, + StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s)) + | (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED), true); for (double t : ss.toArray()) b.accept(t); } diff --git a/jdk/test/java/util/stream/bootlib/java/util/stream/IntStreamTestScenario.java b/jdk/test/java/util/stream/bootlib/java/util/stream/IntStreamTestScenario.java index c12a4ec1ec9..f399cdeef25 100644 --- a/jdk/test/java/util/stream/bootlib/java/util/stream/IntStreamTestScenario.java +++ b/jdk/test/java/util/stream/bootlib/java/util/stream/IntStreamTestScenario.java @@ -140,9 +140,10 @@ public enum IntStreamTestScenario implements OpTestCase.BaseStreamTestScenario { void _run(TestData data, IntConsumer b, Function m) { IntStream s = m.apply(data.parallelStream()); Spliterator.OfInt sp = s.spliterator(); - IntStream ss = StreamSupport.intParallelStream(() -> sp, - StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s)) - | (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED)); + IntStream ss = StreamSupport.intStream(() -> sp, + StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s)) + | (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED), + true); for (int t : ss.toArray()) b.accept(t); } diff --git a/jdk/test/java/util/stream/bootlib/java/util/stream/LongStreamTestScenario.java b/jdk/test/java/util/stream/bootlib/java/util/stream/LongStreamTestScenario.java index c32d6e82425..3010745a55d 100644 --- a/jdk/test/java/util/stream/bootlib/java/util/stream/LongStreamTestScenario.java +++ b/jdk/test/java/util/stream/bootlib/java/util/stream/LongStreamTestScenario.java @@ -140,9 +140,9 @@ public enum LongStreamTestScenario implements OpTestCase.BaseStreamTestScenario void _run(TestData data, LongConsumer b, Function m) { LongStream s = m.apply(data.parallelStream()); Spliterator.OfLong sp = s.spliterator(); - LongStream ss = StreamSupport.longParallelStream(() -> sp, - StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s)) - | (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED)); + LongStream ss = StreamSupport.longStream(() -> sp, + StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s)) + | (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED), true); for (long t : ss.toArray()) b.accept(t); } diff --git a/jdk/test/java/util/stream/bootlib/java/util/stream/StreamTestScenario.java b/jdk/test/java/util/stream/bootlib/java/util/stream/StreamTestScenario.java index c7f09eab1d4..b1abd4320db 100644 --- a/jdk/test/java/util/stream/bootlib/java/util/stream/StreamTestScenario.java +++ b/jdk/test/java/util/stream/bootlib/java/util/stream/StreamTestScenario.java @@ -151,9 +151,9 @@ public enum StreamTestScenario implements OpTestCase.BaseStreamTestScenario { void _run(TestData data, Consumer b, Function> m) { Stream s = m.apply(data.parallelStream()); Spliterator sp = s.spliterator(); - Stream ss = StreamSupport.parallelStream(() -> sp, - StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s)) - | (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED)); + Stream ss = StreamSupport.stream(() -> sp, + StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s)) + | (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED), true); for (Object t : ss.toArray()) b.accept((U) t); } diff --git a/jdk/test/java/util/stream/bootlib/java/util/stream/TestData.java b/jdk/test/java/util/stream/bootlib/java/util/stream/TestData.java index c204b318ed6..f4f0392e5c8 100644 --- a/jdk/test/java/util/stream/bootlib/java/util/stream/TestData.java +++ b/jdk/test/java/util/stream/bootlib/java/util/stream/TestData.java @@ -87,8 +87,8 @@ public interface TestData> public static OfRef ofSpinedBuffer(String name, SpinedBuffer buffer) { return new AbstractTestData.RefTestData<>(name, buffer, - b -> StreamSupport.stream(b.spliterator()), - b -> StreamSupport.parallelStream(b.spliterator()), + b -> StreamSupport.stream(b.spliterator(), false), + b -> StreamSupport.stream(b.spliterator(), true), SpinedBuffer::spliterator, b -> (int) b.count()); } @@ -103,8 +103,8 @@ public interface TestData> public static OfRef ofRefNode(String name, Node node) { return new AbstractTestData.RefTestData<>(name, node, - n -> StreamSupport.stream(n::spliterator, Spliterator.SIZED | Spliterator.ORDERED), - n -> StreamSupport.parallelStream(n::spliterator, Spliterator.SIZED | Spliterator.ORDERED), + n -> StreamSupport.stream(n::spliterator, Spliterator.SIZED | Spliterator.ORDERED, false), + n -> StreamSupport.stream(n::spliterator, Spliterator.SIZED | Spliterator.ORDERED, true), Node::spliterator, n -> (int) n.count()); } @@ -117,8 +117,8 @@ public interface TestData> public static OfInt ofSpinedBuffer(String name, SpinedBuffer.OfInt buffer) { return new AbstractTestData.IntTestData<>(name, buffer, - b -> StreamSupport.intStream(b.spliterator()), - b -> StreamSupport.intParallelStream(b.spliterator()), + b -> StreamSupport.intStream(b.spliterator(), false), + b -> StreamSupport.intStream(b.spliterator(), true), SpinedBuffer.OfInt::spliterator, b -> (int) b.count()); } @@ -134,8 +134,8 @@ public interface TestData> public static OfInt ofNode(String name, Node.OfInt node) { int characteristics = Spliterator.SIZED | Spliterator.ORDERED; return new AbstractTestData.IntTestData<>(name, node, - n -> StreamSupport.intStream(n::spliterator, characteristics), - n -> StreamSupport.intParallelStream(n::spliterator, characteristics), + n -> StreamSupport.intStream(n::spliterator, characteristics, false), + n -> StreamSupport.intStream(n::spliterator, characteristics, true), Node.OfInt::spliterator, n -> (int) n.count()); } @@ -148,8 +148,8 @@ public interface TestData> public static OfLong ofSpinedBuffer(String name, SpinedBuffer.OfLong buffer) { return new AbstractTestData.LongTestData<>(name, buffer, - b -> StreamSupport.longStream(b.spliterator()), - b -> StreamSupport.longParallelStream(b.spliterator()), + b -> StreamSupport.longStream(b.spliterator(), false), + b -> StreamSupport.longStream(b.spliterator(), true), SpinedBuffer.OfLong::spliterator, b -> (int) b.count()); } @@ -165,8 +165,8 @@ public interface TestData> public static OfLong ofNode(String name, Node.OfLong node) { int characteristics = Spliterator.SIZED | Spliterator.ORDERED; return new AbstractTestData.LongTestData<>(name, node, - n -> StreamSupport.longStream(n::spliterator, characteristics), - n -> StreamSupport.longParallelStream(n::spliterator, characteristics), + n -> StreamSupport.longStream(n::spliterator, characteristics, false), + n -> StreamSupport.longStream(n::spliterator, characteristics, true), Node.OfLong::spliterator, n -> (int) n.count()); } @@ -179,8 +179,8 @@ public interface TestData> public static OfDouble ofSpinedBuffer(String name, SpinedBuffer.OfDouble buffer) { return new AbstractTestData.DoubleTestData<>(name, buffer, - b -> StreamSupport.doubleStream(b.spliterator()), - b -> StreamSupport.doubleParallelStream(b.spliterator()), + b -> StreamSupport.doubleStream(b.spliterator(), false), + b -> StreamSupport.doubleStream(b.spliterator(), true), SpinedBuffer.OfDouble::spliterator, b -> (int) b.count()); } @@ -196,8 +196,8 @@ public interface TestData> public static OfDouble ofNode(String name, Node.OfDouble node) { int characteristics = Spliterator.SIZED | Spliterator.ORDERED; return new AbstractTestData.DoubleTestData<>(name, node, - n -> StreamSupport.doubleStream(n::spliterator, characteristics), - n -> StreamSupport.doubleParallelStream(n::spliterator, characteristics), + n -> StreamSupport.doubleStream(n::spliterator, characteristics, false), + n -> StreamSupport.doubleStream(n::spliterator, characteristics, true), Node.OfDouble::spliterator, n -> (int) n.count()); } diff --git a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/DistinctOpTest.java b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/DistinctOpTest.java index ddadacc5a1d..8d9e3f8c01e 100644 --- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/DistinctOpTest.java +++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/DistinctOpTest.java @@ -86,8 +86,8 @@ public class DistinctOpTest extends OpTestCase { static class SortedTestData extends TestData.AbstractTestData.RefTestData> { SortedTestData(List coll) { super("SortedTestData", coll, - c -> StreamSupport.stream(Spliterators.spliterator(c.toArray(), Spliterator.ORDERED | Spliterator.SORTED)), - c -> StreamSupport.parallelStream(Spliterators.spliterator(c.toArray(), Spliterator.ORDERED | Spliterator.SORTED)), + c -> StreamSupport.stream(Spliterators.spliterator(c.toArray(), Spliterator.ORDERED | Spliterator.SORTED), false), + c -> StreamSupport.stream(Spliterators.spliterator(c.toArray(), Spliterator.ORDERED | Spliterator.SORTED), true), c -> Spliterators.spliterator(c.toArray(), Spliterator.ORDERED | Spliterator.SORTED), List::size); } diff --git a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/InfiniteStreamWithLimitOpTest.java b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/InfiniteStreamWithLimitOpTest.java index dc086668f54..0915839415c 100644 --- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/InfiniteStreamWithLimitOpTest.java +++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/InfiniteStreamWithLimitOpTest.java @@ -306,7 +306,7 @@ public class InfiniteStreamWithLimitOpTest extends OpTestCase { private TestData.OfLong proxiedLongRange(long l, long u) { return TestData.Factory.ofLongSupplier( String.format("[%d, %d)", l, u), - () -> StreamSupport.longStream(proxyNotSubsized(LongStream.range(l, u).spliterator()))); + () -> StreamSupport.longStream(proxyNotSubsized(LongStream.range(l, u).spliterator()), false)); } @Test(dataProvider = "Stream.limit") diff --git a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/MatchOpTest.java b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/MatchOpTest.java index e88a8d95e93..dc825da5587 100644 --- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/MatchOpTest.java +++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/MatchOpTest.java @@ -155,7 +155,7 @@ public class MatchOpTest extends OpTestCase { } Supplier> source = () -> Arrays.asList(1, 2, 3, 4).iterator(); - Supplier> s = () -> StreamSupport.stream(Spliterators.spliteratorUnknownSize(new CycleIterator(source), 0)); + Supplier> s = () -> StreamSupport.stream(Spliterators.spliteratorUnknownSize(new CycleIterator(source), 0), false); assertFalse(s.get().allMatch(i -> i > 3)); assertTrue(s.get().anyMatch(i -> i > 3)); @@ -240,7 +240,7 @@ public class MatchOpTest extends OpTestCase { } Supplier source = () -> Arrays.stream(new int[]{1, 2, 3, 4}).iterator(); - Supplier s = () -> StreamSupport.intStream(Spliterators.spliteratorUnknownSize(new CycleIterator(source), 0)); + Supplier s = () -> StreamSupport.intStream(Spliterators.spliteratorUnknownSize(new CycleIterator(source), 0), false); assertFalse(s.get().allMatch(i -> i > 3)); assertTrue(s.get().anyMatch(i -> i > 3)); @@ -325,7 +325,7 @@ public class MatchOpTest extends OpTestCase { } Supplier source = () -> Arrays.stream(new long[]{1, 2, 3, 4}).iterator(); - Supplier s = () -> StreamSupport.longStream(Spliterators.spliteratorUnknownSize(new CycleIterator(source), 0)); + Supplier s = () -> StreamSupport.longStream(Spliterators.spliteratorUnknownSize(new CycleIterator(source), 0), false); assertFalse(s.get().allMatch(i -> i > 3)); assertTrue(s.get().anyMatch(i -> i > 3)); @@ -410,7 +410,7 @@ public class MatchOpTest extends OpTestCase { } Supplier source = () -> Arrays.stream(new double[]{1, 2, 3, 4}).iterator(); - Supplier s = () -> StreamSupport.doubleStream(Spliterators.spliteratorUnknownSize(new CycleIterator(source), 0)); + Supplier s = () -> StreamSupport.doubleStream(Spliterators.spliteratorUnknownSize(new CycleIterator(source), 0), false); assertFalse(s.get().allMatch(i -> i > 3)); assertTrue(s.get().anyMatch(i -> i > 3)); diff --git a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SliceOpTest.java b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SliceOpTest.java index afa1b012653..b8c9b54a343 100644 --- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SliceOpTest.java +++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SliceOpTest.java @@ -237,7 +237,7 @@ public class SliceOpTest extends OpTestCase { List list = IntStream.range(0, 100).boxed().collect(Collectors.toList()); TestData.OfRef data = TestData.Factory.ofSupplier( "Non splitting, not SUBSIZED, ORDERED, stream", - () -> StreamSupport.stream(new NonSplittingNotSubsizedOrderedSpliterator<>(list.spliterator()))); + () -> StreamSupport.stream(new NonSplittingNotSubsizedOrderedSpliterator<>(list.spliterator()), false)); testSkipLimitOps("testSkipLimitOpsWithNonSplittingSpliterator", data); } diff --git a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SortedOpTest.java b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SortedOpTest.java index 956dea39ec3..6c8cab21825 100644 --- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SortedOpTest.java +++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SortedOpTest.java @@ -78,7 +78,7 @@ public class SortedOpTest extends OpTestCase { } private Stream unknownSizeStream(List l) { - return StreamSupport.stream(Spliterators.spliteratorUnknownSize(l.iterator(), 0)); + return StreamSupport.stream(Spliterators.spliteratorUnknownSize(l.iterator(), 0), false); } @Test(dataProvider = "StreamTestData", dataProviderClass = StreamTestDataProvider.class) @@ -150,7 +150,7 @@ public class SortedOpTest extends OpTestCase { } private IntStream unknownSizeIntStream(int[] a) { - return StreamSupport.intStream(Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(a)), 0)); + return StreamSupport.intStream(Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(a)), 0), false); } @Test(dataProvider = "IntStreamTestData", dataProviderClass = IntStreamTestDataProvider.class) @@ -193,7 +193,7 @@ public class SortedOpTest extends OpTestCase { } private LongStream unknownSizeLongStream(long[] a) { - return StreamSupport.longStream(Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(a)), 0)); + return StreamSupport.longStream(Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(a)), 0), false); } @Test(dataProvider = "LongStreamTestData", dataProviderClass = LongStreamTestDataProvider.class) @@ -236,7 +236,7 @@ public class SortedOpTest extends OpTestCase { } private DoubleStream unknownSizeDoubleStream(double[] a) { - return StreamSupport.doubleStream(Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(a)), 0)); + return StreamSupport.doubleStream(Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(a)), 0), false); } @Test(dataProvider = "DoubleStreamTestData", dataProviderClass = DoubleStreamTestDataProvider.class) diff --git a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamSpliteratorTest.java b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamSpliteratorTest.java index bd111cfdb27..f3739784b34 100644 --- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamSpliteratorTest.java +++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamSpliteratorTest.java @@ -266,7 +266,7 @@ public class StreamSpliteratorTest extends OpTestCase { setContext("proxyEstimateSize", proxyEstimateSize); Spliterator sp = intermediateOp.apply(l.stream()).spliterator(); ProxyNoExactSizeSpliterator psp = new ProxyNoExactSizeSpliterator<>(sp, proxyEstimateSize); - Stream s = StreamSupport.parallelStream(psp); + Stream s = StreamSupport.stream(psp, true); terminalOp.accept(s); Assert.assertTrue(psp.splits > 0, String.format("Number of splits should be greater that zero when proxyEstimateSize is %s", @@ -290,14 +290,14 @@ public class StreamSpliteratorTest extends OpTestCase { withData(data). stream((Stream in) -> { Stream out = f.apply(in); - return StreamSupport.stream(() -> out.spliterator(), OpTestCase.getStreamFlags(out)); + return StreamSupport.stream(() -> out.spliterator(), OpTestCase.getStreamFlags(out), false); }). exercise(); withData(data). stream((Stream in) -> { Stream out = f.apply(in); - return StreamSupport.parallelStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out)); + return StreamSupport.stream(() -> out.spliterator(), OpTestCase.getStreamFlags(out), true); }). exercise(); } @@ -362,7 +362,7 @@ public class StreamSpliteratorTest extends OpTestCase { // @@@ Need way to obtain the target size Spliterator.OfInt sp = intermediateOp.apply(IntStream.range(0, 1000)).spliterator(); ProxyNoExactSizeSpliterator.OfInt psp = new ProxyNoExactSizeSpliterator.OfInt(sp, proxyEstimateSize); - IntStream s = StreamSupport.intParallelStream(psp); + IntStream s = StreamSupport.intStream(psp, true); terminalOp.accept(s); Assert.assertTrue(psp.splits > 0, String.format("Number of splits should be greater that zero when proxyEstimateSize is %s", @@ -386,14 +386,14 @@ public class StreamSpliteratorTest extends OpTestCase { withData(data). stream(in -> { IntStream out = f.apply(in); - return StreamSupport.intStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out)); + return StreamSupport.intStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out), false); }). exercise(); withData(data). stream((in) -> { IntStream out = f.apply(in); - return StreamSupport.intParallelStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out)); + return StreamSupport.intStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out), true); }). exercise(); } @@ -455,7 +455,7 @@ public class StreamSpliteratorTest extends OpTestCase { // @@@ Need way to obtain the target size Spliterator.OfLong sp = intermediateOp.apply(LongStream.range(0, 1000)).spliterator(); ProxyNoExactSizeSpliterator.OfLong psp = new ProxyNoExactSizeSpliterator.OfLong(sp, proxyEstimateSize); - LongStream s = StreamSupport.longParallelStream(psp); + LongStream s = StreamSupport.longStream(psp, true); terminalOp.accept(s); Assert.assertTrue(psp.splits > 0, String.format("Number of splits should be greater that zero when proxyEstimateSize is %s", @@ -479,14 +479,14 @@ public class StreamSpliteratorTest extends OpTestCase { withData(data). stream(in -> { LongStream out = f.apply(in); - return StreamSupport.longStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out)); + return StreamSupport.longStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out), false); }). exercise(); withData(data). stream((in) -> { LongStream out = f.apply(in); - return StreamSupport.longParallelStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out)); + return StreamSupport.longStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out), true); }). exercise(); } @@ -548,7 +548,7 @@ public class StreamSpliteratorTest extends OpTestCase { // @@@ Need way to obtain the target size Spliterator.OfDouble sp = intermediateOp.apply(IntStream.range(0, 1000).asDoubleStream()).spliterator(); ProxyNoExactSizeSpliterator.OfDouble psp = new ProxyNoExactSizeSpliterator.OfDouble(sp, proxyEstimateSize); - DoubleStream s = StreamSupport.doubleParallelStream(psp); + DoubleStream s = StreamSupport.doubleStream(psp, true); terminalOp.accept(s); Assert.assertTrue(psp.splits > 0, String.format("Number of splits should be greater that zero when proxyEstimateSize is %s", @@ -572,14 +572,14 @@ public class StreamSpliteratorTest extends OpTestCase { withData(data). stream(in -> { DoubleStream out = f.apply(in); - return StreamSupport.doubleStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out)); + return StreamSupport.doubleStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out), false); }). exercise(); withData(data). stream((in) -> { DoubleStream out = f.apply(in); - return StreamSupport.doubleParallelStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out)); + return StreamSupport.doubleStream(() -> out.spliterator(), OpTestCase.getStreamFlags(out), true); }). exercise(); } From b75b83da3e089598067d43f6b0200310791a4604 Mon Sep 17 00:00:00 2001 From: Anton Litvinov Date: Thu, 4 Jul 2013 16:06:11 +0400 Subject: [PATCH 063/123] 8015730: PIT: On Linux, OGL=true and fbobject=false leads to deadlock or infinite loop Reviewed-by: art, anthony --- .../classes/sun/awt/X11/XErrorHandlerUtil.java | 8 +++++++- jdk/src/solaris/native/sun/awt/awt_util.h | 18 ++++++++++++++---- .../native/sun/java2d/opengl/GLXSurfaceData.c | 10 ++++++---- 3 files changed, 27 insertions(+), 9 deletions(-) diff --git a/jdk/src/solaris/classes/sun/awt/X11/XErrorHandlerUtil.java b/jdk/src/solaris/classes/sun/awt/X11/XErrorHandlerUtil.java index e45f67ffde9..da12cd9ef89 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XErrorHandlerUtil.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XErrorHandlerUtil.java @@ -105,9 +105,15 @@ public final class XErrorHandlerUtil { * Unsets a current synthetic error handler. Must be called with the acquired AWT lock. */ public static void RESTORE_XERROR_HANDLER() { + RESTORE_XERROR_HANDLER(true); + } + + private static void RESTORE_XERROR_HANDLER(boolean doXSync) { // Wait until all requests are processed by the X server // and only then uninstall the error handler. - XSync(); + if (doXSync) { + XSync(); + } current_error_handler = null; } diff --git a/jdk/src/solaris/native/sun/awt/awt_util.h b/jdk/src/solaris/native/sun/awt/awt_util.h index 6e350727806..b93f7744cd6 100644 --- a/jdk/src/solaris/native/sun/awt/awt_util.h +++ b/jdk/src/solaris/native/sun/awt/awt_util.h @@ -46,11 +46,11 @@ /* * Expected types of arguments of the macro. - * (JNIEnv*) + * (JNIEnv*, jboolean) */ -#define RESTORE_XERROR_HANDLER(env) do { \ +#define RESTORE_XERROR_HANDLER(env, doXSync) do { \ JNU_CallStaticMethodByName(env, NULL, "sun/awt/X11/XErrorHandlerUtil", \ - "RESTORE_XERROR_HANDLER", "()V"); \ + "RESTORE_XERROR_HANDLER", "(Z)V", doXSync); \ } while (0) /* @@ -64,8 +64,18 @@ do { \ code; \ } while (0); \ - RESTORE_XERROR_HANDLER(env); \ + RESTORE_XERROR_HANDLER(env, JNI_TRUE); \ if (handlerHasFlag == JNI_TRUE) { \ + GET_HANDLER_ERROR_OCCURRED_FLAG(env, handlerRef, errorOccurredFlag); \ + } \ +} while (0) + +/* + * Expected types of arguments of the macro. + * (JNIEnv*, jobject, jboolean) + */ +#define GET_HANDLER_ERROR_OCCURRED_FLAG(env, handlerRef, errorOccurredFlag) do { \ + if (handlerRef != NULL) { \ errorOccurredFlag = JNU_CallMethodByName(env, NULL, handlerRef, "getErrorOccurredFlag", \ "()Z").z; \ } \ diff --git a/jdk/src/solaris/native/sun/java2d/opengl/GLXSurfaceData.c b/jdk/src/solaris/native/sun/java2d/opengl/GLXSurfaceData.c index 4a4e75f6228..e1cf2c57501 100644 --- a/jdk/src/solaris/native/sun/java2d/opengl/GLXSurfaceData.c +++ b/jdk/src/solaris/native/sun/java2d/opengl/GLXSurfaceData.c @@ -392,10 +392,12 @@ Java_sun_java2d_opengl_GLXSurfaceData_initPbuffer attrlist[3] = height; errorOccurredFlag = JNI_FALSE; - EXEC_WITH_XERROR_HANDLER(env, "sun/awt/X11/XErrorHandler$GLXBadAllocHandler", - "()Lsun/awt/X11/XErrorHandler$GLXBadAllocHandler;", JNI_TRUE, - errorHandlerRef, errorOccurredFlag, - pbuffer = j2d_glXCreatePbuffer(awt_display, glxinfo->fbconfig, attrlist)); + WITH_XERROR_HANDLER(env, "sun/awt/X11/XErrorHandler$GLXBadAllocHandler", + "()Lsun/awt/X11/XErrorHandler$GLXBadAllocHandler;", JNI_TRUE, errorHandlerRef); + pbuffer = j2d_glXCreatePbuffer(awt_display, glxinfo->fbconfig, attrlist); + XSync(awt_display, False); + RESTORE_XERROR_HANDLER(env, JNI_FALSE); + GET_HANDLER_ERROR_OCCURRED_FLAG(env, errorHandlerRef, errorOccurredFlag); if ((pbuffer == 0) || errorOccurredFlag) { J2dRlsTraceLn(J2D_TRACE_ERROR, From f495ca639cb298ccf27dc44ac5fac0f9070eb790 Mon Sep 17 00:00:00 2001 From: Attila Szegedi Date: Thu, 4 Jul 2013 14:10:18 +0200 Subject: [PATCH 064/123] 8019809: return after break incorrectly sets the block as terminal Reviewed-by: jlaskey, lagergren --- .../jdk/nashorn/internal/codegen/Lower.java | 24 ++++++++++++++----- .../internal/ir/BlockLexicalContext.java | 19 ++++++++++----- .../JDK-8019809.js | 0 3 files changed, 31 insertions(+), 12 deletions(-) rename nashorn/test/script/{currently-failing => basic}/JDK-8019809.js (100%) diff --git a/nashorn/src/jdk/nashorn/internal/codegen/Lower.java b/nashorn/src/jdk/nashorn/internal/codegen/Lower.java index 013564c2760..880fea67640 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/Lower.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/Lower.java @@ -32,6 +32,7 @@ import static jdk.nashorn.internal.codegen.CompilerConstants.THIS; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.ListIterator; import jdk.nashorn.internal.ir.BaseNode; import jdk.nashorn.internal.ir.BinaryNode; import jdk.nashorn.internal.ir.Block; @@ -115,6 +116,21 @@ final class Lower extends NodeOperatorVisitor { } return newStatements; } + + @Override + protected Block afterSetStatements(final Block block) { + final List stmts = block.getStatements(); + for(final ListIterator li = stmts.listIterator(stmts.size()); li.hasPrevious();) { + final Statement stmt = li.previous(); + // popStatements() guarantees that the only thing after a terminal statement are uninitialized + // VarNodes. We skip past those, and set the terminal state of the block to the value of the + // terminal state of the first statement that is not an uninitialized VarNode. + if(!(stmt instanceof VarNode && ((VarNode)stmt).getInit() == null)) { + return block.setIsTerminal(this, stmt.isTerminal()); + } + } + return block.setIsTerminal(this, false); + } }); } @@ -132,11 +148,11 @@ final class Lower extends NodeOperatorVisitor { //now we have committed the entire statement list to the block, but we need to truncate //whatever is after the last terminal. block append won't append past it - Statement last = lc.getLastStatement(); if (lc.isFunctionBody()) { final FunctionNode currentFunction = lc.getCurrentFunction(); final boolean isProgram = currentFunction.isProgram(); + final Statement last = lc.getLastStatement(); final ReturnNode returnNode = new ReturnNode( last == null ? block.getLineNumber() : last.getLineNumber(), //TODO? currentFunction.getToken(), @@ -145,11 +161,7 @@ final class Lower extends NodeOperatorVisitor { compilerConstant(RETURN) : LiteralNode.newInstance(block, ScriptRuntime.UNDEFINED)); - last = (Statement)returnNode.accept(this); - } - - if (last != null && last.isTerminal()) { - return block.setIsTerminal(lc, true); + returnNode.accept(this); } return block; diff --git a/nashorn/src/jdk/nashorn/internal/ir/BlockLexicalContext.java b/nashorn/src/jdk/nashorn/internal/ir/BlockLexicalContext.java index 71c80a6b04f..8fecddd0b90 100644 --- a/nashorn/src/jdk/nashorn/internal/ir/BlockLexicalContext.java +++ b/nashorn/src/jdk/nashorn/internal/ir/BlockLexicalContext.java @@ -29,7 +29,6 @@ import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; -import java.util.ListIterator; /** * This is a subclass of lexical context used for filling @@ -63,6 +62,16 @@ public class BlockLexicalContext extends LexicalContext { return sstack.pop(); } + /** + * Override this method to perform some additional processing on the block after its statements have been set. By + * default does nothing and returns the original block. + * @param block the block to operate on + * @return a modified block. + */ + protected Block afterSetStatements(Block block) { + return block; + } + @SuppressWarnings("unchecked") @Override public T pop(final T node) { @@ -70,6 +79,7 @@ public class BlockLexicalContext extends LexicalContext { if (node instanceof Block) { final List newStatements = popStatements(); expected = (T)((Block)node).setStatements(this, newStatements); + expected = (T)afterSetStatements((Block)expected); if (!sstack.isEmpty()) { lastStatement = lastStatement(sstack.peek()); } @@ -107,10 +117,7 @@ public class BlockLexicalContext extends LexicalContext { } private static Statement lastStatement(final List statements) { - for (final ListIterator iter = statements.listIterator(statements.size()); iter.hasPrevious(); ) { - final Statement node = iter.previous(); - return node; - } - return null; + final int s = statements.size(); + return s == 0 ? null : statements.get(s - 1); } } diff --git a/nashorn/test/script/currently-failing/JDK-8019809.js b/nashorn/test/script/basic/JDK-8019809.js similarity index 100% rename from nashorn/test/script/currently-failing/JDK-8019809.js rename to nashorn/test/script/basic/JDK-8019809.js From 0807ef36381851d17375331ae67f8a54bcfb34a5 Mon Sep 17 00:00:00 2001 From: Marcus Lagergren Date: Thu, 4 Jul 2013 17:27:33 +0200 Subject: [PATCH 065/123] 8019821: allInteger switches were confused by boolean cases, as they are a narrower type than int Reviewed-by: sundar, hannesw --- .../jdk/nashorn/internal/codegen/Attr.java | 3 ++ nashorn/test/script/basic/JDK-8019821.js | 37 +++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 nashorn/test/script/basic/JDK-8019821.js diff --git a/nashorn/src/jdk/nashorn/internal/codegen/Attr.java b/nashorn/src/jdk/nashorn/internal/codegen/Attr.java index e9cc259fb3d..d72e6a76c72 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/Attr.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/Attr.java @@ -791,6 +791,9 @@ final class Attr extends NodeOperatorVisitor { } type = Type.widest(type, newCaseNode.getTest().getType()); + if (type.isBoolean()) { + type = Type.OBJECT; //booleans and integers aren't assignment compatible + } } newCases.add(newCaseNode); diff --git a/nashorn/test/script/basic/JDK-8019821.js b/nashorn/test/script/basic/JDK-8019821.js new file mode 100644 index 00000000000..c296ac3c8e8 --- /dev/null +++ b/nashorn/test/script/basic/JDK-8019821.js @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * 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. + */ + +/** + * JDK-8019821: boolean switch value accidentally triggered "allInts" case + * as boolean is considered narrower than int. This caused a ClassCastException + * + * @test + * @run + */ + +function f() { + switch(gc()) { + case true: + case 1: + } +} From 1853f28ab3b46feb9e272c27e6f0a2b19e3e791c Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Fri, 5 Jul 2013 14:38:04 +0530 Subject: [PATCH 066/123] 8019947: inherited property invalidation does not work with two globals in same context Reviewed-by: jlaskey, lagergren, hannesw, attila --- nashorn/make/build-nasgen.xml | 7 - nashorn/make/build.xml | 3 +- .../api/scripting/ScriptObjectMirror.java | 2 +- .../internal/codegen/CodeGenerator.java | 14 +- .../objects/AccessorPropertyDescriptor.java | 8 +- .../internal/objects/ArrayBufferView.java | 11 +- .../objects/BoundScriptFunctionImpl.java | 2 +- .../objects/DataPropertyDescriptor.java | 9 +- .../objects/GenericPropertyDescriptor.java | 8 +- .../jdk/nashorn/internal/objects/Global.java | 236 +++++++++++++++--- .../internal/objects/NativeArguments.java | 24 +- .../nashorn/internal/objects/NativeArray.java | 10 +- .../internal/objects/NativeArrayBuffer.java | 12 +- .../internal/objects/NativeBoolean.java | 28 +-- .../nashorn/internal/objects/NativeDate.java | 26 +- .../nashorn/internal/objects/NativeDebug.java | 5 +- .../nashorn/internal/objects/NativeError.java | 22 +- .../internal/objects/NativeEvalError.java | 17 +- .../internal/objects/NativeFloat32Array.java | 4 +- .../internal/objects/NativeFloat64Array.java | 4 +- .../internal/objects/NativeFunction.java | 1 + .../internal/objects/NativeInt16Array.java | 4 +- .../internal/objects/NativeInt32Array.java | 4 +- .../internal/objects/NativeInt8Array.java | 4 +- .../internal/objects/NativeJSAdapter.java | 24 +- .../nashorn/internal/objects/NativeJSON.java | 5 +- .../nashorn/internal/objects/NativeJava.java | 2 + .../internal/objects/NativeJavaImporter.java | 16 +- .../nashorn/internal/objects/NativeMath.java | 5 +- .../internal/objects/NativeNumber.java | 34 ++- .../internal/objects/NativeObject.java | 2 + .../internal/objects/NativeRangeError.java | 16 +- .../objects/NativeReferenceError.java | 16 +- .../internal/objects/NativeRegExp.java | 33 ++- .../objects/NativeRegExpExecResult.java | 8 +- .../objects/NativeStrictArguments.java | 14 +- .../internal/objects/NativeString.java | 33 +-- .../internal/objects/NativeSyntaxError.java | 12 +- .../internal/objects/NativeTypeError.java | 12 +- .../internal/objects/NativeURIError.java | 12 +- .../internal/objects/NativeUint16Array.java | 4 +- .../internal/objects/NativeUint32Array.java | 4 +- .../internal/objects/NativeUint8Array.java | 4 +- .../objects/NativeUint8ClampedArray.java | 4 +- .../internal/objects/PrototypeObject.java | 22 +- .../internal/objects/ScriptFunctionImpl.java | 59 +++-- .../jdk/nashorn/internal/runtime/Context.java | 26 +- .../internal/runtime/GlobalFunctions.java | 3 - .../internal/runtime/GlobalObject.java | 9 +- .../internal/runtime/ScriptObject.java | 9 + .../internal/runtime/StructureLoader.java | 49 +--- .../src/jdk/nashorn/internal/scripts/JO.java | 16 +- nashorn/src/jdk/nashorn/tools/Shell.java | 3 +- nashorn/test/script/basic/JDK-8019947.js | 68 +++++ .../test/script/basic/JDK-8019947.js.EXPECTED | 3 + 55 files changed, 668 insertions(+), 324 deletions(-) create mode 100644 nashorn/test/script/basic/JDK-8019947.js create mode 100644 nashorn/test/script/basic/JDK-8019947.js.EXPECTED diff --git a/nashorn/make/build-nasgen.xml b/nashorn/make/build-nasgen.xml index a50d41e02c3..9dca5505316 100644 --- a/nashorn/make/build-nasgen.xml +++ b/nashorn/make/build-nasgen.xml @@ -42,11 +42,6 @@ - - - - - @@ -66,7 +61,6 @@ - @@ -75,7 +69,6 @@ - diff --git a/nashorn/make/build.xml b/nashorn/make/build.xml index 58a1d116be1..da2ded1ea1d 100644 --- a/nashorn/make/build.xml +++ b/nashorn/make/build.xml @@ -100,7 +100,8 @@ target="${javac.target}" debug="${javac.debug}" encoding="${javac.encoding}" - includeantruntime="false"> + includeantruntime="false" fork="true"> + diff --git a/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java b/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java index c7dbab5a184..52684cfe0c8 100644 --- a/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java +++ b/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java @@ -308,9 +308,9 @@ public final class ScriptObjectMirror extends JSObject implements Bindings { public void putAll(final Map map) { final ScriptObject oldGlobal = NashornScriptEngine.getNashornGlobal(); final boolean globalChanged = (oldGlobal != global); - final boolean strict = sobj.isStrictContext(); inGlobal(new Callable() { @Override public Object call() { + final boolean strict = global.isStrictContext(); for (final Map.Entry entry : map.entrySet()) { final Object value = entry.getValue(); final Object modValue = globalChanged? wrap(value, oldGlobal) : value; diff --git a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java index df6906c6bb7..52241265513 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java @@ -109,6 +109,8 @@ import jdk.nashorn.internal.ir.WithNode; import jdk.nashorn.internal.ir.debug.ASTWriter; import jdk.nashorn.internal.ir.visitor.NodeOperatorVisitor; import jdk.nashorn.internal.ir.visitor.NodeVisitor; +import jdk.nashorn.internal.objects.Global; +import jdk.nashorn.internal.objects.ScriptFunctionImpl; import jdk.nashorn.internal.parser.Lexer.RegexToken; import jdk.nashorn.internal.parser.TokenType; import jdk.nashorn.internal.runtime.Context; @@ -148,11 +150,9 @@ import jdk.nashorn.internal.runtime.linker.LinkerCallSite; */ final class CodeGenerator extends NodeOperatorVisitor { - /** Name of the Global object, cannot be referred to as .class, @see CodeGenerator */ - private static final String GLOBAL_OBJECT = Compiler.OBJECTS_PACKAGE + '/' + "Global"; + private static final String GLOBAL_OBJECT = Type.getInternalName(Global.class); - /** Name of the ScriptFunctionImpl, cannot be referred to as .class @see FunctionObjectCreator */ - private static final String SCRIPTFUNCTION_IMPL_OBJECT = Compiler.OBJECTS_PACKAGE + '/' + "ScriptFunctionImpl"; + private static final String SCRIPTFUNCTION_IMPL_OBJECT = Type.getInternalName(ScriptFunctionImpl.class); /** Constant data & installation. The only reason the compiler keeps this is because it is assigned * by reflection in class installation */ @@ -3203,11 +3203,7 @@ final class CodeGenerator extends NodeOperatorVisitor rtype, final Class... types) { - try { - return MethodHandles.lookup().findStatic(Global.class, name, MH.type(rtype, types)); - } catch (final NoSuchMethodException | IllegalAccessException e) { - throw new MethodHandleFactory.LookupException(e); - } + return MH.findStatic(MethodHandles.lookup(), Global.class, name, MH.type(rtype, types)); } RegExpResult getLastRegExpResult() { diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeArguments.java b/nashorn/src/jdk/nashorn/internal/objects/NativeArguments.java index 456284d8cfe..443a8938a2c 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeArguments.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeArguments.java @@ -70,14 +70,18 @@ public final class NativeArguments extends ScriptObject { map$ = map; } + static PropertyMap getInitialMap() { + return map$; + } + private Object length; private Object callee; private ArrayData namedArgs; // This is lazily initialized - only when delete is invoked at all private BitSet deleted; - NativeArguments(final ScriptObject proto, final Object[] arguments, final Object callee, final int numParams) { - super(proto, map$); + NativeArguments(final Object[] arguments, final Object callee, final int numParams, final ScriptObject proto, final PropertyMap map) { + super(proto, map); setIsArguments(); setArray(ArrayData.allocate(arguments)); @@ -550,8 +554,13 @@ public final class NativeArguments extends ScriptObject { public static ScriptObject allocate(final Object[] arguments, final ScriptFunction callee, final int numParams) { // Strict functions won't always have a callee for arguments, and will pass null instead. final boolean isStrict = callee == null || callee.isStrict(); - final ScriptObject proto = Global.objectPrototype(); - return isStrict ? new NativeStrictArguments(proto, arguments, numParams) : new NativeArguments(proto, arguments, callee, numParams); + final Global global = Global.instance(); + final ScriptObject proto = global.getObjectPrototype(); + if (isStrict) { + return new NativeStrictArguments(arguments, numParams, proto, global.getStrictArgumentsMap()); + } else { + return new NativeArguments(arguments, callee, numParams, proto, global.getArgumentsMap()); + } } /** @@ -623,11 +632,6 @@ public final class NativeArguments extends ScriptObject { } private static MethodHandle findOwnMH(final String name, final Class rtype, final Class... types) { - try { - return MethodHandles.lookup().findStatic(NativeArguments.class, name, MH.type(rtype, types)); - } catch (final NoSuchMethodException | IllegalAccessException e) { - throw new MethodHandleFactory.LookupException(e); - } + return MH.findStatic(MethodHandles.lookup(), NativeArguments.class, name, MH.type(rtype, types)); } - } diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeArray.java b/nashorn/src/jdk/nashorn/internal/objects/NativeArray.java index 1af79785d9c..ca02cf63e21 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeArray.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeArray.java @@ -86,6 +86,10 @@ public final class NativeArray extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; + static PropertyMap getInitialMap() { + return $nasgenmap$; + } + /* * Constructors. */ @@ -130,7 +134,11 @@ public final class NativeArray extends ScriptObject { } NativeArray(final ArrayData arrayData) { - super(Global.instance().getArrayPrototype(), $nasgenmap$); + this(arrayData, Global.instance()); + } + + NativeArray(final ArrayData arrayData, final Global global) { + super(global.getArrayPrototype(), global.getArrayMap()); this.setArray(arrayData); this.setIsArray(); } diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeArrayBuffer.java b/nashorn/src/jdk/nashorn/internal/objects/NativeArrayBuffer.java index f122bfca8f5..356e7b6cfec 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeArrayBuffer.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeArrayBuffer.java @@ -43,6 +43,10 @@ final class NativeArrayBuffer extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; + static PropertyMap getInitialMap() { + return $nasgenmap$; + } + @Constructor(arity = 1) public static Object constructor(final boolean newObj, final Object self, final Object... args) { if (args.length == 0) { @@ -52,11 +56,15 @@ final class NativeArrayBuffer extends ScriptObject { return new NativeArrayBuffer(JSType.toInt32(args[0])); } - protected NativeArrayBuffer(final byte[] byteArray) { - super(Global.instance().getArrayBufferPrototype(), $nasgenmap$); + protected NativeArrayBuffer(final byte[] byteArray, final Global global) { + super(global.getArrayBufferPrototype(), global.getArrayBufferMap()); this.buffer = byteArray; } + protected NativeArrayBuffer(final byte[] byteArray) { + this(byteArray, Global.instance()); + } + protected NativeArrayBuffer(final int byteLength) { this(new byte[byteLength]); } diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeBoolean.java b/nashorn/src/jdk/nashorn/internal/objects/NativeBoolean.java index bfbbb3d73d7..962086c491e 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeBoolean.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeBoolean.java @@ -56,15 +56,23 @@ public final class NativeBoolean extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; - NativeBoolean(final boolean value) { - this(value, Global.instance().getBooleanPrototype()); + static PropertyMap getInitialMap() { + return $nasgenmap$; } - private NativeBoolean(final boolean value, final ScriptObject proto) { - super(proto, $nasgenmap$); + private NativeBoolean(final boolean value, final ScriptObject proto, final PropertyMap map) { + super(proto, map); this.value = value; } + NativeBoolean(final boolean flag, final Global global) { + this(flag, global.getBooleanPrototype(), global.getBooleanMap()); + } + + NativeBoolean(final boolean flag) { + this(flag, Global.instance()); + } + @Override public String safeToString() { return "[Boolean " + toString() + "]"; @@ -131,11 +139,7 @@ public final class NativeBoolean extends ScriptObject { final boolean flag = JSType.toBoolean(value); if (newObj) { - final ScriptObject proto = (self instanceof ScriptObject) ? - ((ScriptObject)self).getProto() : - Global.instance().getBooleanPrototype(); - - return new NativeBoolean(flag, proto); + return new NativeBoolean(flag); } return flag; @@ -176,10 +180,6 @@ public final class NativeBoolean extends ScriptObject { } private static MethodHandle findWrapFilter() { - try { - return MethodHandles.lookup().findStatic(NativeBoolean.class, "wrapFilter", MH.type(NativeBoolean.class, Object.class)); - } catch (NoSuchMethodException | IllegalAccessException e) { - throw new MethodHandleFactory.LookupException(e); - } + return MH.findStatic(MethodHandles.lookup(), NativeBoolean.class, "wrapFilter", MH.type(NativeBoolean.class, Object.class)); } } diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeDate.java b/nashorn/src/jdk/nashorn/internal/objects/NativeDate.java index 3a7d0ef3535..11ab886e467 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeDate.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeDate.java @@ -104,18 +104,30 @@ public final class NativeDate extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; - NativeDate() { - this(System.currentTimeMillis()); + static PropertyMap getInitialMap() { + return $nasgenmap$; } - NativeDate(final double time) { - super(Global.instance().getDatePrototype(), $nasgenmap$); + private NativeDate(final double time, final ScriptObject proto, final PropertyMap map) { + super(proto, map); final ScriptEnvironment env = Global.getEnv(); this.time = time; this.timezone = env._timezone; } + NativeDate(final double time, final Global global) { + this(time, global.getDatePrototype(), global.getDateMap()); + } + + private NativeDate (final double time) { + this(time, Global.instance()); + } + + private NativeDate() { + this(System.currentTimeMillis()); + } + @Override public String getClassName() { return "Date"; @@ -153,6 +165,10 @@ public final class NativeDate extends ScriptObject { */ @Constructor(arity = 7) public static Object construct(final boolean isNew, final Object self, final Object... args) { + if (! isNew) { + return toStringImpl(new NativeDate(), FORMAT_DATE_TIME); + } + NativeDate result; switch (args.length) { case 0: @@ -182,7 +198,7 @@ public final class NativeDate extends ScriptObject { break; } - return isNew ? result : toStringImpl(new NativeDate(), FORMAT_DATE_TIME); + return result; } @Override diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeDebug.java b/nashorn/src/jdk/nashorn/internal/objects/NativeDebug.java index afcf7b2bfc2..43106eeb7b8 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeDebug.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeDebug.java @@ -51,8 +51,9 @@ public final class NativeDebug extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; - NativeDebug() { - super(Global.objectPrototype(), $nasgenmap$); + private NativeDebug() { + // don't create me! + throw new UnsupportedOperationException(); } @Override diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeError.java b/nashorn/src/jdk/nashorn/internal/objects/NativeError.java index b8f69c502e4..0f233f18b17 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeError.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeError.java @@ -87,8 +87,12 @@ public final class NativeError extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; - NativeError(final Object msg) { - super(Global.instance().getErrorPrototype(), $nasgenmap$); + static PropertyMap getInitialMap() { + return $nasgenmap$; + } + + private NativeError(final Object msg, final ScriptObject proto, final PropertyMap map) { + super(proto, map); if (msg != UNDEFINED) { this.instMessage = JSType.toString(msg); } else { @@ -96,6 +100,14 @@ public final class NativeError extends ScriptObject { } } + NativeError(final Object msg, final Global global) { + this(msg, global.getErrorPrototype(), global.getErrorMap()); + } + + private NativeError(final Object msg) { + this(msg, Global.instance()); + } + @Override public String getClassName() { return "Error"; @@ -354,11 +366,7 @@ public final class NativeError extends ScriptObject { } private static MethodHandle findOwnMH(final String name, final Class rtype, final Class... types) { - try { - return MethodHandles.lookup().findStatic(NativeError.class, name, MH.type(rtype, types)); - } catch (final NoSuchMethodException | IllegalAccessException e) { - throw new MethodHandleFactory.LookupException(e); - } + return MH.findStatic(MethodHandles.lookup(), NativeError.class, name, MH.type(rtype, types)); } private static String getScriptStackString(final ScriptObject sobj, final Throwable exp) { diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeEvalError.java b/nashorn/src/jdk/nashorn/internal/objects/NativeEvalError.java index 2b88f7dc90a..89e9485fd9d 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeEvalError.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeEvalError.java @@ -58,8 +58,12 @@ public final class NativeEvalError extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; - NativeEvalError(final Object msg) { - super(Global.instance().getEvalErrorPrototype(), $nasgenmap$); + static PropertyMap getInitialMap() { + return $nasgenmap$; + } + + private NativeEvalError(final Object msg, final ScriptObject proto, final PropertyMap map) { + super(proto, map); if (msg != UNDEFINED) { this.instMessage = JSType.toString(msg); } else { @@ -67,12 +71,19 @@ public final class NativeEvalError extends ScriptObject { } } + NativeEvalError(final Object msg, final Global global) { + this(msg, global.getEvalErrorPrototype(), global.getEvalErrorMap()); + } + + private NativeEvalError(final Object msg) { + this(msg, Global.instance()); + } + @Override public String getClassName() { return "Error"; } - /** * ECMA 15.11.6.1 EvalError * diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeFloat32Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeFloat32Array.java index 852f448dd1e..614fd6f54d0 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeFloat32Array.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeFloat32Array.java @@ -192,7 +192,7 @@ public final class NativeFloat32Array extends ArrayBufferView { } @Override - protected ScriptObject getPrototype() { - return Global.instance().getFloat32ArrayPrototype(); + protected ScriptObject getPrototype(final Global global) { + return global.getFloat32ArrayPrototype(); } } diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeFloat64Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeFloat64Array.java index 4ea52991243..22467bcc1be 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeFloat64Array.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeFloat64Array.java @@ -202,7 +202,7 @@ public final class NativeFloat64Array extends ArrayBufferView { } @Override - protected ScriptObject getPrototype() { - return Global.instance().getFloat64ArrayPrototype(); + protected ScriptObject getPrototype(final Global global) { + return global.getFloat64ArrayPrototype(); } } diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeFunction.java b/nashorn/src/jdk/nashorn/internal/objects/NativeFunction.java index 5e5f42f0475..c208a35ce7e 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeFunction.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeFunction.java @@ -61,6 +61,7 @@ public final class NativeFunction { // do *not* create me! private NativeFunction() { + throw new UnsupportedOperationException(); } /** diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeInt16Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeInt16Array.java index 24b2383756c..904dbce0390 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeInt16Array.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeInt16Array.java @@ -151,7 +151,7 @@ public final class NativeInt16Array extends ArrayBufferView { } @Override - protected ScriptObject getPrototype() { - return Global.instance().getInt16ArrayPrototype(); + protected ScriptObject getPrototype(final Global global) { + return global.getInt16ArrayPrototype(); } } diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeInt32Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeInt32Array.java index a89d8350a50..78aed11f507 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeInt32Array.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeInt32Array.java @@ -154,7 +154,7 @@ public final class NativeInt32Array extends ArrayBufferView { } @Override - protected ScriptObject getPrototype() { - return Global.instance().getInt32ArrayPrototype(); + protected ScriptObject getPrototype(final Global global) { + return global.getInt32ArrayPrototype(); } } diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeInt8Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeInt8Array.java index 316fdab50d8..3ed5688a45f 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeInt8Array.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeInt8Array.java @@ -144,7 +144,7 @@ public final class NativeInt8Array extends ArrayBufferView { } @Override - protected ScriptObject getPrototype() { - return Global.instance().getInt8ArrayPrototype(); + protected ScriptObject getPrototype(final Global global) { + return global.getInt8ArrayPrototype(); } } diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeJSAdapter.java b/nashorn/src/jdk/nashorn/internal/objects/NativeJSAdapter.java index 5db4a1fddac..8e98f4e1825 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeJSAdapter.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeJSAdapter.java @@ -49,6 +49,7 @@ import jdk.nashorn.internal.runtime.ScriptRuntime; import jdk.nashorn.internal.runtime.arrays.ArrayLikeIterator; import jdk.nashorn.internal.lookup.Lookup; import jdk.nashorn.internal.lookup.MethodHandleFactory; +import jdk.nashorn.internal.scripts.JO; /** * This class is the implementation of the Nashorn-specific global object named {@code JSAdapter}. It can be @@ -146,8 +147,12 @@ public final class NativeJSAdapter extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; - NativeJSAdapter(final ScriptObject proto, final Object overrides, final ScriptObject adaptee) { - super(proto, $nasgenmap$); + static PropertyMap getInitialMap() { + return $nasgenmap$; + } + + NativeJSAdapter(final Object overrides, final ScriptObject adaptee, final ScriptObject proto, final PropertyMap map) { + super(proto, map); this.adaptee = wrapAdaptee(adaptee); if (overrides instanceof ScriptObject) { this.overrides = true; @@ -159,9 +164,7 @@ public final class NativeJSAdapter extends ScriptObject { } private static ScriptObject wrapAdaptee(final ScriptObject adaptee) { - final ScriptObject sobj = new jdk.nashorn.internal.scripts.JO(); - sobj.setProto(adaptee); - return sobj; + return new JO(adaptee, Global.instance().getObjectMap()); } @Override @@ -570,11 +573,12 @@ public final class NativeJSAdapter extends ScriptObject { throw typeError("not.an.object", ScriptRuntime.safeToString(adaptee)); } + final Global global = Global.instance(); if (proto != null && !(proto instanceof ScriptObject)) { - proto = Global.instance().getJSAdapterPrototype(); + proto = global.getJSAdapterPrototype(); } - return new NativeJSAdapter((ScriptObject)proto, overrides, (ScriptObject)adaptee); + return new NativeJSAdapter(overrides, (ScriptObject)adaptee, (ScriptObject)proto, global.getJSAdapterMap()); } @Override @@ -736,10 +740,6 @@ public final class NativeJSAdapter extends ScriptObject { } private static MethodHandle findOwnMH(final String name, final Class rtype, final Class... types) { - try { - return MethodHandles.lookup().findStatic(NativeJSAdapter.class, name, MH.type(rtype, types)); - } catch (final NoSuchMethodException | IllegalAccessException e) { - throw new MethodHandleFactory.LookupException(e); - } + return MH.findStatic(MethodHandles.lookup(), NativeJSAdapter.class, name, MH.type(rtype, types)); } } diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeJSON.java b/nashorn/src/jdk/nashorn/internal/objects/NativeJSON.java index 3270bc84cd6..0fdb170f44b 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeJSON.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeJSON.java @@ -62,8 +62,9 @@ public final class NativeJSON extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; - NativeJSON() { - super(Global.objectPrototype(), $nasgenmap$); + private NativeJSON() { + // don't create me!! + throw new UnsupportedOperationException(); } /** diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeJava.java b/nashorn/src/jdk/nashorn/internal/objects/NativeJava.java index 8303c39367a..be63e531984 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeJava.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeJava.java @@ -60,6 +60,8 @@ public final class NativeJava { private static PropertyMap $nasgenmap$; private NativeJava() { + // don't create me + throw new UnsupportedOperationException(); } /** diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeJavaImporter.java b/nashorn/src/jdk/nashorn/internal/objects/NativeJavaImporter.java index 9d4c15ac4d1..c2d2bd10e81 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeJavaImporter.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeJavaImporter.java @@ -59,11 +59,23 @@ public final class NativeJavaImporter extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; - NativeJavaImporter(final Object[] args) { - super(Global.instance().getJavaImporterPrototype(), $nasgenmap$); + static PropertyMap getInitialMap() { + return $nasgenmap$; + } + + private NativeJavaImporter(final Object[] args, final ScriptObject proto, final PropertyMap map) { + super(proto, map); this.args = args; } + private NativeJavaImporter(final Object[] args, final Global global) { + this(args, global.getJavaImporterPrototype(), global.getJavaImporterMap()); + } + + private NativeJavaImporter(final Object[] args) { + this(args, Global.instance()); + } + @Override public String getClassName() { return "JavaImporter"; diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeMath.java b/nashorn/src/jdk/nashorn/internal/objects/NativeMath.java index 2b093548315..c952bd1d295 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeMath.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeMath.java @@ -45,8 +45,9 @@ public final class NativeMath extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; - NativeMath() { - super(Global.objectPrototype(), $nasgenmap$); + private NativeMath() { + // don't create me! + throw new UnsupportedOperationException(); } /** ECMA 15.8.1.1 - E, always a double constant. Not writable or configurable */ diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeNumber.java b/nashorn/src/jdk/nashorn/internal/objects/NativeNumber.java index 94a7cca1a4d..c69478967f4 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeNumber.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeNumber.java @@ -87,17 +87,26 @@ public final class NativeNumber extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; - NativeNumber(final double value) { - this(value, Global.instance().getNumberPrototype()); + static PropertyMap getInitialMap() { + return $nasgenmap$; } - private NativeNumber(final double value, final ScriptObject proto) { - super(proto, $nasgenmap$); + private NativeNumber(final double value, final ScriptObject proto, final PropertyMap map) { + super(proto, map); this.value = value; this.isInt = isRepresentableAsInt(value); this.isLong = isRepresentableAsLong(value); } + NativeNumber(final double value, final Global global) { + this(value, global.getNumberPrototype(), global.getNumberMap()); + } + + private NativeNumber(final double value) { + this(value, Global.instance()); + } + + @Override public String safeToString() { return "[Number " + toString() + "]"; @@ -165,16 +174,7 @@ public final class NativeNumber extends ScriptObject { public static Object constructor(final boolean newObj, final Object self, final Object... args) { final double num = (args.length > 0) ? JSType.toNumber(args[0]) : 0.0; - if (newObj) { - final ScriptObject proto = - (self instanceof ScriptObject) ? - ((ScriptObject)self).getProto() : - Global.instance().getNumberPrototype(); - - return new NativeNumber(num, proto); - } - - return num; + return newObj? new NativeNumber(num) : num; } /** @@ -380,10 +380,6 @@ public final class NativeNumber extends ScriptObject { } private static MethodHandle findWrapFilter() { - try { - return MethodHandles.lookup().findStatic(NativeNumber.class, "wrapFilter", MH.type(NativeNumber.class, Object.class)); - } catch (final NoSuchMethodException | IllegalAccessException e) { - throw new MethodHandleFactory.LookupException(e); - } + return MH.findStatic(MethodHandles.lookup(), NativeNumber.class, "wrapFilter", MH.type(NativeNumber.class, Object.class)); } } diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java b/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java index 7112557e1d0..6e4791bd20c 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java @@ -58,6 +58,8 @@ public final class NativeObject { private static PropertyMap $nasgenmap$; private NativeObject() { + // don't create me! + throw new UnsupportedOperationException(); } private static ECMAException notAnObject(final Object obj) { diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeRangeError.java b/nashorn/src/jdk/nashorn/internal/objects/NativeRangeError.java index faf68f871f7..d51a0c09d41 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeRangeError.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeRangeError.java @@ -58,8 +58,12 @@ public final class NativeRangeError extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; - NativeRangeError(final Object msg) { - super(Global.instance().getRangeErrorPrototype(), $nasgenmap$); + static PropertyMap getInitialMap() { + return $nasgenmap$; + } + + private NativeRangeError(final Object msg, final ScriptObject proto, final PropertyMap map) { + super(proto, map); if (msg != UNDEFINED) { this.instMessage = JSType.toString(msg); } else { @@ -67,6 +71,14 @@ public final class NativeRangeError extends ScriptObject { } } + NativeRangeError(final Object msg, final Global global) { + this(msg, global.getRangeErrorPrototype(), global.getRangeErrorMap()); + } + + private NativeRangeError(final Object msg) { + this(msg, Global.instance()); + } + @Override public String getClassName() { return "Error"; diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeReferenceError.java b/nashorn/src/jdk/nashorn/internal/objects/NativeReferenceError.java index 954eed641f5..a269b51520a 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeReferenceError.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeReferenceError.java @@ -58,8 +58,12 @@ public final class NativeReferenceError extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; - NativeReferenceError(final Object msg) { - super(Global.instance().getReferenceErrorPrototype(), $nasgenmap$); + static PropertyMap getInitialMap() { + return $nasgenmap$; + } + + private NativeReferenceError(final Object msg, final ScriptObject proto, final PropertyMap map) { + super(proto, map); if (msg != UNDEFINED) { this.instMessage = JSType.toString(msg); } else { @@ -67,6 +71,14 @@ public final class NativeReferenceError extends ScriptObject { } } + NativeReferenceError(final Object msg, final Global global) { + this(msg, global.getReferenceErrorPrototype(), global.getReferenceErrorMap()); + } + + private NativeReferenceError(final Object msg) { + this(msg, Global.instance()); + } + @Override public String getClassName() { return "Error"; diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java b/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java index 1ba8b4df01b..e6aa4be4357 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java @@ -71,7 +71,17 @@ public final class NativeRegExp extends ScriptObject { @SuppressWarnings("unused") private static PropertyMap $nasgenmap$; - NativeRegExp(final String input, final String flagString) { + static PropertyMap getInitialMap() { + return $nasgenmap$; + } + + private NativeRegExp(final Global global) { + super(global.getRegExpPrototype(), global.getRegExpMap()); + this.globalObject = global; + } + + NativeRegExp(final String input, final String flagString, final Global global) { + this(global); try { this.regexp = RegExpFactory.create(input, flagString); } catch (final ParserException e) { @@ -81,17 +91,24 @@ public final class NativeRegExp extends ScriptObject { } this.setLastIndex(0); - init(); + } + + NativeRegExp(final String input, final String flagString) { + this(input, flagString, Global.instance()); + } + + NativeRegExp(final String string, final Global global) { + this(string, "", global); } NativeRegExp(final String string) { - this(string, ""); + this(string, Global.instance()); } NativeRegExp(final NativeRegExp regExp) { + this(Global.instance()); this.lastIndex = regExp.getLastIndexObject(); this.regexp = regExp.getRegExp(); - init(); } @Override @@ -615,7 +632,7 @@ public final class NativeRegExp extends ScriptObject { return null; } - return new NativeRegExpExecResult(match); + return new NativeRegExpExecResult(match, globalObject); } /** @@ -886,12 +903,6 @@ public final class NativeRegExp extends ScriptObject { this.lastIndex = JSType.toObject(lastIndex); } - private void init() { - // Keep reference to global object to support "static" properties of RegExp - this.globalObject = Global.instance(); - this.setProto(globalObject.getRegExpPrototype()); - } - private static NativeRegExp checkRegExp(final Object self) { Global.checkObjectCoercible(self); if (self instanceof NativeRegExp) { diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeRegExpExecResult.java b/nashorn/src/jdk/nashorn/internal/objects/NativeRegExpExecResult.java index 667205528ed..3508e5f67d1 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeRegExpExecResult.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeRegExpExecResult.java @@ -53,8 +53,12 @@ public final class NativeRegExpExecResult extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; - NativeRegExpExecResult(final RegExpResult result) { - super(Global.instance().getArrayPrototype(), $nasgenmap$); + static PropertyMap getInitialMap() { + return $nasgenmap$; + } + + NativeRegExpExecResult(final RegExpResult result, final Global global) { + super(global.getArrayPrototype(), global.getRegExpExecResultMap()); setIsArray(); this.setArray(ArrayData.allocate(result.getGroups().clone())); this.index = result.getIndex(); diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeStrictArguments.java b/nashorn/src/jdk/nashorn/internal/objects/NativeStrictArguments.java index cf434f9fce4..ae2ddb01d8d 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeStrictArguments.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeStrictArguments.java @@ -64,11 +64,15 @@ public final class NativeStrictArguments extends ScriptObject { map$ = map; } + static PropertyMap getInitialMap() { + return map$; + } + private Object length; private final Object[] namedArgs; - NativeStrictArguments(final ScriptObject proto, final Object[] values, final int numParams) { - super(proto, map$); + NativeStrictArguments(final Object[] values, final int numParams,final ScriptObject proto, final PropertyMap map) { + super(proto, map); setIsArguments(); final ScriptFunction func = ScriptFunctionImpl.getTypeErrorThrower(); @@ -143,10 +147,6 @@ public final class NativeStrictArguments extends ScriptObject { } private static MethodHandle findOwnMH(final String name, final Class rtype, final Class... types) { - try { - return MethodHandles.lookup().findStatic(NativeStrictArguments.class, name, MH.type(rtype, types)); - } catch (final NoSuchMethodException | IllegalAccessException e) { - throw new MethodHandleFactory.LookupException(e); - } + return MH.findStatic(MethodHandles.lookup(), NativeStrictArguments.class, name, MH.type(rtype, types)); } } diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeString.java b/nashorn/src/jdk/nashorn/internal/objects/NativeString.java index a5b9ea83e54..aa2eec63571 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeString.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeString.java @@ -41,7 +41,7 @@ import java.util.Locale; import jdk.internal.dynalink.CallSiteDescriptor; import jdk.internal.dynalink.linker.GuardedInvocation; import jdk.internal.dynalink.linker.LinkRequest; -import jdk.nashorn.internal.lookup.MethodHandleFactory; +import jdk.nashorn.internal.lookup.MethodHandleFactory.LookupException; import jdk.nashorn.internal.objects.annotations.Attribute; import jdk.nashorn.internal.objects.annotations.Constructor; import jdk.nashorn.internal.objects.annotations.Function; @@ -74,12 +74,20 @@ public final class NativeString extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; - NativeString(final CharSequence value) { - this(value, Global.instance().getStringPrototype()); + static PropertyMap getInitialMap() { + return $nasgenmap$; } - private NativeString(final CharSequence value, final ScriptObject proto) { - super(proto, $nasgenmap$); + private NativeString(final CharSequence value) { + this(value, Global.instance()); + } + + NativeString(final CharSequence value, final Global global) { + this(value, global.getStringPrototype(), global.getStringMap()); + } + + private NativeString(final CharSequence value, final ScriptObject proto, final PropertyMap map) { + super(proto, map); assert value instanceof String || value instanceof ConsString; this.value = value; } @@ -147,9 +155,9 @@ public final class NativeString extends ScriptObject { if (returnType == Object.class && (self instanceof String || self instanceof ConsString)) { try { - MethodHandle mh = MethodHandles.lookup().findStatic(NativeString.class, "get", desc.getMethodType()); + MethodHandle mh = MH.findStatic(MethodHandles.lookup(), NativeString.class, "get", desc.getMethodType()); return new GuardedInvocation(mh, NashornGuards.getInstanceOf2Guard(String.class, ConsString.class)); - } catch (final NoSuchMethodException | IllegalAccessException e) { + } catch (final LookupException e) { // Shouldn't happen. Fall back to super } } @@ -1065,10 +1073,7 @@ public final class NativeString extends ScriptObject { } private static Object newObj(final Object self, final CharSequence str) { - if (self instanceof ScriptObject) { - return new NativeString(str, ((ScriptObject)self).getProto()); - } - return new NativeString(str, Global.instance().getStringPrototype()); + return new NativeString(str); } /** @@ -1202,10 +1207,6 @@ public final class NativeString extends ScriptObject { } private static MethodHandle findWrapFilter() { - try { - return MethodHandles.lookup().findStatic(NativeString.class, "wrapFilter", MH.type(NativeString.class, Object.class)); - } catch (final NoSuchMethodException | IllegalAccessException e) { - throw new MethodHandleFactory.LookupException(e); - } + return MH.findStatic(MethodHandles.lookup(), NativeString.class, "wrapFilter", MH.type(NativeString.class, Object.class)); } } diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeSyntaxError.java b/nashorn/src/jdk/nashorn/internal/objects/NativeSyntaxError.java index d7d04bbaa6e..45920ba7aec 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeSyntaxError.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeSyntaxError.java @@ -58,8 +58,12 @@ public final class NativeSyntaxError extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; - NativeSyntaxError(final Object msg) { - super(Global.instance().getSyntaxErrorPrototype(), $nasgenmap$); + static PropertyMap getInitialMap() { + return $nasgenmap$; + } + + NativeSyntaxError(final Object msg, final Global global) { + super(global.getSyntaxErrorPrototype(), global.getSyntaxErrorMap()); if (msg != UNDEFINED) { this.instMessage = JSType.toString(msg); } else { @@ -67,6 +71,10 @@ public final class NativeSyntaxError extends ScriptObject { } } + private NativeSyntaxError(final Object msg) { + this(msg, Global.instance()); + } + @Override public String getClassName() { return "Error"; diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeTypeError.java b/nashorn/src/jdk/nashorn/internal/objects/NativeTypeError.java index c811a530569..2b2308b143e 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeTypeError.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeTypeError.java @@ -58,8 +58,12 @@ public final class NativeTypeError extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; - NativeTypeError(final Object msg) { - super(Global.instance().getTypeErrorPrototype(), $nasgenmap$); + static PropertyMap getInitialMap() { + return $nasgenmap$; + } + + NativeTypeError(final Object msg, final Global global) { + super(global.getTypeErrorPrototype(), global.getTypeErrorMap()); if (msg != UNDEFINED) { this.instMessage = JSType.toString(msg); } else { @@ -67,6 +71,10 @@ public final class NativeTypeError extends ScriptObject { } } + private NativeTypeError(final Object msg) { + this(msg, Global.instance()); + } + @Override public String getClassName() { return "Error"; diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeURIError.java b/nashorn/src/jdk/nashorn/internal/objects/NativeURIError.java index 80df6c28529..2caf136954d 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeURIError.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeURIError.java @@ -57,8 +57,12 @@ public final class NativeURIError extends ScriptObject { // initialized by nasgen private static PropertyMap $nasgenmap$; - NativeURIError(final Object msg) { - super(Global.instance().getURIErrorPrototype(), $nasgenmap$); + static PropertyMap getInitialMap() { + return $nasgenmap$; + } + + NativeURIError(final Object msg, final Global global) { + super(global.getURIErrorPrototype(), global.getURIErrorMap()); if (msg != UNDEFINED) { this.instMessage = JSType.toString(msg); } else { @@ -66,6 +70,10 @@ public final class NativeURIError extends ScriptObject { } } + private NativeURIError(final Object msg) { + this(msg, Global.instance()); + } + @Override public String getClassName() { return "Error"; diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeUint16Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeUint16Array.java index d19e787195d..7c37bac9f6e 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeUint16Array.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeUint16Array.java @@ -150,7 +150,7 @@ public final class NativeUint16Array extends ArrayBufferView { } @Override - protected ScriptObject getPrototype() { - return Global.instance().getUint16ArrayPrototype(); + protected ScriptObject getPrototype(final Global global) { + return global.getUint16ArrayPrototype(); } } diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeUint32Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeUint32Array.java index 87a383cb555..9b51db48d0d 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeUint32Array.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeUint32Array.java @@ -169,7 +169,7 @@ public final class NativeUint32Array extends ArrayBufferView { } @Override - protected ScriptObject getPrototype() { - return Global.instance().getUint32ArrayPrototype(); + protected ScriptObject getPrototype(final Global global) { + return global.getUint32ArrayPrototype(); } } diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeUint8Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeUint8Array.java index 6ae786f3fda..be4e59d368b 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeUint8Array.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeUint8Array.java @@ -143,7 +143,7 @@ public final class NativeUint8Array extends ArrayBufferView { } @Override - protected ScriptObject getPrototype() { - return Global.instance().getUint8ArrayPrototype(); + protected ScriptObject getPrototype(final Global global) { + return global.getUint8ArrayPrototype(); } } diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeUint8ClampedArray.java b/nashorn/src/jdk/nashorn/internal/objects/NativeUint8ClampedArray.java index 02b7a4edcd0..43b777ba346 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeUint8ClampedArray.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeUint8ClampedArray.java @@ -160,7 +160,7 @@ public final class NativeUint8ClampedArray extends ArrayBufferView { } @Override - protected ScriptObject getPrototype() { - return Global.instance().getUint8ClampedArrayPrototype(); + protected ScriptObject getPrototype(final Global global) { + return global.getUint8ClampedArrayPrototype(); } } diff --git a/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java b/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java index 3a7205f9bba..c4cda933dd5 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java +++ b/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java @@ -57,8 +57,17 @@ public class PrototypeObject extends ScriptObject { map$ = map; } + static PropertyMap getInitialMap() { + return map$; + } + + private PrototypeObject(final Global global, final PropertyMap map) { + super(map != map$? map.addAll(global.getPrototypeObjectMap()) : global.getPrototypeObjectMap()); + setProto(global.getObjectPrototype()); + } + PrototypeObject() { - this(map$); + this(Global.instance(), map$); } /** @@ -67,12 +76,11 @@ public class PrototypeObject extends ScriptObject { * @param map property map */ public PrototypeObject(final PropertyMap map) { - super(map != map$ ? map.addAll(map$) : map$); - setProto(Global.objectPrototype()); + this(Global.instance(), map); } PrototypeObject(final ScriptFunction func) { - this(map$); + this(Global.instance(), map$); this.constructor = func; } @@ -107,10 +115,6 @@ public class PrototypeObject extends ScriptObject { } private static MethodHandle findOwnMH(final String name, final Class rtype, final Class... types) { - try { - return MethodHandles.lookup().findStatic(PrototypeObject.class, name, MH.type(rtype, types)); - } catch (final NoSuchMethodException | IllegalAccessException e) { - throw new MethodHandleFactory.LookupException(e); - } + return MH.findStatic(MethodHandles.lookup(), PrototypeObject.class, name, MH.type(rtype, types)); } } diff --git a/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java b/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java index d49f4d3331b..91034c43bdf 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java +++ b/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java @@ -53,9 +53,26 @@ public class ScriptFunctionImpl extends ScriptFunction { // property map for non-strict, non-bound functions. private static final PropertyMap map$; + static PropertyMap getInitialMap() { + return map$; + } + + static PropertyMap getInitialStrictMap() { + return strictmodemap$; + } + + static PropertyMap getInitialBoundMap() { + return boundfunctionmap$; + } + // Marker object for lazily initialized prototype object private static final Object LAZY_PROTOTYPE = new Object(); + private ScriptFunctionImpl(final String name, final MethodHandle invokeHandle, final MethodHandle[] specs, final Global global) { + super(name, invokeHandle, global.getFunctionMap(), null, specs, false, true, true); + init(global); + } + /** * Constructor called by Nasgen generated code, no membercount, use the default map. * Creates builtin functions only. @@ -65,8 +82,12 @@ public class ScriptFunctionImpl extends ScriptFunction { * @param specs specialized versions of this method, if available, null otherwise */ ScriptFunctionImpl(final String name, final MethodHandle invokeHandle, final MethodHandle[] specs) { - super(name, invokeHandle, map$, null, specs, false, true, true); - init(); + this(name, invokeHandle, specs, Global.instance()); + } + + private ScriptFunctionImpl(final String name, final MethodHandle invokeHandle, final PropertyMap map, final MethodHandle[] specs, final Global global) { + super(name, invokeHandle, map.addAll(global.getFunctionMap()), null, specs, false, true, true); + init(global); } /** @@ -79,8 +100,12 @@ public class ScriptFunctionImpl extends ScriptFunction { * @param specs specialized versions of this method, if available, null otherwise */ ScriptFunctionImpl(final String name, final MethodHandle invokeHandle, final PropertyMap map, final MethodHandle[] specs) { - super(name, invokeHandle, map.addAll(map$), null, specs, false, true, true); - init(); + this(name, invokeHandle, map, specs, Global.instance()); + } + + private ScriptFunctionImpl(final String name, final MethodHandle methodHandle, final ScriptObject scope, final MethodHandle[] specs, final boolean isStrict, final boolean isBuiltin, final boolean isConstructor, final Global global) { + super(name, methodHandle, getMap(global, isStrict), scope, specs, isStrict, isBuiltin, isConstructor); + init(global); } /** @@ -95,8 +120,12 @@ public class ScriptFunctionImpl extends ScriptFunction { * @param isConstructor can the function be used as a constructor (most can; some built-ins are restricted). */ ScriptFunctionImpl(final String name, final MethodHandle methodHandle, final ScriptObject scope, final MethodHandle[] specs, final boolean isStrict, final boolean isBuiltin, final boolean isConstructor) { - super(name, methodHandle, getMap(isStrict), scope, specs, isStrict, isBuiltin, isConstructor); - init(); + this(name, methodHandle, scope, specs, isStrict, isBuiltin, isConstructor, Global.instance()); + } + + private ScriptFunctionImpl(final RecompilableScriptFunctionData data, final ScriptObject scope, final Global global) { + super(data, getMap(global, data.isStrict()), scope); + init(global); } /** @@ -106,17 +135,17 @@ public class ScriptFunctionImpl extends ScriptFunction { * @param scope scope object */ public ScriptFunctionImpl(final RecompilableScriptFunctionData data, final ScriptObject scope) { - super(data, getMap(data.isStrict()), scope); - init(); + this(data, scope, Global.instance()); } /** * Only invoked internally from {@link BoundScriptFunctionImpl} constructor. * @param data the script function data for the bound function. + * @param global the global object */ - ScriptFunctionImpl(final ScriptFunctionData data) { - super(data, boundfunctionmap$, null); - init(); + ScriptFunctionImpl(final ScriptFunctionData data, final Global global) { + super(data, global.getBoundFunctionMap(), null); + init(global); } static { @@ -159,8 +188,8 @@ public class ScriptFunctionImpl extends ScriptFunction { } // Choose the map based on strict mode! - private static PropertyMap getMap(final boolean strict) { - return strict ? strictmodemap$ : map$; + private static PropertyMap getMap(final Global global, final boolean strict) { + return strict ? global.getStrictFunctionMap() : global.getFunctionMap(); } private static PropertyMap createBoundFunctionMap(final PropertyMap strictModeMap) { @@ -255,8 +284,8 @@ public class ScriptFunctionImpl extends ScriptFunction { } // Internals below.. - private void init() { - this.setProto(Global.instance().getFunctionPrototype()); + private void init(final Global global) { + this.setProto(global.getFunctionPrototype()); this.prototype = LAZY_PROTOTYPE; // We have to fill user accessor functions late as these are stored diff --git a/nashorn/src/jdk/nashorn/internal/runtime/Context.java b/nashorn/src/jdk/nashorn/internal/runtime/Context.java index b39eb44a179..218be74e3bd 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/Context.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/Context.java @@ -36,7 +36,6 @@ import java.io.IOException; import java.io.PrintWriter; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; -import java.lang.reflect.Constructor; import java.net.MalformedURLException; import java.net.URL; import java.security.AccessControlContext; @@ -55,6 +54,7 @@ import jdk.nashorn.internal.codegen.ObjectClassGenerator; import jdk.nashorn.internal.ir.FunctionNode; import jdk.nashorn.internal.ir.debug.ASTWriter; import jdk.nashorn.internal.ir.debug.PrintVisitor; +import jdk.nashorn.internal.objects.Global; import jdk.nashorn.internal.parser.Parser; import jdk.nashorn.internal.runtime.options.Options; @@ -123,8 +123,8 @@ public final class Context { sm.checkPermission(new RuntimePermission("nashorn.setGlobal")); } - if (global != null && !(global instanceof GlobalObject)) { - throw new IllegalArgumentException("global does not implement GlobalObject!"); + if (global != null && !(global instanceof Global)) { + throw new IllegalArgumentException("global is not an instance of Global!"); } setGlobalTrusted(global); @@ -257,8 +257,7 @@ public final class Context { new PrivilegedAction() { @Override public ClassLoader run() { - final StructureLoader structureLoader = new StructureLoader(sharedLoader, Context.this); - return new ScriptLoader(structureLoader, Context.this); + return new ScriptLoader(sharedLoader, Context.this); } }); this.errors = errors; @@ -817,25 +816,12 @@ public final class Context { new PrivilegedAction() { @Override public ScriptLoader run() { - // Generated code won't refer to any class generated by context - // script loader and so parent loader can be the structure - // loader -- which is parent of the context script loader. - return new ScriptLoader((StructureLoader)scriptLoader.getParent(), Context.this); + return new ScriptLoader(sharedLoader, Context.this); } }); } private ScriptObject newGlobalTrusted() { - try { - final Class clazz = Class.forName("jdk.nashorn.internal.objects.Global", true, scriptLoader); - final Constructor cstr = clazz.getConstructor(Context.class); - return (ScriptObject) cstr.newInstance(this); - } catch (final Exception e) { - printStackTrace(e); - if (e instanceof RuntimeException) { - throw (RuntimeException)e; - } - throw new RuntimeException(e); - } + return new Global(this); } } diff --git a/nashorn/src/jdk/nashorn/internal/runtime/GlobalFunctions.java b/nashorn/src/jdk/nashorn/internal/runtime/GlobalFunctions.java index 04211fc6707..c504276f41c 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/GlobalFunctions.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/GlobalFunctions.java @@ -34,9 +34,6 @@ import java.util.Locale; /** * Utilities used by Global class. - * - * These are actual implementation methods for functions exposed by global - * scope. The code lives here to share the code across the contexts. */ public final class GlobalFunctions { diff --git a/nashorn/src/jdk/nashorn/internal/runtime/GlobalObject.java b/nashorn/src/jdk/nashorn/internal/runtime/GlobalObject.java index b802a1a136f..7a118290c71 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/GlobalObject.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/GlobalObject.java @@ -30,14 +30,7 @@ import jdk.internal.dynalink.linker.GuardedInvocation; import jdk.internal.dynalink.linker.LinkRequest; /** - * Runtime interface to the global scope of the current context. - * NOTE: never access {@code jdk.nashorn.internal.objects.Global} class directly - * from runtime/parser/codegen/ir etc. Always go through this interface. - *

    - * The reason for this is that all objects in the @{code jdk.nashorn.internal.objects.*} package - * are different per Context and loaded separately by each Context class loader. Attempting - * to directly refer to an object in this package from the rest of the runtime - * will lead to {@code ClassNotFoundException} thrown upon link time + * Runtime interface to the global scope objects. */ public interface GlobalObject { diff --git a/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java b/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java index 1a081a1b2d5..4443d2ed1f5 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java @@ -1026,6 +1026,15 @@ public abstract class ScriptObject extends PropertyListenerManager implements Pr return context; } + /** + * Set the current context. + * @param ctx context instance to set + */ + protected final void setContext(final Context ctx) { + ctx.getClass(); + this.context = ctx; + } + /** * Return the map of an object. * @return PropertyMap object. diff --git a/nashorn/src/jdk/nashorn/internal/runtime/StructureLoader.java b/nashorn/src/jdk/nashorn/internal/runtime/StructureLoader.java index ff6973a9fc1..bdc40eddcc9 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/StructureLoader.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/StructureLoader.java @@ -25,30 +25,19 @@ package jdk.nashorn.internal.runtime; -import static jdk.nashorn.internal.codegen.Compiler.OBJECTS_PACKAGE; import static jdk.nashorn.internal.codegen.Compiler.SCRIPTS_PACKAGE; import static jdk.nashorn.internal.codegen.Compiler.binaryName; import static jdk.nashorn.internal.codegen.CompilerConstants.JS_OBJECT_PREFIX; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.security.AccessController; -import java.security.CodeSigner; -import java.security.CodeSource; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.security.ProtectionDomain; import jdk.nashorn.internal.codegen.ObjectClassGenerator; /** - * Responsible for on the fly construction of structure classes as well - * as loading jdk.nashorn.internal.objects.* classes. + * Responsible for on the fly construction of structure classes. * */ final class StructureLoader extends NashornLoader { private static final String JS_OBJECT_PREFIX_EXTERNAL = binaryName(SCRIPTS_PACKAGE) + '.' + JS_OBJECT_PREFIX.symbolName(); - private static final String OBJECTS_PACKAGE_EXTERNAL = binaryName(OBJECTS_PACKAGE); /** * Constructor. @@ -68,45 +57,9 @@ final class StructureLoader extends NashornLoader { return loadedClass; } - if (name.startsWith(binaryName(OBJECTS_PACKAGE_EXTERNAL))) { - try { - return AccessController.doPrivileged(new PrivilegedExceptionAction>() { - @Override - public Class run() throws ClassNotFoundException { - final String source = name.replace('.','/') + ".clazz"; - final URL url = getResource(source); - try (final InputStream is = getResourceAsStream(source)) { - if (is == null) { - throw new ClassNotFoundException(name); - } - - byte[] code; - try { - code = Source.readBytes(is); - } catch (final IOException e) { - Context.printStackTrace(e); - throw new ClassNotFoundException(name, e); - } - - final Class cl = defineClass(name, code, 0, code.length, new CodeSource(url, (CodeSigner[])null)); - if (resolve) { - resolveClass(cl); - } - return cl; - } catch (final IOException e) { - throw new RuntimeException(e); - } - } - }); - } catch (final PrivilegedActionException e) { - throw new ClassNotFoundException(name, e); - } - } - return super.loadClassTrusted(name, resolve); } - @Override protected Class findClass(final String name) throws ClassNotFoundException { if (name.startsWith(JS_OBJECT_PREFIX_EXTERNAL)) { diff --git a/nashorn/src/jdk/nashorn/internal/scripts/JO.java b/nashorn/src/jdk/nashorn/internal/scripts/JO.java index b31df1ae6f1..b4da66e5ef4 100644 --- a/nashorn/src/jdk/nashorn/internal/scripts/JO.java +++ b/nashorn/src/jdk/nashorn/internal/scripts/JO.java @@ -36,10 +36,11 @@ public class JO extends ScriptObject { private static final PropertyMap map$ = PropertyMap.newMap(JO.class); /** - * Constructor + * Returns the initial property map to be used. + * @return the initial property map. */ - public JO() { - super(map$); + public static PropertyMap getInitialMap() { + return map$; } /** @@ -52,16 +53,17 @@ public class JO extends ScriptObject { } /** - * Constructor given an initial prototype using the default property map + * Constructor given an initial prototype and an initial property map. * * @param proto the prototype object + * @param map the property map */ - public JO(final ScriptObject proto) { - super(proto, map$); + public JO(final ScriptObject proto, final PropertyMap map) { + super(proto, map); } /** - * Used by FunctionObjectCreator. A method handle of this method is passed to the ScriptFunction constructor. + * A method handle of this method is passed to the ScriptFunction constructor. * * @param map the property map to use for allocatorMap * diff --git a/nashorn/src/jdk/nashorn/tools/Shell.java b/nashorn/src/jdk/nashorn/tools/Shell.java index 708fecc59f1..914c7b6e5cc 100644 --- a/nashorn/src/jdk/nashorn/tools/Shell.java +++ b/nashorn/src/jdk/nashorn/tools/Shell.java @@ -47,6 +47,7 @@ import jdk.nashorn.internal.ir.debug.PrintVisitor; import jdk.nashorn.internal.parser.Parser; import jdk.nashorn.internal.runtime.Context; import jdk.nashorn.internal.runtime.ErrorManager; +import jdk.nashorn.internal.runtime.JSType; import jdk.nashorn.internal.runtime.Property; import jdk.nashorn.internal.runtime.ScriptEnvironment; import jdk.nashorn.internal.runtime.ScriptFunction; @@ -446,7 +447,7 @@ public class Shell { } if (res != null && res != ScriptRuntime.UNDEFINED) { - err.println(ScriptRuntime.safeToString(res)); + err.println(JSType.toString(res)); } } } finally { diff --git a/nashorn/test/script/basic/JDK-8019947.js b/nashorn/test/script/basic/JDK-8019947.js new file mode 100644 index 00000000000..4b64a818b6b --- /dev/null +++ b/nashorn/test/script/basic/JDK-8019947.js @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * 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. + */ + +/** + * JDK-8019947: inherited property invalidation does not work with two globals in same context + * + * @test + * @option -scripting + * @run + */ + +function func(arr) { + try { + print(arr.toString()); + } catch (e) { + print(e.stack); + } +} + +var arr = ["hello", "world"] + +func(arr); + +var global = loadWithNewGlobal({ + name: "t", + script: < Date: Fri, 5 Jul 2013 14:36:54 +0200 Subject: [PATCH 067/123] 8017084: Use spill properties for large object literals Reviewed-by: lagergren, sundar --- .../internal/tools/nasgen/ClassGenerator.java | 4 +- .../tools/nasgen/StringConstants.java | 4 +- .../internal/codegen/CodeGenerator.java | 143 +- .../internal/codegen/FieldObjectCreator.java | 69 +- .../internal/codegen/FinalizeTypes.java | 8 + .../nashorn/internal/codegen/MapCreator.java | 38 +- .../codegen/ObjectClassGenerator.java | 15 +- .../internal/codegen/ObjectCreator.java | 74 +- .../internal/codegen/SpillObjectCreator.java | 134 + .../jdk/nashorn/internal/ir/FunctionNode.java | 24 + .../jdk/nashorn/internal/ir/LiteralNode.java | 50 +- .../nashorn/internal/ir/debug/JSONWriter.java | 2 +- .../internal/objects/NativeArguments.java | 2 +- .../objects/NativeStrictArguments.java | 2 +- .../internal/objects/PrototypeObject.java | 2 +- .../internal/objects/ScriptFunctionImpl.java | 4 +- .../jdk/nashorn/internal/parser/Parser.java | 2 +- .../internal/runtime/AccessorProperty.java | 26 +- .../nashorn/internal/runtime/PropertyMap.java | 41 +- .../internal/runtime/ScriptObject.java | 4 +- .../src/jdk/nashorn/internal/scripts/JO.java | 2 +- nashorn/test/script/basic/JDK-8017084.js | 17625 ++++++++++++++++ .../test/script/basic/JDK-8017084.js.EXPECTED | 13 + 23 files changed, 18053 insertions(+), 235 deletions(-) create mode 100644 nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java create mode 100644 nashorn/test/script/basic/JDK-8017084.js create mode 100644 nashorn/test/script/basic/JDK-8017084.js.EXPECTED diff --git a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java index bc6bb4b2db2..ed0eee61e60 100644 --- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java +++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java @@ -25,6 +25,7 @@ package jdk.nashorn.internal.tools.nasgen; +import static jdk.internal.org.objectweb.asm.Opcodes.ACC_FINAL; import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PRIVATE; import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PUBLIC; import static jdk.internal.org.objectweb.asm.Opcodes.ACC_STATIC; @@ -164,7 +165,6 @@ public class ClassGenerator { mi.visitCode(); mi.pushNull(); mi.putStatic(className, MAP_FIELD_NAME, MAP_DESC); - mi.loadClass(className); mi.invokeStatic(MAP_TYPE, MAP_NEWMAP, MAP_NEWMAP_DESC); // stack: PropertyMap } @@ -236,7 +236,7 @@ public class ClassGenerator { static void addMapField(final ClassVisitor cv) { // add a MAP static field - final FieldVisitor fv = cv.visitField(ACC_PRIVATE | ACC_STATIC, + final FieldVisitor fv = cv.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, MAP_FIELD_NAME, MAP_DESC, null, null); if (fv != null) { fv.visitEnd(); diff --git a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/StringConstants.java b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/StringConstants.java index 5a5032f93a9..d0e3168b31f 100644 --- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/StringConstants.java +++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/StringConstants.java @@ -96,12 +96,10 @@ public interface StringConstants { static final String MAP_TYPE = TYPE_PROPERTYMAP.getInternalName(); static final String MAP_DESC = TYPE_PROPERTYMAP.getDescriptor(); static final String MAP_NEWMAP = "newMap"; - static final String MAP_NEWMAP_DESC = Type.getMethodDescriptor(TYPE_PROPERTYMAP, TYPE_CLASS); + static final String MAP_NEWMAP_DESC = Type.getMethodDescriptor(TYPE_PROPERTYMAP); static final String MAP_DUPLICATE = "duplicate"; static final String MAP_DUPLICATE_DESC = Type.getMethodDescriptor(TYPE_PROPERTYMAP); - static final String MAP_SETFLAGS = "setFlags"; static final String LOOKUP_TYPE = TYPE_LOOKUP.getInternalName(); - static final String LOOKUP_GETMETHOD = "getMethod"; static final String LOOKUP_NEWPROPERTY = "newProperty"; static final String LOOKUP_NEWPROPERTY_DESC = Type.getMethodDescriptor(TYPE_PROPERTYMAP, TYPE_PROPERTYMAP, TYPE_STRING, Type.INT_TYPE, TYPE_METHODHANDLE, TYPE_METHODHANDLE); diff --git a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java index 52241265513..fe4e3676e19 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java @@ -179,6 +179,8 @@ final class CodeGenerator extends NodeOperatorVisitor foc = new FieldObjectCreator(this, nameList, newSymbols, values, true, hasArguments) { + new FieldObjectCreator(this, nameList, newSymbols, values, true, hasArguments) { @Override protected void loadValue(final Symbol value) { method.load(value); @@ -956,8 +958,7 @@ final class CodeGenerator extends NodeOperatorVisitor(this, keys, symbols, values) { - @Override - protected void loadValue(final Node node) { - load(node); - } + if (elements.size() > OBJECT_SPILL_THRESHOLD) { + new SpillObjectCreator(this, keys, symbols, values).makeObject(method); + } else { + new FieldObjectCreator(this, keys, symbols, values) { + @Override + protected void loadValue(final Node node) { + load(node); + } - /** - * Ensure that the properties start out as object types so that - * we can do putfield initializations instead of dynamicSetIndex - * which would be the case to determine initial property type - * otherwise. - * - * Use case, it's very expensive to do a million var x = {a:obj, b:obj} - * just to have to invalidate them immediately on initialization - * - * see NASHORN-594 - */ - @Override - protected MapCreator newMapCreator(final Class fieldObjectClass) { - return new MapCreator(fieldObjectClass, keys, symbols) { - @Override - protected int getPropertyFlags(final Symbol symbol, final boolean isVarArg) { - return super.getPropertyFlags(symbol, isVarArg) | Property.IS_ALWAYS_OBJECT; - } - }; - } + /** + * Ensure that the properties start out as object types so that + * we can do putfield initializations instead of dynamicSetIndex + * which would be the case to determine initial property type + * otherwise. + * + * Use case, it's very expensive to do a million var x = {a:obj, b:obj} + * just to have to invalidate them immediately on initialization + * + * see NASHORN-594 + */ + @Override + protected MapCreator newMapCreator(final Class fieldObjectClass) { + return new MapCreator(fieldObjectClass, keys, symbols) { + @Override + protected int getPropertyFlags(final Symbol symbol, final boolean hasArguments) { + return super.getPropertyFlags(symbol, hasArguments) | Property.IS_ALWAYS_OBJECT; + } + }; + } - }.makeObject(method); + }.makeObject(method); + } method.dup(); globalObjectPrototype(); method.invoke(ScriptObject.SET_PROTO); - if (!hasGettersSetters) { - method.store(objectNode.getSymbol()); - return false; - } + if (hasGettersSetters) { + for (final PropertyNode propertyNode : elements) { + final FunctionNode getter = propertyNode.getGetter(); + final FunctionNode setter = propertyNode.getSetter(); - for (final Node element : elements) { - final PropertyNode propertyNode = (PropertyNode)element; - final Object key = propertyNode.getKey(); - final FunctionNode getter = propertyNode.getGetter(); - final FunctionNode setter = propertyNode.getSetter(); + if (getter == null && setter == null) { + continue; + } - if (getter == null && setter == null) { - continue; + method.dup().loadKey(propertyNode.getKey()); + + if (getter == null) { + method.loadNull(); + } else { + getter.accept(this); + } + + if (setter == null) { + method.loadNull(); + } else { + setter.accept(this); + } + + method.invoke(ScriptObject.SET_USER_ACCESSORS); } - - method.dup().loadKey(key); - - if (getter == null) { - method.loadNull(); - } else { - getter.accept(this); - } - - if (setter == null) { - method.loadNull(); - } else { - setter.accept(this); - } - - method.invoke(ScriptObject.SET_USER_ACCESSORS); } method.store(objectNode.getSymbol()); - return false; } @@ -3183,24 +3181,21 @@ final class CodeGenerator extends NodeOperatorVisitor(), new ArrayList(), false, false) { - @Override - protected void makeObject(final MethodEmitter m) { - final String className = SCRIPTFUNCTION_IMPL_OBJECT; + method._new(className).dup(); + loadConstant(new RecompilableScriptFunctionData(functionNode, compiler.getCodeInstaller(), allocatorClassName, allocatorMap)); - m._new(className).dup(); - loadConstant(new RecompilableScriptFunctionData(functionNode, compiler.getCodeInstaller(), Compiler.binaryName(getClassName()), makeMap())); - - if (isLazy || functionNode.needsParentScope()) { - m.loadCompilerConstant(SCOPE); - } else { - m.loadNull(); - } - m.invoke(constructorNoLookup(className, RecompilableScriptFunctionData.class, ScriptObject.class)); - } - }.makeObject(method); + if (functionNode.isLazy() || functionNode.needsParentScope()) { + method.loadCompilerConstant(SCOPE); + } else { + method.loadNull(); + } + method.invoke(constructorNoLookup(className, RecompilableScriptFunctionData.class, ScriptObject.class)); } // calls on Global class. diff --git a/nashorn/src/jdk/nashorn/internal/codegen/FieldObjectCreator.java b/nashorn/src/jdk/nashorn/internal/codegen/FieldObjectCreator.java index 974b5ba81a7..9e15b4978a4 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/FieldObjectCreator.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/FieldObjectCreator.java @@ -26,15 +26,16 @@ package jdk.nashorn.internal.codegen; import static jdk.nashorn.internal.codegen.CompilerConstants.ARGUMENTS; -import static jdk.nashorn.internal.codegen.CompilerConstants.SCOPE; import static jdk.nashorn.internal.codegen.CompilerConstants.constructorNoLookup; import static jdk.nashorn.internal.codegen.CompilerConstants.typeDescriptor; +import static jdk.nashorn.internal.codegen.ObjectClassGenerator.getPaddedFieldCount; import static jdk.nashorn.internal.codegen.types.Type.OBJECT; import java.util.Iterator; import java.util.List; import jdk.nashorn.internal.codegen.types.Type; import jdk.nashorn.internal.ir.Symbol; +import jdk.nashorn.internal.runtime.Context; import jdk.nashorn.internal.runtime.PropertyMap; import jdk.nashorn.internal.runtime.ScriptObject; import jdk.nashorn.internal.runtime.arrays.ArrayIndex; @@ -48,6 +49,13 @@ import jdk.nashorn.internal.runtime.arrays.ArrayIndex; * @see jdk.nashorn.internal.ir.Node */ public abstract class FieldObjectCreator extends ObjectCreator { + + private String fieldObjectClassName; + private Class fieldObjectClass; + private int fieldCount; + private int paddedFieldCount; + private int paramCount; + /** array of corresponding values to symbols (null for no values) */ private final List values; @@ -80,14 +88,9 @@ public abstract class FieldObjectCreator extends ObjectCreator { super(codegen, keys, symbols, isScope, hasArguments); this.values = values; this.callSiteFlags = codegen.getCallSiteFlags(); - } - /** - * Loads the scope on the stack through the passed method emitter. - * @param method the method emitter to use - */ - protected void loadScope(final MethodEmitter method) { - method.loadCompilerConstant(SCOPE); + countFields(); + findClass(); } /** @@ -137,6 +140,13 @@ public abstract class FieldObjectCreator extends ObjectCreator { } } + @Override + protected PropertyMap makeMap() { + assert propertyMap == null : "property map already initialized"; + propertyMap = newMapCreator(fieldObjectClass).makeFieldMap(hasArguments(), fieldCount, paddedFieldCount); + return propertyMap; + } + /** * Technique for loading an initial value. Defined by anonymous subclasses in code gen. * @@ -173,4 +183,47 @@ public abstract class FieldObjectCreator extends ObjectCreator { loadValue(value); method.dynamicSetIndex(callSiteFlags); } + + /** + * Locate (or indirectly create) the object container class. + */ + private void findClass() { + fieldObjectClassName = isScope() ? + ObjectClassGenerator.getClassName(fieldCount, paramCount) : + ObjectClassGenerator.getClassName(paddedFieldCount); + + try { + this.fieldObjectClass = Context.forStructureClass(Compiler.binaryName(fieldObjectClassName)); + } catch (final ClassNotFoundException e) { + throw new AssertionError("Nashorn has encountered an internal error. Structure can not be created."); + } + } + + /** + * Get the class name for the object class, + * e.g. {@code com.nashorn.oracle.scripts.JO2P0} + * + * @return script class name + */ + String getClassName() { + return fieldObjectClassName; + } + + /** + * Tally the number of fields and parameters. + */ + private void countFields() { + for (final Symbol symbol : this.symbols) { + if (symbol != null) { + if (hasArguments() && symbol.isParam()) { + symbol.setFieldIndex(paramCount++); + } else { + symbol.setFieldIndex(fieldCount++); + } + } + } + + paddedFieldCount = getPaddedFieldCount(fieldCount); + } + } diff --git a/nashorn/src/jdk/nashorn/internal/codegen/FinalizeTypes.java b/nashorn/src/jdk/nashorn/internal/codegen/FinalizeTypes.java index f9d643228e8..14bec19d8ba 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/FinalizeTypes.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/FinalizeTypes.java @@ -175,6 +175,14 @@ final class FinalizeTypes extends NodeOperatorVisitor { if (destType == null) { destType = specBinaryNode.getType(); } + // Register assignments to this object in case this is used as constructor + if (binaryNode.lhs() instanceof AccessNode) { + AccessNode accessNode = (AccessNode) binaryNode.lhs(); + + if (accessNode.getBase().getSymbol().isThis()) { + lc.getCurrentFunction().addThisProperty(accessNode.getProperty().getName()); + } + } return specBinaryNode.setRHS(convert(specBinaryNode.rhs(), destType)); } diff --git a/nashorn/src/jdk/nashorn/internal/codegen/MapCreator.java b/nashorn/src/jdk/nashorn/internal/codegen/MapCreator.java index 609fac9b3ff..6ad03c73691 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/MapCreator.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/MapCreator.java @@ -41,10 +41,10 @@ public class MapCreator { private final Class structure; /** key set for object map */ - private final String[] keys; + final List keys; /** corresponding symbol set for object map */ - private final Symbol[] symbols; + final List symbols; /** * Constructor @@ -54,11 +54,9 @@ public class MapCreator { * @param symbols list of symbols for map */ MapCreator(final Class structure, final List keys, final List symbols) { - final int size = keys.size(); - this.structure = structure; - this.keys = keys.toArray(new String[size]); - this.symbols = symbols.toArray(new Symbol[size]); + this.keys = keys; + this.symbols = symbols; } /** @@ -70,21 +68,37 @@ public class MapCreator { * * @return New map populated with accessor properties. */ - PropertyMap makeMap(final boolean hasArguments, final int fieldCount, final int fieldMaximum) { + PropertyMap makeFieldMap(final boolean hasArguments, final int fieldCount, final int fieldMaximum) { final List properties = new ArrayList<>(); - assert keys != null; - for (int i = 0; i < keys.length; i++) { - final String key = keys[i]; - final Symbol symbol = symbols[i]; + for (int i = 0, length = keys.size(); i < length; i++) { + final String key = keys.get(i); + final Symbol symbol = symbols.get(i); if (symbol != null && !ArrayIndex.isIntArrayIndex(key)) { properties.add(new AccessorProperty(key, getPropertyFlags(symbol, hasArguments), structure, symbol.getFieldIndex())); } } - return PropertyMap.newMap(structure, properties, fieldCount, fieldMaximum); + return PropertyMap.newMap(properties, fieldCount, fieldMaximum, 0); + } + + PropertyMap makeSpillMap(final boolean hasArguments) { + final List properties = new ArrayList<>(); + int spillIndex = 0; + assert keys != null; + + for (int i = 0, length = keys.size(); i < length; i++) { + final String key = keys.get(i); + final Symbol symbol = symbols.get(i); + + if (symbol != null && !ArrayIndex.isIntArrayIndex(key)) { + properties.add(new AccessorProperty(key, getPropertyFlags(symbol, hasArguments), spillIndex++)); + } + } + + return PropertyMap.newMap(properties, 0, 0, spillIndex); } /** diff --git a/nashorn/src/jdk/nashorn/internal/codegen/ObjectClassGenerator.java b/nashorn/src/jdk/nashorn/internal/codegen/ObjectClassGenerator.java index 934df7a6820..7d61db1f691 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/ObjectClassGenerator.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/ObjectClassGenerator.java @@ -73,11 +73,6 @@ public final class ObjectClassGenerator { */ static final int FIELD_PADDING = 4; - /** - * Rounding when calculating the number of fields. - */ - static final int FIELD_ROUNDING = 4; - /** * Debug field logger * Should we print debugging information for fields when they are generated and getters/setters are called? @@ -325,7 +320,6 @@ public final class ObjectClassGenerator { final List initFields = addFields(classEmitter, fieldCount); final MethodEmitter init = newInitMethod(classEmitter); - initializeToUndefined(init, className, initFields); init.returnVoid(); init.end(); @@ -709,6 +703,15 @@ public final class ObjectClassGenerator { } } + /** + * Add padding to field count to avoid creating too many classes and have some spare fields + * @param count the field count + * @return the padded field count + */ + static int getPaddedFieldCount(final int count) { + return count / FIELD_PADDING * FIELD_PADDING + FIELD_PADDING; + } + // // Provide generic getters and setters for undefined types. If a type is undefined, all // and marshals the set to the correct setter depending on the type of the value being set. diff --git a/nashorn/src/jdk/nashorn/internal/codegen/ObjectCreator.java b/nashorn/src/jdk/nashorn/internal/codegen/ObjectCreator.java index b0e5a7730e9..2a8ebba71b4 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/ObjectCreator.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/ObjectCreator.java @@ -25,10 +25,10 @@ package jdk.nashorn.internal.codegen; +import static jdk.nashorn.internal.codegen.CompilerConstants.SCOPE; + import java.util.List; -import static jdk.nashorn.internal.codegen.ObjectClassGenerator.FIELD_PADDING; import jdk.nashorn.internal.ir.Symbol; -import jdk.nashorn.internal.runtime.Context; import jdk.nashorn.internal.runtime.PropertyMap; /** @@ -36,9 +36,6 @@ import jdk.nashorn.internal.runtime.PropertyMap; */ public abstract class ObjectCreator { - /** Compile unit for this ObjectCreator, see CompileUnit */ - //protected final CompileUnit compileUnit; - /** List of keys to initiate in this ObjectCreator */ protected final List keys; @@ -50,12 +47,7 @@ public abstract class ObjectCreator { private final boolean isScope; private final boolean hasArguments; - private int fieldCount; - private int paddedFieldCount; - private int paramCount; - private String fieldObjectClassName; - private Class fieldObjectClass; - private PropertyMap propertyMap; + protected PropertyMap propertyMap; /** * Constructor @@ -72,41 +64,6 @@ public abstract class ObjectCreator { this.symbols = symbols; this.isScope = isScope; this.hasArguments = hasArguments; - - countFields(); - findClass(); - } - - /** - * Tally the number of fields and parameters. - */ - private void countFields() { - for (final Symbol symbol : this.symbols) { - if (symbol != null) { - if (hasArguments() && symbol.isParam()) { - symbol.setFieldIndex(paramCount++); - } else { - symbol.setFieldIndex(fieldCount++); - } - } - } - - paddedFieldCount = fieldCount + FIELD_PADDING; - } - - /** - * Locate (or indirectly create) the object container class. - */ - private void findClass() { - fieldObjectClassName = isScope() ? - ObjectClassGenerator.getClassName(fieldCount, paramCount) : - ObjectClassGenerator.getClassName(paddedFieldCount); - - try { - this.fieldObjectClass = Context.forStructureClass(Compiler.binaryName(fieldObjectClassName)); - } catch (final ClassNotFoundException e) { - throw new AssertionError("Nashorn has encountered an internal error. Structure can not be created."); - } } /** @@ -115,6 +72,12 @@ public abstract class ObjectCreator { */ protected abstract void makeObject(final MethodEmitter method); + /** + * Construct the property map appropriate for the object. + * @return the newly created property map + */ + protected abstract PropertyMap makeMap(); + /** * Create a new MapCreator * @param clazz type of MapCreator @@ -125,12 +88,11 @@ public abstract class ObjectCreator { } /** - * Construct the property map appropriate for the object. - * @return the newly created property map + * Loads the scope on the stack through the passed method emitter. + * @param method the method emitter to use */ - protected PropertyMap makeMap() { - propertyMap = newMapCreator(fieldObjectClass).makeMap(hasArguments(), fieldCount, paddedFieldCount); - return propertyMap; + protected void loadScope(final MethodEmitter method) { + method.loadCompilerConstant(SCOPE); } /** @@ -143,16 +105,6 @@ public abstract class ObjectCreator { return method; } - /** - * Get the class name for the object class, - * e.g. {@code com.nashorn.oracle.scripts.JO2P0} - * - * @return script class name - */ - String getClassName() { - return fieldObjectClassName; - } - /** * Is this a scope object * @return true if scope diff --git a/nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java b/nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java new file mode 100644 index 00000000000..33e1d432ac3 --- /dev/null +++ b/nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2010-2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.nashorn.internal.codegen; + +import jdk.nashorn.internal.codegen.types.Type; +import jdk.nashorn.internal.ir.LiteralNode; +import jdk.nashorn.internal.ir.Node; +import jdk.nashorn.internal.ir.Symbol; +import jdk.nashorn.internal.runtime.Property; +import jdk.nashorn.internal.runtime.PropertyMap; +import jdk.nashorn.internal.runtime.ScriptObject; +import jdk.nashorn.internal.scripts.JO; + +import java.util.List; + +import static jdk.nashorn.internal.codegen.CompilerConstants.constructorNoLookup; +import static jdk.nashorn.internal.codegen.types.Type.OBJECT; + +/** + * An object creator that uses spill properties. + */ +public class SpillObjectCreator extends ObjectCreator { + + private final List values; + + /** + * Constructor + * + * @param codegen code generator + * @param keys keys for fields in object + * @param symbols symbols for fields in object + * @param values list of values corresponding to keys + */ + protected SpillObjectCreator(final CodeGenerator codegen, final List keys, final List symbols, final List values) { + super(codegen, keys, symbols, false, false); + this.values = values; + makeMap(); + } + + @Override + protected void makeObject(final MethodEmitter method) { + assert !isScope() : "spill scope objects are not currently supported"; + + final int length = keys.size(); + final Object[] presetValues = new Object[propertyMap.size()]; + final Class clazz = JO.class; + + // Compute constant values + for (int i = 0; i < length; i++) { + final String key = keys.get(i); + final Property property = propertyMap.findProperty(key); + + if (property != null) { + presetValues[property.getSlot()] = LiteralNode.objectAsConstant(values.get(i)); + } + } + + method._new(clazz).dup(); + codegen.loadConstant(propertyMap); + + method.invoke(constructorNoLookup(JO.class, PropertyMap.class)); + + method.dup(); + codegen.loadConstant(presetValues); + + // Create properties with non-constant values + for (int i = 0; i < length; i++) { + final String key = keys.get(i); + final Property property = propertyMap.findProperty(key); + + if (property != null && presetValues[property.getSlot()] == LiteralNode.POSTSET_MARKER) { + method.dup(); + method.load(property.getSlot()); + codegen.load(values.get(i)).convert(OBJECT); + method.arraystore(); + presetValues[property.getSlot()] = null; + } + } + + method.putField(Type.typeFor(ScriptObject.class).getInternalName(), "spill", Type.OBJECT_ARRAY.getDescriptor()); + final int callSiteFlags = codegen.getCallSiteFlags(); + + // Assign properties with valid array index keys + for (int i = 0; i < length; i++) { + final String key = keys.get(i); + final Property property = propertyMap.findProperty(key); + final Node value = values.get(i); + + if (property == null && value != null) { + method.dup(); + method.load(keys.get(i)); + codegen.load(value); + method.dynamicSetIndex(callSiteFlags); + } + } + } + + @Override + protected PropertyMap makeMap() { + assert propertyMap == null : "property map already initialized"; + + propertyMap = new MapCreator(JO.class, keys, symbols) { + @Override + protected int getPropertyFlags(Symbol symbol, boolean hasArguments) { + return super.getPropertyFlags(symbol, hasArguments) | Property.IS_SPILL | Property.IS_ALWAYS_OBJECT; + } + }.makeSpillMap(false); + + return propertyMap; + } +} diff --git a/nashorn/src/jdk/nashorn/internal/ir/FunctionNode.java b/nashorn/src/jdk/nashorn/internal/ir/FunctionNode.java index 3640db30e87..8caff9d28fd 100644 --- a/nashorn/src/jdk/nashorn/internal/ir/FunctionNode.java +++ b/nashorn/src/jdk/nashorn/internal/ir/FunctionNode.java @@ -131,6 +131,10 @@ public final class FunctionNode extends LexicalContextNode implements Flags thisProperties; + /** Function flags. */ private final int flags; @@ -277,6 +281,7 @@ public final class FunctionNode extends LexicalContextNode implements Flags(); + } + thisProperties.add(key); + } + + /** + * Get the number of properties assigned to the this object in this function. + * @return number of properties + */ + public int countThisProperties() { + return thisProperties == null ? 0 : thisProperties.size(); + } + /** * Return the kind of this function * @see FunctionNode.Kind diff --git a/nashorn/src/jdk/nashorn/internal/ir/LiteralNode.java b/nashorn/src/jdk/nashorn/internal/ir/LiteralNode.java index a7cea66a256..2c812dbbea5 100644 --- a/nashorn/src/jdk/nashorn/internal/ir/LiteralNode.java +++ b/nashorn/src/jdk/nashorn/internal/ir/LiteralNode.java @@ -49,6 +49,9 @@ public abstract class LiteralNode extends Node implements PropertyKey { /** Literal value */ protected final T value; + /** Marker for values that must be computed at runtime */ + public static final Object POSTSET_MARKER = new Object(); + /** * Constructor * @@ -495,6 +498,30 @@ public abstract class LiteralNode extends Node implements PropertyKey { return new LexerTokenLiteralNode(parent.getToken(), parent.getFinish(), value); } + /** + * Get the constant value for an object, or {@link #POSTSET_MARKER} if the value can't be statically computed. + * + * @param object a node or value object + * @return the constant value or {@code POSTSET_MARKER} + */ + public static Object objectAsConstant(final Object object) { + if (object == null) { + return null; + } else if (object instanceof Number || object instanceof String || object instanceof Boolean) { + return object; + } else if (object instanceof LiteralNode) { + return objectAsConstant(((LiteralNode)object).getValue()); + } else if (object instanceof UnaryNode) { + final UnaryNode unaryNode = (UnaryNode)object; + + if (unaryNode.isTokenType(TokenType.CONVERT) && unaryNode.getType().isObject()) { + return objectAsConstant(unaryNode.rhs()); + } + } + + return POSTSET_MARKER; + } + private static final class NullLiteralNode extends LiteralNode { private NullLiteralNode(final long token, final int finish) { @@ -525,11 +552,6 @@ public abstract class LiteralNode extends Node implements PropertyKey { * Array literal node class. */ public static final class ArrayLiteralNode extends LiteralNode { - private static class PostsetMarker { - //empty - } - - private static PostsetMarker POSTSET_MARKER = new PostsetMarker(); /** Array element type. */ private Type elementType; @@ -740,24 +762,6 @@ public abstract class LiteralNode extends Node implements PropertyKey { } } - private Object objectAsConstant(final Object object) { - if (object == null) { - return null; - } else if (object instanceof Number || object instanceof String || object instanceof Boolean) { - return object; - } else if (object instanceof LiteralNode) { - return objectAsConstant(((LiteralNode)object).getValue()); - } else if (object instanceof UnaryNode) { - final UnaryNode unaryNode = (UnaryNode)object; - - if (unaryNode.isTokenType(TokenType.CONVERT) && unaryNode.getType().isObject()) { - return objectAsConstant(unaryNode.rhs()); - } - } - - return POSTSET_MARKER; - } - @Override public Node[] getArray() { return value; diff --git a/nashorn/src/jdk/nashorn/internal/ir/debug/JSONWriter.java b/nashorn/src/jdk/nashorn/internal/ir/debug/JSONWriter.java index 4415ebd7689..9ac46dc6000 100644 --- a/nashorn/src/jdk/nashorn/internal/ir/debug/JSONWriter.java +++ b/nashorn/src/jdk/nashorn/internal/ir/debug/JSONWriter.java @@ -514,7 +514,7 @@ public final class JSONWriter extends NodeVisitor { type("ArrayExpression"); comma(); - final Node[] value = (Node[])literalNode.getValue(); + final Node[] value = literalNode.getArray(); array("elements", Arrays.asList(value)); } else { type("Literal"); diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeArguments.java b/nashorn/src/jdk/nashorn/internal/objects/NativeArguments.java index 443a8938a2c..4a5b5986197 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeArguments.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeArguments.java @@ -64,7 +64,7 @@ public final class NativeArguments extends ScriptObject { private static final PropertyMap map$; static { - PropertyMap map = PropertyMap.newMap(NativeArguments.class); + PropertyMap map = PropertyMap.newMap(); map = Lookup.newProperty(map, "length", Property.NOT_ENUMERABLE, G$LENGTH, S$LENGTH); map = Lookup.newProperty(map, "callee", Property.NOT_ENUMERABLE, G$CALLEE, S$CALLEE); map$ = map; diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeStrictArguments.java b/nashorn/src/jdk/nashorn/internal/objects/NativeStrictArguments.java index ae2ddb01d8d..df2d17dd054 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeStrictArguments.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeStrictArguments.java @@ -54,7 +54,7 @@ public final class NativeStrictArguments extends ScriptObject { private static final PropertyMap map$; static { - PropertyMap map = PropertyMap.newMap(NativeStrictArguments.class); + PropertyMap map = PropertyMap.newMap(); map = Lookup.newProperty(map, "length", Property.NOT_ENUMERABLE, G$LENGTH, S$LENGTH); // In strict mode, the caller and callee properties should throw TypeError // Need to add properties directly to map since slots are assigned speculatively by newUserAccessors. diff --git a/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java b/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java index c4cda933dd5..64af421598f 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java +++ b/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java @@ -52,7 +52,7 @@ public class PrototypeObject extends ScriptObject { private static final MethodHandle SET_CONSTRUCTOR = findOwnMH("setConstructor", void.class, Object.class, Object.class); static { - PropertyMap map = PropertyMap.newMap(PrototypeObject.class); + PropertyMap map = PropertyMap.newMap(); map = Lookup.newProperty(map, "constructor", Property.NOT_ENUMERABLE, GET_CONSTRUCTOR, SET_CONSTRUCTOR); map$ = map; } diff --git a/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java b/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java index 91034c43bdf..921073d4484 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java +++ b/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java @@ -149,7 +149,7 @@ public class ScriptFunctionImpl extends ScriptFunction { } static { - PropertyMap map = PropertyMap.newMap(ScriptFunctionImpl.class); + PropertyMap map = PropertyMap.newMap(); map = Lookup.newProperty(map, "prototype", Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE, G$PROTOTYPE, S$PROTOTYPE); map = Lookup.newProperty(map, "length", Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE | Property.NOT_WRITABLE, G$LENGTH, null); map = Lookup.newProperty(map, "name", Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE | Property.NOT_WRITABLE, G$NAME, null); @@ -201,7 +201,7 @@ public class ScriptFunctionImpl extends ScriptFunction { // Instance of this class is used as global anonymous function which // serves as Function.prototype object. private static class AnonymousFunction extends ScriptFunctionImpl { - private static final PropertyMap nasgenmap$$ = PropertyMap.newMap(AnonymousFunction.class); + private static final PropertyMap nasgenmap$$ = PropertyMap.newMap(); AnonymousFunction() { super("", GlobalFunctions.ANONYMOUS, nasgenmap$$, null); diff --git a/nashorn/src/jdk/nashorn/internal/parser/Parser.java b/nashorn/src/jdk/nashorn/internal/parser/Parser.java index efd6eda6435..4c6107d570e 100644 --- a/nashorn/src/jdk/nashorn/internal/parser/Parser.java +++ b/nashorn/src/jdk/nashorn/internal/parser/Parser.java @@ -2009,7 +2009,7 @@ loop: } if (!redefinitionOk) { - throw error(AbstractParser.message("property.redefinition", key.toString()), property.getToken()); + throw error(AbstractParser.message("property.redefinition", key), property.getToken()); } PropertyNode newProperty = existingProperty; diff --git a/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java b/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java index 1144eb630bd..6840d458c4e 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java @@ -140,8 +140,8 @@ public class AccessorProperty extends Property { this.primitiveGetter = bindTo(property.primitiveGetter, delegate); this.primitiveSetter = bindTo(property.primitiveSetter, delegate); - this.objectGetter = bindTo(property.objectGetter, delegate); - this.objectSetter = bindTo(property.objectSetter, delegate); + this.objectGetter = bindTo(property.ensureObjectGetter(), delegate); + this.objectSetter = bindTo(property.ensureObjectSetter(), delegate); setCurrentType(property.getCurrentType()); } @@ -331,12 +331,26 @@ public class AccessorProperty extends Property { } } - @Override - public MethodHandle getGetter(final Class type) { + // Spill getters and setters are lazily initialized, see JDK-8011630 + private MethodHandle ensureObjectGetter() { if (isSpill() && objectGetter == null) { objectGetter = getSpillGetter(); } + return objectGetter; + } + + private MethodHandle ensureObjectSetter() { + if (isSpill() && objectSetter == null) { + objectSetter = getSpillSetter(); + } + return objectSetter; + } + + @Override + public MethodHandle getGetter(final Class type) { final int i = getAccessorTypeIndex(type); + ensureObjectGetter(); + if (getters[i] == null) { getters[i] = debug( createGetter(currentType, type, primitiveGetter, objectGetter), @@ -372,9 +386,7 @@ public class AccessorProperty extends Property { } private MethodHandle generateSetter(final Class forType, final Class type) { - if (isSpill() && objectSetter == null) { - objectSetter = getSpillSetter(); - } + ensureObjectSetter(); MethodHandle mh = createSetter(forType, type, primitiveSetter, objectSetter); mh = debug(mh, currentType, type, "set"); return mh; diff --git a/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java b/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java index e03a3ef836e..f8d9b437c07 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java @@ -91,14 +91,16 @@ public final class PropertyMap implements Iterable, PropertyListener { /** * Constructor. * - * @param properties A {@link PropertyHashMap} with initial contents. - * @param fieldCount Number of fields in use. + * @param properties A {@link PropertyHashMap} with initial contents. + * @param fieldCount Number of fields in use. * @param fieldMaximum Number of fields available. + * @param spillLength Number of spill slots used. */ - private PropertyMap(final PropertyHashMap properties, final int fieldCount, final int fieldMaximum) { + private PropertyMap(final PropertyHashMap properties, final int fieldCount, final int fieldMaximum, final int spillLength) { this.properties = properties; this.fieldCount = fieldCount; this.fieldMaximum = fieldMaximum; + this.spillLength = spillLength; if (Context.DEBUG) { count++; @@ -111,7 +113,7 @@ public final class PropertyMap implements Iterable, PropertyListener { * @param properties A {@link PropertyHashMap} with initial contents. */ private PropertyMap(final PropertyHashMap properties) { - this(properties, 0, 0); + this(properties, 0, 0, 0); } /** @@ -159,42 +161,23 @@ public final class PropertyMap implements Iterable, PropertyListener { /** * Public property map allocator. * - * @param structure Class the map's {@link AccessorProperty}s apply to. - * @param properties Collection of initial properties. - * @param fieldCount Number of fields in use. + * @param properties Collection of initial properties. + * @param fieldCount Number of fields in use. * @param fieldMaximum Number of fields available. - * + * @param spillLength Number of used spill slots. * @return New {@link PropertyMap}. */ - public static PropertyMap newMap(final Class structure, final Collection properties, final int fieldCount, final int fieldMaximum) { - // Reduce the number of empty maps in the context. - if (structure == JO.class) { - return EMPTY_MAP; - } - + public static PropertyMap newMap(final Collection properties, final int fieldCount, final int fieldMaximum, final int spillLength) { PropertyHashMap newProperties = EMPTY_HASHMAP.immutableAdd(properties); - - return new PropertyMap(newProperties, fieldCount, fieldMaximum); - } - - /** - * Public property map factory allocator - * - * @param structure Class the map's {@link AccessorProperty}s apply to. - * - * @return New {@link PropertyMap}. - */ - public static PropertyMap newMap(final Class structure) { - return newMap(structure, null, 0, 0); + return new PropertyMap(newProperties, fieldCount, fieldMaximum, spillLength); } /** * Return a sharable empty map. * - * @param context the context * @return New empty {@link PropertyMap}. */ - public static PropertyMap newEmptyMap(final Context context) { + public static PropertyMap newMap() { return new PropertyMap(EMPTY_HASHMAP); } diff --git a/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java b/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java index 4443d2ed1f5..e4eaf77e581 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java @@ -170,7 +170,7 @@ public abstract class ScriptObject extends PropertyListenerManager implements Pr } this.arrayData = ArrayData.EMPTY_ARRAY; - this.setMap(map == null ? PropertyMap.newMap(getClass()) : map); + this.setMap(map == null ? PropertyMap.newMap() : map); } /** @@ -188,7 +188,7 @@ public abstract class ScriptObject extends PropertyListenerManager implements Pr } this.arrayData = ArrayData.EMPTY_ARRAY; - this.setMap(map == null ? PropertyMap.newMap(getClass()) : map); + this.setMap(map == null ? PropertyMap.newMap() : map); this.proto = proto; if (proto != null) { diff --git a/nashorn/src/jdk/nashorn/internal/scripts/JO.java b/nashorn/src/jdk/nashorn/internal/scripts/JO.java index b4da66e5ef4..d6173918933 100644 --- a/nashorn/src/jdk/nashorn/internal/scripts/JO.java +++ b/nashorn/src/jdk/nashorn/internal/scripts/JO.java @@ -33,7 +33,7 @@ import jdk.nashorn.internal.runtime.ScriptObject; */ public class JO extends ScriptObject { - private static final PropertyMap map$ = PropertyMap.newMap(JO.class); + private static final PropertyMap map$ = PropertyMap.newMap(); /** * Returns the initial property map to be used. diff --git a/nashorn/test/script/basic/JDK-8017084.js b/nashorn/test/script/basic/JDK-8017084.js new file mode 100644 index 00000000000..ceac68ee58c --- /dev/null +++ b/nashorn/test/script/basic/JDK-8017084.js @@ -0,0 +1,17625 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * 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. + */ + +/** + * JDK-8017084: Use spill properties for large object literals + * + * @test + * @run + */ + +var x = { + a: 1, + b: 2, + c: 3, + d: 4, + e: 5, + f: 6, + g: 7, + h: 8, + i: 9, + j: 10, + k: 11, + l: 12, + m: 13, + n: 14, + o: 15, + p: 16, + q: 17, + r: 18, + s: 19, + t: 20, + u: 21, + v: 22, + w: 23, + x: 24, + y: 25, + az: 26, + aa: 27, + ab: 28, + ac: 29, + ad: 30, + ae: 31, + af: 32, + ag: 33, + ah: 34, + ai: 35, + aj: 36, + ak: 37, + al: 38, + am: 39, + an: 40, + ao: 41, + ap: 42, + aq: 43, + ar: 44, + as: 45, + at: 46, + au: 47, + av: 48, + aw: 49, + ax: 50, + ay: 51, + bz: 52, + ba: 53, + bb: 54, + bc: 55, + bd: 56, + be: 57, + bf: 58, + bg: 59, + bh: 60, + bi: 61, + bj: 62, + bk: 63, + bl: 64, + bm: 65, + bn: 66, + bo: 67, + bp: 68, + bq: 69, + br: 70, + bs: 71, + bt: 72, + bu: 73, + bv: 74, + bw: 75, + bx: 76, + by: 77, + cz: 78, + ca: 79, + cb: 80, + cc: 81, + cd: 82, + ce: 83, + cf: 84, + cg: 85, + ch: 86, + ci: 87, + cj: 88, + ck: 89, + cl: 90, + cm: 91, + cn: 92, + co: 93, + cp: 94, + cq: 95, + cr: 96, + cs: 97, + ct: 98, + cu: 99, + cv: 100, + cw: 101, + cx: 102, + cy: 103, + dz: 104, + da: 105, + db: 106, + dc: 107, + dd: 108, + de: 109, + df: 110, + dg: 111, + dh: 112, + di: 113, + dj: 114, + dk: 115, + dl: 116, + dm: 117, + dn: 118, + do: 119, + dp: 120, + dq: 121, + dr: 122, + ds: 123, + dt: 124, + du: 125, + dv: 126, + dw: 127, + dx: 128, + dy: 129, + ez: 130, + ea: 131, + eb: 132, + ec: 133, + ed: 134, + ee: 135, + ef: 136, + eg: 137, + eh: 138, + ei: 139, + ej: 140, + ek: 141, + el: 142, + em: 143, + en: 144, + eo: 145, + ep: 146, + eq: 147, + er: 148, + es: 149, + et: 150, + eu: 151, + ev: 152, + ew: 153, + ex: 154, + ey: 155, + fz: 156, + fa: 157, + fb: 158, + fc: 159, + fd: 160, + fe: 161, + ff: 162, + fg: 163, + fh: 164, + fi: 165, + fj: 166, + fk: 167, + fl: 168, + fm: 169, + fn: 170, + fo: 171, + fp: 172, + fq: 173, + fr: 174, + fs: 175, + ft: 176, + fu: 177, + fv: 178, + fw: 179, + fx: 180, + fy: 181, + gz: 182, + ga: 183, + gb: 184, + gc: 185, + gd: 186, + ge: 187, + gf: 188, + gg: 189, + gh: 190, + gi: 191, + gj: 192, + gk: 193, + gl: 194, + gm: 195, + gn: 196, + go: 197, + gp: 198, + gq: 199, + gr: 200, + gs: 201, + gt: 202, + gu: 203, + gv: 204, + gw: 205, + gx: 206, + gy: 207, + hz: 208, + ha: 209, + hb: 210, + hc: 211, + hd: 212, + he: 213, + hf: 214, + hg: 215, + hh: 216, + hi: 217, + hj: 218, + hk: 219, + hl: 220, + hm: 221, + hn: 222, + ho: 223, + hp: 224, + hq: 225, + hr: 226, + hs: 227, + ht: 228, + hu: 229, + hv: 230, + hw: 231, + hx: 232, + hy: 233, + iz: 234, + ia: 235, + ib: 236, + ic: 237, + id: 238, + ie: 239, + if: 240, + ig: 241, + ih: 242, + ii: 243, + ij: 244, + ik: 245, + il: 246, + im: 247, + in: 248, + io: 249, + ip: 250, + iq: 251, + ir: 252, + is: 253, + it: 254, + iu: 255, + iv: 256, + iw: 257, + ix: 258, + iy: 259, + jz: 260, + ja: 261, + jb: 262, + jc: 263, + jd: 264, + je: 265, + jf: 266, + jg: 267, + jh: 268, + ji: 269, + jj: 270, + jk: 271, + jl: 272, + jm: 273, + jn: 274, + jo: 275, + jp: 276, + jq: 277, + jr: 278, + js: 279, + jt: 280, + ju: 281, + jv: 282, + jw: 283, + jx: 284, + jy: 285, + kz: 286, + ka: 287, + kb: 288, + kc: 289, + kd: 290, + ke: 291, + kf: 292, + kg: 293, + kh: 294, + ki: 295, + kj: 296, + kk: 297, + kl: 298, + km: 299, + kn: 300, + ko: 301, + kp: 302, + kq: 303, + kr: 304, + ks: 305, + kt: 306, + ku: 307, + kv: 308, + kw: 309, + kx: 310, + ky: 311, + lz: 312, + la: 313, + lb: 314, + lc: 315, + ld: 316, + le: 317, + lf: 318, + lg: 319, + lh: 320, + li: 321, + lj: 322, + lk: 323, + ll: 324, + lm: 325, + ln: 326, + lo: 327, + lp: 328, + lq: 329, + lr: 330, + ls: 331, + lt: 332, + lu: 333, + lv: 334, + lw: 335, + lx: 336, + ly: 337, + mz: 338, + ma: 339, + mb: 340, + mc: 341, + md: 342, + me: 343, + mf: 344, + mg: 345, + mh: 346, + mi: 347, + mj: 348, + mk: 349, + ml: 350, + mm: 351, + mn: 352, + mo: 353, + mp: 354, + mq: 355, + mr: 356, + ms: 357, + mt: 358, + mu: 359, + mv: 360, + mw: 361, + mx: 362, + my: 363, + nz: 364, + na: 365, + nb: 366, + nc: 367, + nd: 368, + ne: 369, + nf: 370, + ng: 371, + nh: 372, + ni: 373, + nj: 374, + nk: 375, + nl: 376, + nm: 377, + nn: 378, + no: 379, + np: 380, + nq: 381, + nr: 382, + ns: 383, + nt: 384, + nu: 385, + nv: 386, + nw: 387, + nx: 388, + ny: 389, + oz: 390, + oa: 391, + ob: 392, + oc: 393, + od: 394, + oe: 395, + of: 396, + og: 397, + oh: 398, + oi: 399, + oj: 400, + ok: 401, + ol: 402, + om: 403, + on: 404, + oo: 405, + op: 406, + oq: 407, + or: 408, + os: 409, + ot: 410, + ou: 411, + ov: 412, + ow: 413, + ox: 414, + oy: 415, + pz: 416, + pa: 417, + pb: 418, + pc: 419, + pd: 420, + pe: 421, + pf: 422, + pg: 423, + ph: 424, + pi: 425, + pj: 426, + pk: 427, + pl: 428, + pm: 429, + pn: 430, + po: 431, + pp: 432, + pq: 433, + pr: 434, + ps: 435, + pt: 436, + pu: 437, + pv: 438, + pw: 439, + px: 440, + py: 441, + qz: 442, + qa: 443, + qb: 444, + qc: 445, + qd: 446, + qe: 447, + qf: 448, + qg: 449, + qh: 450, + qi: 451, + qj: 452, + qk: 453, + ql: 454, + qm: 455, + qn: 456, + qo: 457, + qp: 458, + qq: 459, + qr: 460, + qs: 461, + qt: 462, + qu: 463, + qv: 464, + qw: 465, + qx: 466, + qy: 467, + rz: 468, + ra: 469, + rb: 470, + rc: 471, + rd: 472, + re: 473, + rf: 474, + rg: 475, + rh: 476, + ri: 477, + rj: 478, + rk: 479, + rl: 480, + rm: 481, + rn: 482, + ro: 483, + rp: 484, + rq: 485, + rr: 486, + rs: 487, + rt: 488, + ru: 489, + rv: 490, + rw: 491, + rx: 492, + ry: 493, + sz: 494, + sa: 495, + sb: 496, + sc: 497, + sd: 498, + se: 499, + sf: 500, + sg: 501, + sh: 502, + si: 503, + sj: 504, + sk: 505, + sl: 506, + sm: 507, + sn: 508, + so: 509, + sp: 510, + sq: 511, + sr: 512, + ss: 513, + st: 514, + su: 515, + sv: 516, + sw: 517, + sx: 518, + sy: 519, + tz: 520, + ta: 521, + tb: 522, + tc: 523, + td: 524, + te: 525, + tf: 526, + tg: 527, + th: 528, + ti: 529, + tj: 530, + tk: 531, + tl: 532, + tm: 533, + tn: 534, + to: 535, + tp: 536, + tq: 537, + tr: 538, + ts: 539, + tt: 540, + tu: 541, + tv: 542, + tw: 543, + tx: 544, + ty: 545, + uz: 546, + ua: 547, + ub: 548, + uc: 549, + ud: 550, + ue: 551, + uf: 552, + ug: 553, + uh: 554, + ui: 555, + uj: 556, + uk: 557, + ul: 558, + um: 559, + un: 560, + uo: 561, + up: 562, + uq: 563, + ur: 564, + us: 565, + ut: 566, + uu: 567, + uv: 568, + uw: 569, + ux: 570, + uy: 571, + vz: 572, + va: 573, + vb: 574, + vc: 575, + vd: 576, + ve: 577, + vf: 578, + vg: 579, + vh: 580, + vi: 581, + vj: 582, + vk: 583, + vl: 584, + vm: 585, + vn: 586, + vo: 587, + vp: 588, + vq: 589, + vr: 590, + vs: 591, + vt: 592, + vu: 593, + vv: 594, + vw: 595, + vx: 596, + vy: 597, + wz: 598, + wa: 599, + wb: 600, + wc: 601, + wd: 602, + we: 603, + wf: 604, + wg: 605, + wh: 606, + wi: 607, + wj: 608, + wk: 609, + wl: 610, + wm: 611, + wn: 612, + wo: 613, + wp: 614, + wq: 615, + wr: 616, + ws: 617, + wt: 618, + wu: 619, + wv: 620, + ww: 621, + wx: 622, + wy: 623, + xz: 624, + xa: 625, + xb: 626, + xc: 627, + xd: 628, + xe: 629, + xf: 630, + xg: 631, + xh: 632, + xi: 633, + xj: 634, + xk: 635, + xl: 636, + xm: 637, + xn: 638, + xo: 639, + xp: 640, + xq: 641, + xr: 642, + xs: 643, + xt: 644, + xu: 645, + xv: 646, + xw: 647, + xx: 648, + xy: 649, + yz: 650, + ya: 651, + yb: 652, + yc: 653, + yd: 654, + ye: 655, + yf: 656, + yg: 657, + yh: 658, + yi: 659, + yj: 660, + yk: 661, + yl: 662, + ym: 663, + yn: 664, + yo: 665, + yp: 666, + yq: 667, + yr: 668, + ys: 669, + yt: 670, + yu: 671, + yv: 672, + yw: 673, + yx: 674, + yy: 675, + azz: 676, + aza: 677, + azb: 678, + azc: 679, + azd: 680, + aze: 681, + azf: 682, + azg: 683, + azh: 684, + azi: 685, + azj: 686, + azk: 687, + azl: 688, + azm: 689, + azn: 690, + azo: 691, + azp: 692, + azq: 693, + azr: 694, + azs: 695, + azt: 696, + azu: 697, + azv: 698, + azw: 699, + azx: 700, + azy: 701, + aaz: 702, + aaa: 703, + aab: 704, + aac: 705, + aad: 706, + aae: 707, + aaf: 708, + aag: 709, + aah: 710, + aai: 711, + aaj: 712, + aak: 713, + aal: 714, + aam: 715, + aan: 716, + aao: 717, + aap: 718, + aaq: 719, + aar: 720, + aas: 721, + aat: 722, + aau: 723, + aav: 724, + aaw: 725, + aax: 726, + aay: 727, + abz: 728, + aba: 729, + abb: 730, + abc: 731, + abd: 732, + abe: 733, + abf: 734, + abg: 735, + abh: 736, + abi: 737, + abj: 738, + abk: 739, + abl: 740, + abm: 741, + abn: 742, + abo: 743, + abp: 744, + abq: 745, + abr: 746, + abs: 747, + abt: 748, + abu: 749, + abv: 750, + abw: 751, + abx: 752, + aby: 753, + acz: 754, + aca: 755, + acb: 756, + acc: 757, + acd: 758, + ace: 759, + acf: 760, + acg: 761, + ach: 762, + aci: 763, + acj: 764, + ack: 765, + acl: 766, + acm: 767, + acn: 768, + aco: 769, + acp: 770, + acq: 771, + acr: 772, + acs: 773, + act: 774, + acu: 775, + acv: 776, + acw: 777, + acx: 778, + acy: 779, + adz: 780, + ada: 781, + adb: 782, + adc: 783, + add: 784, + ade: 785, + adf: 786, + adg: 787, + adh: 788, + adi: 789, + adj: 790, + adk: 791, + adl: 792, + adm: 793, + adn: 794, + ado: 795, + adp: 796, + adq: 797, + adr: 798, + ads: 799, + adt: 800, + adu: 801, + adv: 802, + adw: 803, + adx: 804, + ady: 805, + aez: 806, + aea: 807, + aeb: 808, + aec: 809, + aed: 810, + aee: 811, + aef: 812, + aeg: 813, + aeh: 814, + aei: 815, + aej: 816, + aek: 817, + ael: 818, + aem: 819, + aen: 820, + aeo: 821, + aep: 822, + aeq: 823, + aer: 824, + aes: 825, + aet: 826, + aeu: 827, + aev: 828, + aew: 829, + aex: 830, + aey: 831, + afz: 832, + afa: 833, + afb: 834, + afc: 835, + afd: 836, + afe: 837, + aff: 838, + afg: 839, + afh: 840, + afi: 841, + afj: 842, + afk: 843, + afl: 844, + afm: 845, + afn: 846, + afo: 847, + afp: 848, + afq: 849, + afr: 850, + afs: 851, + aft: 852, + afu: 853, + afv: 854, + afw: 855, + afx: 856, + afy: 857, + agz: 858, + aga: 859, + agb: 860, + agc: 861, + agd: 862, + age: 863, + agf: 864, + agg: 865, + agh: 866, + agi: 867, + agj: 868, + agk: 869, + agl: 870, + agm: 871, + agn: 872, + ago: 873, + agp: 874, + agq: 875, + agr: 876, + ags: 877, + agt: 878, + agu: 879, + agv: 880, + agw: 881, + agx: 882, + agy: 883, + ahz: 884, + aha: 885, + ahb: 886, + ahc: 887, + ahd: 888, + ahe: 889, + ahf: 890, + ahg: 891, + ahh: 892, + ahi: 893, + ahj: 894, + ahk: 895, + ahl: 896, + ahm: 897, + ahn: 898, + aho: 899, + ahp: 900, + ahq: 901, + ahr: 902, + ahs: 903, + aht: 904, + ahu: 905, + ahv: 906, + ahw: 907, + ahx: 908, + ahy: 909, + aiz: 910, + aia: 911, + aib: 912, + aic: 913, + aid: 914, + aie: 915, + aif: 916, + aig: 917, + aih: 918, + aii: 919, + aij: 920, + aik: 921, + ail: 922, + aim: 923, + ain: 924, + aio: 925, + aip: 926, + aiq: 927, + air: 928, + ais: 929, + ait: 930, + aiu: 931, + aiv: 932, + aiw: 933, + aix: 934, + aiy: 935, + ajz: 936, + aja: 937, + ajb: 938, + ajc: 939, + ajd: 940, + aje: 941, + ajf: 942, + ajg: 943, + ajh: 944, + aji: 945, + ajj: 946, + ajk: 947, + ajl: 948, + ajm: 949, + ajn: 950, + ajo: 951, + ajp: 952, + ajq: 953, + ajr: 954, + ajs: 955, + ajt: 956, + aju: 957, + ajv: 958, + ajw: 959, + ajx: 960, + ajy: 961, + akz: 962, + aka: 963, + akb: 964, + akc: 965, + akd: 966, + ake: 967, + akf: 968, + akg: 969, + akh: 970, + aki: 971, + akj: 972, + akk: 973, + akl: 974, + akm: 975, + akn: 976, + ako: 977, + akp: 978, + akq: 979, + akr: 980, + aks: 981, + akt: 982, + aku: 983, + akv: 984, + akw: 985, + akx: 986, + aky: 987, + alz: 988, + ala: 989, + alb: 990, + alc: 991, + ald: 992, + ale: 993, + alf: 994, + alg: 995, + alh: 996, + ali: 997, + alj: 998, + alk: 999, + all: 1000, + alm: 1001, + aln: 1002, + alo: 1003, + alp: 1004, + alq: 1005, + alr: 1006, + als: 1007, + alt: 1008, + alu: 1009, + alv: 1010, + alw: 1011, + alx: 1012, + aly: 1013, + amz: 1014, + ama: 1015, + amb: 1016, + amc: 1017, + amd: 1018, + ame: 1019, + amf: 1020, + amg: 1021, + amh: 1022, + ami: 1023, + amj: 1024, + amk: 1025, + aml: 1026, + amm: 1027, + amn: 1028, + amo: 1029, + amp: 1030, + amq: 1031, + amr: 1032, + ams: 1033, + amt: 1034, + amu: 1035, + amv: 1036, + amw: 1037, + amx: 1038, + amy: 1039, + anz: 1040, + ana: 1041, + anb: 1042, + anc: 1043, + and: 1044, + ane: 1045, + anf: 1046, + ang: 1047, + anh: 1048, + ani: 1049, + anj: 1050, + ank: 1051, + anl: 1052, + anm: 1053, + ann: 1054, + ano: 1055, + anp: 1056, + anq: 1057, + anr: 1058, + ans: 1059, + ant: 1060, + anu: 1061, + anv: 1062, + anw: 1063, + anx: 1064, + any: 1065, + aoz: 1066, + aoa: 1067, + aob: 1068, + aoc: 1069, + aod: 1070, + aoe: 1071, + aof: 1072, + aog: 1073, + aoh: 1074, + aoi: 1075, + aoj: 1076, + aok: 1077, + aol: 1078, + aom: 1079, + aon: 1080, + aoo: 1081, + aop: 1082, + aoq: 1083, + aor: 1084, + aos: 1085, + aot: 1086, + aou: 1087, + aov: 1088, + aow: 1089, + aox: 1090, + aoy: 1091, + apz: 1092, + apa: 1093, + apb: 1094, + apc: 1095, + apd: 1096, + ape: 1097, + apf: 1098, + apg: 1099, + aph: 1100, + api: 1101, + apj: 1102, + apk: 1103, + apl: 1104, + apm: 1105, + apn: 1106, + apo: 1107, + app: 1108, + apq: 1109, + apr: 1110, + aps: 1111, + apt: 1112, + apu: 1113, + apv: 1114, + apw: 1115, + apx: 1116, + apy: 1117, + aqz: 1118, + aqa: 1119, + aqb: 1120, + aqc: 1121, + aqd: 1122, + aqe: 1123, + aqf: 1124, + aqg: 1125, + aqh: 1126, + aqi: 1127, + aqj: 1128, + aqk: 1129, + aql: 1130, + aqm: 1131, + aqn: 1132, + aqo: 1133, + aqp: 1134, + aqq: 1135, + aqr: 1136, + aqs: 1137, + aqt: 1138, + aqu: 1139, + aqv: 1140, + aqw: 1141, + aqx: 1142, + aqy: 1143, + arz: 1144, + ara: 1145, + arb: 1146, + arc: 1147, + ard: 1148, + are: 1149, + arf: 1150, + arg: 1151, + arh: 1152, + ari: 1153, + arj: 1154, + ark: 1155, + arl: 1156, + arm: 1157, + arn: 1158, + aro: 1159, + arp: 1160, + arq: 1161, + arr: 1162, + ars: 1163, + art: 1164, + aru: 1165, + arv: 1166, + arw: 1167, + arx: 1168, + ary: 1169, + asz: 1170, + asa: 1171, + asb: 1172, + asc: 1173, + asd: 1174, + ase: 1175, + asf: 1176, + asg: 1177, + ash: 1178, + asi: 1179, + asj: 1180, + ask: 1181, + asl: 1182, + asm: 1183, + asn: 1184, + aso: 1185, + asp: 1186, + asq: 1187, + asr: 1188, + ass: 1189, + ast: 1190, + asu: 1191, + asv: 1192, + asw: 1193, + asx: 1194, + asy: 1195, + atz: 1196, + ata: 1197, + atb: 1198, + atc: 1199, + atd: 1200, + ate: 1201, + atf: 1202, + atg: 1203, + ath: 1204, + ati: 1205, + atj: 1206, + atk: 1207, + atl: 1208, + atm: 1209, + atn: 1210, + ato: 1211, + atp: 1212, + atq: 1213, + atr: 1214, + ats: 1215, + att: 1216, + atu: 1217, + atv: 1218, + atw: 1219, + atx: 1220, + aty: 1221, + auz: 1222, + aua: 1223, + aub: 1224, + auc: 1225, + aud: 1226, + aue: 1227, + auf: 1228, + aug: 1229, + auh: 1230, + aui: 1231, + auj: 1232, + auk: 1233, + aul: 1234, + aum: 1235, + aun: 1236, + auo: 1237, + aup: 1238, + auq: 1239, + aur: 1240, + aus: 1241, + aut: 1242, + auu: 1243, + auv: 1244, + auw: 1245, + aux: 1246, + auy: 1247, + avz: 1248, + ava: 1249, + avb: 1250, + avc: 1251, + avd: 1252, + ave: 1253, + avf: 1254, + avg: 1255, + avh: 1256, + avi: 1257, + avj: 1258, + avk: 1259, + avl: 1260, + avm: 1261, + avn: 1262, + avo: 1263, + avp: 1264, + avq: 1265, + avr: 1266, + avs: 1267, + avt: 1268, + avu: 1269, + avv: 1270, + avw: 1271, + avx: 1272, + avy: 1273, + awz: 1274, + awa: 1275, + awb: 1276, + awc: 1277, + awd: 1278, + awe: 1279, + awf: 1280, + awg: 1281, + awh: 1282, + awi: 1283, + awj: 1284, + awk: 1285, + awl: 1286, + awm: 1287, + awn: 1288, + awo: 1289, + awp: 1290, + awq: 1291, + awr: 1292, + aws: 1293, + awt: 1294, + awu: 1295, + awv: 1296, + aww: 1297, + awx: 1298, + awy: 1299, + axz: 1300, + axa: 1301, + axb: 1302, + axc: 1303, + axd: 1304, + axe: 1305, + axf: 1306, + axg: 1307, + axh: 1308, + axi: 1309, + axj: 1310, + axk: 1311, + axl: 1312, + axm: 1313, + axn: 1314, + axo: 1315, + axp: 1316, + axq: 1317, + axr: 1318, + axs: 1319, + axt: 1320, + axu: 1321, + axv: 1322, + axw: 1323, + axx: 1324, + axy: 1325, + ayz: 1326, + aya: 1327, + ayb: 1328, + ayc: 1329, + ayd: 1330, + aye: 1331, + ayf: 1332, + ayg: 1333, + ayh: 1334, + ayi: 1335, + ayj: 1336, + ayk: 1337, + ayl: 1338, + aym: 1339, + ayn: 1340, + ayo: 1341, + ayp: 1342, + ayq: 1343, + ayr: 1344, + ays: 1345, + ayt: 1346, + ayu: 1347, + ayv: 1348, + ayw: 1349, + ayx: 1350, + ayy: 1351, + bzz: 1352, + bza: 1353, + bzb: 1354, + bzc: 1355, + bzd: 1356, + bze: 1357, + bzf: 1358, + bzg: 1359, + bzh: 1360, + bzi: 1361, + bzj: 1362, + bzk: 1363, + bzl: 1364, + bzm: 1365, + bzn: 1366, + bzo: 1367, + bzp: 1368, + bzq: 1369, + bzr: 1370, + bzs: 1371, + bzt: 1372, + bzu: 1373, + bzv: 1374, + bzw: 1375, + bzx: 1376, + bzy: 1377, + baz: 1378, + baa: 1379, + bab: 1380, + bac: 1381, + bad: 1382, + bae: 1383, + baf: 1384, + bag: 1385, + bah: 1386, + bai: 1387, + baj: 1388, + bak: 1389, + bal: 1390, + bam: 1391, + ban: 1392, + bao: 1393, + bap: 1394, + baq: 1395, + bar: 1396, + bas: 1397, + bat: 1398, + bau: 1399, + bav: 1400, + baw: 1401, + bax: 1402, + bay: 1403, + bbz: 1404, + bba: 1405, + bbb: 1406, + bbc: 1407, + bbd: 1408, + bbe: 1409, + bbf: 1410, + bbg: 1411, + bbh: 1412, + bbi: 1413, + bbj: 1414, + bbk: 1415, + bbl: 1416, + bbm: 1417, + bbn: 1418, + bbo: 1419, + bbp: 1420, + bbq: 1421, + bbr: 1422, + bbs: 1423, + bbt: 1424, + bbu: 1425, + bbv: 1426, + bbw: 1427, + bbx: 1428, + bby: 1429, + bcz: 1430, + bca: 1431, + bcb: 1432, + bcc: 1433, + bcd: 1434, + bce: 1435, + bcf: 1436, + bcg: 1437, + bch: 1438, + bci: 1439, + bcj: 1440, + bck: 1441, + bcl: 1442, + bcm: 1443, + bcn: 1444, + bco: 1445, + bcp: 1446, + bcq: 1447, + bcr: 1448, + bcs: 1449, + bct: 1450, + bcu: 1451, + bcv: 1452, + bcw: 1453, + bcx: 1454, + bcy: 1455, + bdz: 1456, + bda: 1457, + bdb: 1458, + bdc: 1459, + bdd: 1460, + bde: 1461, + bdf: 1462, + bdg: 1463, + bdh: 1464, + bdi: 1465, + bdj: 1466, + bdk: 1467, + bdl: 1468, + bdm: 1469, + bdn: 1470, + bdo: 1471, + bdp: 1472, + bdq: 1473, + bdr: 1474, + bds: 1475, + bdt: 1476, + bdu: 1477, + bdv: 1478, + bdw: 1479, + bdx: 1480, + bdy: 1481, + bez: 1482, + bea: 1483, + beb: 1484, + bec: 1485, + bed: 1486, + bee: 1487, + bef: 1488, + beg: 1489, + beh: 1490, + bei: 1491, + bej: 1492, + bek: 1493, + bel: 1494, + bem: 1495, + ben: 1496, + beo: 1497, + bep: 1498, + beq: 1499, + ber: 1500, + bes: 1501, + bet: 1502, + beu: 1503, + bev: 1504, + bew: 1505, + bex: 1506, + bey: 1507, + bfz: 1508, + bfa: 1509, + bfb: 1510, + bfc: 1511, + bfd: 1512, + bfe: 1513, + bff: 1514, + bfg: 1515, + bfh: 1516, + bfi: 1517, + bfj: 1518, + bfk: 1519, + bfl: 1520, + bfm: 1521, + bfn: 1522, + bfo: 1523, + bfp: 1524, + bfq: 1525, + bfr: 1526, + bfs: 1527, + bft: 1528, + bfu: 1529, + bfv: 1530, + bfw: 1531, + bfx: 1532, + bfy: 1533, + bgz: 1534, + bga: 1535, + bgb: 1536, + bgc: 1537, + bgd: 1538, + bge: 1539, + bgf: 1540, + bgg: 1541, + bgh: 1542, + bgi: 1543, + bgj: 1544, + bgk: 1545, + bgl: 1546, + bgm: 1547, + bgn: 1548, + bgo: 1549, + bgp: 1550, + bgq: 1551, + bgr: 1552, + bgs: 1553, + bgt: 1554, + bgu: 1555, + bgv: 1556, + bgw: 1557, + bgx: 1558, + bgy: 1559, + bhz: 1560, + bha: 1561, + bhb: 1562, + bhc: 1563, + bhd: 1564, + bhe: 1565, + bhf: 1566, + bhg: 1567, + bhh: 1568, + bhi: 1569, + bhj: 1570, + bhk: 1571, + bhl: 1572, + bhm: 1573, + bhn: 1574, + bho: 1575, + bhp: 1576, + bhq: 1577, + bhr: 1578, + bhs: 1579, + bht: 1580, + bhu: 1581, + bhv: 1582, + bhw: 1583, + bhx: 1584, + bhy: 1585, + biz: 1586, + bia: 1587, + bib: 1588, + bic: 1589, + bid: 1590, + bie: 1591, + bif: 1592, + big: 1593, + bih: 1594, + bii: 1595, + bij: 1596, + bik: 1597, + bil: 1598, + bim: 1599, + bin: 1600, + bio: 1601, + bip: 1602, + biq: 1603, + bir: 1604, + bis: 1605, + bit: 1606, + biu: 1607, + biv: 1608, + biw: 1609, + bix: 1610, + biy: 1611, + bjz: 1612, + bja: 1613, + bjb: 1614, + bjc: 1615, + bjd: 1616, + bje: 1617, + bjf: 1618, + bjg: 1619, + bjh: 1620, + bji: 1621, + bjj: 1622, + bjk: 1623, + bjl: 1624, + bjm: 1625, + bjn: 1626, + bjo: 1627, + bjp: 1628, + bjq: 1629, + bjr: 1630, + bjs: 1631, + bjt: 1632, + bju: 1633, + bjv: 1634, + bjw: 1635, + bjx: 1636, + bjy: 1637, + bkz: 1638, + bka: 1639, + bkb: 1640, + bkc: 1641, + bkd: 1642, + bke: 1643, + bkf: 1644, + bkg: 1645, + bkh: 1646, + bki: 1647, + bkj: 1648, + bkk: 1649, + bkl: 1650, + bkm: 1651, + bkn: 1652, + bko: 1653, + bkp: 1654, + bkq: 1655, + bkr: 1656, + bks: 1657, + bkt: 1658, + bku: 1659, + bkv: 1660, + bkw: 1661, + bkx: 1662, + bky: 1663, + blz: 1664, + bla: 1665, + blb: 1666, + blc: 1667, + bld: 1668, + ble: 1669, + blf: 1670, + blg: 1671, + blh: 1672, + bli: 1673, + blj: 1674, + blk: 1675, + bll: 1676, + blm: 1677, + bln: 1678, + blo: 1679, + blp: 1680, + blq: 1681, + blr: 1682, + bls: 1683, + blt: 1684, + blu: 1685, + blv: 1686, + blw: 1687, + blx: 1688, + bly: 1689, + bmz: 1690, + bma: 1691, + bmb: 1692, + bmc: 1693, + bmd: 1694, + bme: 1695, + bmf: 1696, + bmg: 1697, + bmh: 1698, + bmi: 1699, + bmj: 1700, + bmk: 1701, + bml: 1702, + bmm: 1703, + bmn: 1704, + bmo: 1705, + bmp: 1706, + bmq: 1707, + bmr: 1708, + bms: 1709, + bmt: 1710, + bmu: 1711, + bmv: 1712, + bmw: 1713, + bmx: 1714, + bmy: 1715, + bnz: 1716, + bna: 1717, + bnb: 1718, + bnc: 1719, + bnd: 1720, + bne: 1721, + bnf: 1722, + bng: 1723, + bnh: 1724, + bni: 1725, + bnj: 1726, + bnk: 1727, + bnl: 1728, + bnm: 1729, + bnn: 1730, + bno: 1731, + bnp: 1732, + bnq: 1733, + bnr: 1734, + bns: 1735, + bnt: 1736, + bnu: 1737, + bnv: 1738, + bnw: 1739, + bnx: 1740, + bny: 1741, + boz: 1742, + boa: 1743, + bob: 1744, + boc: 1745, + bod: 1746, + boe: 1747, + bof: 1748, + bog: 1749, + boh: 1750, + boi: 1751, + boj: 1752, + bok: 1753, + bol: 1754, + bom: 1755, + bon: 1756, + boo: 1757, + bop: 1758, + boq: 1759, + bor: 1760, + bos: 1761, + bot: 1762, + bou: 1763, + bov: 1764, + bow: 1765, + box: 1766, + boy: 1767, + bpz: 1768, + bpa: 1769, + bpb: 1770, + bpc: 1771, + bpd: 1772, + bpe: 1773, + bpf: 1774, + bpg: 1775, + bph: 1776, + bpi: 1777, + bpj: 1778, + bpk: 1779, + bpl: 1780, + bpm: 1781, + bpn: 1782, + bpo: 1783, + bpp: 1784, + bpq: 1785, + bpr: 1786, + bps: 1787, + bpt: 1788, + bpu: 1789, + bpv: 1790, + bpw: 1791, + bpx: 1792, + bpy: 1793, + bqz: 1794, + bqa: 1795, + bqb: 1796, + bqc: 1797, + bqd: 1798, + bqe: 1799, + bqf: 1800, + bqg: 1801, + bqh: 1802, + bqi: 1803, + bqj: 1804, + bqk: 1805, + bql: 1806, + bqm: 1807, + bqn: 1808, + bqo: 1809, + bqp: 1810, + bqq: 1811, + bqr: 1812, + bqs: 1813, + bqt: 1814, + bqu: 1815, + bqv: 1816, + bqw: 1817, + bqx: 1818, + bqy: 1819, + brz: 1820, + bra: 1821, + brb: 1822, + brc: 1823, + brd: 1824, + bre: 1825, + brf: 1826, + brg: 1827, + brh: 1828, + bri: 1829, + brj: 1830, + brk: 1831, + brl: 1832, + brm: 1833, + brn: 1834, + bro: 1835, + brp: 1836, + brq: 1837, + brr: 1838, + brs: 1839, + brt: 1840, + bru: 1841, + brv: 1842, + brw: 1843, + brx: 1844, + bry: 1845, + bsz: 1846, + bsa: 1847, + bsb: 1848, + bsc: 1849, + bsd: 1850, + bse: 1851, + bsf: 1852, + bsg: 1853, + bsh: 1854, + bsi: 1855, + bsj: 1856, + bsk: 1857, + bsl: 1858, + bsm: 1859, + bsn: 1860, + bso: 1861, + bsp: 1862, + bsq: 1863, + bsr: 1864, + bss: 1865, + bst: 1866, + bsu: 1867, + bsv: 1868, + bsw: 1869, + bsx: 1870, + bsy: 1871, + btz: 1872, + bta: 1873, + btb: 1874, + btc: 1875, + btd: 1876, + bte: 1877, + btf: 1878, + btg: 1879, + bth: 1880, + bti: 1881, + btj: 1882, + btk: 1883, + btl: 1884, + btm: 1885, + btn: 1886, + bto: 1887, + btp: 1888, + btq: 1889, + btr: 1890, + bts: 1891, + btt: 1892, + btu: 1893, + btv: 1894, + btw: 1895, + btx: 1896, + bty: 1897, + buz: 1898, + bua: 1899, + bub: 1900, + buc: 1901, + bud: 1902, + bue: 1903, + buf: 1904, + bug: 1905, + buh: 1906, + bui: 1907, + buj: 1908, + buk: 1909, + bul: 1910, + bum: 1911, + bun: 1912, + buo: 1913, + bup: 1914, + buq: 1915, + bur: 1916, + bus: 1917, + but: 1918, + buu: 1919, + buv: 1920, + buw: 1921, + bux: 1922, + buy: 1923, + bvz: 1924, + bva: 1925, + bvb: 1926, + bvc: 1927, + bvd: 1928, + bve: 1929, + bvf: 1930, + bvg: 1931, + bvh: 1932, + bvi: 1933, + bvj: 1934, + bvk: 1935, + bvl: 1936, + bvm: 1937, + bvn: 1938, + bvo: 1939, + bvp: 1940, + bvq: 1941, + bvr: 1942, + bvs: 1943, + bvt: 1944, + bvu: 1945, + bvv: 1946, + bvw: 1947, + bvx: 1948, + bvy: 1949, + bwz: 1950, + bwa: 1951, + bwb: 1952, + bwc: 1953, + bwd: 1954, + bwe: 1955, + bwf: 1956, + bwg: 1957, + bwh: 1958, + bwi: 1959, + bwj: 1960, + bwk: 1961, + bwl: 1962, + bwm: 1963, + bwn: 1964, + bwo: 1965, + bwp: 1966, + bwq: 1967, + bwr: 1968, + bws: 1969, + bwt: 1970, + bwu: 1971, + bwv: 1972, + bww: 1973, + bwx: 1974, + bwy: 1975, + bxz: 1976, + bxa: 1977, + bxb: 1978, + bxc: 1979, + bxd: 1980, + bxe: 1981, + bxf: 1982, + bxg: 1983, + bxh: 1984, + bxi: 1985, + bxj: 1986, + bxk: 1987, + bxl: 1988, + bxm: 1989, + bxn: 1990, + bxo: 1991, + bxp: 1992, + bxq: 1993, + bxr: 1994, + bxs: 1995, + bxt: 1996, + bxu: 1997, + bxv: 1998, + bxw: 1999, + bxx: 2000, + bxy: 2001, + byz: 2002, + bya: 2003, + byb: 2004, + byc: 2005, + byd: 2006, + bye: 2007, + byf: 2008, + byg: 2009, + byh: 2010, + byi: 2011, + byj: 2012, + byk: 2013, + byl: 2014, + bym: 2015, + byn: 2016, + byo: 2017, + byp: 2018, + byq: 2019, + byr: 2020, + bys: 2021, + byt: 2022, + byu: 2023, + byv: 2024, + byw: 2025, + byx: 2026, + byy: 2027, + czz: 2028, + cza: 2029, + czb: 2030, + czc: 2031, + czd: 2032, + cze: 2033, + czf: 2034, + czg: 2035, + czh: 2036, + czi: 2037, + czj: 2038, + czk: 2039, + czl: 2040, + czm: 2041, + czn: 2042, + czo: 2043, + czp: 2044, + czq: 2045, + czr: 2046, + czs: 2047, + czt: 2048, + czu: 2049, + czv: 2050, + czw: 2051, + czx: 2052, + czy: 2053, + caz: 2054, + caa: 2055, + cab: 2056, + cac: 2057, + cad: 2058, + cae: 2059, + caf: 2060, + cag: 2061, + cah: 2062, + cai: 2063, + caj: 2064, + cak: 2065, + cal: 2066, + cam: 2067, + can: 2068, + cao: 2069, + cap: 2070, + caq: 2071, + car: 2072, + cas: 2073, + cat: 2074, + cau: 2075, + cav: 2076, + caw: 2077, + cax: 2078, + cay: 2079, + cbz: 2080, + cba: 2081, + cbb: 2082, + cbc: 2083, + cbd: 2084, + cbe: 2085, + cbf: 2086, + cbg: 2087, + cbh: 2088, + cbi: 2089, + cbj: 2090, + cbk: 2091, + cbl: 2092, + cbm: 2093, + cbn: 2094, + cbo: 2095, + cbp: 2096, + cbq: 2097, + cbr: 2098, + cbs: 2099, + cbt: 2100, + cbu: 2101, + cbv: 2102, + cbw: 2103, + cbx: 2104, + cby: 2105, + ccz: 2106, + cca: 2107, + ccb: 2108, + ccc: 2109, + ccd: 2110, + cce: 2111, + ccf: 2112, + ccg: 2113, + cch: 2114, + cci: 2115, + ccj: 2116, + cck: 2117, + ccl: 2118, + ccm: 2119, + ccn: 2120, + cco: 2121, + ccp: 2122, + ccq: 2123, + ccr: 2124, + ccs: 2125, + cct: 2126, + ccu: 2127, + ccv: 2128, + ccw: 2129, + ccx: 2130, + ccy: 2131, + cdz: 2132, + cda: 2133, + cdb: 2134, + cdc: 2135, + cdd: 2136, + cde: 2137, + cdf: 2138, + cdg: 2139, + cdh: 2140, + cdi: 2141, + cdj: 2142, + cdk: 2143, + cdl: 2144, + cdm: 2145, + cdn: 2146, + cdo: 2147, + cdp: 2148, + cdq: 2149, + cdr: 2150, + cds: 2151, + cdt: 2152, + cdu: 2153, + cdv: 2154, + cdw: 2155, + cdx: 2156, + cdy: 2157, + cez: 2158, + cea: 2159, + ceb: 2160, + cec: 2161, + ced: 2162, + cee: 2163, + cef: 2164, + ceg: 2165, + ceh: 2166, + cei: 2167, + cej: 2168, + cek: 2169, + cel: 2170, + cem: 2171, + cen: 2172, + ceo: 2173, + cep: 2174, + ceq: 2175, + cer: 2176, + ces: 2177, + cet: 2178, + ceu: 2179, + cev: 2180, + cew: 2181, + cex: 2182, + cey: 2183, + cfz: 2184, + cfa: 2185, + cfb: 2186, + cfc: 2187, + cfd: 2188, + cfe: 2189, + cff: 2190, + cfg: 2191, + cfh: 2192, + cfi: 2193, + cfj: 2194, + cfk: 2195, + cfl: 2196, + cfm: 2197, + cfn: 2198, + cfo: 2199, + cfp: 2200, + cfq: 2201, + cfr: 2202, + cfs: 2203, + cft: 2204, + cfu: 2205, + cfv: 2206, + cfw: 2207, + cfx: 2208, + cfy: 2209, + cgz: 2210, + cga: 2211, + cgb: 2212, + cgc: 2213, + cgd: 2214, + cge: 2215, + cgf: 2216, + cgg: 2217, + cgh: 2218, + cgi: 2219, + cgj: 2220, + cgk: 2221, + cgl: 2222, + cgm: 2223, + cgn: 2224, + cgo: 2225, + cgp: 2226, + cgq: 2227, + cgr: 2228, + cgs: 2229, + cgt: 2230, + cgu: 2231, + cgv: 2232, + cgw: 2233, + cgx: 2234, + cgy: 2235, + chz: 2236, + cha: 2237, + chb: 2238, + chc: 2239, + chd: 2240, + che: 2241, + chf: 2242, + chg: 2243, + chh: 2244, + chi: 2245, + chj: 2246, + chk: 2247, + chl: 2248, + chm: 2249, + chn: 2250, + cho: 2251, + chp: 2252, + chq: 2253, + chr: 2254, + chs: 2255, + cht: 2256, + chu: 2257, + chv: 2258, + chw: 2259, + chx: 2260, + chy: 2261, + ciz: 2262, + cia: 2263, + cib: 2264, + cic: 2265, + cid: 2266, + cie: 2267, + cif: 2268, + cig: 2269, + cih: 2270, + cii: 2271, + cij: 2272, + cik: 2273, + cil: 2274, + cim: 2275, + cin: 2276, + cio: 2277, + cip: 2278, + ciq: 2279, + cir: 2280, + cis: 2281, + cit: 2282, + ciu: 2283, + civ: 2284, + ciw: 2285, + cix: 2286, + ciy: 2287, + cjz: 2288, + cja: 2289, + cjb: 2290, + cjc: 2291, + cjd: 2292, + cje: 2293, + cjf: 2294, + cjg: 2295, + cjh: 2296, + cji: 2297, + cjj: 2298, + cjk: 2299, + cjl: 2300, + cjm: 2301, + cjn: 2302, + cjo: 2303, + cjp: 2304, + cjq: 2305, + cjr: 2306, + cjs: 2307, + cjt: 2308, + cju: 2309, + cjv: 2310, + cjw: 2311, + cjx: 2312, + cjy: 2313, + ckz: 2314, + cka: 2315, + ckb: 2316, + ckc: 2317, + ckd: 2318, + cke: 2319, + ckf: 2320, + ckg: 2321, + ckh: 2322, + cki: 2323, + ckj: 2324, + ckk: 2325, + ckl: 2326, + ckm: 2327, + ckn: 2328, + cko: 2329, + ckp: 2330, + ckq: 2331, + ckr: 2332, + cks: 2333, + ckt: 2334, + cku: 2335, + ckv: 2336, + ckw: 2337, + ckx: 2338, + cky: 2339, + clz: 2340, + cla: 2341, + clb: 2342, + clc: 2343, + cld: 2344, + cle: 2345, + clf: 2346, + clg: 2347, + clh: 2348, + cli: 2349, + clj: 2350, + clk: 2351, + cll: 2352, + clm: 2353, + cln: 2354, + clo: 2355, + clp: 2356, + clq: 2357, + clr: 2358, + cls: 2359, + clt: 2360, + clu: 2361, + clv: 2362, + clw: 2363, + clx: 2364, + cly: 2365, + cmz: 2366, + cma: 2367, + cmb: 2368, + cmc: 2369, + cmd: 2370, + cme: 2371, + cmf: 2372, + cmg: 2373, + cmh: 2374, + cmi: 2375, + cmj: 2376, + cmk: 2377, + cml: 2378, + cmm: 2379, + cmn: 2380, + cmo: 2381, + cmp: 2382, + cmq: 2383, + cmr: 2384, + cms: 2385, + cmt: 2386, + cmu: 2387, + cmv: 2388, + cmw: 2389, + cmx: 2390, + cmy: 2391, + cnz: 2392, + cna: 2393, + cnb: 2394, + cnc: 2395, + cnd: 2396, + cne: 2397, + cnf: 2398, + cng: 2399, + cnh: 2400, + cni: 2401, + cnj: 2402, + cnk: 2403, + cnl: 2404, + cnm: 2405, + cnn: 2406, + cno: 2407, + cnp: 2408, + cnq: 2409, + cnr: 2410, + cns: 2411, + cnt: 2412, + cnu: 2413, + cnv: 2414, + cnw: 2415, + cnx: 2416, + cny: 2417, + coz: 2418, + coa: 2419, + cob: 2420, + coc: 2421, + cod: 2422, + coe: 2423, + cof: 2424, + cog: 2425, + coh: 2426, + coi: 2427, + coj: 2428, + cok: 2429, + col: 2430, + com: 2431, + con: 2432, + coo: 2433, + cop: 2434, + coq: 2435, + cor: 2436, + cos: 2437, + cot: 2438, + cou: 2439, + cov: 2440, + cow: 2441, + cox: 2442, + coy: 2443, + cpz: 2444, + cpa: 2445, + cpb: 2446, + cpc: 2447, + cpd: 2448, + cpe: 2449, + cpf: 2450, + cpg: 2451, + cph: 2452, + cpi: 2453, + cpj: 2454, + cpk: 2455, + cpl: 2456, + cpm: 2457, + cpn: 2458, + cpo: 2459, + cpp: 2460, + cpq: 2461, + cpr: 2462, + cps: 2463, + cpt: 2464, + cpu: 2465, + cpv: 2466, + cpw: 2467, + cpx: 2468, + cpy: 2469, + cqz: 2470, + cqa: 2471, + cqb: 2472, + cqc: 2473, + cqd: 2474, + cqe: 2475, + cqf: 2476, + cqg: 2477, + cqh: 2478, + cqi: 2479, + cqj: 2480, + cqk: 2481, + cql: 2482, + cqm: 2483, + cqn: 2484, + cqo: 2485, + cqp: 2486, + cqq: 2487, + cqr: 2488, + cqs: 2489, + cqt: 2490, + cqu: 2491, + cqv: 2492, + cqw: 2493, + cqx: 2494, + cqy: 2495, + crz: 2496, + cra: 2497, + crb: 2498, + crc: 2499, + crd: 2500, + cre: 2501, + crf: 2502, + crg: 2503, + crh: 2504, + cri: 2505, + crj: 2506, + crk: 2507, + crl: 2508, + crm: 2509, + crn: 2510, + cro: 2511, + crp: 2512, + crq: 2513, + crr: 2514, + crs: 2515, + crt: 2516, + cru: 2517, + crv: 2518, + crw: 2519, + crx: 2520, + cry: 2521, + csz: 2522, + csa: 2523, + csb: 2524, + csc: 2525, + csd: 2526, + cse: 2527, + csf: 2528, + csg: 2529, + csh: 2530, + csi: 2531, + csj: 2532, + csk: 2533, + csl: 2534, + csm: 2535, + csn: 2536, + cso: 2537, + csp: 2538, + csq: 2539, + csr: 2540, + css: 2541, + cst: 2542, + csu: 2543, + csv: 2544, + csw: 2545, + csx: 2546, + csy: 2547, + ctz: 2548, + cta: 2549, + ctb: 2550, + ctc: 2551, + ctd: 2552, + cte: 2553, + ctf: 2554, + ctg: 2555, + cth: 2556, + cti: 2557, + ctj: 2558, + ctk: 2559, + ctl: 2560, + ctm: 2561, + ctn: 2562, + cto: 2563, + ctp: 2564, + ctq: 2565, + ctr: 2566, + cts: 2567, + ctt: 2568, + ctu: 2569, + ctv: 2570, + ctw: 2571, + ctx: 2572, + cty: 2573, + cuz: 2574, + cua: 2575, + cub: 2576, + cuc: 2577, + cud: 2578, + cue: 2579, + cuf: 2580, + cug: 2581, + cuh: 2582, + cui: 2583, + cuj: 2584, + cuk: 2585, + cul: 2586, + cum: 2587, + cun: 2588, + cuo: 2589, + cup: 2590, + cuq: 2591, + cur: 2592, + cus: 2593, + cut: 2594, + cuu: 2595, + cuv: 2596, + cuw: 2597, + cux: 2598, + cuy: 2599, + cvz: 2600, + cva: 2601, + cvb: 2602, + cvc: 2603, + cvd: 2604, + cve: 2605, + cvf: 2606, + cvg: 2607, + cvh: 2608, + cvi: 2609, + cvj: 2610, + cvk: 2611, + cvl: 2612, + cvm: 2613, + cvn: 2614, + cvo: 2615, + cvp: 2616, + cvq: 2617, + cvr: 2618, + cvs: 2619, + cvt: 2620, + cvu: 2621, + cvv: 2622, + cvw: 2623, + cvx: 2624, + cvy: 2625, + cwz: 2626, + cwa: 2627, + cwb: 2628, + cwc: 2629, + cwd: 2630, + cwe: 2631, + cwf: 2632, + cwg: 2633, + cwh: 2634, + cwi: 2635, + cwj: 2636, + cwk: 2637, + cwl: 2638, + cwm: 2639, + cwn: 2640, + cwo: 2641, + cwp: 2642, + cwq: 2643, + cwr: 2644, + cws: 2645, + cwt: 2646, + cwu: 2647, + cwv: 2648, + cww: 2649, + cwx: 2650, + cwy: 2651, + cxz: 2652, + cxa: 2653, + cxb: 2654, + cxc: 2655, + cxd: 2656, + cxe: 2657, + cxf: 2658, + cxg: 2659, + cxh: 2660, + cxi: 2661, + cxj: 2662, + cxk: 2663, + cxl: 2664, + cxm: 2665, + cxn: 2666, + cxo: 2667, + cxp: 2668, + cxq: 2669, + cxr: 2670, + cxs: 2671, + cxt: 2672, + cxu: 2673, + cxv: 2674, + cxw: 2675, + cxx: 2676, + cxy: 2677, + cyz: 2678, + cya: 2679, + cyb: 2680, + cyc: 2681, + cyd: 2682, + cye: 2683, + cyf: 2684, + cyg: 2685, + cyh: 2686, + cyi: 2687, + cyj: 2688, + cyk: 2689, + cyl: 2690, + cym: 2691, + cyn: 2692, + cyo: 2693, + cyp: 2694, + cyq: 2695, + cyr: 2696, + cys: 2697, + cyt: 2698, + cyu: 2699, + cyv: 2700, + cyw: 2701, + cyx: 2702, + cyy: 2703, + dzz: 2704, + dza: 2705, + dzb: 2706, + dzc: 2707, + dzd: 2708, + dze: 2709, + dzf: 2710, + dzg: 2711, + dzh: 2712, + dzi: 2713, + dzj: 2714, + dzk: 2715, + dzl: 2716, + dzm: 2717, + dzn: 2718, + dzo: 2719, + dzp: 2720, + dzq: 2721, + dzr: 2722, + dzs: 2723, + dzt: 2724, + dzu: 2725, + dzv: 2726, + dzw: 2727, + dzx: 2728, + dzy: 2729, + daz: 2730, + daa: 2731, + dab: 2732, + dac: 2733, + dad: 2734, + dae: 2735, + daf: 2736, + dag: 2737, + dah: 2738, + dai: 2739, + daj: 2740, + dak: 2741, + dal: 2742, + dam: 2743, + dan: 2744, + dao: 2745, + dap: 2746, + daq: 2747, + dar: 2748, + das: 2749, + dat: 2750, + dau: 2751, + dav: 2752, + daw: 2753, + dax: 2754, + day: 2755, + dbz: 2756, + dba: 2757, + dbb: 2758, + dbc: 2759, + dbd: 2760, + dbe: 2761, + dbf: 2762, + dbg: 2763, + dbh: 2764, + dbi: 2765, + dbj: 2766, + dbk: 2767, + dbl: 2768, + dbm: 2769, + dbn: 2770, + dbo: 2771, + dbp: 2772, + dbq: 2773, + dbr: 2774, + dbs: 2775, + dbt: 2776, + dbu: 2777, + dbv: 2778, + dbw: 2779, + dbx: 2780, + dby: 2781, + dcz: 2782, + dca: 2783, + dcb: 2784, + dcc: 2785, + dcd: 2786, + dce: 2787, + dcf: 2788, + dcg: 2789, + dch: 2790, + dci: 2791, + dcj: 2792, + dck: 2793, + dcl: 2794, + dcm: 2795, + dcn: 2796, + dco: 2797, + dcp: 2798, + dcq: 2799, + dcr: 2800, + dcs: 2801, + dct: 2802, + dcu: 2803, + dcv: 2804, + dcw: 2805, + dcx: 2806, + dcy: 2807, + ddz: 2808, + dda: 2809, + ddb: 2810, + ddc: 2811, + ddd: 2812, + dde: 2813, + ddf: 2814, + ddg: 2815, + ddh: 2816, + ddi: 2817, + ddj: 2818, + ddk: 2819, + ddl: 2820, + ddm: 2821, + ddn: 2822, + ddo: 2823, + ddp: 2824, + ddq: 2825, + ddr: 2826, + dds: 2827, + ddt: 2828, + ddu: 2829, + ddv: 2830, + ddw: 2831, + ddx: 2832, + ddy: 2833, + dez: 2834, + dea: 2835, + deb: 2836, + dec: 2837, + ded: 2838, + dee: 2839, + def: 2840, + deg: 2841, + deh: 2842, + dei: 2843, + dej: 2844, + dek: 2845, + del: 2846, + dem: 2847, + den: 2848, + deo: 2849, + dep: 2850, + deq: 2851, + der: 2852, + des: 2853, + det: 2854, + deu: 2855, + dev: 2856, + dew: 2857, + dex: 2858, + dey: 2859, + dfz: 2860, + dfa: 2861, + dfb: 2862, + dfc: 2863, + dfd: 2864, + dfe: 2865, + dff: 2866, + dfg: 2867, + dfh: 2868, + dfi: 2869, + dfj: 2870, + dfk: 2871, + dfl: 2872, + dfm: 2873, + dfn: 2874, + dfo: 2875, + dfp: 2876, + dfq: 2877, + dfr: 2878, + dfs: 2879, + dft: 2880, + dfu: 2881, + dfv: 2882, + dfw: 2883, + dfx: 2884, + dfy: 2885, + dgz: 2886, + dga: 2887, + dgb: 2888, + dgc: 2889, + dgd: 2890, + dge: 2891, + dgf: 2892, + dgg: 2893, + dgh: 2894, + dgi: 2895, + dgj: 2896, + dgk: 2897, + dgl: 2898, + dgm: 2899, + dgn: 2900, + dgo: 2901, + dgp: 2902, + dgq: 2903, + dgr: 2904, + dgs: 2905, + dgt: 2906, + dgu: 2907, + dgv: 2908, + dgw: 2909, + dgx: 2910, + dgy: 2911, + dhz: 2912, + dha: 2913, + dhb: 2914, + dhc: 2915, + dhd: 2916, + dhe: 2917, + dhf: 2918, + dhg: 2919, + dhh: 2920, + dhi: 2921, + dhj: 2922, + dhk: 2923, + dhl: 2924, + dhm: 2925, + dhn: 2926, + dho: 2927, + dhp: 2928, + dhq: 2929, + dhr: 2930, + dhs: 2931, + dht: 2932, + dhu: 2933, + dhv: 2934, + dhw: 2935, + dhx: 2936, + dhy: 2937, + diz: 2938, + dia: 2939, + dib: 2940, + dic: 2941, + did: 2942, + die: 2943, + dif: 2944, + dig: 2945, + dih: 2946, + dii: 2947, + dij: 2948, + dik: 2949, + dil: 2950, + dim: 2951, + din: 2952, + dio: 2953, + dip: 2954, + diq: 2955, + dir: 2956, + dis: 2957, + dit: 2958, + diu: 2959, + div: 2960, + diw: 2961, + dix: 2962, + diy: 2963, + djz: 2964, + dja: 2965, + djb: 2966, + djc: 2967, + djd: 2968, + dje: 2969, + djf: 2970, + djg: 2971, + djh: 2972, + dji: 2973, + djj: 2974, + djk: 2975, + djl: 2976, + djm: 2977, + djn: 2978, + djo: 2979, + djp: 2980, + djq: 2981, + djr: 2982, + djs: 2983, + djt: 2984, + dju: 2985, + djv: 2986, + djw: 2987, + djx: 2988, + djy: 2989, + dkz: 2990, + dka: 2991, + dkb: 2992, + dkc: 2993, + dkd: 2994, + dke: 2995, + dkf: 2996, + dkg: 2997, + dkh: 2998, + dki: 2999, + dkj: 3000, + dkk: 3001, + dkl: 3002, + dkm: 3003, + dkn: 3004, + dko: 3005, + dkp: 3006, + dkq: 3007, + dkr: 3008, + dks: 3009, + dkt: 3010, + dku: 3011, + dkv: 3012, + dkw: 3013, + dkx: 3014, + dky: 3015, + dlz: 3016, + dla: 3017, + dlb: 3018, + dlc: 3019, + dld: 3020, + dle: 3021, + dlf: 3022, + dlg: 3023, + dlh: 3024, + dli: 3025, + dlj: 3026, + dlk: 3027, + dll: 3028, + dlm: 3029, + dln: 3030, + dlo: 3031, + dlp: 3032, + dlq: 3033, + dlr: 3034, + dls: 3035, + dlt: 3036, + dlu: 3037, + dlv: 3038, + dlw: 3039, + dlx: 3040, + dly: 3041, + dmz: 3042, + dma: 3043, + dmb: 3044, + dmc: 3045, + dmd: 3046, + dme: 3047, + dmf: 3048, + dmg: 3049, + dmh: 3050, + dmi: 3051, + dmj: 3052, + dmk: 3053, + dml: 3054, + dmm: 3055, + dmn: 3056, + dmo: 3057, + dmp: 3058, + dmq: 3059, + dmr: 3060, + dms: 3061, + dmt: 3062, + dmu: 3063, + dmv: 3064, + dmw: 3065, + dmx: 3066, + dmy: 3067, + dnz: 3068, + dna: 3069, + dnb: 3070, + dnc: 3071, + dnd: 3072, + dne: 3073, + dnf: 3074, + dng: 3075, + dnh: 3076, + dni: 3077, + dnj: 3078, + dnk: 3079, + dnl: 3080, + dnm: 3081, + dnn: 3082, + dno: 3083, + dnp: 3084, + dnq: 3085, + dnr: 3086, + dns: 3087, + dnt: 3088, + dnu: 3089, + dnv: 3090, + dnw: 3091, + dnx: 3092, + dny: 3093, + doz: 3094, + doa: 3095, + dob: 3096, + doc: 3097, + dod: 3098, + doe: 3099, + dof: 3100, + dog: 3101, + doh: 3102, + doi: 3103, + doj: 3104, + dok: 3105, + dol: 3106, + dom: 3107, + don: 3108, + doo: 3109, + dop: 3110, + doq: 3111, + dor: 3112, + dos: 3113, + dot: 3114, + dou: 3115, + dov: 3116, + dow: 3117, + dox: 3118, + doy: 3119, + dpz: 3120, + dpa: 3121, + dpb: 3122, + dpc: 3123, + dpd: 3124, + dpe: 3125, + dpf: 3126, + dpg: 3127, + dph: 3128, + dpi: 3129, + dpj: 3130, + dpk: 3131, + dpl: 3132, + dpm: 3133, + dpn: 3134, + dpo: 3135, + dpp: 3136, + dpq: 3137, + dpr: 3138, + dps: 3139, + dpt: 3140, + dpu: 3141, + dpv: 3142, + dpw: 3143, + dpx: 3144, + dpy: 3145, + dqz: 3146, + dqa: 3147, + dqb: 3148, + dqc: 3149, + dqd: 3150, + dqe: 3151, + dqf: 3152, + dqg: 3153, + dqh: 3154, + dqi: 3155, + dqj: 3156, + dqk: 3157, + dql: 3158, + dqm: 3159, + dqn: 3160, + dqo: 3161, + dqp: 3162, + dqq: 3163, + dqr: 3164, + dqs: 3165, + dqt: 3166, + dqu: 3167, + dqv: 3168, + dqw: 3169, + dqx: 3170, + dqy: 3171, + drz: 3172, + dra: 3173, + drb: 3174, + drc: 3175, + drd: 3176, + dre: 3177, + drf: 3178, + drg: 3179, + drh: 3180, + dri: 3181, + drj: 3182, + drk: 3183, + drl: 3184, + drm: 3185, + drn: 3186, + dro: 3187, + drp: 3188, + drq: 3189, + drr: 3190, + drs: 3191, + drt: 3192, + dru: 3193, + drv: 3194, + drw: 3195, + drx: 3196, + dry: 3197, + dsz: 3198, + dsa: 3199, + dsb: 3200, + dsc: 3201, + dsd: 3202, + dse: 3203, + dsf: 3204, + dsg: 3205, + dsh: 3206, + dsi: 3207, + dsj: 3208, + dsk: 3209, + dsl: 3210, + dsm: 3211, + dsn: 3212, + dso: 3213, + dsp: 3214, + dsq: 3215, + dsr: 3216, + dss: 3217, + dst: 3218, + dsu: 3219, + dsv: 3220, + dsw: 3221, + dsx: 3222, + dsy: 3223, + dtz: 3224, + dta: 3225, + dtb: 3226, + dtc: 3227, + dtd: 3228, + dte: 3229, + dtf: 3230, + dtg: 3231, + dth: 3232, + dti: 3233, + dtj: 3234, + dtk: 3235, + dtl: 3236, + dtm: 3237, + dtn: 3238, + dto: 3239, + dtp: 3240, + dtq: 3241, + dtr: 3242, + dts: 3243, + dtt: 3244, + dtu: 3245, + dtv: 3246, + dtw: 3247, + dtx: 3248, + dty: 3249, + duz: 3250, + dua: 3251, + dub: 3252, + duc: 3253, + dud: 3254, + due: 3255, + duf: 3256, + dug: 3257, + duh: 3258, + dui: 3259, + duj: 3260, + duk: 3261, + dul: 3262, + dum: 3263, + dun: 3264, + duo: 3265, + dup: 3266, + duq: 3267, + dur: 3268, + dus: 3269, + dut: 3270, + duu: 3271, + duv: 3272, + duw: 3273, + dux: 3274, + duy: 3275, + dvz: 3276, + dva: 3277, + dvb: 3278, + dvc: 3279, + dvd: 3280, + dve: 3281, + dvf: 3282, + dvg: 3283, + dvh: 3284, + dvi: 3285, + dvj: 3286, + dvk: 3287, + dvl: 3288, + dvm: 3289, + dvn: 3290, + dvo: 3291, + dvp: 3292, + dvq: 3293, + dvr: 3294, + dvs: 3295, + dvt: 3296, + dvu: 3297, + dvv: 3298, + dvw: 3299, + dvx: 3300, + dvy: 3301, + dwz: 3302, + dwa: 3303, + dwb: 3304, + dwc: 3305, + dwd: 3306, + dwe: 3307, + dwf: 3308, + dwg: 3309, + dwh: 3310, + dwi: 3311, + dwj: 3312, + dwk: 3313, + dwl: 3314, + dwm: 3315, + dwn: 3316, + dwo: 3317, + dwp: 3318, + dwq: 3319, + dwr: 3320, + dws: 3321, + dwt: 3322, + dwu: 3323, + dwv: 3324, + dww: 3325, + dwx: 3326, + dwy: 3327, + dxz: 3328, + dxa: 3329, + dxb: 3330, + dxc: 3331, + dxd: 3332, + dxe: 3333, + dxf: 3334, + dxg: 3335, + dxh: 3336, + dxi: 3337, + dxj: 3338, + dxk: 3339, + dxl: 3340, + dxm: 3341, + dxn: 3342, + dxo: 3343, + dxp: 3344, + dxq: 3345, + dxr: 3346, + dxs: 3347, + dxt: 3348, + dxu: 3349, + dxv: 3350, + dxw: 3351, + dxx: 3352, + dxy: 3353, + dyz: 3354, + dya: 3355, + dyb: 3356, + dyc: 3357, + dyd: 3358, + dye: 3359, + dyf: 3360, + dyg: 3361, + dyh: 3362, + dyi: 3363, + dyj: 3364, + dyk: 3365, + dyl: 3366, + dym: 3367, + dyn: 3368, + dyo: 3369, + dyp: 3370, + dyq: 3371, + dyr: 3372, + dys: 3373, + dyt: 3374, + dyu: 3375, + dyv: 3376, + dyw: 3377, + dyx: 3378, + dyy: 3379, + ezz: 3380, + eza: 3381, + ezb: 3382, + ezc: 3383, + ezd: 3384, + eze: 3385, + ezf: 3386, + ezg: 3387, + ezh: 3388, + ezi: 3389, + ezj: 3390, + ezk: 3391, + ezl: 3392, + ezm: 3393, + ezn: 3394, + ezo: 3395, + ezp: 3396, + ezq: 3397, + ezr: 3398, + ezs: 3399, + ezt: 3400, + ezu: 3401, + ezv: 3402, + ezw: 3403, + ezx: 3404, + ezy: 3405, + eaz: 3406, + eaa: 3407, + eab: 3408, + eac: 3409, + ead: 3410, + eae: 3411, + eaf: 3412, + eag: 3413, + eah: 3414, + eai: 3415, + eaj: 3416, + eak: 3417, + eal: 3418, + eam: 3419, + ean: 3420, + eao: 3421, + eap: 3422, + eaq: 3423, + ear: 3424, + eas: 3425, + eat: 3426, + eau: 3427, + eav: 3428, + eaw: 3429, + eax: 3430, + eay: 3431, + ebz: 3432, + eba: 3433, + ebb: 3434, + ebc: 3435, + ebd: 3436, + ebe: 3437, + ebf: 3438, + ebg: 3439, + ebh: 3440, + ebi: 3441, + ebj: 3442, + ebk: 3443, + ebl: 3444, + ebm: 3445, + ebn: 3446, + ebo: 3447, + ebp: 3448, + ebq: 3449, + ebr: 3450, + ebs: 3451, + ebt: 3452, + ebu: 3453, + ebv: 3454, + ebw: 3455, + ebx: 3456, + eby: 3457, + ecz: 3458, + eca: 3459, + ecb: 3460, + ecc: 3461, + ecd: 3462, + ece: 3463, + ecf: 3464, + ecg: 3465, + ech: 3466, + eci: 3467, + ecj: 3468, + eck: 3469, + ecl: 3470, + ecm: 3471, + ecn: 3472, + eco: 3473, + ecp: 3474, + ecq: 3475, + ecr: 3476, + ecs: 3477, + ect: 3478, + ecu: 3479, + ecv: 3480, + ecw: 3481, + ecx: 3482, + ecy: 3483, + edz: 3484, + eda: 3485, + edb: 3486, + edc: 3487, + edd: 3488, + ede: 3489, + edf: 3490, + edg: 3491, + edh: 3492, + edi: 3493, + edj: 3494, + edk: 3495, + edl: 3496, + edm: 3497, + edn: 3498, + edo: 3499, + edp: 3500, + edq: 3501, + edr: 3502, + eds: 3503, + edt: 3504, + edu: 3505, + edv: 3506, + edw: 3507, + edx: 3508, + edy: 3509, + eez: 3510, + eea: 3511, + eeb: 3512, + eec: 3513, + eed: 3514, + eee: 3515, + eef: 3516, + eeg: 3517, + eeh: 3518, + eei: 3519, + eej: 3520, + eek: 3521, + eel: 3522, + eem: 3523, + een: 3524, + eeo: 3525, + eep: 3526, + eeq: 3527, + eer: 3528, + ees: 3529, + eet: 3530, + eeu: 3531, + eev: 3532, + eew: 3533, + eex: 3534, + eey: 3535, + efz: 3536, + efa: 3537, + efb: 3538, + efc: 3539, + efd: 3540, + efe: 3541, + eff: 3542, + efg: 3543, + efh: 3544, + efi: 3545, + efj: 3546, + efk: 3547, + efl: 3548, + efm: 3549, + efn: 3550, + efo: 3551, + efp: 3552, + efq: 3553, + efr: 3554, + efs: 3555, + eft: 3556, + efu: 3557, + efv: 3558, + efw: 3559, + efx: 3560, + efy: 3561, + egz: 3562, + ega: 3563, + egb: 3564, + egc: 3565, + egd: 3566, + ege: 3567, + egf: 3568, + egg: 3569, + egh: 3570, + egi: 3571, + egj: 3572, + egk: 3573, + egl: 3574, + egm: 3575, + egn: 3576, + ego: 3577, + egp: 3578, + egq: 3579, + egr: 3580, + egs: 3581, + egt: 3582, + egu: 3583, + egv: 3584, + egw: 3585, + egx: 3586, + egy: 3587, + ehz: 3588, + eha: 3589, + ehb: 3590, + ehc: 3591, + ehd: 3592, + ehe: 3593, + ehf: 3594, + ehg: 3595, + ehh: 3596, + ehi: 3597, + ehj: 3598, + ehk: 3599, + ehl: 3600, + ehm: 3601, + ehn: 3602, + eho: 3603, + ehp: 3604, + ehq: 3605, + ehr: 3606, + ehs: 3607, + eht: 3608, + ehu: 3609, + ehv: 3610, + ehw: 3611, + ehx: 3612, + ehy: 3613, + eiz: 3614, + eia: 3615, + eib: 3616, + eic: 3617, + eid: 3618, + eie: 3619, + eif: 3620, + eig: 3621, + eih: 3622, + eii: 3623, + eij: 3624, + eik: 3625, + eil: 3626, + eim: 3627, + ein: 3628, + eio: 3629, + eip: 3630, + eiq: 3631, + eir: 3632, + eis: 3633, + eit: 3634, + eiu: 3635, + eiv: 3636, + eiw: 3637, + eix: 3638, + eiy: 3639, + ejz: 3640, + eja: 3641, + ejb: 3642, + ejc: 3643, + ejd: 3644, + eje: 3645, + ejf: 3646, + ejg: 3647, + ejh: 3648, + eji: 3649, + ejj: 3650, + ejk: 3651, + ejl: 3652, + ejm: 3653, + ejn: 3654, + ejo: 3655, + ejp: 3656, + ejq: 3657, + ejr: 3658, + ejs: 3659, + ejt: 3660, + eju: 3661, + ejv: 3662, + ejw: 3663, + ejx: 3664, + ejy: 3665, + ekz: 3666, + eka: 3667, + ekb: 3668, + ekc: 3669, + ekd: 3670, + eke: 3671, + ekf: 3672, + ekg: 3673, + ekh: 3674, + eki: 3675, + ekj: 3676, + ekk: 3677, + ekl: 3678, + ekm: 3679, + ekn: 3680, + eko: 3681, + ekp: 3682, + ekq: 3683, + ekr: 3684, + eks: 3685, + ekt: 3686, + eku: 3687, + ekv: 3688, + ekw: 3689, + ekx: 3690, + eky: 3691, + elz: 3692, + ela: 3693, + elb: 3694, + elc: 3695, + eld: 3696, + ele: 3697, + elf: 3698, + elg: 3699, + elh: 3700, + eli: 3701, + elj: 3702, + elk: 3703, + ell: 3704, + elm: 3705, + eln: 3706, + elo: 3707, + elp: 3708, + elq: 3709, + elr: 3710, + els: 3711, + elt: 3712, + elu: 3713, + elv: 3714, + elw: 3715, + elx: 3716, + ely: 3717, + emz: 3718, + ema: 3719, + emb: 3720, + emc: 3721, + emd: 3722, + eme: 3723, + emf: 3724, + emg: 3725, + emh: 3726, + emi: 3727, + emj: 3728, + emk: 3729, + eml: 3730, + emm: 3731, + emn: 3732, + emo: 3733, + emp: 3734, + emq: 3735, + emr: 3736, + ems: 3737, + emt: 3738, + emu: 3739, + emv: 3740, + emw: 3741, + emx: 3742, + emy: 3743, + enz: 3744, + ena: 3745, + enb: 3746, + enc: 3747, + end: 3748, + ene: 3749, + enf: 3750, + eng: 3751, + enh: 3752, + eni: 3753, + enj: 3754, + enk: 3755, + enl: 3756, + enm: 3757, + enn: 3758, + eno: 3759, + enp: 3760, + enq: 3761, + enr: 3762, + ens: 3763, + ent: 3764, + enu: 3765, + env: 3766, + enw: 3767, + enx: 3768, + eny: 3769, + eoz: 3770, + eoa: 3771, + eob: 3772, + eoc: 3773, + eod: 3774, + eoe: 3775, + eof: 3776, + eog: 3777, + eoh: 3778, + eoi: 3779, + eoj: 3780, + eok: 3781, + eol: 3782, + eom: 3783, + eon: 3784, + eoo: 3785, + eop: 3786, + eoq: 3787, + eor: 3788, + eos: 3789, + eot: 3790, + eou: 3791, + eov: 3792, + eow: 3793, + eox: 3794, + eoy: 3795, + epz: 3796, + epa: 3797, + epb: 3798, + epc: 3799, + epd: 3800, + epe: 3801, + epf: 3802, + epg: 3803, + eph: 3804, + epi: 3805, + epj: 3806, + epk: 3807, + epl: 3808, + epm: 3809, + epn: 3810, + epo: 3811, + epp: 3812, + epq: 3813, + epr: 3814, + eps: 3815, + ept: 3816, + epu: 3817, + epv: 3818, + epw: 3819, + epx: 3820, + epy: 3821, + eqz: 3822, + eqa: 3823, + eqb: 3824, + eqc: 3825, + eqd: 3826, + eqe: 3827, + eqf: 3828, + eqg: 3829, + eqh: 3830, + eqi: 3831, + eqj: 3832, + eqk: 3833, + eql: 3834, + eqm: 3835, + eqn: 3836, + eqo: 3837, + eqp: 3838, + eqq: 3839, + eqr: 3840, + eqs: 3841, + eqt: 3842, + equ: 3843, + eqv: 3844, + eqw: 3845, + eqx: 3846, + eqy: 3847, + erz: 3848, + era: 3849, + erb: 3850, + erc: 3851, + erd: 3852, + ere: 3853, + erf: 3854, + erg: 3855, + erh: 3856, + eri: 3857, + erj: 3858, + erk: 3859, + erl: 3860, + erm: 3861, + ern: 3862, + ero: 3863, + erp: 3864, + erq: 3865, + err: 3866, + ers: 3867, + ert: 3868, + eru: 3869, + erv: 3870, + erw: 3871, + erx: 3872, + ery: 3873, + esz: 3874, + esa: 3875, + esb: 3876, + esc: 3877, + esd: 3878, + ese: 3879, + esf: 3880, + esg: 3881, + esh: 3882, + esi: 3883, + esj: 3884, + esk: 3885, + esl: 3886, + esm: 3887, + esn: 3888, + eso: 3889, + esp: 3890, + esq: 3891, + esr: 3892, + ess: 3893, + est: 3894, + esu: 3895, + esv: 3896, + esw: 3897, + esx: 3898, + esy: 3899, + etz: 3900, + eta: 3901, + etb: 3902, + etc: 3903, + etd: 3904, + ete: 3905, + etf: 3906, + etg: 3907, + eth: 3908, + eti: 3909, + etj: 3910, + etk: 3911, + etl: 3912, + etm: 3913, + etn: 3914, + eto: 3915, + etp: 3916, + etq: 3917, + etr: 3918, + ets: 3919, + ett: 3920, + etu: 3921, + etv: 3922, + etw: 3923, + etx: 3924, + ety: 3925, + euz: 3926, + eua: 3927, + eub: 3928, + euc: 3929, + eud: 3930, + eue: 3931, + euf: 3932, + eug: 3933, + euh: 3934, + eui: 3935, + euj: 3936, + euk: 3937, + eul: 3938, + eum: 3939, + eun: 3940, + euo: 3941, + eup: 3942, + euq: 3943, + eur: 3944, + eus: 3945, + eut: 3946, + euu: 3947, + euv: 3948, + euw: 3949, + eux: 3950, + euy: 3951, + evz: 3952, + eva: 3953, + evb: 3954, + evc: 3955, + evd: 3956, + eve: 3957, + evf: 3958, + evg: 3959, + evh: 3960, + evi: 3961, + evj: 3962, + evk: 3963, + evl: 3964, + evm: 3965, + evn: 3966, + evo: 3967, + evp: 3968, + evq: 3969, + evr: 3970, + evs: 3971, + evt: 3972, + evu: 3973, + evv: 3974, + evw: 3975, + evx: 3976, + evy: 3977, + ewz: 3978, + ewa: 3979, + ewb: 3980, + ewc: 3981, + ewd: 3982, + ewe: 3983, + ewf: 3984, + ewg: 3985, + ewh: 3986, + ewi: 3987, + ewj: 3988, + ewk: 3989, + ewl: 3990, + ewm: 3991, + ewn: 3992, + ewo: 3993, + ewp: 3994, + ewq: 3995, + ewr: 3996, + ews: 3997, + ewt: 3998, + ewu: 3999, + ewv: 4000, + eww: 4001, + ewx: 4002, + ewy: 4003, + exz: 4004, + exa: 4005, + exb: 4006, + exc: 4007, + exd: 4008, + exe: 4009, + exf: 4010, + exg: 4011, + exh: 4012, + exi: 4013, + exj: 4014, + exk: 4015, + exl: 4016, + exm: 4017, + exn: 4018, + exo: 4019, + exp: 4020, + exq: 4021, + exr: 4022, + exs: 4023, + ext: 4024, + exu: 4025, + exv: 4026, + exw: 4027, + exx: 4028, + exy: 4029, + eyz: 4030, + eya: 4031, + eyb: 4032, + eyc: 4033, + eyd: 4034, + eye: 4035, + eyf: 4036, + eyg: 4037, + eyh: 4038, + eyi: 4039, + eyj: 4040, + eyk: 4041, + eyl: 4042, + eym: 4043, + eyn: 4044, + eyo: 4045, + eyp: 4046, + eyq: 4047, + eyr: 4048, + eys: 4049, + eyt: 4050, + eyu: 4051, + eyv: 4052, + eyw: 4053, + eyx: 4054, + eyy: 4055, + fzz: 4056, + fza: 4057, + fzb: 4058, + fzc: 4059, + fzd: 4060, + fze: 4061, + fzf: 4062, + fzg: 4063, + fzh: 4064, + fzi: 4065, + fzj: 4066, + fzk: 4067, + fzl: 4068, + fzm: 4069, + fzn: 4070, + fzo: 4071, + fzp: 4072, + fzq: 4073, + fzr: 4074, + fzs: 4075, + fzt: 4076, + fzu: 4077, + fzv: 4078, + fzw: 4079, + fzx: 4080, + fzy: 4081, + faz: 4082, + faa: 4083, + fab: 4084, + fac: 4085, + fad: 4086, + fae: 4087, + faf: 4088, + fag: 4089, + fah: 4090, + fai: 4091, + faj: 4092, + fak: 4093, + fal: 4094, + fam: 4095, + fan: 4096, + fao: 4097, + fap: 4098, + faq: 4099, + far: 4100, + fas: 4101, + fat: 4102, + fau: 4103, + fav: 4104, + faw: 4105, + fax: 4106, + fay: 4107, + fbz: 4108, + fba: 4109, + fbb: 4110, + fbc: 4111, + fbd: 4112, + fbe: 4113, + fbf: 4114, + fbg: 4115, + fbh: 4116, + fbi: 4117, + fbj: 4118, + fbk: 4119, + fbl: 4120, + fbm: 4121, + fbn: 4122, + fbo: 4123, + fbp: 4124, + fbq: 4125, + fbr: 4126, + fbs: 4127, + fbt: 4128, + fbu: 4129, + fbv: 4130, + fbw: 4131, + fbx: 4132, + fby: 4133, + fcz: 4134, + fca: 4135, + fcb: 4136, + fcc: 4137, + fcd: 4138, + fce: 4139, + fcf: 4140, + fcg: 4141, + fch: 4142, + fci: 4143, + fcj: 4144, + fck: 4145, + fcl: 4146, + fcm: 4147, + fcn: 4148, + fco: 4149, + fcp: 4150, + fcq: 4151, + fcr: 4152, + fcs: 4153, + fct: 4154, + fcu: 4155, + fcv: 4156, + fcw: 4157, + fcx: 4158, + fcy: 4159, + fdz: 4160, + fda: 4161, + fdb: 4162, + fdc: 4163, + fdd: 4164, + fde: 4165, + fdf: 4166, + fdg: 4167, + fdh: 4168, + fdi: 4169, + fdj: 4170, + fdk: 4171, + fdl: 4172, + fdm: 4173, + fdn: 4174, + fdo: 4175, + fdp: 4176, + fdq: 4177, + fdr: 4178, + fds: 4179, + fdt: 4180, + fdu: 4181, + fdv: 4182, + fdw: 4183, + fdx: 4184, + fdy: 4185, + fez: 4186, + fea: 4187, + feb: 4188, + fec: 4189, + fed: 4190, + fee: 4191, + fef: 4192, + feg: 4193, + feh: 4194, + fei: 4195, + fej: 4196, + fek: 4197, + fel: 4198, + fem: 4199, + fen: 4200, + feo: 4201, + fep: 4202, + feq: 4203, + fer: 4204, + fes: 4205, + fet: 4206, + feu: 4207, + fev: 4208, + few: 4209, + fex: 4210, + fey: 4211, + ffz: 4212, + ffa: 4213, + ffb: 4214, + ffc: 4215, + ffd: 4216, + ffe: 4217, + fff: 4218, + ffg: 4219, + ffh: 4220, + ffi: 4221, + ffj: 4222, + ffk: 4223, + ffl: 4224, + ffm: 4225, + ffn: 4226, + ffo: 4227, + ffp: 4228, + ffq: 4229, + ffr: 4230, + ffs: 4231, + fft: 4232, + ffu: 4233, + ffv: 4234, + ffw: 4235, + ffx: 4236, + ffy: 4237, + fgz: 4238, + fga: 4239, + fgb: 4240, + fgc: 4241, + fgd: 4242, + fge: 4243, + fgf: 4244, + fgg: 4245, + fgh: 4246, + fgi: 4247, + fgj: 4248, + fgk: 4249, + fgl: 4250, + fgm: 4251, + fgn: 4252, + fgo: 4253, + fgp: 4254, + fgq: 4255, + fgr: 4256, + fgs: 4257, + fgt: 4258, + fgu: 4259, + fgv: 4260, + fgw: 4261, + fgx: 4262, + fgy: 4263, + fhz: 4264, + fha: 4265, + fhb: 4266, + fhc: 4267, + fhd: 4268, + fhe: 4269, + fhf: 4270, + fhg: 4271, + fhh: 4272, + fhi: 4273, + fhj: 4274, + fhk: 4275, + fhl: 4276, + fhm: 4277, + fhn: 4278, + fho: 4279, + fhp: 4280, + fhq: 4281, + fhr: 4282, + fhs: 4283, + fht: 4284, + fhu: 4285, + fhv: 4286, + fhw: 4287, + fhx: 4288, + fhy: 4289, + fiz: 4290, + fia: 4291, + fib: 4292, + fic: 4293, + fid: 4294, + fie: 4295, + fif: 4296, + fig: 4297, + fih: 4298, + fii: 4299, + fij: 4300, + fik: 4301, + fil: 4302, + fim: 4303, + fin: 4304, + fio: 4305, + fip: 4306, + fiq: 4307, + fir: 4308, + fis: 4309, + fit: 4310, + fiu: 4311, + fiv: 4312, + fiw: 4313, + fix: 4314, + fiy: 4315, + fjz: 4316, + fja: 4317, + fjb: 4318, + fjc: 4319, + fjd: 4320, + fje: 4321, + fjf: 4322, + fjg: 4323, + fjh: 4324, + fji: 4325, + fjj: 4326, + fjk: 4327, + fjl: 4328, + fjm: 4329, + fjn: 4330, + fjo: 4331, + fjp: 4332, + fjq: 4333, + fjr: 4334, + fjs: 4335, + fjt: 4336, + fju: 4337, + fjv: 4338, + fjw: 4339, + fjx: 4340, + fjy: 4341, + fkz: 4342, + fka: 4343, + fkb: 4344, + fkc: 4345, + fkd: 4346, + fke: 4347, + fkf: 4348, + fkg: 4349, + fkh: 4350, + fki: 4351, + fkj: 4352, + fkk: 4353, + fkl: 4354, + fkm: 4355, + fkn: 4356, + fko: 4357, + fkp: 4358, + fkq: 4359, + fkr: 4360, + fks: 4361, + fkt: 4362, + fku: 4363, + fkv: 4364, + fkw: 4365, + fkx: 4366, + fky: 4367, + flz: 4368, + fla: 4369, + flb: 4370, + flc: 4371, + fld: 4372, + fle: 4373, + flf: 4374, + flg: 4375, + flh: 4376, + fli: 4377, + flj: 4378, + flk: 4379, + fll: 4380, + flm: 4381, + fln: 4382, + flo: 4383, + flp: 4384, + flq: 4385, + flr: 4386, + fls: 4387, + flt: 4388, + flu: 4389, + flv: 4390, + flw: 4391, + flx: 4392, + fly: 4393, + fmz: 4394, + fma: 4395, + fmb: 4396, + fmc: 4397, + fmd: 4398, + fme: 4399, + fmf: 4400, + fmg: 4401, + fmh: 4402, + fmi: 4403, + fmj: 4404, + fmk: 4405, + fml: 4406, + fmm: 4407, + fmn: 4408, + fmo: 4409, + fmp: 4410, + fmq: 4411, + fmr: 4412, + fms: 4413, + fmt: 4414, + fmu: 4415, + fmv: 4416, + fmw: 4417, + fmx: 4418, + fmy: 4419, + fnz: 4420, + fna: 4421, + fnb: 4422, + fnc: 4423, + fnd: 4424, + fne: 4425, + fnf: 4426, + fng: 4427, + fnh: 4428, + fni: 4429, + fnj: 4430, + fnk: 4431, + fnl: 4432, + fnm: 4433, + fnn: 4434, + fno: 4435, + fnp: 4436, + fnq: 4437, + fnr: 4438, + fns: 4439, + fnt: 4440, + fnu: 4441, + fnv: 4442, + fnw: 4443, + fnx: 4444, + fny: 4445, + foz: 4446, + foa: 4447, + fob: 4448, + foc: 4449, + fod: 4450, + foe: 4451, + fof: 4452, + fog: 4453, + foh: 4454, + foi: 4455, + foj: 4456, + fok: 4457, + fol: 4458, + fom: 4459, + fon: 4460, + foo: 4461, + fop: 4462, + foq: 4463, + for: 4464, + fos: 4465, + fot: 4466, + fou: 4467, + fov: 4468, + fow: 4469, + fox: 4470, + foy: 4471, + fpz: 4472, + fpa: 4473, + fpb: 4474, + fpc: 4475, + fpd: 4476, + fpe: 4477, + fpf: 4478, + fpg: 4479, + fph: 4480, + fpi: 4481, + fpj: 4482, + fpk: 4483, + fpl: 4484, + fpm: 4485, + fpn: 4486, + fpo: 4487, + fpp: 4488, + fpq: 4489, + fpr: 4490, + fps: 4491, + fpt: 4492, + fpu: 4493, + fpv: 4494, + fpw: 4495, + fpx: 4496, + fpy: 4497, + fqz: 4498, + fqa: 4499, + fqb: 4500, + fqc: 4501, + fqd: 4502, + fqe: 4503, + fqf: 4504, + fqg: 4505, + fqh: 4506, + fqi: 4507, + fqj: 4508, + fqk: 4509, + fql: 4510, + fqm: 4511, + fqn: 4512, + fqo: 4513, + fqp: 4514, + fqq: 4515, + fqr: 4516, + fqs: 4517, + fqt: 4518, + fqu: 4519, + fqv: 4520, + fqw: 4521, + fqx: 4522, + fqy: 4523, + frz: 4524, + fra: 4525, + frb: 4526, + frc: 4527, + frd: 4528, + fre: 4529, + frf: 4530, + frg: 4531, + frh: 4532, + fri: 4533, + frj: 4534, + frk: 4535, + frl: 4536, + frm: 4537, + frn: 4538, + fro: 4539, + frp: 4540, + frq: 4541, + frr: 4542, + frs: 4543, + frt: 4544, + fru: 4545, + frv: 4546, + frw: 4547, + frx: 4548, + fry: 4549, + fsz: 4550, + fsa: 4551, + fsb: 4552, + fsc: 4553, + fsd: 4554, + fse: 4555, + fsf: 4556, + fsg: 4557, + fsh: 4558, + fsi: 4559, + fsj: 4560, + fsk: 4561, + fsl: 4562, + fsm: 4563, + fsn: 4564, + fso: 4565, + fsp: 4566, + fsq: 4567, + fsr: 4568, + fss: 4569, + fst: 4570, + fsu: 4571, + fsv: 4572, + fsw: 4573, + fsx: 4574, + fsy: 4575, + ftz: 4576, + fta: 4577, + ftb: 4578, + ftc: 4579, + ftd: 4580, + fte: 4581, + ftf: 4582, + ftg: 4583, + fth: 4584, + fti: 4585, + ftj: 4586, + ftk: 4587, + ftl: 4588, + ftm: 4589, + ftn: 4590, + fto: 4591, + ftp: 4592, + ftq: 4593, + ftr: 4594, + fts: 4595, + ftt: 4596, + ftu: 4597, + ftv: 4598, + ftw: 4599, + ftx: 4600, + fty: 4601, + fuz: 4602, + fua: 4603, + fub: 4604, + fuc: 4605, + fud: 4606, + fue: 4607, + fuf: 4608, + fug: 4609, + fuh: 4610, + fui: 4611, + fuj: 4612, + fuk: 4613, + ful: 4614, + fum: 4615, + fun: 4616, + fuo: 4617, + fup: 4618, + fuq: 4619, + fur: 4620, + fus: 4621, + fut: 4622, + fuu: 4623, + fuv: 4624, + fuw: 4625, + fux: 4626, + fuy: 4627, + fvz: 4628, + fva: 4629, + fvb: 4630, + fvc: 4631, + fvd: 4632, + fve: 4633, + fvf: 4634, + fvg: 4635, + fvh: 4636, + fvi: 4637, + fvj: 4638, + fvk: 4639, + fvl: 4640, + fvm: 4641, + fvn: 4642, + fvo: 4643, + fvp: 4644, + fvq: 4645, + fvr: 4646, + fvs: 4647, + fvt: 4648, + fvu: 4649, + fvv: 4650, + fvw: 4651, + fvx: 4652, + fvy: 4653, + fwz: 4654, + fwa: 4655, + fwb: 4656, + fwc: 4657, + fwd: 4658, + fwe: 4659, + fwf: 4660, + fwg: 4661, + fwh: 4662, + fwi: 4663, + fwj: 4664, + fwk: 4665, + fwl: 4666, + fwm: 4667, + fwn: 4668, + fwo: 4669, + fwp: 4670, + fwq: 4671, + fwr: 4672, + fws: 4673, + fwt: 4674, + fwu: 4675, + fwv: 4676, + fww: 4677, + fwx: 4678, + fwy: 4679, + fxz: 4680, + fxa: 4681, + fxb: 4682, + fxc: 4683, + fxd: 4684, + fxe: 4685, + fxf: 4686, + fxg: 4687, + fxh: 4688, + fxi: 4689, + fxj: 4690, + fxk: 4691, + fxl: 4692, + fxm: 4693, + fxn: 4694, + fxo: 4695, + fxp: 4696, + fxq: 4697, + fxr: 4698, + fxs: 4699, + fxt: 4700, + fxu: 4701, + fxv: 4702, + fxw: 4703, + fxx: 4704, + fxy: 4705, + fyz: 4706, + fya: 4707, + fyb: 4708, + fyc: 4709, + fyd: 4710, + fye: 4711, + fyf: 4712, + fyg: 4713, + fyh: 4714, + fyi: 4715, + fyj: 4716, + fyk: 4717, + fyl: 4718, + fym: 4719, + fyn: 4720, + fyo: 4721, + fyp: 4722, + fyq: 4723, + fyr: 4724, + fys: 4725, + fyt: 4726, + fyu: 4727, + fyv: 4728, + fyw: 4729, + fyx: 4730, + fyy: 4731, + gzz: 4732, + gza: 4733, + gzb: 4734, + gzc: 4735, + gzd: 4736, + gze: 4737, + gzf: 4738, + gzg: 4739, + gzh: 4740, + gzi: 4741, + gzj: 4742, + gzk: 4743, + gzl: 4744, + gzm: 4745, + gzn: 4746, + gzo: 4747, + gzp: 4748, + gzq: 4749, + gzr: 4750, + gzs: 4751, + gzt: 4752, + gzu: 4753, + gzv: 4754, + gzw: 4755, + gzx: 4756, + gzy: 4757, + gaz: 4758, + gaa: 4759, + gab: 4760, + gac: 4761, + gad: 4762, + gae: 4763, + gaf: 4764, + gag: 4765, + gah: 4766, + gai: 4767, + gaj: 4768, + gak: 4769, + gal: 4770, + gam: 4771, + gan: 4772, + gao: 4773, + gap: 4774, + gaq: 4775, + gar: 4776, + gas: 4777, + gat: 4778, + gau: 4779, + gav: 4780, + gaw: 4781, + gax: 4782, + gay: 4783, + gbz: 4784, + gba: 4785, + gbb: 4786, + gbc: 4787, + gbd: 4788, + gbe: 4789, + gbf: 4790, + gbg: 4791, + gbh: 4792, + gbi: 4793, + gbj: 4794, + gbk: 4795, + gbl: 4796, + gbm: 4797, + gbn: 4798, + gbo: 4799, + gbp: 4800, + gbq: 4801, + gbr: 4802, + gbs: 4803, + gbt: 4804, + gbu: 4805, + gbv: 4806, + gbw: 4807, + gbx: 4808, + gby: 4809, + gcz: 4810, + gca: 4811, + gcb: 4812, + gcc: 4813, + gcd: 4814, + gce: 4815, + gcf: 4816, + gcg: 4817, + gch: 4818, + gci: 4819, + gcj: 4820, + gck: 4821, + gcl: 4822, + gcm: 4823, + gcn: 4824, + gco: 4825, + gcp: 4826, + gcq: 4827, + gcr: 4828, + gcs: 4829, + gct: 4830, + gcu: 4831, + gcv: 4832, + gcw: 4833, + gcx: 4834, + gcy: 4835, + gdz: 4836, + gda: 4837, + gdb: 4838, + gdc: 4839, + gdd: 4840, + gde: 4841, + gdf: 4842, + gdg: 4843, + gdh: 4844, + gdi: 4845, + gdj: 4846, + gdk: 4847, + gdl: 4848, + gdm: 4849, + gdn: 4850, + gdo: 4851, + gdp: 4852, + gdq: 4853, + gdr: 4854, + gds: 4855, + gdt: 4856, + gdu: 4857, + gdv: 4858, + gdw: 4859, + gdx: 4860, + gdy: 4861, + gez: 4862, + gea: 4863, + geb: 4864, + gec: 4865, + ged: 4866, + gee: 4867, + gef: 4868, + geg: 4869, + geh: 4870, + gei: 4871, + gej: 4872, + gek: 4873, + gel: 4874, + gem: 4875, + gen: 4876, + geo: 4877, + gep: 4878, + geq: 4879, + ger: 4880, + ges: 4881, + get: 4882, + geu: 4883, + gev: 4884, + gew: 4885, + gex: 4886, + gey: 4887, + gfz: 4888, + gfa: 4889, + gfb: 4890, + gfc: 4891, + gfd: 4892, + gfe: 4893, + gff: 4894, + gfg: 4895, + gfh: 4896, + gfi: 4897, + gfj: 4898, + gfk: 4899, + gfl: 4900, + gfm: 4901, + gfn: 4902, + gfo: 4903, + gfp: 4904, + gfq: 4905, + gfr: 4906, + gfs: 4907, + gft: 4908, + gfu: 4909, + gfv: 4910, + gfw: 4911, + gfx: 4912, + gfy: 4913, + ggz: 4914, + gga: 4915, + ggb: 4916, + ggc: 4917, + ggd: 4918, + gge: 4919, + ggf: 4920, + ggg: 4921, + ggh: 4922, + ggi: 4923, + ggj: 4924, + ggk: 4925, + ggl: 4926, + ggm: 4927, + ggn: 4928, + ggo: 4929, + ggp: 4930, + ggq: 4931, + ggr: 4932, + ggs: 4933, + ggt: 4934, + ggu: 4935, + ggv: 4936, + ggw: 4937, + ggx: 4938, + ggy: 4939, + ghz: 4940, + gha: 4941, + ghb: 4942, + ghc: 4943, + ghd: 4944, + ghe: 4945, + ghf: 4946, + ghg: 4947, + ghh: 4948, + ghi: 4949, + ghj: 4950, + ghk: 4951, + ghl: 4952, + ghm: 4953, + ghn: 4954, + gho: 4955, + ghp: 4956, + ghq: 4957, + ghr: 4958, + ghs: 4959, + ght: 4960, + ghu: 4961, + ghv: 4962, + ghw: 4963, + ghx: 4964, + ghy: 4965, + giz: 4966, + gia: 4967, + gib: 4968, + gic: 4969, + gid: 4970, + gie: 4971, + gif: 4972, + gig: 4973, + gih: 4974, + gii: 4975, + gij: 4976, + gik: 4977, + gil: 4978, + gim: 4979, + gin: 4980, + gio: 4981, + gip: 4982, + giq: 4983, + gir: 4984, + gis: 4985, + git: 4986, + giu: 4987, + giv: 4988, + giw: 4989, + gix: 4990, + giy: 4991, + gjz: 4992, + gja: 4993, + gjb: 4994, + gjc: 4995, + gjd: 4996, + gje: 4997, + gjf: 4998, + gjg: 4999, + gjh: 5000, + gji: 5001, + gjj: 5002, + gjk: 5003, + gjl: 5004, + gjm: 5005, + gjn: 5006, + gjo: 5007, + gjp: 5008, + gjq: 5009, + gjr: 5010, + gjs: 5011, + gjt: 5012, + gju: 5013, + gjv: 5014, + gjw: 5015, + gjx: 5016, + gjy: 5017, + gkz: 5018, + gka: 5019, + gkb: 5020, + gkc: 5021, + gkd: 5022, + gke: 5023, + gkf: 5024, + gkg: 5025, + gkh: 5026, + gki: 5027, + gkj: 5028, + gkk: 5029, + gkl: 5030, + gkm: 5031, + gkn: 5032, + gko: 5033, + gkp: 5034, + gkq: 5035, + gkr: 5036, + gks: 5037, + gkt: 5038, + gku: 5039, + gkv: 5040, + gkw: 5041, + gkx: 5042, + gky: 5043, + glz: 5044, + gla: 5045, + glb: 5046, + glc: 5047, + gld: 5048, + gle: 5049, + glf: 5050, + glg: 5051, + glh: 5052, + gli: 5053, + glj: 5054, + glk: 5055, + gll: 5056, + glm: 5057, + gln: 5058, + glo: 5059, + glp: 5060, + glq: 5061, + glr: 5062, + gls: 5063, + glt: 5064, + glu: 5065, + glv: 5066, + glw: 5067, + glx: 5068, + gly: 5069, + gmz: 5070, + gma: 5071, + gmb: 5072, + gmc: 5073, + gmd: 5074, + gme: 5075, + gmf: 5076, + gmg: 5077, + gmh: 5078, + gmi: 5079, + gmj: 5080, + gmk: 5081, + gml: 5082, + gmm: 5083, + gmn: 5084, + gmo: 5085, + gmp: 5086, + gmq: 5087, + gmr: 5088, + gms: 5089, + gmt: 5090, + gmu: 5091, + gmv: 5092, + gmw: 5093, + gmx: 5094, + gmy: 5095, + gnz: 5096, + gna: 5097, + gnb: 5098, + gnc: 5099, + gnd: 5100, + gne: 5101, + gnf: 5102, + gng: 5103, + gnh: 5104, + gni: 5105, + gnj: 5106, + gnk: 5107, + gnl: 5108, + gnm: 5109, + gnn: 5110, + gno: 5111, + gnp: 5112, + gnq: 5113, + gnr: 5114, + gns: 5115, + gnt: 5116, + gnu: 5117, + gnv: 5118, + gnw: 5119, + gnx: 5120, + gny: 5121, + goz: 5122, + goa: 5123, + gob: 5124, + goc: 5125, + god: 5126, + goe: 5127, + gof: 5128, + gog: 5129, + goh: 5130, + goi: 5131, + goj: 5132, + gok: 5133, + gol: 5134, + gom: 5135, + gon: 5136, + goo: 5137, + gop: 5138, + goq: 5139, + gor: 5140, + gos: 5141, + got: 5142, + gou: 5143, + gov: 5144, + gow: 5145, + gox: 5146, + goy: 5147, + gpz: 5148, + gpa: 5149, + gpb: 5150, + gpc: 5151, + gpd: 5152, + gpe: 5153, + gpf: 5154, + gpg: 5155, + gph: 5156, + gpi: 5157, + gpj: 5158, + gpk: 5159, + gpl: 5160, + gpm: 5161, + gpn: 5162, + gpo: 5163, + gpp: 5164, + gpq: 5165, + gpr: 5166, + gps: 5167, + gpt: 5168, + gpu: 5169, + gpv: 5170, + gpw: 5171, + gpx: 5172, + gpy: 5173, + gqz: 5174, + gqa: 5175, + gqb: 5176, + gqc: 5177, + gqd: 5178, + gqe: 5179, + gqf: 5180, + gqg: 5181, + gqh: 5182, + gqi: 5183, + gqj: 5184, + gqk: 5185, + gql: 5186, + gqm: 5187, + gqn: 5188, + gqo: 5189, + gqp: 5190, + gqq: 5191, + gqr: 5192, + gqs: 5193, + gqt: 5194, + gqu: 5195, + gqv: 5196, + gqw: 5197, + gqx: 5198, + gqy: 5199, + grz: 5200, + gra: 5201, + grb: 5202, + grc: 5203, + grd: 5204, + gre: 5205, + grf: 5206, + grg: 5207, + grh: 5208, + gri: 5209, + grj: 5210, + grk: 5211, + grl: 5212, + grm: 5213, + grn: 5214, + gro: 5215, + grp: 5216, + grq: 5217, + grr: 5218, + grs: 5219, + grt: 5220, + gru: 5221, + grv: 5222, + grw: 5223, + grx: 5224, + gry: 5225, + gsz: 5226, + gsa: 5227, + gsb: 5228, + gsc: 5229, + gsd: 5230, + gse: 5231, + gsf: 5232, + gsg: 5233, + gsh: 5234, + gsi: 5235, + gsj: 5236, + gsk: 5237, + gsl: 5238, + gsm: 5239, + gsn: 5240, + gso: 5241, + gsp: 5242, + gsq: 5243, + gsr: 5244, + gss: 5245, + gst: 5246, + gsu: 5247, + gsv: 5248, + gsw: 5249, + gsx: 5250, + gsy: 5251, + gtz: 5252, + gta: 5253, + gtb: 5254, + gtc: 5255, + gtd: 5256, + gte: 5257, + gtf: 5258, + gtg: 5259, + gth: 5260, + gti: 5261, + gtj: 5262, + gtk: 5263, + gtl: 5264, + gtm: 5265, + gtn: 5266, + gto: 5267, + gtp: 5268, + gtq: 5269, + gtr: 5270, + gts: 5271, + gtt: 5272, + gtu: 5273, + gtv: 5274, + gtw: 5275, + gtx: 5276, + gty: 5277, + guz: 5278, + gua: 5279, + gub: 5280, + guc: 5281, + gud: 5282, + gue: 5283, + guf: 5284, + gug: 5285, + guh: 5286, + gui: 5287, + guj: 5288, + guk: 5289, + gul: 5290, + gum: 5291, + gun: 5292, + guo: 5293, + gup: 5294, + guq: 5295, + gur: 5296, + gus: 5297, + gut: 5298, + guu: 5299, + guv: 5300, + guw: 5301, + gux: 5302, + guy: 5303, + gvz: 5304, + gva: 5305, + gvb: 5306, + gvc: 5307, + gvd: 5308, + gve: 5309, + gvf: 5310, + gvg: 5311, + gvh: 5312, + gvi: 5313, + gvj: 5314, + gvk: 5315, + gvl: 5316, + gvm: 5317, + gvn: 5318, + gvo: 5319, + gvp: 5320, + gvq: 5321, + gvr: 5322, + gvs: 5323, + gvt: 5324, + gvu: 5325, + gvv: 5326, + gvw: 5327, + gvx: 5328, + gvy: 5329, + gwz: 5330, + gwa: 5331, + gwb: 5332, + gwc: 5333, + gwd: 5334, + gwe: 5335, + gwf: 5336, + gwg: 5337, + gwh: 5338, + gwi: 5339, + gwj: 5340, + gwk: 5341, + gwl: 5342, + gwm: 5343, + gwn: 5344, + gwo: 5345, + gwp: 5346, + gwq: 5347, + gwr: 5348, + gws: 5349, + gwt: 5350, + gwu: 5351, + gwv: 5352, + gww: 5353, + gwx: 5354, + gwy: 5355, + gxz: 5356, + gxa: 5357, + gxb: 5358, + gxc: 5359, + gxd: 5360, + gxe: 5361, + gxf: 5362, + gxg: 5363, + gxh: 5364, + gxi: 5365, + gxj: 5366, + gxk: 5367, + gxl: 5368, + gxm: 5369, + gxn: 5370, + gxo: 5371, + gxp: 5372, + gxq: 5373, + gxr: 5374, + gxs: 5375, + gxt: 5376, + gxu: 5377, + gxv: 5378, + gxw: 5379, + gxx: 5380, + gxy: 5381, + gyz: 5382, + gya: 5383, + gyb: 5384, + gyc: 5385, + gyd: 5386, + gye: 5387, + gyf: 5388, + gyg: 5389, + gyh: 5390, + gyi: 5391, + gyj: 5392, + gyk: 5393, + gyl: 5394, + gym: 5395, + gyn: 5396, + gyo: 5397, + gyp: 5398, + gyq: 5399, + gyr: 5400, + gys: 5401, + gyt: 5402, + gyu: 5403, + gyv: 5404, + gyw: 5405, + gyx: 5406, + gyy: 5407, + hzz: 5408, + hza: 5409, + hzb: 5410, + hzc: 5411, + hzd: 5412, + hze: 5413, + hzf: 5414, + hzg: 5415, + hzh: 5416, + hzi: 5417, + hzj: 5418, + hzk: 5419, + hzl: 5420, + hzm: 5421, + hzn: 5422, + hzo: 5423, + hzp: 5424, + hzq: 5425, + hzr: 5426, + hzs: 5427, + hzt: 5428, + hzu: 5429, + hzv: 5430, + hzw: 5431, + hzx: 5432, + hzy: 5433, + haz: 5434, + haa: 5435, + hab: 5436, + hac: 5437, + had: 5438, + hae: 5439, + haf: 5440, + hag: 5441, + hah: 5442, + hai: 5443, + haj: 5444, + hak: 5445, + hal: 5446, + ham: 5447, + han: 5448, + hao: 5449, + hap: 5450, + haq: 5451, + har: 5452, + has: 5453, + hat: 5454, + hau: 5455, + hav: 5456, + haw: 5457, + hax: 5458, + hay: 5459, + hbz: 5460, + hba: 5461, + hbb: 5462, + hbc: 5463, + hbd: 5464, + hbe: 5465, + hbf: 5466, + hbg: 5467, + hbh: 5468, + hbi: 5469, + hbj: 5470, + hbk: 5471, + hbl: 5472, + hbm: 5473, + hbn: 5474, + hbo: 5475, + hbp: 5476, + hbq: 5477, + hbr: 5478, + hbs: 5479, + hbt: 5480, + hbu: 5481, + hbv: 5482, + hbw: 5483, + hbx: 5484, + hby: 5485, + hcz: 5486, + hca: 5487, + hcb: 5488, + hcc: 5489, + hcd: 5490, + hce: 5491, + hcf: 5492, + hcg: 5493, + hch: 5494, + hci: 5495, + hcj: 5496, + hck: 5497, + hcl: 5498, + hcm: 5499, + hcn: 5500, + hco: 5501, + hcp: 5502, + hcq: 5503, + hcr: 5504, + hcs: 5505, + hct: 5506, + hcu: 5507, + hcv: 5508, + hcw: 5509, + hcx: 5510, + hcy: 5511, + hdz: 5512, + hda: 5513, + hdb: 5514, + hdc: 5515, + hdd: 5516, + hde: 5517, + hdf: 5518, + hdg: 5519, + hdh: 5520, + hdi: 5521, + hdj: 5522, + hdk: 5523, + hdl: 5524, + hdm: 5525, + hdn: 5526, + hdo: 5527, + hdp: 5528, + hdq: 5529, + hdr: 5530, + hds: 5531, + hdt: 5532, + hdu: 5533, + hdv: 5534, + hdw: 5535, + hdx: 5536, + hdy: 5537, + hez: 5538, + hea: 5539, + heb: 5540, + hec: 5541, + hed: 5542, + hee: 5543, + hef: 5544, + heg: 5545, + heh: 5546, + hei: 5547, + hej: 5548, + hek: 5549, + hel: 5550, + hem: 5551, + hen: 5552, + heo: 5553, + hep: 5554, + heq: 5555, + her: 5556, + hes: 5557, + het: 5558, + heu: 5559, + hev: 5560, + hew: 5561, + hex: 5562, + hey: 5563, + hfz: 5564, + hfa: 5565, + hfb: 5566, + hfc: 5567, + hfd: 5568, + hfe: 5569, + hff: 5570, + hfg: 5571, + hfh: 5572, + hfi: 5573, + hfj: 5574, + hfk: 5575, + hfl: 5576, + hfm: 5577, + hfn: 5578, + hfo: 5579, + hfp: 5580, + hfq: 5581, + hfr: 5582, + hfs: 5583, + hft: 5584, + hfu: 5585, + hfv: 5586, + hfw: 5587, + hfx: 5588, + hfy: 5589, + hgz: 5590, + hga: 5591, + hgb: 5592, + hgc: 5593, + hgd: 5594, + hge: 5595, + hgf: 5596, + hgg: 5597, + hgh: 5598, + hgi: 5599, + hgj: 5600, + hgk: 5601, + hgl: 5602, + hgm: 5603, + hgn: 5604, + hgo: 5605, + hgp: 5606, + hgq: 5607, + hgr: 5608, + hgs: 5609, + hgt: 5610, + hgu: 5611, + hgv: 5612, + hgw: 5613, + hgx: 5614, + hgy: 5615, + hhz: 5616, + hha: 5617, + hhb: 5618, + hhc: 5619, + hhd: 5620, + hhe: 5621, + hhf: 5622, + hhg: 5623, + hhh: 5624, + hhi: 5625, + hhj: 5626, + hhk: 5627, + hhl: 5628, + hhm: 5629, + hhn: 5630, + hho: 5631, + hhp: 5632, + hhq: 5633, + hhr: 5634, + hhs: 5635, + hht: 5636, + hhu: 5637, + hhv: 5638, + hhw: 5639, + hhx: 5640, + hhy: 5641, + hiz: 5642, + hia: 5643, + hib: 5644, + hic: 5645, + hid: 5646, + hie: 5647, + hif: 5648, + hig: 5649, + hih: 5650, + hii: 5651, + hij: 5652, + hik: 5653, + hil: 5654, + him: 5655, + hin: 5656, + hio: 5657, + hip: 5658, + hiq: 5659, + hir: 5660, + his: 5661, + hit: 5662, + hiu: 5663, + hiv: 5664, + hiw: 5665, + hix: 5666, + hiy: 5667, + hjz: 5668, + hja: 5669, + hjb: 5670, + hjc: 5671, + hjd: 5672, + hje: 5673, + hjf: 5674, + hjg: 5675, + hjh: 5676, + hji: 5677, + hjj: 5678, + hjk: 5679, + hjl: 5680, + hjm: 5681, + hjn: 5682, + hjo: 5683, + hjp: 5684, + hjq: 5685, + hjr: 5686, + hjs: 5687, + hjt: 5688, + hju: 5689, + hjv: 5690, + hjw: 5691, + hjx: 5692, + hjy: 5693, + hkz: 5694, + hka: 5695, + hkb: 5696, + hkc: 5697, + hkd: 5698, + hke: 5699, + hkf: 5700, + hkg: 5701, + hkh: 5702, + hki: 5703, + hkj: 5704, + hkk: 5705, + hkl: 5706, + hkm: 5707, + hkn: 5708, + hko: 5709, + hkp: 5710, + hkq: 5711, + hkr: 5712, + hks: 5713, + hkt: 5714, + hku: 5715, + hkv: 5716, + hkw: 5717, + hkx: 5718, + hky: 5719, + hlz: 5720, + hla: 5721, + hlb: 5722, + hlc: 5723, + hld: 5724, + hle: 5725, + hlf: 5726, + hlg: 5727, + hlh: 5728, + hli: 5729, + hlj: 5730, + hlk: 5731, + hll: 5732, + hlm: 5733, + hln: 5734, + hlo: 5735, + hlp: 5736, + hlq: 5737, + hlr: 5738, + hls: 5739, + hlt: 5740, + hlu: 5741, + hlv: 5742, + hlw: 5743, + hlx: 5744, + hly: 5745, + hmz: 5746, + hma: 5747, + hmb: 5748, + hmc: 5749, + hmd: 5750, + hme: 5751, + hmf: 5752, + hmg: 5753, + hmh: 5754, + hmi: 5755, + hmj: 5756, + hmk: 5757, + hml: 5758, + hmm: 5759, + hmn: 5760, + hmo: 5761, + hmp: 5762, + hmq: 5763, + hmr: 5764, + hms: 5765, + hmt: 5766, + hmu: 5767, + hmv: 5768, + hmw: 5769, + hmx: 5770, + hmy: 5771, + hnz: 5772, + hna: 5773, + hnb: 5774, + hnc: 5775, + hnd: 5776, + hne: 5777, + hnf: 5778, + hng: 5779, + hnh: 5780, + hni: 5781, + hnj: 5782, + hnk: 5783, + hnl: 5784, + hnm: 5785, + hnn: 5786, + hno: 5787, + hnp: 5788, + hnq: 5789, + hnr: 5790, + hns: 5791, + hnt: 5792, + hnu: 5793, + hnv: 5794, + hnw: 5795, + hnx: 5796, + hny: 5797, + hoz: 5798, + hoa: 5799, + hob: 5800, + hoc: 5801, + hod: 5802, + hoe: 5803, + hof: 5804, + hog: 5805, + hoh: 5806, + hoi: 5807, + hoj: 5808, + hok: 5809, + hol: 5810, + hom: 5811, + hon: 5812, + hoo: 5813, + hop: 5814, + hoq: 5815, + hor: 5816, + hos: 5817, + hot: 5818, + hou: 5819, + hov: 5820, + how: 5821, + hox: 5822, + hoy: 5823, + hpz: 5824, + hpa: 5825, + hpb: 5826, + hpc: 5827, + hpd: 5828, + hpe: 5829, + hpf: 5830, + hpg: 5831, + hph: 5832, + hpi: 5833, + hpj: 5834, + hpk: 5835, + hpl: 5836, + hpm: 5837, + hpn: 5838, + hpo: 5839, + hpp: 5840, + hpq: 5841, + hpr: 5842, + hps: 5843, + hpt: 5844, + hpu: 5845, + hpv: 5846, + hpw: 5847, + hpx: 5848, + hpy: 5849, + hqz: 5850, + hqa: 5851, + hqb: 5852, + hqc: 5853, + hqd: 5854, + hqe: 5855, + hqf: 5856, + hqg: 5857, + hqh: 5858, + hqi: 5859, + hqj: 5860, + hqk: 5861, + hql: 5862, + hqm: 5863, + hqn: 5864, + hqo: 5865, + hqp: 5866, + hqq: 5867, + hqr: 5868, + hqs: 5869, + hqt: 5870, + hqu: 5871, + hqv: 5872, + hqw: 5873, + hqx: 5874, + hqy: 5875, + hrz: 5876, + hra: 5877, + hrb: 5878, + hrc: 5879, + hrd: 5880, + hre: 5881, + hrf: 5882, + hrg: 5883, + hrh: 5884, + hri: 5885, + hrj: 5886, + hrk: 5887, + hrl: 5888, + hrm: 5889, + hrn: 5890, + hro: 5891, + hrp: 5892, + hrq: 5893, + hrr: 5894, + hrs: 5895, + hrt: 5896, + hru: 5897, + hrv: 5898, + hrw: 5899, + hrx: 5900, + hry: 5901, + hsz: 5902, + hsa: 5903, + hsb: 5904, + hsc: 5905, + hsd: 5906, + hse: 5907, + hsf: 5908, + hsg: 5909, + hsh: 5910, + hsi: 5911, + hsj: 5912, + hsk: 5913, + hsl: 5914, + hsm: 5915, + hsn: 5916, + hso: 5917, + hsp: 5918, + hsq: 5919, + hsr: 5920, + hss: 5921, + hst: 5922, + hsu: 5923, + hsv: 5924, + hsw: 5925, + hsx: 5926, + hsy: 5927, + htz: 5928, + hta: 5929, + htb: 5930, + htc: 5931, + htd: 5932, + hte: 5933, + htf: 5934, + htg: 5935, + hth: 5936, + hti: 5937, + htj: 5938, + htk: 5939, + htl: 5940, + htm: 5941, + htn: 5942, + hto: 5943, + htp: 5944, + htq: 5945, + htr: 5946, + hts: 5947, + htt: 5948, + htu: 5949, + htv: 5950, + htw: 5951, + htx: 5952, + hty: 5953, + huz: 5954, + hua: 5955, + hub: 5956, + huc: 5957, + hud: 5958, + hue: 5959, + huf: 5960, + hug: 5961, + huh: 5962, + hui: 5963, + huj: 5964, + huk: 5965, + hul: 5966, + hum: 5967, + hun: 5968, + huo: 5969, + hup: 5970, + huq: 5971, + hur: 5972, + hus: 5973, + hut: 5974, + huu: 5975, + huv: 5976, + huw: 5977, + hux: 5978, + huy: 5979, + hvz: 5980, + hva: 5981, + hvb: 5982, + hvc: 5983, + hvd: 5984, + hve: 5985, + hvf: 5986, + hvg: 5987, + hvh: 5988, + hvi: 5989, + hvj: 5990, + hvk: 5991, + hvl: 5992, + hvm: 5993, + hvn: 5994, + hvo: 5995, + hvp: 5996, + hvq: 5997, + hvr: 5998, + hvs: 5999, + hvt: 6000, + hvu: 6001, + hvv: 6002, + hvw: 6003, + hvx: 6004, + hvy: 6005, + hwz: 6006, + hwa: 6007, + hwb: 6008, + hwc: 6009, + hwd: 6010, + hwe: 6011, + hwf: 6012, + hwg: 6013, + hwh: 6014, + hwi: 6015, + hwj: 6016, + hwk: 6017, + hwl: 6018, + hwm: 6019, + hwn: 6020, + hwo: 6021, + hwp: 6022, + hwq: 6023, + hwr: 6024, + hws: 6025, + hwt: 6026, + hwu: 6027, + hwv: 6028, + hww: 6029, + hwx: 6030, + hwy: 6031, + hxz: 6032, + hxa: 6033, + hxb: 6034, + hxc: 6035, + hxd: 6036, + hxe: 6037, + hxf: 6038, + hxg: 6039, + hxh: 6040, + hxi: 6041, + hxj: 6042, + hxk: 6043, + hxl: 6044, + hxm: 6045, + hxn: 6046, + hxo: 6047, + hxp: 6048, + hxq: 6049, + hxr: 6050, + hxs: 6051, + hxt: 6052, + hxu: 6053, + hxv: 6054, + hxw: 6055, + hxx: 6056, + hxy: 6057, + hyz: 6058, + hya: 6059, + hyb: 6060, + hyc: 6061, + hyd: 6062, + hye: 6063, + hyf: 6064, + hyg: 6065, + hyh: 6066, + hyi: 6067, + hyj: 6068, + hyk: 6069, + hyl: 6070, + hym: 6071, + hyn: 6072, + hyo: 6073, + hyp: 6074, + hyq: 6075, + hyr: 6076, + hys: 6077, + hyt: 6078, + hyu: 6079, + hyv: 6080, + hyw: 6081, + hyx: 6082, + hyy: 6083, + izz: 6084, + iza: 6085, + izb: 6086, + izc: 6087, + izd: 6088, + ize: 6089, + izf: 6090, + izg: 6091, + izh: 6092, + izi: 6093, + izj: 6094, + izk: 6095, + izl: 6096, + izm: 6097, + izn: 6098, + izo: 6099, + izp: 6100, + izq: 6101, + izr: 6102, + izs: 6103, + izt: 6104, + izu: 6105, + izv: 6106, + izw: 6107, + izx: 6108, + izy: 6109, + iaz: 6110, + iaa: 6111, + iab: 6112, + iac: 6113, + iad: 6114, + iae: 6115, + iaf: 6116, + iag: 6117, + iah: 6118, + iai: 6119, + iaj: 6120, + iak: 6121, + ial: 6122, + iam: 6123, + ian: 6124, + iao: 6125, + iap: 6126, + iaq: 6127, + iar: 6128, + ias: 6129, + iat: 6130, + iau: 6131, + iav: 6132, + iaw: 6133, + iax: 6134, + iay: 6135, + ibz: 6136, + iba: 6137, + ibb: 6138, + ibc: 6139, + ibd: 6140, + ibe: 6141, + ibf: 6142, + ibg: 6143, + ibh: 6144, + ibi: 6145, + ibj: 6146, + ibk: 6147, + ibl: 6148, + ibm: 6149, + ibn: 6150, + ibo: 6151, + ibp: 6152, + ibq: 6153, + ibr: 6154, + ibs: 6155, + ibt: 6156, + ibu: 6157, + ibv: 6158, + ibw: 6159, + ibx: 6160, + iby: 6161, + icz: 6162, + ica: 6163, + icb: 6164, + icc: 6165, + icd: 6166, + ice: 6167, + icf: 6168, + icg: 6169, + ich: 6170, + ici: 6171, + icj: 6172, + ick: 6173, + icl: 6174, + icm: 6175, + icn: 6176, + ico: 6177, + icp: 6178, + icq: 6179, + icr: 6180, + ics: 6181, + ict: 6182, + icu: 6183, + icv: 6184, + icw: 6185, + icx: 6186, + icy: 6187, + idz: 6188, + ida: 6189, + idb: 6190, + idc: 6191, + idd: 6192, + ide: 6193, + idf: 6194, + idg: 6195, + idh: 6196, + idi: 6197, + idj: 6198, + idk: 6199, + idl: 6200, + idm: 6201, + idn: 6202, + ido: 6203, + idp: 6204, + idq: 6205, + idr: 6206, + ids: 6207, + idt: 6208, + idu: 6209, + idv: 6210, + idw: 6211, + idx: 6212, + idy: 6213, + iez: 6214, + iea: 6215, + ieb: 6216, + iec: 6217, + ied: 6218, + iee: 6219, + ief: 6220, + ieg: 6221, + ieh: 6222, + iei: 6223, + iej: 6224, + iek: 6225, + iel: 6226, + iem: 6227, + ien: 6228, + ieo: 6229, + iep: 6230, + ieq: 6231, + ier: 6232, + ies: 6233, + iet: 6234, + ieu: 6235, + iev: 6236, + iew: 6237, + iex: 6238, + iey: 6239, + ifz: 6240, + ifa: 6241, + ifb: 6242, + ifc: 6243, + ifd: 6244, + ife: 6245, + iff: 6246, + ifg: 6247, + ifh: 6248, + ifi: 6249, + ifj: 6250, + ifk: 6251, + ifl: 6252, + ifm: 6253, + ifn: 6254, + ifo: 6255, + ifp: 6256, + ifq: 6257, + ifr: 6258, + ifs: 6259, + ift: 6260, + ifu: 6261, + ifv: 6262, + ifw: 6263, + ifx: 6264, + ify: 6265, + igz: 6266, + iga: 6267, + igb: 6268, + igc: 6269, + igd: 6270, + ige: 6271, + igf: 6272, + igg: 6273, + igh: 6274, + igi: 6275, + igj: 6276, + igk: 6277, + igl: 6278, + igm: 6279, + ign: 6280, + igo: 6281, + igp: 6282, + igq: 6283, + igr: 6284, + igs: 6285, + igt: 6286, + igu: 6287, + igv: 6288, + igw: 6289, + igx: 6290, + igy: 6291, + ihz: 6292, + iha: 6293, + ihb: 6294, + ihc: 6295, + ihd: 6296, + ihe: 6297, + ihf: 6298, + ihg: 6299, + ihh: 6300, + ihi: 6301, + ihj: 6302, + ihk: 6303, + ihl: 6304, + ihm: 6305, + ihn: 6306, + iho: 6307, + ihp: 6308, + ihq: 6309, + ihr: 6310, + ihs: 6311, + iht: 6312, + ihu: 6313, + ihv: 6314, + ihw: 6315, + ihx: 6316, + ihy: 6317, + iiz: 6318, + iia: 6319, + iib: 6320, + iic: 6321, + iid: 6322, + iie: 6323, + iif: 6324, + iig: 6325, + iih: 6326, + iii: 6327, + iij: 6328, + iik: 6329, + iil: 6330, + iim: 6331, + iin: 6332, + iio: 6333, + iip: 6334, + iiq: 6335, + iir: 6336, + iis: 6337, + iit: 6338, + iiu: 6339, + iiv: 6340, + iiw: 6341, + iix: 6342, + iiy: 6343, + ijz: 6344, + ija: 6345, + ijb: 6346, + ijc: 6347, + ijd: 6348, + ije: 6349, + ijf: 6350, + ijg: 6351, + ijh: 6352, + iji: 6353, + ijj: 6354, + ijk: 6355, + ijl: 6356, + ijm: 6357, + ijn: 6358, + ijo: 6359, + ijp: 6360, + ijq: 6361, + ijr: 6362, + ijs: 6363, + ijt: 6364, + iju: 6365, + ijv: 6366, + ijw: 6367, + ijx: 6368, + ijy: 6369, + ikz: 6370, + ika: 6371, + ikb: 6372, + ikc: 6373, + ikd: 6374, + ike: 6375, + ikf: 6376, + ikg: 6377, + ikh: 6378, + iki: 6379, + ikj: 6380, + ikk: 6381, + ikl: 6382, + ikm: 6383, + ikn: 6384, + iko: 6385, + ikp: 6386, + ikq: 6387, + ikr: 6388, + iks: 6389, + ikt: 6390, + iku: 6391, + ikv: 6392, + ikw: 6393, + ikx: 6394, + iky: 6395, + ilz: 6396, + ila: 6397, + ilb: 6398, + ilc: 6399, + ild: 6400, + ile: 6401, + ilf: 6402, + ilg: 6403, + ilh: 6404, + ili: 6405, + ilj: 6406, + ilk: 6407, + ill: 6408, + ilm: 6409, + iln: 6410, + ilo: 6411, + ilp: 6412, + ilq: 6413, + ilr: 6414, + ils: 6415, + ilt: 6416, + ilu: 6417, + ilv: 6418, + ilw: 6419, + ilx: 6420, + ily: 6421, + imz: 6422, + ima: 6423, + imb: 6424, + imc: 6425, + imd: 6426, + ime: 6427, + imf: 6428, + img: 6429, + imh: 6430, + imi: 6431, + imj: 6432, + imk: 6433, + iml: 6434, + imm: 6435, + imn: 6436, + imo: 6437, + imp: 6438, + imq: 6439, + imr: 6440, + ims: 6441, + imt: 6442, + imu: 6443, + imv: 6444, + imw: 6445, + imx: 6446, + imy: 6447, + inz: 6448, + ina: 6449, + inb: 6450, + inc: 6451, + ind: 6452, + ine: 6453, + inf: 6454, + ing: 6455, + inh: 6456, + ini: 6457, + inj: 6458, + ink: 6459, + inl: 6460, + inm: 6461, + inn: 6462, + ino: 6463, + inp: 6464, + inq: 6465, + inr: 6466, + ins: 6467, + int: 6468, + inu: 6469, + inv: 6470, + inw: 6471, + inx: 6472, + iny: 6473, + ioz: 6474, + ioa: 6475, + iob: 6476, + ioc: 6477, + iod: 6478, + ioe: 6479, + iof: 6480, + iog: 6481, + ioh: 6482, + ioi: 6483, + ioj: 6484, + iok: 6485, + iol: 6486, + iom: 6487, + ion: 6488, + ioo: 6489, + iop: 6490, + ioq: 6491, + ior: 6492, + ios: 6493, + iot: 6494, + iou: 6495, + iov: 6496, + iow: 6497, + iox: 6498, + ioy: 6499, + ipz: 6500, + ipa: 6501, + ipb: 6502, + ipc: 6503, + ipd: 6504, + ipe: 6505, + ipf: 6506, + ipg: 6507, + iph: 6508, + ipi: 6509, + ipj: 6510, + ipk: 6511, + ipl: 6512, + ipm: 6513, + ipn: 6514, + ipo: 6515, + ipp: 6516, + ipq: 6517, + ipr: 6518, + ips: 6519, + ipt: 6520, + ipu: 6521, + ipv: 6522, + ipw: 6523, + ipx: 6524, + ipy: 6525, + iqz: 6526, + iqa: 6527, + iqb: 6528, + iqc: 6529, + iqd: 6530, + iqe: 6531, + iqf: 6532, + iqg: 6533, + iqh: 6534, + iqi: 6535, + iqj: 6536, + iqk: 6537, + iql: 6538, + iqm: 6539, + iqn: 6540, + iqo: 6541, + iqp: 6542, + iqq: 6543, + iqr: 6544, + iqs: 6545, + iqt: 6546, + iqu: 6547, + iqv: 6548, + iqw: 6549, + iqx: 6550, + iqy: 6551, + irz: 6552, + ira: 6553, + irb: 6554, + irc: 6555, + ird: 6556, + ire: 6557, + irf: 6558, + irg: 6559, + irh: 6560, + iri: 6561, + irj: 6562, + irk: 6563, + irl: 6564, + irm: 6565, + irn: 6566, + iro: 6567, + irp: 6568, + irq: 6569, + irr: 6570, + irs: 6571, + irt: 6572, + iru: 6573, + irv: 6574, + irw: 6575, + irx: 6576, + iry: 6577, + isz: 6578, + isa: 6579, + isb: 6580, + isc: 6581, + isd: 6582, + ise: 6583, + isf: 6584, + isg: 6585, + ish: 6586, + isi: 6587, + isj: 6588, + isk: 6589, + isl: 6590, + ism: 6591, + isn: 6592, + iso: 6593, + isp: 6594, + isq: 6595, + isr: 6596, + iss: 6597, + ist: 6598, + isu: 6599, + isv: 6600, + isw: 6601, + isx: 6602, + isy: 6603, + itz: 6604, + ita: 6605, + itb: 6606, + itc: 6607, + itd: 6608, + ite: 6609, + itf: 6610, + itg: 6611, + ith: 6612, + iti: 6613, + itj: 6614, + itk: 6615, + itl: 6616, + itm: 6617, + itn: 6618, + ito: 6619, + itp: 6620, + itq: 6621, + itr: 6622, + its: 6623, + itt: 6624, + itu: 6625, + itv: 6626, + itw: 6627, + itx: 6628, + ity: 6629, + iuz: 6630, + iua: 6631, + iub: 6632, + iuc: 6633, + iud: 6634, + iue: 6635, + iuf: 6636, + iug: 6637, + iuh: 6638, + iui: 6639, + iuj: 6640, + iuk: 6641, + iul: 6642, + ium: 6643, + iun: 6644, + iuo: 6645, + iup: 6646, + iuq: 6647, + iur: 6648, + ius: 6649, + iut: 6650, + iuu: 6651, + iuv: 6652, + iuw: 6653, + iux: 6654, + iuy: 6655, + ivz: 6656, + iva: 6657, + ivb: 6658, + ivc: 6659, + ivd: 6660, + ive: 6661, + ivf: 6662, + ivg: 6663, + ivh: 6664, + ivi: 6665, + ivj: 6666, + ivk: 6667, + ivl: 6668, + ivm: 6669, + ivn: 6670, + ivo: 6671, + ivp: 6672, + ivq: 6673, + ivr: 6674, + ivs: 6675, + ivt: 6676, + ivu: 6677, + ivv: 6678, + ivw: 6679, + ivx: 6680, + ivy: 6681, + iwz: 6682, + iwa: 6683, + iwb: 6684, + iwc: 6685, + iwd: 6686, + iwe: 6687, + iwf: 6688, + iwg: 6689, + iwh: 6690, + iwi: 6691, + iwj: 6692, + iwk: 6693, + iwl: 6694, + iwm: 6695, + iwn: 6696, + iwo: 6697, + iwp: 6698, + iwq: 6699, + iwr: 6700, + iws: 6701, + iwt: 6702, + iwu: 6703, + iwv: 6704, + iww: 6705, + iwx: 6706, + iwy: 6707, + ixz: 6708, + ixa: 6709, + ixb: 6710, + ixc: 6711, + ixd: 6712, + ixe: 6713, + ixf: 6714, + ixg: 6715, + ixh: 6716, + ixi: 6717, + ixj: 6718, + ixk: 6719, + ixl: 6720, + ixm: 6721, + ixn: 6722, + ixo: 6723, + ixp: 6724, + ixq: 6725, + ixr: 6726, + ixs: 6727, + ixt: 6728, + ixu: 6729, + ixv: 6730, + ixw: 6731, + ixx: 6732, + ixy: 6733, + iyz: 6734, + iya: 6735, + iyb: 6736, + iyc: 6737, + iyd: 6738, + iye: 6739, + iyf: 6740, + iyg: 6741, + iyh: 6742, + iyi: 6743, + iyj: 6744, + iyk: 6745, + iyl: 6746, + iym: 6747, + iyn: 6748, + iyo: 6749, + iyp: 6750, + iyq: 6751, + iyr: 6752, + iys: 6753, + iyt: 6754, + iyu: 6755, + iyv: 6756, + iyw: 6757, + iyx: 6758, + iyy: 6759, + jzz: 6760, + jza: 6761, + jzb: 6762, + jzc: 6763, + jzd: 6764, + jze: 6765, + jzf: 6766, + jzg: 6767, + jzh: 6768, + jzi: 6769, + jzj: 6770, + jzk: 6771, + jzl: 6772, + jzm: 6773, + jzn: 6774, + jzo: 6775, + jzp: 6776, + jzq: 6777, + jzr: 6778, + jzs: 6779, + jzt: 6780, + jzu: 6781, + jzv: 6782, + jzw: 6783, + jzx: 6784, + jzy: 6785, + jaz: 6786, + jaa: 6787, + jab: 6788, + jac: 6789, + jad: 6790, + jae: 6791, + jaf: 6792, + jag: 6793, + jah: 6794, + jai: 6795, + jaj: 6796, + jak: 6797, + jal: 6798, + jam: 6799, + jan: 6800, + jao: 6801, + jap: 6802, + jaq: 6803, + jar: 6804, + jas: 6805, + jat: 6806, + jau: 6807, + jav: 6808, + jaw: 6809, + jax: 6810, + jay: 6811, + jbz: 6812, + jba: 6813, + jbb: 6814, + jbc: 6815, + jbd: 6816, + jbe: 6817, + jbf: 6818, + jbg: 6819, + jbh: 6820, + jbi: 6821, + jbj: 6822, + jbk: 6823, + jbl: 6824, + jbm: 6825, + jbn: 6826, + jbo: 6827, + jbp: 6828, + jbq: 6829, + jbr: 6830, + jbs: 6831, + jbt: 6832, + jbu: 6833, + jbv: 6834, + jbw: 6835, + jbx: 6836, + jby: 6837, + jcz: 6838, + jca: 6839, + jcb: 6840, + jcc: 6841, + jcd: 6842, + jce: 6843, + jcf: 6844, + jcg: 6845, + jch: 6846, + jci: 6847, + jcj: 6848, + jck: 6849, + jcl: 6850, + jcm: 6851, + jcn: 6852, + jco: 6853, + jcp: 6854, + jcq: 6855, + jcr: 6856, + jcs: 6857, + jct: 6858, + jcu: 6859, + jcv: 6860, + jcw: 6861, + jcx: 6862, + jcy: 6863, + jdz: 6864, + jda: 6865, + jdb: 6866, + jdc: 6867, + jdd: 6868, + jde: 6869, + jdf: 6870, + jdg: 6871, + jdh: 6872, + jdi: 6873, + jdj: 6874, + jdk: 6875, + jdl: 6876, + jdm: 6877, + jdn: 6878, + jdo: 6879, + jdp: 6880, + jdq: 6881, + jdr: 6882, + jds: 6883, + jdt: 6884, + jdu: 6885, + jdv: 6886, + jdw: 6887, + jdx: 6888, + jdy: 6889, + jez: 6890, + jea: 6891, + jeb: 6892, + jec: 6893, + jed: 6894, + jee: 6895, + jef: 6896, + jeg: 6897, + jeh: 6898, + jei: 6899, + jej: 6900, + jek: 6901, + jel: 6902, + jem: 6903, + jen: 6904, + jeo: 6905, + jep: 6906, + jeq: 6907, + jer: 6908, + jes: 6909, + jet: 6910, + jeu: 6911, + jev: 6912, + jew: 6913, + jex: 6914, + jey: 6915, + jfz: 6916, + jfa: 6917, + jfb: 6918, + jfc: 6919, + jfd: 6920, + jfe: 6921, + jff: 6922, + jfg: 6923, + jfh: 6924, + jfi: 6925, + jfj: 6926, + jfk: 6927, + jfl: 6928, + jfm: 6929, + jfn: 6930, + jfo: 6931, + jfp: 6932, + jfq: 6933, + jfr: 6934, + jfs: 6935, + jft: 6936, + jfu: 6937, + jfv: 6938, + jfw: 6939, + jfx: 6940, + jfy: 6941, + jgz: 6942, + jga: 6943, + jgb: 6944, + jgc: 6945, + jgd: 6946, + jge: 6947, + jgf: 6948, + jgg: 6949, + jgh: 6950, + jgi: 6951, + jgj: 6952, + jgk: 6953, + jgl: 6954, + jgm: 6955, + jgn: 6956, + jgo: 6957, + jgp: 6958, + jgq: 6959, + jgr: 6960, + jgs: 6961, + jgt: 6962, + jgu: 6963, + jgv: 6964, + jgw: 6965, + jgx: 6966, + jgy: 6967, + jhz: 6968, + jha: 6969, + jhb: 6970, + jhc: 6971, + jhd: 6972, + jhe: 6973, + jhf: 6974, + jhg: 6975, + jhh: 6976, + jhi: 6977, + jhj: 6978, + jhk: 6979, + jhl: 6980, + jhm: 6981, + jhn: 6982, + jho: 6983, + jhp: 6984, + jhq: 6985, + jhr: 6986, + jhs: 6987, + jht: 6988, + jhu: 6989, + jhv: 6990, + jhw: 6991, + jhx: 6992, + jhy: 6993, + jiz: 6994, + jia: 6995, + jib: 6996, + jic: 6997, + jid: 6998, + jie: 6999, + jif: 7000, + jig: 7001, + jih: 7002, + jii: 7003, + jij: 7004, + jik: 7005, + jil: 7006, + jim: 7007, + jin: 7008, + jio: 7009, + jip: 7010, + jiq: 7011, + jir: 7012, + jis: 7013, + jit: 7014, + jiu: 7015, + jiv: 7016, + jiw: 7017, + jix: 7018, + jiy: 7019, + jjz: 7020, + jja: 7021, + jjb: 7022, + jjc: 7023, + jjd: 7024, + jje: 7025, + jjf: 7026, + jjg: 7027, + jjh: 7028, + jji: 7029, + jjj: 7030, + jjk: 7031, + jjl: 7032, + jjm: 7033, + jjn: 7034, + jjo: 7035, + jjp: 7036, + jjq: 7037, + jjr: 7038, + jjs: 7039, + jjt: 7040, + jju: 7041, + jjv: 7042, + jjw: 7043, + jjx: 7044, + jjy: 7045, + jkz: 7046, + jka: 7047, + jkb: 7048, + jkc: 7049, + jkd: 7050, + jke: 7051, + jkf: 7052, + jkg: 7053, + jkh: 7054, + jki: 7055, + jkj: 7056, + jkk: 7057, + jkl: 7058, + jkm: 7059, + jkn: 7060, + jko: 7061, + jkp: 7062, + jkq: 7063, + jkr: 7064, + jks: 7065, + jkt: 7066, + jku: 7067, + jkv: 7068, + jkw: 7069, + jkx: 7070, + jky: 7071, + jlz: 7072, + jla: 7073, + jlb: 7074, + jlc: 7075, + jld: 7076, + jle: 7077, + jlf: 7078, + jlg: 7079, + jlh: 7080, + jli: 7081, + jlj: 7082, + jlk: 7083, + jll: 7084, + jlm: 7085, + jln: 7086, + jlo: 7087, + jlp: 7088, + jlq: 7089, + jlr: 7090, + jls: 7091, + jlt: 7092, + jlu: 7093, + jlv: 7094, + jlw: 7095, + jlx: 7096, + jly: 7097, + jmz: 7098, + jma: 7099, + jmb: 7100, + jmc: 7101, + jmd: 7102, + jme: 7103, + jmf: 7104, + jmg: 7105, + jmh: 7106, + jmi: 7107, + jmj: 7108, + jmk: 7109, + jml: 7110, + jmm: 7111, + jmn: 7112, + jmo: 7113, + jmp: 7114, + jmq: 7115, + jmr: 7116, + jms: 7117, + jmt: 7118, + jmu: 7119, + jmv: 7120, + jmw: 7121, + jmx: 7122, + jmy: 7123, + jnz: 7124, + jna: 7125, + jnb: 7126, + jnc: 7127, + jnd: 7128, + jne: 7129, + jnf: 7130, + jng: 7131, + jnh: 7132, + jni: 7133, + jnj: 7134, + jnk: 7135, + jnl: 7136, + jnm: 7137, + jnn: 7138, + jno: 7139, + jnp: 7140, + jnq: 7141, + jnr: 7142, + jns: 7143, + jnt: 7144, + jnu: 7145, + jnv: 7146, + jnw: 7147, + jnx: 7148, + jny: 7149, + joz: 7150, + joa: 7151, + job: 7152, + joc: 7153, + jod: 7154, + joe: 7155, + jof: 7156, + jog: 7157, + joh: 7158, + joi: 7159, + joj: 7160, + jok: 7161, + jol: 7162, + jom: 7163, + jon: 7164, + joo: 7165, + jop: 7166, + joq: 7167, + jor: 7168, + jos: 7169, + jot: 7170, + jou: 7171, + jov: 7172, + jow: 7173, + jox: 7174, + joy: 7175, + jpz: 7176, + jpa: 7177, + jpb: 7178, + jpc: 7179, + jpd: 7180, + jpe: 7181, + jpf: 7182, + jpg: 7183, + jph: 7184, + jpi: 7185, + jpj: 7186, + jpk: 7187, + jpl: 7188, + jpm: 7189, + jpn: 7190, + jpo: 7191, + jpp: 7192, + jpq: 7193, + jpr: 7194, + jps: 7195, + jpt: 7196, + jpu: 7197, + jpv: 7198, + jpw: 7199, + jpx: 7200, + jpy: 7201, + jqz: 7202, + jqa: 7203, + jqb: 7204, + jqc: 7205, + jqd: 7206, + jqe: 7207, + jqf: 7208, + jqg: 7209, + jqh: 7210, + jqi: 7211, + jqj: 7212, + jqk: 7213, + jql: 7214, + jqm: 7215, + jqn: 7216, + jqo: 7217, + jqp: 7218, + jqq: 7219, + jqr: 7220, + jqs: 7221, + jqt: 7222, + jqu: 7223, + jqv: 7224, + jqw: 7225, + jqx: 7226, + jqy: 7227, + jrz: 7228, + jra: 7229, + jrb: 7230, + jrc: 7231, + jrd: 7232, + jre: 7233, + jrf: 7234, + jrg: 7235, + jrh: 7236, + jri: 7237, + jrj: 7238, + jrk: 7239, + jrl: 7240, + jrm: 7241, + jrn: 7242, + jro: 7243, + jrp: 7244, + jrq: 7245, + jrr: 7246, + jrs: 7247, + jrt: 7248, + jru: 7249, + jrv: 7250, + jrw: 7251, + jrx: 7252, + jry: 7253, + jsz: 7254, + jsa: 7255, + jsb: 7256, + jsc: 7257, + jsd: 7258, + jse: 7259, + jsf: 7260, + jsg: 7261, + jsh: 7262, + jsi: 7263, + jsj: 7264, + jsk: 7265, + jsl: 7266, + jsm: 7267, + jsn: 7268, + jso: 7269, + jsp: 7270, + jsq: 7271, + jsr: 7272, + jss: 7273, + jst: 7274, + jsu: 7275, + jsv: 7276, + jsw: 7277, + jsx: 7278, + jsy: 7279, + jtz: 7280, + jta: 7281, + jtb: 7282, + jtc: 7283, + jtd: 7284, + jte: 7285, + jtf: 7286, + jtg: 7287, + jth: 7288, + jti: 7289, + jtj: 7290, + jtk: 7291, + jtl: 7292, + jtm: 7293, + jtn: 7294, + jto: 7295, + jtp: 7296, + jtq: 7297, + jtr: 7298, + jts: 7299, + jtt: 7300, + jtu: 7301, + jtv: 7302, + jtw: 7303, + jtx: 7304, + jty: 7305, + juz: 7306, + jua: 7307, + jub: 7308, + juc: 7309, + jud: 7310, + jue: 7311, + juf: 7312, + jug: 7313, + juh: 7314, + jui: 7315, + juj: 7316, + juk: 7317, + jul: 7318, + jum: 7319, + jun: 7320, + juo: 7321, + jup: 7322, + juq: 7323, + jur: 7324, + jus: 7325, + jut: 7326, + juu: 7327, + juv: 7328, + juw: 7329, + jux: 7330, + juy: 7331, + jvz: 7332, + jva: 7333, + jvb: 7334, + jvc: 7335, + jvd: 7336, + jve: 7337, + jvf: 7338, + jvg: 7339, + jvh: 7340, + jvi: 7341, + jvj: 7342, + jvk: 7343, + jvl: 7344, + jvm: 7345, + jvn: 7346, + jvo: 7347, + jvp: 7348, + jvq: 7349, + jvr: 7350, + jvs: 7351, + jvt: 7352, + jvu: 7353, + jvv: 7354, + jvw: 7355, + jvx: 7356, + jvy: 7357, + jwz: 7358, + jwa: 7359, + jwb: 7360, + jwc: 7361, + jwd: 7362, + jwe: 7363, + jwf: 7364, + jwg: 7365, + jwh: 7366, + jwi: 7367, + jwj: 7368, + jwk: 7369, + jwl: 7370, + jwm: 7371, + jwn: 7372, + jwo: 7373, + jwp: 7374, + jwq: 7375, + jwr: 7376, + jws: 7377, + jwt: 7378, + jwu: 7379, + jwv: 7380, + jww: 7381, + jwx: 7382, + jwy: 7383, + jxz: 7384, + jxa: 7385, + jxb: 7386, + jxc: 7387, + jxd: 7388, + jxe: 7389, + jxf: 7390, + jxg: 7391, + jxh: 7392, + jxi: 7393, + jxj: 7394, + jxk: 7395, + jxl: 7396, + jxm: 7397, + jxn: 7398, + jxo: 7399, + jxp: 7400, + jxq: 7401, + jxr: 7402, + jxs: 7403, + jxt: 7404, + jxu: 7405, + jxv: 7406, + jxw: 7407, + jxx: 7408, + jxy: 7409, + jyz: 7410, + jya: 7411, + jyb: 7412, + jyc: 7413, + jyd: 7414, + jye: 7415, + jyf: 7416, + jyg: 7417, + jyh: 7418, + jyi: 7419, + jyj: 7420, + jyk: 7421, + jyl: 7422, + jym: 7423, + jyn: 7424, + jyo: 7425, + jyp: 7426, + jyq: 7427, + jyr: 7428, + jys: 7429, + jyt: 7430, + jyu: 7431, + jyv: 7432, + jyw: 7433, + jyx: 7434, + jyy: 7435, + kzz: 7436, + kza: 7437, + kzb: 7438, + kzc: 7439, + kzd: 7440, + kze: 7441, + kzf: 7442, + kzg: 7443, + kzh: 7444, + kzi: 7445, + kzj: 7446, + kzk: 7447, + kzl: 7448, + kzm: 7449, + kzn: 7450, + kzo: 7451, + kzp: 7452, + kzq: 7453, + kzr: 7454, + kzs: 7455, + kzt: 7456, + kzu: 7457, + kzv: 7458, + kzw: 7459, + kzx: 7460, + kzy: 7461, + kaz: 7462, + kaa: 7463, + kab: 7464, + kac: 7465, + kad: 7466, + kae: 7467, + kaf: 7468, + kag: 7469, + kah: 7470, + kai: 7471, + kaj: 7472, + kak: 7473, + kal: 7474, + kam: 7475, + kan: 7476, + kao: 7477, + kap: 7478, + kaq: 7479, + kar: 7480, + kas: 7481, + kat: 7482, + kau: 7483, + kav: 7484, + kaw: 7485, + kax: 7486, + kay: 7487, + kbz: 7488, + kba: 7489, + kbb: 7490, + kbc: 7491, + kbd: 7492, + kbe: 7493, + kbf: 7494, + kbg: 7495, + kbh: 7496, + kbi: 7497, + kbj: 7498, + kbk: 7499, + kbl: 7500, + kbm: 7501, + kbn: 7502, + kbo: 7503, + kbp: 7504, + kbq: 7505, + kbr: 7506, + kbs: 7507, + kbt: 7508, + kbu: 7509, + kbv: 7510, + kbw: 7511, + kbx: 7512, + kby: 7513, + kcz: 7514, + kca: 7515, + kcb: 7516, + kcc: 7517, + kcd: 7518, + kce: 7519, + kcf: 7520, + kcg: 7521, + kch: 7522, + kci: 7523, + kcj: 7524, + kck: 7525, + kcl: 7526, + kcm: 7527, + kcn: 7528, + kco: 7529, + kcp: 7530, + kcq: 7531, + kcr: 7532, + kcs: 7533, + kct: 7534, + kcu: 7535, + kcv: 7536, + kcw: 7537, + kcx: 7538, + kcy: 7539, + kdz: 7540, + kda: 7541, + kdb: 7542, + kdc: 7543, + kdd: 7544, + kde: 7545, + kdf: 7546, + kdg: 7547, + kdh: 7548, + kdi: 7549, + kdj: 7550, + kdk: 7551, + kdl: 7552, + kdm: 7553, + kdn: 7554, + kdo: 7555, + kdp: 7556, + kdq: 7557, + kdr: 7558, + kds: 7559, + kdt: 7560, + kdu: 7561, + kdv: 7562, + kdw: 7563, + kdx: 7564, + kdy: 7565, + kez: 7566, + kea: 7567, + keb: 7568, + kec: 7569, + ked: 7570, + kee: 7571, + kef: 7572, + keg: 7573, + keh: 7574, + kei: 7575, + kej: 7576, + kek: 7577, + kel: 7578, + kem: 7579, + ken: 7580, + keo: 7581, + kep: 7582, + keq: 7583, + ker: 7584, + kes: 7585, + ket: 7586, + keu: 7587, + kev: 7588, + kew: 7589, + kex: 7590, + key: 7591, + kfz: 7592, + kfa: 7593, + kfb: 7594, + kfc: 7595, + kfd: 7596, + kfe: 7597, + kff: 7598, + kfg: 7599, + kfh: 7600, + kfi: 7601, + kfj: 7602, + kfk: 7603, + kfl: 7604, + kfm: 7605, + kfn: 7606, + kfo: 7607, + kfp: 7608, + kfq: 7609, + kfr: 7610, + kfs: 7611, + kft: 7612, + kfu: 7613, + kfv: 7614, + kfw: 7615, + kfx: 7616, + kfy: 7617, + kgz: 7618, + kga: 7619, + kgb: 7620, + kgc: 7621, + kgd: 7622, + kge: 7623, + kgf: 7624, + kgg: 7625, + kgh: 7626, + kgi: 7627, + kgj: 7628, + kgk: 7629, + kgl: 7630, + kgm: 7631, + kgn: 7632, + kgo: 7633, + kgp: 7634, + kgq: 7635, + kgr: 7636, + kgs: 7637, + kgt: 7638, + kgu: 7639, + kgv: 7640, + kgw: 7641, + kgx: 7642, + kgy: 7643, + khz: 7644, + kha: 7645, + khb: 7646, + khc: 7647, + khd: 7648, + khe: 7649, + khf: 7650, + khg: 7651, + khh: 7652, + khi: 7653, + khj: 7654, + khk: 7655, + khl: 7656, + khm: 7657, + khn: 7658, + kho: 7659, + khp: 7660, + khq: 7661, + khr: 7662, + khs: 7663, + kht: 7664, + khu: 7665, + khv: 7666, + khw: 7667, + khx: 7668, + khy: 7669, + kiz: 7670, + kia: 7671, + kib: 7672, + kic: 7673, + kid: 7674, + kie: 7675, + kif: 7676, + kig: 7677, + kih: 7678, + kii: 7679, + kij: 7680, + kik: 7681, + kil: 7682, + kim: 7683, + kin: 7684, + kio: 7685, + kip: 7686, + kiq: 7687, + kir: 7688, + kis: 7689, + kit: 7690, + kiu: 7691, + kiv: 7692, + kiw: 7693, + kix: 7694, + kiy: 7695, + kjz: 7696, + kja: 7697, + kjb: 7698, + kjc: 7699, + kjd: 7700, + kje: 7701, + kjf: 7702, + kjg: 7703, + kjh: 7704, + kji: 7705, + kjj: 7706, + kjk: 7707, + kjl: 7708, + kjm: 7709, + kjn: 7710, + kjo: 7711, + kjp: 7712, + kjq: 7713, + kjr: 7714, + kjs: 7715, + kjt: 7716, + kju: 7717, + kjv: 7718, + kjw: 7719, + kjx: 7720, + kjy: 7721, + kkz: 7722, + kka: 7723, + kkb: 7724, + kkc: 7725, + kkd: 7726, + kke: 7727, + kkf: 7728, + kkg: 7729, + kkh: 7730, + kki: 7731, + kkj: 7732, + kkk: 7733, + kkl: 7734, + kkm: 7735, + kkn: 7736, + kko: 7737, + kkp: 7738, + kkq: 7739, + kkr: 7740, + kks: 7741, + kkt: 7742, + kku: 7743, + kkv: 7744, + kkw: 7745, + kkx: 7746, + kky: 7747, + klz: 7748, + kla: 7749, + klb: 7750, + klc: 7751, + kld: 7752, + kle: 7753, + klf: 7754, + klg: 7755, + klh: 7756, + kli: 7757, + klj: 7758, + klk: 7759, + kll: 7760, + klm: 7761, + kln: 7762, + klo: 7763, + klp: 7764, + klq: 7765, + klr: 7766, + kls: 7767, + klt: 7768, + klu: 7769, + klv: 7770, + klw: 7771, + klx: 7772, + kly: 7773, + kmz: 7774, + kma: 7775, + kmb: 7776, + kmc: 7777, + kmd: 7778, + kme: 7779, + kmf: 7780, + kmg: 7781, + kmh: 7782, + kmi: 7783, + kmj: 7784, + kmk: 7785, + kml: 7786, + kmm: 7787, + kmn: 7788, + kmo: 7789, + kmp: 7790, + kmq: 7791, + kmr: 7792, + kms: 7793, + kmt: 7794, + kmu: 7795, + kmv: 7796, + kmw: 7797, + kmx: 7798, + kmy: 7799, + knz: 7800, + kna: 7801, + knb: 7802, + knc: 7803, + knd: 7804, + kne: 7805, + knf: 7806, + kng: 7807, + knh: 7808, + kni: 7809, + knj: 7810, + knk: 7811, + knl: 7812, + knm: 7813, + knn: 7814, + kno: 7815, + knp: 7816, + knq: 7817, + knr: 7818, + kns: 7819, + knt: 7820, + knu: 7821, + knv: 7822, + knw: 7823, + knx: 7824, + kny: 7825, + koz: 7826, + koa: 7827, + kob: 7828, + koc: 7829, + kod: 7830, + koe: 7831, + kof: 7832, + kog: 7833, + koh: 7834, + koi: 7835, + koj: 7836, + kok: 7837, + kol: 7838, + kom: 7839, + kon: 7840, + koo: 7841, + kop: 7842, + koq: 7843, + kor: 7844, + kos: 7845, + kot: 7846, + kou: 7847, + kov: 7848, + kow: 7849, + kox: 7850, + koy: 7851, + kpz: 7852, + kpa: 7853, + kpb: 7854, + kpc: 7855, + kpd: 7856, + kpe: 7857, + kpf: 7858, + kpg: 7859, + kph: 7860, + kpi: 7861, + kpj: 7862, + kpk: 7863, + kpl: 7864, + kpm: 7865, + kpn: 7866, + kpo: 7867, + kpp: 7868, + kpq: 7869, + kpr: 7870, + kps: 7871, + kpt: 7872, + kpu: 7873, + kpv: 7874, + kpw: 7875, + kpx: 7876, + kpy: 7877, + kqz: 7878, + kqa: 7879, + kqb: 7880, + kqc: 7881, + kqd: 7882, + kqe: 7883, + kqf: 7884, + kqg: 7885, + kqh: 7886, + kqi: 7887, + kqj: 7888, + kqk: 7889, + kql: 7890, + kqm: 7891, + kqn: 7892, + kqo: 7893, + kqp: 7894, + kqq: 7895, + kqr: 7896, + kqs: 7897, + kqt: 7898, + kqu: 7899, + kqv: 7900, + kqw: 7901, + kqx: 7902, + kqy: 7903, + krz: 7904, + kra: 7905, + krb: 7906, + krc: 7907, + krd: 7908, + kre: 7909, + krf: 7910, + krg: 7911, + krh: 7912, + kri: 7913, + krj: 7914, + krk: 7915, + krl: 7916, + krm: 7917, + krn: 7918, + kro: 7919, + krp: 7920, + krq: 7921, + krr: 7922, + krs: 7923, + krt: 7924, + kru: 7925, + krv: 7926, + krw: 7927, + krx: 7928, + kry: 7929, + ksz: 7930, + ksa: 7931, + ksb: 7932, + ksc: 7933, + ksd: 7934, + kse: 7935, + ksf: 7936, + ksg: 7937, + ksh: 7938, + ksi: 7939, + ksj: 7940, + ksk: 7941, + ksl: 7942, + ksm: 7943, + ksn: 7944, + kso: 7945, + ksp: 7946, + ksq: 7947, + ksr: 7948, + kss: 7949, + kst: 7950, + ksu: 7951, + ksv: 7952, + ksw: 7953, + ksx: 7954, + ksy: 7955, + ktz: 7956, + kta: 7957, + ktb: 7958, + ktc: 7959, + ktd: 7960, + kte: 7961, + ktf: 7962, + ktg: 7963, + kth: 7964, + kti: 7965, + ktj: 7966, + ktk: 7967, + ktl: 7968, + ktm: 7969, + ktn: 7970, + kto: 7971, + ktp: 7972, + ktq: 7973, + ktr: 7974, + kts: 7975, + ktt: 7976, + ktu: 7977, + ktv: 7978, + ktw: 7979, + ktx: 7980, + kty: 7981, + kuz: 7982, + kua: 7983, + kub: 7984, + kuc: 7985, + kud: 7986, + kue: 7987, + kuf: 7988, + kug: 7989, + kuh: 7990, + kui: 7991, + kuj: 7992, + kuk: 7993, + kul: 7994, + kum: 7995, + kun: 7996, + kuo: 7997, + kup: 7998, + kuq: 7999, + kur: 8000, + kus: 8001, + kut: 8002, + kuu: 8003, + kuv: 8004, + kuw: 8005, + kux: 8006, + kuy: 8007, + kvz: 8008, + kva: 8009, + kvb: 8010, + kvc: 8011, + kvd: 8012, + kve: 8013, + kvf: 8014, + kvg: 8015, + kvh: 8016, + kvi: 8017, + kvj: 8018, + kvk: 8019, + kvl: 8020, + kvm: 8021, + kvn: 8022, + kvo: 8023, + kvp: 8024, + kvq: 8025, + kvr: 8026, + kvs: 8027, + kvt: 8028, + kvu: 8029, + kvv: 8030, + kvw: 8031, + kvx: 8032, + kvy: 8033, + kwz: 8034, + kwa: 8035, + kwb: 8036, + kwc: 8037, + kwd: 8038, + kwe: 8039, + kwf: 8040, + kwg: 8041, + kwh: 8042, + kwi: 8043, + kwj: 8044, + kwk: 8045, + kwl: 8046, + kwm: 8047, + kwn: 8048, + kwo: 8049, + kwp: 8050, + kwq: 8051, + kwr: 8052, + kws: 8053, + kwt: 8054, + kwu: 8055, + kwv: 8056, + kww: 8057, + kwx: 8058, + kwy: 8059, + kxz: 8060, + kxa: 8061, + kxb: 8062, + kxc: 8063, + kxd: 8064, + kxe: 8065, + kxf: 8066, + kxg: 8067, + kxh: 8068, + kxi: 8069, + kxj: 8070, + kxk: 8071, + kxl: 8072, + kxm: 8073, + kxn: 8074, + kxo: 8075, + kxp: 8076, + kxq: 8077, + kxr: 8078, + kxs: 8079, + kxt: 8080, + kxu: 8081, + kxv: 8082, + kxw: 8083, + kxx: 8084, + kxy: 8085, + kyz: 8086, + kya: 8087, + kyb: 8088, + kyc: 8089, + kyd: 8090, + kye: 8091, + kyf: 8092, + kyg: 8093, + kyh: 8094, + kyi: 8095, + kyj: 8096, + kyk: 8097, + kyl: 8098, + kym: 8099, + kyn: 8100, + kyo: 8101, + kyp: 8102, + kyq: 8103, + kyr: 8104, + kys: 8105, + kyt: 8106, + kyu: 8107, + kyv: 8108, + kyw: 8109, + kyx: 8110, + kyy: 8111, + lzz: 8112, + lza: 8113, + lzb: 8114, + lzc: 8115, + lzd: 8116, + lze: 8117, + lzf: 8118, + lzg: 8119, + lzh: 8120, + lzi: 8121, + lzj: 8122, + lzk: 8123, + lzl: 8124, + lzm: 8125, + lzn: 8126, + lzo: 8127, + lzp: 8128, + lzq: 8129, + lzr: 8130, + lzs: 8131, + lzt: 8132, + lzu: 8133, + lzv: 8134, + lzw: 8135, + lzx: 8136, + lzy: 8137, + laz: 8138, + laa: 8139, + lab: 8140, + lac: 8141, + lad: 8142, + lae: 8143, + laf: 8144, + lag: 8145, + lah: 8146, + lai: 8147, + laj: 8148, + lak: 8149, + lal: 8150, + lam: 8151, + lan: 8152, + lao: 8153, + lap: 8154, + laq: 8155, + lar: 8156, + las: 8157, + lat: 8158, + lau: 8159, + lav: 8160, + law: 8161, + lax: 8162, + lay: 8163, + lbz: 8164, + lba: 8165, + lbb: 8166, + lbc: 8167, + lbd: 8168, + lbe: 8169, + lbf: 8170, + lbg: 8171, + lbh: 8172, + lbi: 8173, + lbj: 8174, + lbk: 8175, + lbl: 8176, + lbm: 8177, + lbn: 8178, + lbo: 8179, + lbp: 8180, + lbq: 8181, + lbr: 8182, + lbs: 8183, + lbt: 8184, + lbu: 8185, + lbv: 8186, + lbw: 8187, + lbx: 8188, + lby: 8189, + lcz: 8190, + lca: 8191, + lcb: 8192, + lcc: 8193, + lcd: 8194, + lce: 8195, + lcf: 8196, + lcg: 8197, + lch: 8198, + lci: 8199, + lcj: 8200, + lck: 8201, + lcl: 8202, + lcm: 8203, + lcn: 8204, + lco: 8205, + lcp: 8206, + lcq: 8207, + lcr: 8208, + lcs: 8209, + lct: 8210, + lcu: 8211, + lcv: 8212, + lcw: 8213, + lcx: 8214, + lcy: 8215, + ldz: 8216, + lda: 8217, + ldb: 8218, + ldc: 8219, + ldd: 8220, + lde: 8221, + ldf: 8222, + ldg: 8223, + ldh: 8224, + ldi: 8225, + ldj: 8226, + ldk: 8227, + ldl: 8228, + ldm: 8229, + ldn: 8230, + ldo: 8231, + ldp: 8232, + ldq: 8233, + ldr: 8234, + lds: 8235, + ldt: 8236, + ldu: 8237, + ldv: 8238, + ldw: 8239, + ldx: 8240, + ldy: 8241, + lez: 8242, + lea: 8243, + leb: 8244, + lec: 8245, + led: 8246, + lee: 8247, + lef: 8248, + leg: 8249, + leh: 8250, + lei: 8251, + lej: 8252, + lek: 8253, + lel: 8254, + lem: 8255, + len: 8256, + leo: 8257, + lep: 8258, + leq: 8259, + ler: 8260, + les: 8261, + let: 8262, + leu: 8263, + lev: 8264, + lew: 8265, + lex: 8266, + ley: 8267, + lfz: 8268, + lfa: 8269, + lfb: 8270, + lfc: 8271, + lfd: 8272, + lfe: 8273, + lff: 8274, + lfg: 8275, + lfh: 8276, + lfi: 8277, + lfj: 8278, + lfk: 8279, + lfl: 8280, + lfm: 8281, + lfn: 8282, + lfo: 8283, + lfp: 8284, + lfq: 8285, + lfr: 8286, + lfs: 8287, + lft: 8288, + lfu: 8289, + lfv: 8290, + lfw: 8291, + lfx: 8292, + lfy: 8293, + lgz: 8294, + lga: 8295, + lgb: 8296, + lgc: 8297, + lgd: 8298, + lge: 8299, + lgf: 8300, + lgg: 8301, + lgh: 8302, + lgi: 8303, + lgj: 8304, + lgk: 8305, + lgl: 8306, + lgm: 8307, + lgn: 8308, + lgo: 8309, + lgp: 8310, + lgq: 8311, + lgr: 8312, + lgs: 8313, + lgt: 8314, + lgu: 8315, + lgv: 8316, + lgw: 8317, + lgx: 8318, + lgy: 8319, + lhz: 8320, + lha: 8321, + lhb: 8322, + lhc: 8323, + lhd: 8324, + lhe: 8325, + lhf: 8326, + lhg: 8327, + lhh: 8328, + lhi: 8329, + lhj: 8330, + lhk: 8331, + lhl: 8332, + lhm: 8333, + lhn: 8334, + lho: 8335, + lhp: 8336, + lhq: 8337, + lhr: 8338, + lhs: 8339, + lht: 8340, + lhu: 8341, + lhv: 8342, + lhw: 8343, + lhx: 8344, + lhy: 8345, + liz: 8346, + lia: 8347, + lib: 8348, + lic: 8349, + lid: 8350, + lie: 8351, + lif: 8352, + lig: 8353, + lih: 8354, + lii: 8355, + lij: 8356, + lik: 8357, + lil: 8358, + lim: 8359, + lin: 8360, + lio: 8361, + lip: 8362, + liq: 8363, + lir: 8364, + lis: 8365, + lit: 8366, + liu: 8367, + liv: 8368, + liw: 8369, + lix: 8370, + liy: 8371, + ljz: 8372, + lja: 8373, + ljb: 8374, + ljc: 8375, + ljd: 8376, + lje: 8377, + ljf: 8378, + ljg: 8379, + ljh: 8380, + lji: 8381, + ljj: 8382, + ljk: 8383, + ljl: 8384, + ljm: 8385, + ljn: 8386, + ljo: 8387, + ljp: 8388, + ljq: 8389, + ljr: 8390, + ljs: 8391, + ljt: 8392, + lju: 8393, + ljv: 8394, + ljw: 8395, + ljx: 8396, + ljy: 8397, + lkz: 8398, + lka: 8399, + lkb: 8400, + lkc: 8401, + lkd: 8402, + lke: 8403, + lkf: 8404, + lkg: 8405, + lkh: 8406, + lki: 8407, + lkj: 8408, + lkk: 8409, + lkl: 8410, + lkm: 8411, + lkn: 8412, + lko: 8413, + lkp: 8414, + lkq: 8415, + lkr: 8416, + lks: 8417, + lkt: 8418, + lku: 8419, + lkv: 8420, + lkw: 8421, + lkx: 8422, + lky: 8423, + llz: 8424, + lla: 8425, + llb: 8426, + llc: 8427, + lld: 8428, + lle: 8429, + llf: 8430, + llg: 8431, + llh: 8432, + lli: 8433, + llj: 8434, + llk: 8435, + lll: 8436, + llm: 8437, + lln: 8438, + llo: 8439, + llp: 8440, + llq: 8441, + llr: 8442, + lls: 8443, + llt: 8444, + llu: 8445, + llv: 8446, + llw: 8447, + llx: 8448, + lly: 8449, + lmz: 8450, + lma: 8451, + lmb: 8452, + lmc: 8453, + lmd: 8454, + lme: 8455, + lmf: 8456, + lmg: 8457, + lmh: 8458, + lmi: 8459, + lmj: 8460, + lmk: 8461, + lml: 8462, + lmm: 8463, + lmn: 8464, + lmo: 8465, + lmp: 8466, + lmq: 8467, + lmr: 8468, + lms: 8469, + lmt: 8470, + lmu: 8471, + lmv: 8472, + lmw: 8473, + lmx: 8474, + lmy: 8475, + lnz: 8476, + lna: 8477, + lnb: 8478, + lnc: 8479, + lnd: 8480, + lne: 8481, + lnf: 8482, + lng: 8483, + lnh: 8484, + lni: 8485, + lnj: 8486, + lnk: 8487, + lnl: 8488, + lnm: 8489, + lnn: 8490, + lno: 8491, + lnp: 8492, + lnq: 8493, + lnr: 8494, + lns: 8495, + lnt: 8496, + lnu: 8497, + lnv: 8498, + lnw: 8499, + lnx: 8500, + lny: 8501, + loz: 8502, + loa: 8503, + lob: 8504, + loc: 8505, + lod: 8506, + loe: 8507, + lof: 8508, + log: 8509, + loh: 8510, + loi: 8511, + loj: 8512, + lok: 8513, + lol: 8514, + lom: 8515, + lon: 8516, + loo: 8517, + lop: 8518, + loq: 8519, + lor: 8520, + los: 8521, + lot: 8522, + lou: 8523, + lov: 8524, + low: 8525, + lox: 8526, + loy: 8527, + lpz: 8528, + lpa: 8529, + lpb: 8530, + lpc: 8531, + lpd: 8532, + lpe: 8533, + lpf: 8534, + lpg: 8535, + lph: 8536, + lpi: 8537, + lpj: 8538, + lpk: 8539, + lpl: 8540, + lpm: 8541, + lpn: 8542, + lpo: 8543, + lpp: 8544, + lpq: 8545, + lpr: 8546, + lps: 8547, + lpt: 8548, + lpu: 8549, + lpv: 8550, + lpw: 8551, + lpx: 8552, + lpy: 8553, + lqz: 8554, + lqa: 8555, + lqb: 8556, + lqc: 8557, + lqd: 8558, + lqe: 8559, + lqf: 8560, + lqg: 8561, + lqh: 8562, + lqi: 8563, + lqj: 8564, + lqk: 8565, + lql: 8566, + lqm: 8567, + lqn: 8568, + lqo: 8569, + lqp: 8570, + lqq: 8571, + lqr: 8572, + lqs: 8573, + lqt: 8574, + lqu: 8575, + lqv: 8576, + lqw: 8577, + lqx: 8578, + lqy: 8579, + lrz: 8580, + lra: 8581, + lrb: 8582, + lrc: 8583, + lrd: 8584, + lre: 8585, + lrf: 8586, + lrg: 8587, + lrh: 8588, + lri: 8589, + lrj: 8590, + lrk: 8591, + lrl: 8592, + lrm: 8593, + lrn: 8594, + lro: 8595, + lrp: 8596, + lrq: 8597, + lrr: 8598, + lrs: 8599, + lrt: 8600, + lru: 8601, + lrv: 8602, + lrw: 8603, + lrx: 8604, + lry: 8605, + lsz: 8606, + lsa: 8607, + lsb: 8608, + lsc: 8609, + lsd: 8610, + lse: 8611, + lsf: 8612, + lsg: 8613, + lsh: 8614, + lsi: 8615, + lsj: 8616, + lsk: 8617, + lsl: 8618, + lsm: 8619, + lsn: 8620, + lso: 8621, + lsp: 8622, + lsq: 8623, + lsr: 8624, + lss: 8625, + lst: 8626, + lsu: 8627, + lsv: 8628, + lsw: 8629, + lsx: 8630, + lsy: 8631, + ltz: 8632, + lta: 8633, + ltb: 8634, + ltc: 8635, + ltd: 8636, + lte: 8637, + ltf: 8638, + ltg: 8639, + lth: 8640, + lti: 8641, + ltj: 8642, + ltk: 8643, + ltl: 8644, + ltm: 8645, + ltn: 8646, + lto: 8647, + ltp: 8648, + ltq: 8649, + ltr: 8650, + lts: 8651, + ltt: 8652, + ltu: 8653, + ltv: 8654, + ltw: 8655, + ltx: 8656, + lty: 8657, + luz: 8658, + lua: 8659, + lub: 8660, + luc: 8661, + lud: 8662, + lue: 8663, + luf: 8664, + lug: 8665, + luh: 8666, + lui: 8667, + luj: 8668, + luk: 8669, + lul: 8670, + lum: 8671, + lun: 8672, + luo: 8673, + lup: 8674, + luq: 8675, + lur: 8676, + lus: 8677, + lut: 8678, + luu: 8679, + luv: 8680, + luw: 8681, + lux: 8682, + luy: 8683, + lvz: 8684, + lva: 8685, + lvb: 8686, + lvc: 8687, + lvd: 8688, + lve: 8689, + lvf: 8690, + lvg: 8691, + lvh: 8692, + lvi: 8693, + lvj: 8694, + lvk: 8695, + lvl: 8696, + lvm: 8697, + lvn: 8698, + lvo: 8699, + lvp: 8700, + lvq: 8701, + lvr: 8702, + lvs: 8703, + lvt: 8704, + lvu: 8705, + lvv: 8706, + lvw: 8707, + lvx: 8708, + lvy: 8709, + lwz: 8710, + lwa: 8711, + lwb: 8712, + lwc: 8713, + lwd: 8714, + lwe: 8715, + lwf: 8716, + lwg: 8717, + lwh: 8718, + lwi: 8719, + lwj: 8720, + lwk: 8721, + lwl: 8722, + lwm: 8723, + lwn: 8724, + lwo: 8725, + lwp: 8726, + lwq: 8727, + lwr: 8728, + lws: 8729, + lwt: 8730, + lwu: 8731, + lwv: 8732, + lww: 8733, + lwx: 8734, + lwy: 8735, + lxz: 8736, + lxa: 8737, + lxb: 8738, + lxc: 8739, + lxd: 8740, + lxe: 8741, + lxf: 8742, + lxg: 8743, + lxh: 8744, + lxi: 8745, + lxj: 8746, + lxk: 8747, + lxl: 8748, + lxm: 8749, + lxn: 8750, + lxo: 8751, + lxp: 8752, + lxq: 8753, + lxr: 8754, + lxs: 8755, + lxt: 8756, + lxu: 8757, + lxv: 8758, + lxw: 8759, + lxx: 8760, + lxy: 8761, + lyz: 8762, + lya: 8763, + lyb: 8764, + lyc: 8765, + lyd: 8766, + lye: 8767, + lyf: 8768, + lyg: 8769, + lyh: 8770, + lyi: 8771, + lyj: 8772, + lyk: 8773, + lyl: 8774, + lym: 8775, + lyn: 8776, + lyo: 8777, + lyp: 8778, + lyq: 8779, + lyr: 8780, + lys: 8781, + lyt: 8782, + lyu: 8783, + lyv: 8784, + lyw: 8785, + lyx: 8786, + lyy: 8787, + mzz: 8788, + mza: 8789, + mzb: 8790, + mzc: 8791, + mzd: 8792, + mze: 8793, + mzf: 8794, + mzg: 8795, + mzh: 8796, + mzi: 8797, + mzj: 8798, + mzk: 8799, + mzl: 8800, + mzm: 8801, + mzn: 8802, + mzo: 8803, + mzp: 8804, + mzq: 8805, + mzr: 8806, + mzs: 8807, + mzt: 8808, + mzu: 8809, + mzv: 8810, + mzw: 8811, + mzx: 8812, + mzy: 8813, + maz: 8814, + maa: 8815, + mab: 8816, + mac: 8817, + mad: 8818, + mae: 8819, + maf: 8820, + mag: 8821, + mah: 8822, + mai: 8823, + maj: 8824, + mak: 8825, + mal: 8826, + mam: 8827, + man: 8828, + mao: 8829, + map: 8830, + maq: 8831, + mar: 8832, + mas: 8833, + mat: 8834, + mau: 8835, + mav: 8836, + maw: 8837, + max: 8838, + may: 8839, + mbz: 8840, + mba: 8841, + mbb: 8842, + mbc: 8843, + mbd: 8844, + mbe: 8845, + mbf: 8846, + mbg: 8847, + mbh: 8848, + mbi: 8849, + mbj: 8850, + mbk: 8851, + mbl: 8852, + mbm: 8853, + mbn: 8854, + mbo: 8855, + mbp: 8856, + mbq: 8857, + mbr: 8858, + mbs: 8859, + mbt: 8860, + mbu: 8861, + mbv: 8862, + mbw: 8863, + mbx: 8864, + mby: 8865, + mcz: 8866, + mca: 8867, + mcb: 8868, + mcc: 8869, + mcd: 8870, + mce: 8871, + mcf: 8872, + mcg: 8873, + mch: 8874, + mci: 8875, + mcj: 8876, + mck: 8877, + mcl: 8878, + mcm: 8879, + mcn: 8880, + mco: 8881, + mcp: 8882, + mcq: 8883, + mcr: 8884, + mcs: 8885, + mct: 8886, + mcu: 8887, + mcv: 8888, + mcw: 8889, + mcx: 8890, + mcy: 8891, + mdz: 8892, + mda: 8893, + mdb: 8894, + mdc: 8895, + mdd: 8896, + mde: 8897, + mdf: 8898, + mdg: 8899, + mdh: 8900, + mdi: 8901, + mdj: 8902, + mdk: 8903, + mdl: 8904, + mdm: 8905, + mdn: 8906, + mdo: 8907, + mdp: 8908, + mdq: 8909, + mdr: 8910, + mds: 8911, + mdt: 8912, + mdu: 8913, + mdv: 8914, + mdw: 8915, + mdx: 8916, + mdy: 8917, + mez: 8918, + mea: 8919, + meb: 8920, + mec: 8921, + med: 8922, + mee: 8923, + mef: 8924, + meg: 8925, + meh: 8926, + mei: 8927, + mej: 8928, + mek: 8929, + mel: 8930, + mem: 8931, + men: 8932, + meo: 8933, + mep: 8934, + meq: 8935, + mer: 8936, + mes: 8937, + met: 8938, + meu: 8939, + mev: 8940, + mew: 8941, + mex: 8942, + mey: 8943, + mfz: 8944, + mfa: 8945, + mfb: 8946, + mfc: 8947, + mfd: 8948, + mfe: 8949, + mff: 8950, + mfg: 8951, + mfh: 8952, + mfi: 8953, + mfj: 8954, + mfk: 8955, + mfl: 8956, + mfm: 8957, + mfn: 8958, + mfo: 8959, + mfp: 8960, + mfq: 8961, + mfr: 8962, + mfs: 8963, + mft: 8964, + mfu: 8965, + mfv: 8966, + mfw: 8967, + mfx: 8968, + mfy: 8969, + mgz: 8970, + mga: 8971, + mgb: 8972, + mgc: 8973, + mgd: 8974, + mge: 8975, + mgf: 8976, + mgg: 8977, + mgh: 8978, + mgi: 8979, + mgj: 8980, + mgk: 8981, + mgl: 8982, + mgm: 8983, + mgn: 8984, + mgo: 8985, + mgp: 8986, + mgq: 8987, + mgr: 8988, + mgs: 8989, + mgt: 8990, + mgu: 8991, + mgv: 8992, + mgw: 8993, + mgx: 8994, + mgy: 8995, + mhz: 8996, + mha: 8997, + mhb: 8998, + mhc: 8999, + mhd: 9000, + mhe: 9001, + mhf: 9002, + mhg: 9003, + mhh: 9004, + mhi: 9005, + mhj: 9006, + mhk: 9007, + mhl: 9008, + mhm: 9009, + mhn: 9010, + mho: 9011, + mhp: 9012, + mhq: 9013, + mhr: 9014, + mhs: 9015, + mht: 9016, + mhu: 9017, + mhv: 9018, + mhw: 9019, + mhx: 9020, + mhy: 9021, + miz: 9022, + mia: 9023, + mib: 9024, + mic: 9025, + mid: 9026, + mie: 9027, + mif: 9028, + mig: 9029, + mih: 9030, + mii: 9031, + mij: 9032, + mik: 9033, + mil: 9034, + mim: 9035, + min: 9036, + mio: 9037, + mip: 9038, + miq: 9039, + mir: 9040, + mis: 9041, + mit: 9042, + miu: 9043, + miv: 9044, + miw: 9045, + mix: 9046, + miy: 9047, + mjz: 9048, + mja: 9049, + mjb: 9050, + mjc: 9051, + mjd: 9052, + mje: 9053, + mjf: 9054, + mjg: 9055, + mjh: 9056, + mji: 9057, + mjj: 9058, + mjk: 9059, + mjl: 9060, + mjm: 9061, + mjn: 9062, + mjo: 9063, + mjp: 9064, + mjq: 9065, + mjr: 9066, + mjs: 9067, + mjt: 9068, + mju: 9069, + mjv: 9070, + mjw: 9071, + mjx: 9072, + mjy: 9073, + mkz: 9074, + mka: 9075, + mkb: 9076, + mkc: 9077, + mkd: 9078, + mke: 9079, + mkf: 9080, + mkg: 9081, + mkh: 9082, + mki: 9083, + mkj: 9084, + mkk: 9085, + mkl: 9086, + mkm: 9087, + mkn: 9088, + mko: 9089, + mkp: 9090, + mkq: 9091, + mkr: 9092, + mks: 9093, + mkt: 9094, + mku: 9095, + mkv: 9096, + mkw: 9097, + mkx: 9098, + mky: 9099, + mlz: 9100, + mla: 9101, + mlb: 9102, + mlc: 9103, + mld: 9104, + mle: 9105, + mlf: 9106, + mlg: 9107, + mlh: 9108, + mli: 9109, + mlj: 9110, + mlk: 9111, + mll: 9112, + mlm: 9113, + mln: 9114, + mlo: 9115, + mlp: 9116, + mlq: 9117, + mlr: 9118, + mls: 9119, + mlt: 9120, + mlu: 9121, + mlv: 9122, + mlw: 9123, + mlx: 9124, + mly: 9125, + mmz: 9126, + mma: 9127, + mmb: 9128, + mmc: 9129, + mmd: 9130, + mme: 9131, + mmf: 9132, + mmg: 9133, + mmh: 9134, + mmi: 9135, + mmj: 9136, + mmk: 9137, + mml: 9138, + mmm: 9139, + mmn: 9140, + mmo: 9141, + mmp: 9142, + mmq: 9143, + mmr: 9144, + mms: 9145, + mmt: 9146, + mmu: 9147, + mmv: 9148, + mmw: 9149, + mmx: 9150, + mmy: 9151, + mnz: 9152, + mna: 9153, + mnb: 9154, + mnc: 9155, + mnd: 9156, + mne: 9157, + mnf: 9158, + mng: 9159, + mnh: 9160, + mni: 9161, + mnj: 9162, + mnk: 9163, + mnl: 9164, + mnm: 9165, + mnn: 9166, + mno: 9167, + mnp: 9168, + mnq: 9169, + mnr: 9170, + mns: 9171, + mnt: 9172, + mnu: 9173, + mnv: 9174, + mnw: 9175, + mnx: 9176, + mny: 9177, + moz: 9178, + moa: 9179, + mob: 9180, + moc: 9181, + mod: 9182, + moe: 9183, + mof: 9184, + mog: 9185, + moh: 9186, + moi: 9187, + moj: 9188, + mok: 9189, + mol: 9190, + mom: 9191, + mon: 9192, + moo: 9193, + mop: 9194, + moq: 9195, + mor: 9196, + mos: 9197, + mot: 9198, + mou: 9199, + mov: 9200, + mow: 9201, + mox: 9202, + moy: 9203, + mpz: 9204, + mpa: 9205, + mpb: 9206, + mpc: 9207, + mpd: 9208, + mpe: 9209, + mpf: 9210, + mpg: 9211, + mph: 9212, + mpi: 9213, + mpj: 9214, + mpk: 9215, + mpl: 9216, + mpm: 9217, + mpn: 9218, + mpo: 9219, + mpp: 9220, + mpq: 9221, + mpr: 9222, + mps: 9223, + mpt: 9224, + mpu: 9225, + mpv: 9226, + mpw: 9227, + mpx: 9228, + mpy: 9229, + mqz: 9230, + mqa: 9231, + mqb: 9232, + mqc: 9233, + mqd: 9234, + mqe: 9235, + mqf: 9236, + mqg: 9237, + mqh: 9238, + mqi: 9239, + mqj: 9240, + mqk: 9241, + mql: 9242, + mqm: 9243, + mqn: 9244, + mqo: 9245, + mqp: 9246, + mqq: 9247, + mqr: 9248, + mqs: 9249, + mqt: 9250, + mqu: 9251, + mqv: 9252, + mqw: 9253, + mqx: 9254, + mqy: 9255, + mrz: 9256, + mra: 9257, + mrb: 9258, + mrc: 9259, + mrd: 9260, + mre: 9261, + mrf: 9262, + mrg: 9263, + mrh: 9264, + mri: 9265, + mrj: 9266, + mrk: 9267, + mrl: 9268, + mrm: 9269, + mrn: 9270, + mro: 9271, + mrp: 9272, + mrq: 9273, + mrr: 9274, + mrs: 9275, + mrt: 9276, + mru: 9277, + mrv: 9278, + mrw: 9279, + mrx: 9280, + mry: 9281, + msz: 9282, + msa: 9283, + msb: 9284, + msc: 9285, + msd: 9286, + mse: 9287, + msf: 9288, + msg: 9289, + msh: 9290, + msi: 9291, + msj: 9292, + msk: 9293, + msl: 9294, + msm: 9295, + msn: 9296, + mso: 9297, + msp: 9298, + msq: 9299, + msr: 9300, + mss: 9301, + mst: 9302, + msu: 9303, + msv: 9304, + msw: 9305, + msx: 9306, + msy: 9307, + mtz: 9308, + mta: 9309, + mtb: 9310, + mtc: 9311, + mtd: 9312, + mte: 9313, + mtf: 9314, + mtg: 9315, + mth: 9316, + mti: 9317, + mtj: 9318, + mtk: 9319, + mtl: 9320, + mtm: 9321, + mtn: 9322, + mto: 9323, + mtp: 9324, + mtq: 9325, + mtr: 9326, + mts: 9327, + mtt: 9328, + mtu: 9329, + mtv: 9330, + mtw: 9331, + mtx: 9332, + mty: 9333, + muz: 9334, + mua: 9335, + mub: 9336, + muc: 9337, + mud: 9338, + mue: 9339, + muf: 9340, + mug: 9341, + muh: 9342, + mui: 9343, + muj: 9344, + muk: 9345, + mul: 9346, + mum: 9347, + mun: 9348, + muo: 9349, + mup: 9350, + muq: 9351, + mur: 9352, + mus: 9353, + mut: 9354, + muu: 9355, + muv: 9356, + muw: 9357, + mux: 9358, + muy: 9359, + mvz: 9360, + mva: 9361, + mvb: 9362, + mvc: 9363, + mvd: 9364, + mve: 9365, + mvf: 9366, + mvg: 9367, + mvh: 9368, + mvi: 9369, + mvj: 9370, + mvk: 9371, + mvl: 9372, + mvm: 9373, + mvn: 9374, + mvo: 9375, + mvp: 9376, + mvq: 9377, + mvr: 9378, + mvs: 9379, + mvt: 9380, + mvu: 9381, + mvv: 9382, + mvw: 9383, + mvx: 9384, + mvy: 9385, + mwz: 9386, + mwa: 9387, + mwb: 9388, + mwc: 9389, + mwd: 9390, + mwe: 9391, + mwf: 9392, + mwg: 9393, + mwh: 9394, + mwi: 9395, + mwj: 9396, + mwk: 9397, + mwl: 9398, + mwm: 9399, + mwn: 9400, + mwo: 9401, + mwp: 9402, + mwq: 9403, + mwr: 9404, + mws: 9405, + mwt: 9406, + mwu: 9407, + mwv: 9408, + mww: 9409, + mwx: 9410, + mwy: 9411, + mxz: 9412, + mxa: 9413, + mxb: 9414, + mxc: 9415, + mxd: 9416, + mxe: 9417, + mxf: 9418, + mxg: 9419, + mxh: 9420, + mxi: 9421, + mxj: 9422, + mxk: 9423, + mxl: 9424, + mxm: 9425, + mxn: 9426, + mxo: 9427, + mxp: 9428, + mxq: 9429, + mxr: 9430, + mxs: 9431, + mxt: 9432, + mxu: 9433, + mxv: 9434, + mxw: 9435, + mxx: 9436, + mxy: 9437, + myz: 9438, + mya: 9439, + myb: 9440, + myc: 9441, + myd: 9442, + mye: 9443, + myf: 9444, + myg: 9445, + myh: 9446, + myi: 9447, + myj: 9448, + myk: 9449, + myl: 9450, + mym: 9451, + myn: 9452, + myo: 9453, + myp: 9454, + myq: 9455, + myr: 9456, + mys: 9457, + myt: 9458, + myu: 9459, + myv: 9460, + myw: 9461, + myx: 9462, + myy: 9463, + nzz: 9464, + nza: 9465, + nzb: 9466, + nzc: 9467, + nzd: 9468, + nze: 9469, + nzf: 9470, + nzg: 9471, + nzh: 9472, + nzi: 9473, + nzj: 9474, + nzk: 9475, + nzl: 9476, + nzm: 9477, + nzn: 9478, + nzo: 9479, + nzp: 9480, + nzq: 9481, + nzr: 9482, + nzs: 9483, + nzt: 9484, + nzu: 9485, + nzv: 9486, + nzw: 9487, + nzx: 9488, + nzy: 9489, + naz: 9490, + naa: 9491, + nab: 9492, + nac: 9493, + nad: 9494, + nae: 9495, + naf: 9496, + nag: 9497, + nah: 9498, + nai: 9499, + naj: 9500, + nak: 9501, + nal: 9502, + nam: 9503, + nan: 9504, + nao: 9505, + nap: 9506, + naq: 9507, + nar: 9508, + nas: 9509, + nat: 9510, + nau: 9511, + nav: 9512, + naw: 9513, + nax: 9514, + nay: 9515, + nbz: 9516, + nba: 9517, + nbb: 9518, + nbc: 9519, + nbd: 9520, + nbe: 9521, + nbf: 9522, + nbg: 9523, + nbh: 9524, + nbi: 9525, + nbj: 9526, + nbk: 9527, + nbl: 9528, + nbm: 9529, + nbn: 9530, + nbo: 9531, + nbp: 9532, + nbq: 9533, + nbr: 9534, + nbs: 9535, + nbt: 9536, + nbu: 9537, + nbv: 9538, + nbw: 9539, + nbx: 9540, + nby: 9541, + ncz: 9542, + nca: 9543, + ncb: 9544, + ncc: 9545, + ncd: 9546, + nce: 9547, + ncf: 9548, + ncg: 9549, + nch: 9550, + nci: 9551, + ncj: 9552, + nck: 9553, + ncl: 9554, + ncm: 9555, + ncn: 9556, + nco: 9557, + ncp: 9558, + ncq: 9559, + ncr: 9560, + ncs: 9561, + nct: 9562, + ncu: 9563, + ncv: 9564, + ncw: 9565, + ncx: 9566, + ncy: 9567, + ndz: 9568, + nda: 9569, + ndb: 9570, + ndc: 9571, + ndd: 9572, + nde: 9573, + ndf: 9574, + ndg: 9575, + ndh: 9576, + ndi: 9577, + ndj: 9578, + ndk: 9579, + ndl: 9580, + ndm: 9581, + ndn: 9582, + ndo: 9583, + ndp: 9584, + ndq: 9585, + ndr: 9586, + nds: 9587, + ndt: 9588, + ndu: 9589, + ndv: 9590, + ndw: 9591, + ndx: 9592, + ndy: 9593, + nez: 9594, + nea: 9595, + neb: 9596, + nec: 9597, + ned: 9598, + nee: 9599, + nef: 9600, + neg: 9601, + neh: 9602, + nei: 9603, + nej: 9604, + nek: 9605, + nel: 9606, + nem: 9607, + nen: 9608, + neo: 9609, + nep: 9610, + neq: 9611, + ner: 9612, + nes: 9613, + net: 9614, + neu: 9615, + nev: 9616, + new: 9617, + nex: 9618, + ney: 9619, + nfz: 9620, + nfa: 9621, + nfb: 9622, + nfc: 9623, + nfd: 9624, + nfe: 9625, + nff: 9626, + nfg: 9627, + nfh: 9628, + nfi: 9629, + nfj: 9630, + nfk: 9631, + nfl: 9632, + nfm: 9633, + nfn: 9634, + nfo: 9635, + nfp: 9636, + nfq: 9637, + nfr: 9638, + nfs: 9639, + nft: 9640, + nfu: 9641, + nfv: 9642, + nfw: 9643, + nfx: 9644, + nfy: 9645, + ngz: 9646, + nga: 9647, + ngb: 9648, + ngc: 9649, + ngd: 9650, + nge: 9651, + ngf: 9652, + ngg: 9653, + ngh: 9654, + ngi: 9655, + ngj: 9656, + ngk: 9657, + ngl: 9658, + ngm: 9659, + ngn: 9660, + ngo: 9661, + ngp: 9662, + ngq: 9663, + ngr: 9664, + ngs: 9665, + ngt: 9666, + ngu: 9667, + ngv: 9668, + ngw: 9669, + ngx: 9670, + ngy: 9671, + nhz: 9672, + nha: 9673, + nhb: 9674, + nhc: 9675, + nhd: 9676, + nhe: 9677, + nhf: 9678, + nhg: 9679, + nhh: 9680, + nhi: 9681, + nhj: 9682, + nhk: 9683, + nhl: 9684, + nhm: 9685, + nhn: 9686, + nho: 9687, + nhp: 9688, + nhq: 9689, + nhr: 9690, + nhs: 9691, + nht: 9692, + nhu: 9693, + nhv: 9694, + nhw: 9695, + nhx: 9696, + nhy: 9697, + niz: 9698, + nia: 9699, + nib: 9700, + nic: 9701, + nid: 9702, + nie: 9703, + nif: 9704, + nig: 9705, + nih: 9706, + nii: 9707, + nij: 9708, + nik: 9709, + nil: 9710, + nim: 9711, + nin: 9712, + nio: 9713, + nip: 9714, + niq: 9715, + nir: 9716, + nis: 9717, + nit: 9718, + niu: 9719, + niv: 9720, + niw: 9721, + nix: 9722, + niy: 9723, + njz: 9724, + nja: 9725, + njb: 9726, + njc: 9727, + njd: 9728, + nje: 9729, + njf: 9730, + njg: 9731, + njh: 9732, + nji: 9733, + njj: 9734, + njk: 9735, + njl: 9736, + njm: 9737, + njn: 9738, + njo: 9739, + njp: 9740, + njq: 9741, + njr: 9742, + njs: 9743, + njt: 9744, + nju: 9745, + njv: 9746, + njw: 9747, + njx: 9748, + njy: 9749, + nkz: 9750, + nka: 9751, + nkb: 9752, + nkc: 9753, + nkd: 9754, + nke: 9755, + nkf: 9756, + nkg: 9757, + nkh: 9758, + nki: 9759, + nkj: 9760, + nkk: 9761, + nkl: 9762, + nkm: 9763, + nkn: 9764, + nko: 9765, + nkp: 9766, + nkq: 9767, + nkr: 9768, + nks: 9769, + nkt: 9770, + nku: 9771, + nkv: 9772, + nkw: 9773, + nkx: 9774, + nky: 9775, + nlz: 9776, + nla: 9777, + nlb: 9778, + nlc: 9779, + nld: 9780, + nle: 9781, + nlf: 9782, + nlg: 9783, + nlh: 9784, + nli: 9785, + nlj: 9786, + nlk: 9787, + nll: 9788, + nlm: 9789, + nln: 9790, + nlo: 9791, + nlp: 9792, + nlq: 9793, + nlr: 9794, + nls: 9795, + nlt: 9796, + nlu: 9797, + nlv: 9798, + nlw: 9799, + nlx: 9800, + nly: 9801, + nmz: 9802, + nma: 9803, + nmb: 9804, + nmc: 9805, + nmd: 9806, + nme: 9807, + nmf: 9808, + nmg: 9809, + nmh: 9810, + nmi: 9811, + nmj: 9812, + nmk: 9813, + nml: 9814, + nmm: 9815, + nmn: 9816, + nmo: 9817, + nmp: 9818, + nmq: 9819, + nmr: 9820, + nms: 9821, + nmt: 9822, + nmu: 9823, + nmv: 9824, + nmw: 9825, + nmx: 9826, + nmy: 9827, + nnz: 9828, + nna: 9829, + nnb: 9830, + nnc: 9831, + nnd: 9832, + nne: 9833, + nnf: 9834, + nng: 9835, + nnh: 9836, + nni: 9837, + nnj: 9838, + nnk: 9839, + nnl: 9840, + nnm: 9841, + nnn: 9842, + nno: 9843, + nnp: 9844, + nnq: 9845, + nnr: 9846, + nns: 9847, + nnt: 9848, + nnu: 9849, + nnv: 9850, + nnw: 9851, + nnx: 9852, + nny: 9853, + noz: 9854, + noa: 9855, + nob: 9856, + noc: 9857, + nod: 9858, + noe: 9859, + nof: 9860, + nog: 9861, + noh: 9862, + noi: 9863, + noj: 9864, + nok: 9865, + nol: 9866, + nom: 9867, + non: 9868, + noo: 9869, + nop: 9870, + noq: 9871, + nor: 9872, + nos: 9873, + not: 9874, + nou: 9875, + nov: 9876, + now: 9877, + nox: 9878, + noy: 9879, + npz: 9880, + npa: 9881, + npb: 9882, + npc: 9883, + npd: 9884, + npe: 9885, + npf: 9886, + npg: 9887, + nph: 9888, + npi: 9889, + npj: 9890, + npk: 9891, + npl: 9892, + npm: 9893, + npn: 9894, + npo: 9895, + npp: 9896, + npq: 9897, + npr: 9898, + nps: 9899, + npt: 9900, + npu: 9901, + npv: 9902, + npw: 9903, + npx: 9904, + npy: 9905, + nqz: 9906, + nqa: 9907, + nqb: 9908, + nqc: 9909, + nqd: 9910, + nqe: 9911, + nqf: 9912, + nqg: 9913, + nqh: 9914, + nqi: 9915, + nqj: 9916, + nqk: 9917, + nql: 9918, + nqm: 9919, + nqn: 9920, + nqo: 9921, + nqp: 9922, + nqq: 9923, + nqr: 9924, + nqs: 9925, + nqt: 9926, + nqu: 9927, + nqv: 9928, + nqw: 9929, + nqx: 9930, + nqy: 9931, + nrz: 9932, + nra: 9933, + nrb: 9934, + nrc: 9935, + nrd: 9936, + nre: 9937, + nrf: 9938, + nrg: 9939, + nrh: 9940, + nri: 9941, + nrj: 9942, + nrk: 9943, + nrl: 9944, + nrm: 9945, + nrn: 9946, + nro: 9947, + nrp: 9948, + nrq: 9949, + nrr: 9950, + nrs: 9951, + nrt: 9952, + nru: 9953, + nrv: 9954, + nrw: 9955, + nrx: 9956, + nry: 9957, + nsz: 9958, + nsa: 9959, + nsb: 9960, + nsc: 9961, + nsd: 9962, + nse: 9963, + nsf: 9964, + nsg: 9965, + nsh: 9966, + nsi: 9967, + nsj: 9968, + nsk: 9969, + nsl: 9970, + nsm: 9971, + nsn: 9972, + nso: 9973, + nsp: 9974, + nsq: 9975, + nsr: 9976, + nss: 9977, + nst: 9978, + nsu: 9979, + nsv: 9980, + nsw: 9981, + nsx: 9982, + nsy: 9983, + ntz: 9984, + nta: 9985, + ntb: 9986, + ntc: 9987, + ntd: 9988, + nte: 9989, + ntf: 9990, + ntg: 9991, + nth: 9992, + nti: 9993, + ntj: 9994, + ntk: 9995, + ntl: 9996, + ntm: 9997, + ntn: 9998, + nto: 9999, + ntp: 10000, + ntq: 10001, + ntr: 10002, + nts: 10003, + ntt: 10004, + ntu: 10005, + ntv: 10006, + ntw: 10007, + ntx: 10008, + nty: 10009, + nuz: 10010, + nua: 10011, + nub: 10012, + nuc: 10013, + nud: 10014, + nue: 10015, + nuf: 10016, + nug: 10017, + nuh: 10018, + nui: 10019, + nuj: 10020, + nuk: 10021, + nul: 10022, + num: 10023, + nun: 10024, + nuo: 10025, + nup: 10026, + nuq: 10027, + nur: 10028, + nus: 10029, + nut: 10030, + nuu: 10031, + nuv: 10032, + nuw: 10033, + nux: 10034, + nuy: 10035, + nvz: 10036, + nva: 10037, + nvb: 10038, + nvc: 10039, + nvd: 10040, + nve: 10041, + nvf: 10042, + nvg: 10043, + nvh: 10044, + nvi: 10045, + nvj: 10046, + nvk: 10047, + nvl: 10048, + nvm: 10049, + nvn: 10050, + nvo: 10051, + nvp: 10052, + nvq: 10053, + nvr: 10054, + nvs: 10055, + nvt: 10056, + nvu: 10057, + nvv: 10058, + nvw: 10059, + nvx: 10060, + nvy: 10061, + nwz: 10062, + nwa: 10063, + nwb: 10064, + nwc: 10065, + nwd: 10066, + nwe: 10067, + nwf: 10068, + nwg: 10069, + nwh: 10070, + nwi: 10071, + nwj: 10072, + nwk: 10073, + nwl: 10074, + nwm: 10075, + nwn: 10076, + nwo: 10077, + nwp: 10078, + nwq: 10079, + nwr: 10080, + nws: 10081, + nwt: 10082, + nwu: 10083, + nwv: 10084, + nww: 10085, + nwx: 10086, + nwy: 10087, + nxz: 10088, + nxa: 10089, + nxb: 10090, + nxc: 10091, + nxd: 10092, + nxe: 10093, + nxf: 10094, + nxg: 10095, + nxh: 10096, + nxi: 10097, + nxj: 10098, + nxk: 10099, + nxl: 10100, + nxm: 10101, + nxn: 10102, + nxo: 10103, + nxp: 10104, + nxq: 10105, + nxr: 10106, + nxs: 10107, + nxt: 10108, + nxu: 10109, + nxv: 10110, + nxw: 10111, + nxx: 10112, + nxy: 10113, + nyz: 10114, + nya: 10115, + nyb: 10116, + nyc: 10117, + nyd: 10118, + nye: 10119, + nyf: 10120, + nyg: 10121, + nyh: 10122, + nyi: 10123, + nyj: 10124, + nyk: 10125, + nyl: 10126, + nym: 10127, + nyn: 10128, + nyo: 10129, + nyp: 10130, + nyq: 10131, + nyr: 10132, + nys: 10133, + nyt: 10134, + nyu: 10135, + nyv: 10136, + nyw: 10137, + nyx: 10138, + nyy: 10139, + ozz: 10140, + oza: 10141, + ozb: 10142, + ozc: 10143, + ozd: 10144, + oze: 10145, + ozf: 10146, + ozg: 10147, + ozh: 10148, + ozi: 10149, + ozj: 10150, + ozk: 10151, + ozl: 10152, + ozm: 10153, + ozn: 10154, + ozo: 10155, + ozp: 10156, + ozq: 10157, + ozr: 10158, + ozs: 10159, + ozt: 10160, + ozu: 10161, + ozv: 10162, + ozw: 10163, + ozx: 10164, + ozy: 10165, + oaz: 10166, + oaa: 10167, + oab: 10168, + oac: 10169, + oad: 10170, + oae: 10171, + oaf: 10172, + oag: 10173, + oah: 10174, + oai: 10175, + oaj: 10176, + oak: 10177, + oal: 10178, + oam: 10179, + oan: 10180, + oao: 10181, + oap: 10182, + oaq: 10183, + oar: 10184, + oas: 10185, + oat: 10186, + oau: 10187, + oav: 10188, + oaw: 10189, + oax: 10190, + oay: 10191, + obz: 10192, + oba: 10193, + obb: 10194, + obc: 10195, + obd: 10196, + obe: 10197, + obf: 10198, + obg: 10199, + obh: 10200, + obi: 10201, + obj: 10202, + obk: 10203, + obl: 10204, + obm: 10205, + obn: 10206, + obo: 10207, + obp: 10208, + obq: 10209, + obr: 10210, + obs: 10211, + obt: 10212, + obu: 10213, + obv: 10214, + obw: 10215, + obx: 10216, + oby: 10217, + ocz: 10218, + oca: 10219, + ocb: 10220, + occ: 10221, + ocd: 10222, + oce: 10223, + ocf: 10224, + ocg: 10225, + och: 10226, + oci: 10227, + ocj: 10228, + ock: 10229, + ocl: 10230, + ocm: 10231, + ocn: 10232, + oco: 10233, + ocp: 10234, + ocq: 10235, + ocr: 10236, + ocs: 10237, + oct: 10238, + ocu: 10239, + ocv: 10240, + ocw: 10241, + ocx: 10242, + ocy: 10243, + odz: 10244, + oda: 10245, + odb: 10246, + odc: 10247, + odd: 10248, + ode: 10249, + odf: 10250, + odg: 10251, + odh: 10252, + odi: 10253, + odj: 10254, + odk: 10255, + odl: 10256, + odm: 10257, + odn: 10258, + odo: 10259, + odp: 10260, + odq: 10261, + odr: 10262, + ods: 10263, + odt: 10264, + odu: 10265, + odv: 10266, + odw: 10267, + odx: 10268, + ody: 10269, + oez: 10270, + oea: 10271, + oeb: 10272, + oec: 10273, + oed: 10274, + oee: 10275, + oef: 10276, + oeg: 10277, + oeh: 10278, + oei: 10279, + oej: 10280, + oek: 10281, + oel: 10282, + oem: 10283, + oen: 10284, + oeo: 10285, + oep: 10286, + oeq: 10287, + oer: 10288, + oes: 10289, + oet: 10290, + oeu: 10291, + oev: 10292, + oew: 10293, + oex: 10294, + oey: 10295, + ofz: 10296, + ofa: 10297, + ofb: 10298, + ofc: 10299, + ofd: 10300, + ofe: 10301, + off: 10302, + ofg: 10303, + ofh: 10304, + ofi: 10305, + ofj: 10306, + ofk: 10307, + ofl: 10308, + ofm: 10309, + ofn: 10310, + ofo: 10311, + ofp: 10312, + ofq: 10313, + ofr: 10314, + ofs: 10315, + oft: 10316, + ofu: 10317, + ofv: 10318, + ofw: 10319, + ofx: 10320, + ofy: 10321, + ogz: 10322, + oga: 10323, + ogb: 10324, + ogc: 10325, + ogd: 10326, + oge: 10327, + ogf: 10328, + ogg: 10329, + ogh: 10330, + ogi: 10331, + ogj: 10332, + ogk: 10333, + ogl: 10334, + ogm: 10335, + ogn: 10336, + ogo: 10337, + ogp: 10338, + ogq: 10339, + ogr: 10340, + ogs: 10341, + ogt: 10342, + ogu: 10343, + ogv: 10344, + ogw: 10345, + ogx: 10346, + ogy: 10347, + ohz: 10348, + oha: 10349, + ohb: 10350, + ohc: 10351, + ohd: 10352, + ohe: 10353, + ohf: 10354, + ohg: 10355, + ohh: 10356, + ohi: 10357, + ohj: 10358, + ohk: 10359, + ohl: 10360, + ohm: 10361, + ohn: 10362, + oho: 10363, + ohp: 10364, + ohq: 10365, + ohr: 10366, + ohs: 10367, + oht: 10368, + ohu: 10369, + ohv: 10370, + ohw: 10371, + ohx: 10372, + ohy: 10373, + oiz: 10374, + oia: 10375, + oib: 10376, + oic: 10377, + oid: 10378, + oie: 10379, + oif: 10380, + oig: 10381, + oih: 10382, + oii: 10383, + oij: 10384, + oik: 10385, + oil: 10386, + oim: 10387, + oin: 10388, + oio: 10389, + oip: 10390, + oiq: 10391, + oir: 10392, + ois: 10393, + oit: 10394, + oiu: 10395, + oiv: 10396, + oiw: 10397, + oix: 10398, + oiy: 10399, + ojz: 10400, + oja: 10401, + ojb: 10402, + ojc: 10403, + ojd: 10404, + oje: 10405, + ojf: 10406, + ojg: 10407, + ojh: 10408, + oji: 10409, + ojj: 10410, + ojk: 10411, + ojl: 10412, + ojm: 10413, + ojn: 10414, + ojo: 10415, + ojp: 10416, + ojq: 10417, + ojr: 10418, + ojs: 10419, + ojt: 10420, + oju: 10421, + ojv: 10422, + ojw: 10423, + ojx: 10424, + ojy: 10425, + okz: 10426, + oka: 10427, + okb: 10428, + okc: 10429, + okd: 10430, + oke: 10431, + okf: 10432, + okg: 10433, + okh: 10434, + oki: 10435, + okj: 10436, + okk: 10437, + okl: 10438, + okm: 10439, + okn: 10440, + oko: 10441, + okp: 10442, + okq: 10443, + okr: 10444, + oks: 10445, + okt: 10446, + oku: 10447, + okv: 10448, + okw: 10449, + okx: 10450, + oky: 10451, + olz: 10452, + ola: 10453, + olb: 10454, + olc: 10455, + old: 10456, + ole: 10457, + olf: 10458, + olg: 10459, + olh: 10460, + oli: 10461, + olj: 10462, + olk: 10463, + oll: 10464, + olm: 10465, + oln: 10466, + olo: 10467, + olp: 10468, + olq: 10469, + olr: 10470, + ols: 10471, + olt: 10472, + olu: 10473, + olv: 10474, + olw: 10475, + olx: 10476, + oly: 10477, + omz: 10478, + oma: 10479, + omb: 10480, + omc: 10481, + omd: 10482, + ome: 10483, + omf: 10484, + omg: 10485, + omh: 10486, + omi: 10487, + omj: 10488, + omk: 10489, + oml: 10490, + omm: 10491, + omn: 10492, + omo: 10493, + omp: 10494, + omq: 10495, + omr: 10496, + oms: 10497, + omt: 10498, + omu: 10499, + omv: 10500, + omw: 10501, + omx: 10502, + omy: 10503, + onz: 10504, + ona: 10505, + onb: 10506, + onc: 10507, + ond: 10508, + one: 10509, + onf: 10510, + ong: 10511, + onh: 10512, + oni: 10513, + onj: 10514, + onk: 10515, + onl: 10516, + onm: 10517, + onn: 10518, + ono: 10519, + onp: 10520, + onq: 10521, + onr: 10522, + ons: 10523, + ont: 10524, + onu: 10525, + onv: 10526, + onw: 10527, + onx: 10528, + ony: 10529, + ooz: 10530, + ooa: 10531, + oob: 10532, + ooc: 10533, + ood: 10534, + ooe: 10535, + oof: 10536, + oog: 10537, + ooh: 10538, + ooi: 10539, + ooj: 10540, + ook: 10541, + ool: 10542, + oom: 10543, + oon: 10544, + ooo: 10545, + oop: 10546, + ooq: 10547, + oor: 10548, + oos: 10549, + oot: 10550, + oou: 10551, + oov: 10552, + oow: 10553, + oox: 10554, + ooy: 10555, + opz: 10556, + opa: 10557, + opb: 10558, + opc: 10559, + opd: 10560, + ope: 10561, + opf: 10562, + opg: 10563, + oph: 10564, + opi: 10565, + opj: 10566, + opk: 10567, + opl: 10568, + opm: 10569, + opn: 10570, + opo: 10571, + opp: 10572, + opq: 10573, + opr: 10574, + ops: 10575, + opt: 10576, + opu: 10577, + opv: 10578, + opw: 10579, + opx: 10580, + opy: 10581, + oqz: 10582, + oqa: 10583, + oqb: 10584, + oqc: 10585, + oqd: 10586, + oqe: 10587, + oqf: 10588, + oqg: 10589, + oqh: 10590, + oqi: 10591, + oqj: 10592, + oqk: 10593, + oql: 10594, + oqm: 10595, + oqn: 10596, + oqo: 10597, + oqp: 10598, + oqq: 10599, + oqr: 10600, + oqs: 10601, + oqt: 10602, + oqu: 10603, + oqv: 10604, + oqw: 10605, + oqx: 10606, + oqy: 10607, + orz: 10608, + ora: 10609, + orb: 10610, + orc: 10611, + ord: 10612, + ore: 10613, + orf: 10614, + org: 10615, + orh: 10616, + ori: 10617, + orj: 10618, + ork: 10619, + orl: 10620, + orm: 10621, + orn: 10622, + oro: 10623, + orp: 10624, + orq: 10625, + orr: 10626, + ors: 10627, + ort: 10628, + oru: 10629, + orv: 10630, + orw: 10631, + orx: 10632, + ory: 10633, + osz: 10634, + osa: 10635, + osb: 10636, + osc: 10637, + osd: 10638, + ose: 10639, + osf: 10640, + osg: 10641, + osh: 10642, + osi: 10643, + osj: 10644, + osk: 10645, + osl: 10646, + osm: 10647, + osn: 10648, + oso: 10649, + osp: 10650, + osq: 10651, + osr: 10652, + oss: 10653, + ost: 10654, + osu: 10655, + osv: 10656, + osw: 10657, + osx: 10658, + osy: 10659, + otz: 10660, + ota: 10661, + otb: 10662, + otc: 10663, + otd: 10664, + ote: 10665, + otf: 10666, + otg: 10667, + oth: 10668, + oti: 10669, + otj: 10670, + otk: 10671, + otl: 10672, + otm: 10673, + otn: 10674, + oto: 10675, + otp: 10676, + otq: 10677, + otr: 10678, + ots: 10679, + ott: 10680, + otu: 10681, + otv: 10682, + otw: 10683, + otx: 10684, + oty: 10685, + ouz: 10686, + oua: 10687, + oub: 10688, + ouc: 10689, + oud: 10690, + oue: 10691, + ouf: 10692, + oug: 10693, + ouh: 10694, + oui: 10695, + ouj: 10696, + ouk: 10697, + oul: 10698, + oum: 10699, + oun: 10700, + ouo: 10701, + oup: 10702, + ouq: 10703, + our: 10704, + ous: 10705, + out: 10706, + ouu: 10707, + ouv: 10708, + ouw: 10709, + oux: 10710, + ouy: 10711, + ovz: 10712, + ova: 10713, + ovb: 10714, + ovc: 10715, + ovd: 10716, + ove: 10717, + ovf: 10718, + ovg: 10719, + ovh: 10720, + ovi: 10721, + ovj: 10722, + ovk: 10723, + ovl: 10724, + ovm: 10725, + ovn: 10726, + ovo: 10727, + ovp: 10728, + ovq: 10729, + ovr: 10730, + ovs: 10731, + ovt: 10732, + ovu: 10733, + ovv: 10734, + ovw: 10735, + ovx: 10736, + ovy: 10737, + owz: 10738, + owa: 10739, + owb: 10740, + owc: 10741, + owd: 10742, + owe: 10743, + owf: 10744, + owg: 10745, + owh: 10746, + owi: 10747, + owj: 10748, + owk: 10749, + owl: 10750, + owm: 10751, + own: 10752, + owo: 10753, + owp: 10754, + owq: 10755, + owr: 10756, + ows: 10757, + owt: 10758, + owu: 10759, + owv: 10760, + oww: 10761, + owx: 10762, + owy: 10763, + oxz: 10764, + oxa: 10765, + oxb: 10766, + oxc: 10767, + oxd: 10768, + oxe: 10769, + oxf: 10770, + oxg: 10771, + oxh: 10772, + oxi: 10773, + oxj: 10774, + oxk: 10775, + oxl: 10776, + oxm: 10777, + oxn: 10778, + oxo: 10779, + oxp: 10780, + oxq: 10781, + oxr: 10782, + oxs: 10783, + oxt: 10784, + oxu: 10785, + oxv: 10786, + oxw: 10787, + oxx: 10788, + oxy: 10789, + oyz: 10790, + oya: 10791, + oyb: 10792, + oyc: 10793, + oyd: 10794, + oye: 10795, + oyf: 10796, + oyg: 10797, + oyh: 10798, + oyi: 10799, + oyj: 10800, + oyk: 10801, + oyl: 10802, + oym: 10803, + oyn: 10804, + oyo: 10805, + oyp: 10806, + oyq: 10807, + oyr: 10808, + oys: 10809, + oyt: 10810, + oyu: 10811, + oyv: 10812, + oyw: 10813, + oyx: 10814, + oyy: 10815, + pzz: 10816, + pza: 10817, + pzb: 10818, + pzc: 10819, + pzd: 10820, + pze: 10821, + pzf: 10822, + pzg: 10823, + pzh: 10824, + pzi: 10825, + pzj: 10826, + pzk: 10827, + pzl: 10828, + pzm: 10829, + pzn: 10830, + pzo: 10831, + pzp: 10832, + pzq: 10833, + pzr: 10834, + pzs: 10835, + pzt: 10836, + pzu: 10837, + pzv: 10838, + pzw: 10839, + pzx: 10840, + pzy: 10841, + paz: 10842, + paa: 10843, + pab: 10844, + pac: 10845, + pad: 10846, + pae: 10847, + paf: 10848, + pag: 10849, + pah: 10850, + pai: 10851, + paj: 10852, + pak: 10853, + pal: 10854, + pam: 10855, + pan: 10856, + pao: 10857, + pap: 10858, + paq: 10859, + par: 10860, + pas: 10861, + pat: 10862, + pau: 10863, + pav: 10864, + paw: 10865, + pax: 10866, + pay: 10867, + pbz: 10868, + pba: 10869, + pbb: 10870, + pbc: 10871, + pbd: 10872, + pbe: 10873, + pbf: 10874, + pbg: 10875, + pbh: 10876, + pbi: 10877, + pbj: 10878, + pbk: 10879, + pbl: 10880, + pbm: 10881, + pbn: 10882, + pbo: 10883, + pbp: 10884, + pbq: 10885, + pbr: 10886, + pbs: 10887, + pbt: 10888, + pbu: 10889, + pbv: 10890, + pbw: 10891, + pbx: 10892, + pby: 10893, + pcz: 10894, + pca: 10895, + pcb: 10896, + pcc: 10897, + pcd: 10898, + pce: 10899, + pcf: 10900, + pcg: 10901, + pch: 10902, + pci: 10903, + pcj: 10904, + pck: 10905, + pcl: 10906, + pcm: 10907, + pcn: 10908, + pco: 10909, + pcp: 10910, + pcq: 10911, + pcr: 10912, + pcs: 10913, + pct: 10914, + pcu: 10915, + pcv: 10916, + pcw: 10917, + pcx: 10918, + pcy: 10919, + pdz: 10920, + pda: 10921, + pdb: 10922, + pdc: 10923, + pdd: 10924, + pde: 10925, + pdf: 10926, + pdg: 10927, + pdh: 10928, + pdi: 10929, + pdj: 10930, + pdk: 10931, + pdl: 10932, + pdm: 10933, + pdn: 10934, + pdo: 10935, + pdp: 10936, + pdq: 10937, + pdr: 10938, + pds: 10939, + pdt: 10940, + pdu: 10941, + pdv: 10942, + pdw: 10943, + pdx: 10944, + pdy: 10945, + pez: 10946, + pea: 10947, + peb: 10948, + pec: 10949, + ped: 10950, + pee: 10951, + pef: 10952, + peg: 10953, + peh: 10954, + pei: 10955, + pej: 10956, + pek: 10957, + pel: 10958, + pem: 10959, + pen: 10960, + peo: 10961, + pep: 10962, + peq: 10963, + per: 10964, + pes: 10965, + pet: 10966, + peu: 10967, + pev: 10968, + pew: 10969, + pex: 10970, + pey: 10971, + pfz: 10972, + pfa: 10973, + pfb: 10974, + pfc: 10975, + pfd: 10976, + pfe: 10977, + pff: 10978, + pfg: 10979, + pfh: 10980, + pfi: 10981, + pfj: 10982, + pfk: 10983, + pfl: 10984, + pfm: 10985, + pfn: 10986, + pfo: 10987, + pfp: 10988, + pfq: 10989, + pfr: 10990, + pfs: 10991, + pft: 10992, + pfu: 10993, + pfv: 10994, + pfw: 10995, + pfx: 10996, + pfy: 10997, + pgz: 10998, + pga: 10999, + pgb: 11000, + pgc: 11001, + pgd: 11002, + pge: 11003, + pgf: 11004, + pgg: 11005, + pgh: 11006, + pgi: 11007, + pgj: 11008, + pgk: 11009, + pgl: 11010, + pgm: 11011, + pgn: 11012, + pgo: 11013, + pgp: 11014, + pgq: 11015, + pgr: 11016, + pgs: 11017, + pgt: 11018, + pgu: 11019, + pgv: 11020, + pgw: 11021, + pgx: 11022, + pgy: 11023, + phz: 11024, + pha: 11025, + phb: 11026, + phc: 11027, + phd: 11028, + phe: 11029, + phf: 11030, + phg: 11031, + phh: 11032, + phi: 11033, + phj: 11034, + phk: 11035, + phl: 11036, + phm: 11037, + phn: 11038, + pho: 11039, + php: 11040, + phq: 11041, + phr: 11042, + phs: 11043, + pht: 11044, + phu: 11045, + phv: 11046, + phw: 11047, + phx: 11048, + phy: 11049, + piz: 11050, + pia: 11051, + pib: 11052, + pic: 11053, + pid: 11054, + pie: 11055, + pif: 11056, + pig: 11057, + pih: 11058, + pii: 11059, + pij: 11060, + pik: 11061, + pil: 11062, + pim: 11063, + pin: 11064, + pio: 11065, + pip: 11066, + piq: 11067, + pir: 11068, + pis: 11069, + pit: 11070, + piu: 11071, + piv: 11072, + piw: 11073, + pix: 11074, + piy: 11075, + pjz: 11076, + pja: 11077, + pjb: 11078, + pjc: 11079, + pjd: 11080, + pje: 11081, + pjf: 11082, + pjg: 11083, + pjh: 11084, + pji: 11085, + pjj: 11086, + pjk: 11087, + pjl: 11088, + pjm: 11089, + pjn: 11090, + pjo: 11091, + pjp: 11092, + pjq: 11093, + pjr: 11094, + pjs: 11095, + pjt: 11096, + pju: 11097, + pjv: 11098, + pjw: 11099, + pjx: 11100, + pjy: 11101, + pkz: 11102, + pka: 11103, + pkb: 11104, + pkc: 11105, + pkd: 11106, + pke: 11107, + pkf: 11108, + pkg: 11109, + pkh: 11110, + pki: 11111, + pkj: 11112, + pkk: 11113, + pkl: 11114, + pkm: 11115, + pkn: 11116, + pko: 11117, + pkp: 11118, + pkq: 11119, + pkr: 11120, + pks: 11121, + pkt: 11122, + pku: 11123, + pkv: 11124, + pkw: 11125, + pkx: 11126, + pky: 11127, + plz: 11128, + pla: 11129, + plb: 11130, + plc: 11131, + pld: 11132, + ple: 11133, + plf: 11134, + plg: 11135, + plh: 11136, + pli: 11137, + plj: 11138, + plk: 11139, + pll: 11140, + plm: 11141, + pln: 11142, + plo: 11143, + plp: 11144, + plq: 11145, + plr: 11146, + pls: 11147, + plt: 11148, + plu: 11149, + plv: 11150, + plw: 11151, + plx: 11152, + ply: 11153, + pmz: 11154, + pma: 11155, + pmb: 11156, + pmc: 11157, + pmd: 11158, + pme: 11159, + pmf: 11160, + pmg: 11161, + pmh: 11162, + pmi: 11163, + pmj: 11164, + pmk: 11165, + pml: 11166, + pmm: 11167, + pmn: 11168, + pmo: 11169, + pmp: 11170, + pmq: 11171, + pmr: 11172, + pms: 11173, + pmt: 11174, + pmu: 11175, + pmv: 11176, + pmw: 11177, + pmx: 11178, + pmy: 11179, + pnz: 11180, + pna: 11181, + pnb: 11182, + pnc: 11183, + pnd: 11184, + pne: 11185, + pnf: 11186, + png: 11187, + pnh: 11188, + pni: 11189, + pnj: 11190, + pnk: 11191, + pnl: 11192, + pnm: 11193, + pnn: 11194, + pno: 11195, + pnp: 11196, + pnq: 11197, + pnr: 11198, + pns: 11199, + pnt: 11200, + pnu: 11201, + pnv: 11202, + pnw: 11203, + pnx: 11204, + pny: 11205, + poz: 11206, + poa: 11207, + pob: 11208, + poc: 11209, + pod: 11210, + poe: 11211, + pof: 11212, + pog: 11213, + poh: 11214, + poi: 11215, + poj: 11216, + pok: 11217, + pol: 11218, + pom: 11219, + pon: 11220, + poo: 11221, + pop: 11222, + poq: 11223, + por: 11224, + pos: 11225, + pot: 11226, + pou: 11227, + pov: 11228, + pow: 11229, + pox: 11230, + poy: 11231, + ppz: 11232, + ppa: 11233, + ppb: 11234, + ppc: 11235, + ppd: 11236, + ppe: 11237, + ppf: 11238, + ppg: 11239, + pph: 11240, + ppi: 11241, + ppj: 11242, + ppk: 11243, + ppl: 11244, + ppm: 11245, + ppn: 11246, + ppo: 11247, + ppp: 11248, + ppq: 11249, + ppr: 11250, + pps: 11251, + ppt: 11252, + ppu: 11253, + ppv: 11254, + ppw: 11255, + ppx: 11256, + ppy: 11257, + pqz: 11258, + pqa: 11259, + pqb: 11260, + pqc: 11261, + pqd: 11262, + pqe: 11263, + pqf: 11264, + pqg: 11265, + pqh: 11266, + pqi: 11267, + pqj: 11268, + pqk: 11269, + pql: 11270, + pqm: 11271, + pqn: 11272, + pqo: 11273, + pqp: 11274, + pqq: 11275, + pqr: 11276, + pqs: 11277, + pqt: 11278, + pqu: 11279, + pqv: 11280, + pqw: 11281, + pqx: 11282, + pqy: 11283, + prz: 11284, + pra: 11285, + prb: 11286, + prc: 11287, + prd: 11288, + pre: 11289, + prf: 11290, + prg: 11291, + prh: 11292, + pri: 11293, + prj: 11294, + prk: 11295, + prl: 11296, + prm: 11297, + prn: 11298, + pro: 11299, + prp: 11300, + prq: 11301, + prr: 11302, + prs: 11303, + prt: 11304, + pru: 11305, + prv: 11306, + prw: 11307, + prx: 11308, + pry: 11309, + psz: 11310, + psa: 11311, + psb: 11312, + psc: 11313, + psd: 11314, + pse: 11315, + psf: 11316, + psg: 11317, + psh: 11318, + psi: 11319, + psj: 11320, + psk: 11321, + psl: 11322, + psm: 11323, + psn: 11324, + pso: 11325, + psp: 11326, + psq: 11327, + psr: 11328, + pss: 11329, + pst: 11330, + psu: 11331, + psv: 11332, + psw: 11333, + psx: 11334, + psy: 11335, + ptz: 11336, + pta: 11337, + ptb: 11338, + ptc: 11339, + ptd: 11340, + pte: 11341, + ptf: 11342, + ptg: 11343, + pth: 11344, + pti: 11345, + ptj: 11346, + ptk: 11347, + ptl: 11348, + ptm: 11349, + ptn: 11350, + pto: 11351, + ptp: 11352, + ptq: 11353, + ptr: 11354, + pts: 11355, + ptt: 11356, + ptu: 11357, + ptv: 11358, + ptw: 11359, + ptx: 11360, + pty: 11361, + puz: 11362, + pua: 11363, + pub: 11364, + puc: 11365, + pud: 11366, + pue: 11367, + puf: 11368, + pug: 11369, + puh: 11370, + pui: 11371, + puj: 11372, + puk: 11373, + pul: 11374, + pum: 11375, + pun: 11376, + puo: 11377, + pup: 11378, + puq: 11379, + pur: 11380, + pus: 11381, + put: 11382, + puu: 11383, + puv: 11384, + puw: 11385, + pux: 11386, + puy: 11387, + pvz: 11388, + pva: 11389, + pvb: 11390, + pvc: 11391, + pvd: 11392, + pve: 11393, + pvf: 11394, + pvg: 11395, + pvh: 11396, + pvi: 11397, + pvj: 11398, + pvk: 11399, + pvl: 11400, + pvm: 11401, + pvn: 11402, + pvo: 11403, + pvp: 11404, + pvq: 11405, + pvr: 11406, + pvs: 11407, + pvt: 11408, + pvu: 11409, + pvv: 11410, + pvw: 11411, + pvx: 11412, + pvy: 11413, + pwz: 11414, + pwa: 11415, + pwb: 11416, + pwc: 11417, + pwd: 11418, + pwe: 11419, + pwf: 11420, + pwg: 11421, + pwh: 11422, + pwi: 11423, + pwj: 11424, + pwk: 11425, + pwl: 11426, + pwm: 11427, + pwn: 11428, + pwo: 11429, + pwp: 11430, + pwq: 11431, + pwr: 11432, + pws: 11433, + pwt: 11434, + pwu: 11435, + pwv: 11436, + pww: 11437, + pwx: 11438, + pwy: 11439, + pxz: 11440, + pxa: 11441, + pxb: 11442, + pxc: 11443, + pxd: 11444, + pxe: 11445, + pxf: 11446, + pxg: 11447, + pxh: 11448, + pxi: 11449, + pxj: 11450, + pxk: 11451, + pxl: 11452, + pxm: 11453, + pxn: 11454, + pxo: 11455, + pxp: 11456, + pxq: 11457, + pxr: 11458, + pxs: 11459, + pxt: 11460, + pxu: 11461, + pxv: 11462, + pxw: 11463, + pxx: 11464, + pxy: 11465, + pyz: 11466, + pya: 11467, + pyb: 11468, + pyc: 11469, + pyd: 11470, + pye: 11471, + pyf: 11472, + pyg: 11473, + pyh: 11474, + pyi: 11475, + pyj: 11476, + pyk: 11477, + pyl: 11478, + pym: 11479, + pyn: 11480, + pyo: 11481, + pyp: 11482, + pyq: 11483, + pyr: 11484, + pys: 11485, + pyt: 11486, + pyu: 11487, + pyv: 11488, + pyw: 11489, + pyx: 11490, + pyy: 11491, + qzz: 11492, + qza: 11493, + qzb: 11494, + qzc: 11495, + qzd: 11496, + qze: 11497, + qzf: 11498, + qzg: 11499, + qzh: 11500, + qzi: 11501, + qzj: 11502, + qzk: 11503, + qzl: 11504, + qzm: 11505, + qzn: 11506, + qzo: 11507, + qzp: 11508, + qzq: 11509, + qzr: 11510, + qzs: 11511, + qzt: 11512, + qzu: 11513, + qzv: 11514, + qzw: 11515, + qzx: 11516, + qzy: 11517, + qaz: 11518, + qaa: 11519, + qab: 11520, + qac: 11521, + qad: 11522, + qae: 11523, + qaf: 11524, + qag: 11525, + qah: 11526, + qai: 11527, + qaj: 11528, + qak: 11529, + qal: 11530, + qam: 11531, + qan: 11532, + qao: 11533, + qap: 11534, + qaq: 11535, + qar: 11536, + qas: 11537, + qat: 11538, + qau: 11539, + qav: 11540, + qaw: 11541, + qax: 11542, + qay: 11543, + qbz: 11544, + qba: 11545, + qbb: 11546, + qbc: 11547, + qbd: 11548, + qbe: 11549, + qbf: 11550, + qbg: 11551, + qbh: 11552, + qbi: 11553, + qbj: 11554, + qbk: 11555, + qbl: 11556, + qbm: 11557, + qbn: 11558, + qbo: 11559, + qbp: 11560, + qbq: 11561, + qbr: 11562, + qbs: 11563, + qbt: 11564, + qbu: 11565, + qbv: 11566, + qbw: 11567, + qbx: 11568, + qby: 11569, + qcz: 11570, + qca: 11571, + qcb: 11572, + qcc: 11573, + qcd: 11574, + qce: 11575, + qcf: 11576, + qcg: 11577, + qch: 11578, + qci: 11579, + qcj: 11580, + qck: 11581, + qcl: 11582, + qcm: 11583, + qcn: 11584, + qco: 11585, + qcp: 11586, + qcq: 11587, + qcr: 11588, + qcs: 11589, + qct: 11590, + qcu: 11591, + qcv: 11592, + qcw: 11593, + qcx: 11594, + qcy: 11595, + qdz: 11596, + qda: 11597, + qdb: 11598, + qdc: 11599, + qdd: 11600, + qde: 11601, + qdf: 11602, + qdg: 11603, + qdh: 11604, + qdi: 11605, + qdj: 11606, + qdk: 11607, + qdl: 11608, + qdm: 11609, + qdn: 11610, + qdo: 11611, + qdp: 11612, + qdq: 11613, + qdr: 11614, + qds: 11615, + qdt: 11616, + qdu: 11617, + qdv: 11618, + qdw: 11619, + qdx: 11620, + qdy: 11621, + qez: 11622, + qea: 11623, + qeb: 11624, + qec: 11625, + qed: 11626, + qee: 11627, + qef: 11628, + qeg: 11629, + qeh: 11630, + qei: 11631, + qej: 11632, + qek: 11633, + qel: 11634, + qem: 11635, + qen: 11636, + qeo: 11637, + qep: 11638, + qeq: 11639, + qer: 11640, + qes: 11641, + qet: 11642, + qeu: 11643, + qev: 11644, + qew: 11645, + qex: 11646, + qey: 11647, + qfz: 11648, + qfa: 11649, + qfb: 11650, + qfc: 11651, + qfd: 11652, + qfe: 11653, + qff: 11654, + qfg: 11655, + qfh: 11656, + qfi: 11657, + qfj: 11658, + qfk: 11659, + qfl: 11660, + qfm: 11661, + qfn: 11662, + qfo: 11663, + qfp: 11664, + qfq: 11665, + qfr: 11666, + qfs: 11667, + qft: 11668, + qfu: 11669, + qfv: 11670, + qfw: 11671, + qfx: 11672, + qfy: 11673, + qgz: 11674, + qga: 11675, + qgb: 11676, + qgc: 11677, + qgd: 11678, + qge: 11679, + qgf: 11680, + qgg: 11681, + qgh: 11682, + qgi: 11683, + qgj: 11684, + qgk: 11685, + qgl: 11686, + qgm: 11687, + qgn: 11688, + qgo: 11689, + qgp: 11690, + qgq: 11691, + qgr: 11692, + qgs: 11693, + qgt: 11694, + qgu: 11695, + qgv: 11696, + qgw: 11697, + qgx: 11698, + qgy: 11699, + qhz: 11700, + qha: 11701, + qhb: 11702, + qhc: 11703, + qhd: 11704, + qhe: 11705, + qhf: 11706, + qhg: 11707, + qhh: 11708, + qhi: 11709, + qhj: 11710, + qhk: 11711, + qhl: 11712, + qhm: 11713, + qhn: 11714, + qho: 11715, + qhp: 11716, + qhq: 11717, + qhr: 11718, + qhs: 11719, + qht: 11720, + qhu: 11721, + qhv: 11722, + qhw: 11723, + qhx: 11724, + qhy: 11725, + qiz: 11726, + qia: 11727, + qib: 11728, + qic: 11729, + qid: 11730, + qie: 11731, + qif: 11732, + qig: 11733, + qih: 11734, + qii: 11735, + qij: 11736, + qik: 11737, + qil: 11738, + qim: 11739, + qin: 11740, + qio: 11741, + qip: 11742, + qiq: 11743, + qir: 11744, + qis: 11745, + qit: 11746, + qiu: 11747, + qiv: 11748, + qiw: 11749, + qix: 11750, + qiy: 11751, + qjz: 11752, + qja: 11753, + qjb: 11754, + qjc: 11755, + qjd: 11756, + qje: 11757, + qjf: 11758, + qjg: 11759, + qjh: 11760, + qji: 11761, + qjj: 11762, + qjk: 11763, + qjl: 11764, + qjm: 11765, + qjn: 11766, + qjo: 11767, + qjp: 11768, + qjq: 11769, + qjr: 11770, + qjs: 11771, + qjt: 11772, + qju: 11773, + qjv: 11774, + qjw: 11775, + qjx: 11776, + qjy: 11777, + qkz: 11778, + qka: 11779, + qkb: 11780, + qkc: 11781, + qkd: 11782, + qke: 11783, + qkf: 11784, + qkg: 11785, + qkh: 11786, + qki: 11787, + qkj: 11788, + qkk: 11789, + qkl: 11790, + qkm: 11791, + qkn: 11792, + qko: 11793, + qkp: 11794, + qkq: 11795, + qkr: 11796, + qks: 11797, + qkt: 11798, + qku: 11799, + qkv: 11800, + qkw: 11801, + qkx: 11802, + qky: 11803, + qlz: 11804, + qla: 11805, + qlb: 11806, + qlc: 11807, + qld: 11808, + qle: 11809, + qlf: 11810, + qlg: 11811, + qlh: 11812, + qli: 11813, + qlj: 11814, + qlk: 11815, + qll: 11816, + qlm: 11817, + qln: 11818, + qlo: 11819, + qlp: 11820, + qlq: 11821, + qlr: 11822, + qls: 11823, + qlt: 11824, + qlu: 11825, + qlv: 11826, + qlw: 11827, + qlx: 11828, + qly: 11829, + qmz: 11830, + qma: 11831, + qmb: 11832, + qmc: 11833, + qmd: 11834, + qme: 11835, + qmf: 11836, + qmg: 11837, + qmh: 11838, + qmi: 11839, + qmj: 11840, + qmk: 11841, + qml: 11842, + qmm: 11843, + qmn: 11844, + qmo: 11845, + qmp: 11846, + qmq: 11847, + qmr: 11848, + qms: 11849, + qmt: 11850, + qmu: 11851, + qmv: 11852, + qmw: 11853, + qmx: 11854, + qmy: 11855, + qnz: 11856, + qna: 11857, + qnb: 11858, + qnc: 11859, + qnd: 11860, + qne: 11861, + qnf: 11862, + qng: 11863, + qnh: 11864, + qni: 11865, + qnj: 11866, + qnk: 11867, + qnl: 11868, + qnm: 11869, + qnn: 11870, + qno: 11871, + qnp: 11872, + qnq: 11873, + qnr: 11874, + qns: 11875, + qnt: 11876, + qnu: 11877, + qnv: 11878, + qnw: 11879, + qnx: 11880, + qny: 11881, + qoz: 11882, + qoa: 11883, + qob: 11884, + qoc: 11885, + qod: 11886, + qoe: 11887, + qof: 11888, + qog: 11889, + qoh: 11890, + qoi: 11891, + qoj: 11892, + qok: 11893, + qol: 11894, + qom: 11895, + qon: 11896, + qoo: 11897, + qop: 11898, + qoq: 11899, + qor: 11900, + qos: 11901, + qot: 11902, + qou: 11903, + qov: 11904, + qow: 11905, + qox: 11906, + qoy: 11907, + qpz: 11908, + qpa: 11909, + qpb: 11910, + qpc: 11911, + qpd: 11912, + qpe: 11913, + qpf: 11914, + qpg: 11915, + qph: 11916, + qpi: 11917, + qpj: 11918, + qpk: 11919, + qpl: 11920, + qpm: 11921, + qpn: 11922, + qpo: 11923, + qpp: 11924, + qpq: 11925, + qpr: 11926, + qps: 11927, + qpt: 11928, + qpu: 11929, + qpv: 11930, + qpw: 11931, + qpx: 11932, + qpy: 11933, + qqz: 11934, + qqa: 11935, + qqb: 11936, + qqc: 11937, + qqd: 11938, + qqe: 11939, + qqf: 11940, + qqg: 11941, + qqh: 11942, + qqi: 11943, + qqj: 11944, + qqk: 11945, + qql: 11946, + qqm: 11947, + qqn: 11948, + qqo: 11949, + qqp: 11950, + qqq: 11951, + qqr: 11952, + qqs: 11953, + qqt: 11954, + qqu: 11955, + qqv: 11956, + qqw: 11957, + qqx: 11958, + qqy: 11959, + qrz: 11960, + qra: 11961, + qrb: 11962, + qrc: 11963, + qrd: 11964, + qre: 11965, + qrf: 11966, + qrg: 11967, + qrh: 11968, + qri: 11969, + qrj: 11970, + qrk: 11971, + qrl: 11972, + qrm: 11973, + qrn: 11974, + qro: 11975, + qrp: 11976, + qrq: 11977, + qrr: 11978, + qrs: 11979, + qrt: 11980, + qru: 11981, + qrv: 11982, + qrw: 11983, + qrx: 11984, + qry: 11985, + qsz: 11986, + qsa: 11987, + qsb: 11988, + qsc: 11989, + qsd: 11990, + qse: 11991, + qsf: 11992, + qsg: 11993, + qsh: 11994, + qsi: 11995, + qsj: 11996, + qsk: 11997, + qsl: 11998, + qsm: 11999, + qsn: 12000, + qso: 12001, + qsp: 12002, + qsq: 12003, + qsr: 12004, + qss: 12005, + qst: 12006, + qsu: 12007, + qsv: 12008, + qsw: 12009, + qsx: 12010, + qsy: 12011, + qtz: 12012, + qta: 12013, + qtb: 12014, + qtc: 12015, + qtd: 12016, + qte: 12017, + qtf: 12018, + qtg: 12019, + qth: 12020, + qti: 12021, + qtj: 12022, + qtk: 12023, + qtl: 12024, + qtm: 12025, + qtn: 12026, + qto: 12027, + qtp: 12028, + qtq: 12029, + qtr: 12030, + qts: 12031, + qtt: 12032, + qtu: 12033, + qtv: 12034, + qtw: 12035, + qtx: 12036, + qty: 12037, + quz: 12038, + qua: 12039, + qub: 12040, + quc: 12041, + qud: 12042, + que: 12043, + quf: 12044, + qug: 12045, + quh: 12046, + qui: 12047, + quj: 12048, + quk: 12049, + qul: 12050, + qum: 12051, + qun: 12052, + quo: 12053, + qup: 12054, + quq: 12055, + qur: 12056, + qus: 12057, + qut: 12058, + quu: 12059, + quv: 12060, + quw: 12061, + qux: 12062, + quy: 12063, + qvz: 12064, + qva: 12065, + qvb: 12066, + qvc: 12067, + qvd: 12068, + qve: 12069, + qvf: 12070, + qvg: 12071, + qvh: 12072, + qvi: 12073, + qvj: 12074, + qvk: 12075, + qvl: 12076, + qvm: 12077, + qvn: 12078, + qvo: 12079, + qvp: 12080, + qvq: 12081, + qvr: 12082, + qvs: 12083, + qvt: 12084, + qvu: 12085, + qvv: 12086, + qvw: 12087, + qvx: 12088, + qvy: 12089, + qwz: 12090, + qwa: 12091, + qwb: 12092, + qwc: 12093, + qwd: 12094, + qwe: 12095, + qwf: 12096, + qwg: 12097, + qwh: 12098, + qwi: 12099, + qwj: 12100, + qwk: 12101, + qwl: 12102, + qwm: 12103, + qwn: 12104, + qwo: 12105, + qwp: 12106, + qwq: 12107, + qwr: 12108, + qws: 12109, + qwt: 12110, + qwu: 12111, + qwv: 12112, + qww: 12113, + qwx: 12114, + qwy: 12115, + qxz: 12116, + qxa: 12117, + qxb: 12118, + qxc: 12119, + qxd: 12120, + qxe: 12121, + qxf: 12122, + qxg: 12123, + qxh: 12124, + qxi: 12125, + qxj: 12126, + qxk: 12127, + qxl: 12128, + qxm: 12129, + qxn: 12130, + qxo: 12131, + qxp: 12132, + qxq: 12133, + qxr: 12134, + qxs: 12135, + qxt: 12136, + qxu: 12137, + qxv: 12138, + qxw: 12139, + qxx: 12140, + qxy: 12141, + qyz: 12142, + qya: 12143, + qyb: 12144, + qyc: 12145, + qyd: 12146, + qye: 12147, + qyf: 12148, + qyg: 12149, + qyh: 12150, + qyi: 12151, + qyj: 12152, + qyk: 12153, + qyl: 12154, + qym: 12155, + qyn: 12156, + qyo: 12157, + qyp: 12158, + qyq: 12159, + qyr: 12160, + qys: 12161, + qyt: 12162, + qyu: 12163, + qyv: 12164, + qyw: 12165, + qyx: 12166, + qyy: 12167, + rzz: 12168, + rza: 12169, + rzb: 12170, + rzc: 12171, + rzd: 12172, + rze: 12173, + rzf: 12174, + rzg: 12175, + rzh: 12176, + rzi: 12177, + rzj: 12178, + rzk: 12179, + rzl: 12180, + rzm: 12181, + rzn: 12182, + rzo: 12183, + rzp: 12184, + rzq: 12185, + rzr: 12186, + rzs: 12187, + rzt: 12188, + rzu: 12189, + rzv: 12190, + rzw: 12191, + rzx: 12192, + rzy: 12193, + raz: 12194, + raa: 12195, + rab: 12196, + rac: 12197, + rad: 12198, + rae: 12199, + raf: 12200, + rag: 12201, + rah: 12202, + rai: 12203, + raj: 12204, + rak: 12205, + ral: 12206, + ram: 12207, + ran: 12208, + rao: 12209, + rap: 12210, + raq: 12211, + rar: 12212, + ras: 12213, + rat: 12214, + rau: 12215, + rav: 12216, + raw: 12217, + rax: 12218, + ray: 12219, + rbz: 12220, + rba: 12221, + rbb: 12222, + rbc: 12223, + rbd: 12224, + rbe: 12225, + rbf: 12226, + rbg: 12227, + rbh: 12228, + rbi: 12229, + rbj: 12230, + rbk: 12231, + rbl: 12232, + rbm: 12233, + rbn: 12234, + rbo: 12235, + rbp: 12236, + rbq: 12237, + rbr: 12238, + rbs: 12239, + rbt: 12240, + rbu: 12241, + rbv: 12242, + rbw: 12243, + rbx: 12244, + rby: 12245, + rcz: 12246, + rca: 12247, + rcb: 12248, + rcc: 12249, + rcd: 12250, + rce: 12251, + rcf: 12252, + rcg: 12253, + rch: 12254, + rci: 12255, + rcj: 12256, + rck: 12257, + rcl: 12258, + rcm: 12259, + rcn: 12260, + rco: 12261, + rcp: 12262, + rcq: 12263, + rcr: 12264, + rcs: 12265, + rct: 12266, + rcu: 12267, + rcv: 12268, + rcw: 12269, + rcx: 12270, + rcy: 12271, + rdz: 12272, + rda: 12273, + rdb: 12274, + rdc: 12275, + rdd: 12276, + rde: 12277, + rdf: 12278, + rdg: 12279, + rdh: 12280, + rdi: 12281, + rdj: 12282, + rdk: 12283, + rdl: 12284, + rdm: 12285, + rdn: 12286, + rdo: 12287, + rdp: 12288, + rdq: 12289, + rdr: 12290, + rds: 12291, + rdt: 12292, + rdu: 12293, + rdv: 12294, + rdw: 12295, + rdx: 12296, + rdy: 12297, + rez: 12298, + rea: 12299, + reb: 12300, + rec: 12301, + red: 12302, + ree: 12303, + ref: 12304, + reg: 12305, + reh: 12306, + rei: 12307, + rej: 12308, + rek: 12309, + rel: 12310, + rem: 12311, + ren: 12312, + reo: 12313, + rep: 12314, + req: 12315, + rer: 12316, + res: 12317, + ret: 12318, + reu: 12319, + rev: 12320, + rew: 12321, + rex: 12322, + rey: 12323, + rfz: 12324, + rfa: 12325, + rfb: 12326, + rfc: 12327, + rfd: 12328, + rfe: 12329, + rff: 12330, + rfg: 12331, + rfh: 12332, + rfi: 12333, + rfj: 12334, + rfk: 12335, + rfl: 12336, + rfm: 12337, + rfn: 12338, + rfo: 12339, + rfp: 12340, + rfq: 12341, + rfr: 12342, + rfs: 12343, + rft: 12344, + rfu: 12345, + rfv: 12346, + rfw: 12347, + rfx: 12348, + rfy: 12349, + rgz: 12350, + rga: 12351, + rgb: 12352, + rgc: 12353, + rgd: 12354, + rge: 12355, + rgf: 12356, + rgg: 12357, + rgh: 12358, + rgi: 12359, + rgj: 12360, + rgk: 12361, + rgl: 12362, + rgm: 12363, + rgn: 12364, + rgo: 12365, + rgp: 12366, + rgq: 12367, + rgr: 12368, + rgs: 12369, + rgt: 12370, + rgu: 12371, + rgv: 12372, + rgw: 12373, + rgx: 12374, + rgy: 12375, + rhz: 12376, + rha: 12377, + rhb: 12378, + rhc: 12379, + rhd: 12380, + rhe: 12381, + rhf: 12382, + rhg: 12383, + rhh: 12384, + rhi: 12385, + rhj: 12386, + rhk: 12387, + rhl: 12388, + rhm: 12389, + rhn: 12390, + rho: 12391, + rhp: 12392, + rhq: 12393, + rhr: 12394, + rhs: 12395, + rht: 12396, + rhu: 12397, + rhv: 12398, + rhw: 12399, + rhx: 12400, + rhy: 12401, + riz: 12402, + ria: 12403, + rib: 12404, + ric: 12405, + rid: 12406, + rie: 12407, + rif: 12408, + rig: 12409, + rih: 12410, + rii: 12411, + rij: 12412, + rik: 12413, + ril: 12414, + rim: 12415, + rin: 12416, + rio: 12417, + rip: 12418, + riq: 12419, + rir: 12420, + ris: 12421, + rit: 12422, + riu: 12423, + riv: 12424, + riw: 12425, + rix: 12426, + riy: 12427, + rjz: 12428, + rja: 12429, + rjb: 12430, + rjc: 12431, + rjd: 12432, + rje: 12433, + rjf: 12434, + rjg: 12435, + rjh: 12436, + rji: 12437, + rjj: 12438, + rjk: 12439, + rjl: 12440, + rjm: 12441, + rjn: 12442, + rjo: 12443, + rjp: 12444, + rjq: 12445, + rjr: 12446, + rjs: 12447, + rjt: 12448, + rju: 12449, + rjv: 12450, + rjw: 12451, + rjx: 12452, + rjy: 12453, + rkz: 12454, + rka: 12455, + rkb: 12456, + rkc: 12457, + rkd: 12458, + rke: 12459, + rkf: 12460, + rkg: 12461, + rkh: 12462, + rki: 12463, + rkj: 12464, + rkk: 12465, + rkl: 12466, + rkm: 12467, + rkn: 12468, + rko: 12469, + rkp: 12470, + rkq: 12471, + rkr: 12472, + rks: 12473, + rkt: 12474, + rku: 12475, + rkv: 12476, + rkw: 12477, + rkx: 12478, + rky: 12479, + rlz: 12480, + rla: 12481, + rlb: 12482, + rlc: 12483, + rld: 12484, + rle: 12485, + rlf: 12486, + rlg: 12487, + rlh: 12488, + rli: 12489, + rlj: 12490, + rlk: 12491, + rll: 12492, + rlm: 12493, + rln: 12494, + rlo: 12495, + rlp: 12496, + rlq: 12497, + rlr: 12498, + rls: 12499, + rlt: 12500, + rlu: 12501, + rlv: 12502, + rlw: 12503, + rlx: 12504, + rly: 12505, + rmz: 12506, + rma: 12507, + rmb: 12508, + rmc: 12509, + rmd: 12510, + rme: 12511, + rmf: 12512, + rmg: 12513, + rmh: 12514, + rmi: 12515, + rmj: 12516, + rmk: 12517, + rml: 12518, + rmm: 12519, + rmn: 12520, + rmo: 12521, + rmp: 12522, + rmq: 12523, + rmr: 12524, + rms: 12525, + rmt: 12526, + rmu: 12527, + rmv: 12528, + rmw: 12529, + rmx: 12530, + rmy: 12531, + rnz: 12532, + rna: 12533, + rnb: 12534, + rnc: 12535, + rnd: 12536, + rne: 12537, + rnf: 12538, + rng: 12539, + rnh: 12540, + rni: 12541, + rnj: 12542, + rnk: 12543, + rnl: 12544, + rnm: 12545, + rnn: 12546, + rno: 12547, + rnp: 12548, + rnq: 12549, + rnr: 12550, + rns: 12551, + rnt: 12552, + rnu: 12553, + rnv: 12554, + rnw: 12555, + rnx: 12556, + rny: 12557, + roz: 12558, + roa: 12559, + rob: 12560, + roc: 12561, + rod: 12562, + roe: 12563, + rof: 12564, + rog: 12565, + roh: 12566, + roi: 12567, + roj: 12568, + rok: 12569, + rol: 12570, + rom: 12571, + ron: 12572, + roo: 12573, + rop: 12574, + roq: 12575, + ror: 12576, + ros: 12577, + rot: 12578, + rou: 12579, + rov: 12580, + row: 12581, + rox: 12582, + roy: 12583, + rpz: 12584, + rpa: 12585, + rpb: 12586, + rpc: 12587, + rpd: 12588, + rpe: 12589, + rpf: 12590, + rpg: 12591, + rph: 12592, + rpi: 12593, + rpj: 12594, + rpk: 12595, + rpl: 12596, + rpm: 12597, + rpn: 12598, + rpo: 12599, + rpp: 12600, + rpq: 12601, + rpr: 12602, + rps: 12603, + rpt: 12604, + rpu: 12605, + rpv: 12606, + rpw: 12607, + rpx: 12608, + rpy: 12609, + rqz: 12610, + rqa: 12611, + rqb: 12612, + rqc: 12613, + rqd: 12614, + rqe: 12615, + rqf: 12616, + rqg: 12617, + rqh: 12618, + rqi: 12619, + rqj: 12620, + rqk: 12621, + rql: 12622, + rqm: 12623, + rqn: 12624, + rqo: 12625, + rqp: 12626, + rqq: 12627, + rqr: 12628, + rqs: 12629, + rqt: 12630, + rqu: 12631, + rqv: 12632, + rqw: 12633, + rqx: 12634, + rqy: 12635, + rrz: 12636, + rra: 12637, + rrb: 12638, + rrc: 12639, + rrd: 12640, + rre: 12641, + rrf: 12642, + rrg: 12643, + rrh: 12644, + rri: 12645, + rrj: 12646, + rrk: 12647, + rrl: 12648, + rrm: 12649, + rrn: 12650, + rro: 12651, + rrp: 12652, + rrq: 12653, + rrr: 12654, + rrs: 12655, + rrt: 12656, + rru: 12657, + rrv: 12658, + rrw: 12659, + rrx: 12660, + rry: 12661, + rsz: 12662, + rsa: 12663, + rsb: 12664, + rsc: 12665, + rsd: 12666, + rse: 12667, + rsf: 12668, + rsg: 12669, + rsh: 12670, + rsi: 12671, + rsj: 12672, + rsk: 12673, + rsl: 12674, + rsm: 12675, + rsn: 12676, + rso: 12677, + rsp: 12678, + rsq: 12679, + rsr: 12680, + rss: 12681, + rst: 12682, + rsu: 12683, + rsv: 12684, + rsw: 12685, + rsx: 12686, + rsy: 12687, + rtz: 12688, + rta: 12689, + rtb: 12690, + rtc: 12691, + rtd: 12692, + rte: 12693, + rtf: 12694, + rtg: 12695, + rth: 12696, + rti: 12697, + rtj: 12698, + rtk: 12699, + rtl: 12700, + rtm: 12701, + rtn: 12702, + rto: 12703, + rtp: 12704, + rtq: 12705, + rtr: 12706, + rts: 12707, + rtt: 12708, + rtu: 12709, + rtv: 12710, + rtw: 12711, + rtx: 12712, + rty: 12713, + ruz: 12714, + rua: 12715, + rub: 12716, + ruc: 12717, + rud: 12718, + rue: 12719, + ruf: 12720, + rug: 12721, + ruh: 12722, + rui: 12723, + ruj: 12724, + ruk: 12725, + rul: 12726, + rum: 12727, + run: 12728, + ruo: 12729, + rup: 12730, + ruq: 12731, + rur: 12732, + rus: 12733, + rut: 12734, + ruu: 12735, + ruv: 12736, + ruw: 12737, + rux: 12738, + ruy: 12739, + rvz: 12740, + rva: 12741, + rvb: 12742, + rvc: 12743, + rvd: 12744, + rve: 12745, + rvf: 12746, + rvg: 12747, + rvh: 12748, + rvi: 12749, + rvj: 12750, + rvk: 12751, + rvl: 12752, + rvm: 12753, + rvn: 12754, + rvo: 12755, + rvp: 12756, + rvq: 12757, + rvr: 12758, + rvs: 12759, + rvt: 12760, + rvu: 12761, + rvv: 12762, + rvw: 12763, + rvx: 12764, + rvy: 12765, + rwz: 12766, + rwa: 12767, + rwb: 12768, + rwc: 12769, + rwd: 12770, + rwe: 12771, + rwf: 12772, + rwg: 12773, + rwh: 12774, + rwi: 12775, + rwj: 12776, + rwk: 12777, + rwl: 12778, + rwm: 12779, + rwn: 12780, + rwo: 12781, + rwp: 12782, + rwq: 12783, + rwr: 12784, + rws: 12785, + rwt: 12786, + rwu: 12787, + rwv: 12788, + rww: 12789, + rwx: 12790, + rwy: 12791, + rxz: 12792, + rxa: 12793, + rxb: 12794, + rxc: 12795, + rxd: 12796, + rxe: 12797, + rxf: 12798, + rxg: 12799, + rxh: 12800, + rxi: 12801, + rxj: 12802, + rxk: 12803, + rxl: 12804, + rxm: 12805, + rxn: 12806, + rxo: 12807, + rxp: 12808, + rxq: 12809, + rxr: 12810, + rxs: 12811, + rxt: 12812, + rxu: 12813, + rxv: 12814, + rxw: 12815, + rxx: 12816, + rxy: 12817, + ryz: 12818, + rya: 12819, + ryb: 12820, + ryc: 12821, + ryd: 12822, + rye: 12823, + ryf: 12824, + ryg: 12825, + ryh: 12826, + ryi: 12827, + ryj: 12828, + ryk: 12829, + ryl: 12830, + rym: 12831, + ryn: 12832, + ryo: 12833, + ryp: 12834, + ryq: 12835, + ryr: 12836, + rys: 12837, + ryt: 12838, + ryu: 12839, + ryv: 12840, + ryw: 12841, + ryx: 12842, + ryy: 12843, + szz: 12844, + sza: 12845, + szb: 12846, + szc: 12847, + szd: 12848, + sze: 12849, + szf: 12850, + szg: 12851, + szh: 12852, + szi: 12853, + szj: 12854, + szk: 12855, + szl: 12856, + szm: 12857, + szn: 12858, + szo: 12859, + szp: 12860, + szq: 12861, + szr: 12862, + szs: 12863, + szt: 12864, + szu: 12865, + szv: 12866, + szw: 12867, + szx: 12868, + szy: 12869, + saz: 12870, + saa: 12871, + sab: 12872, + sac: 12873, + sad: 12874, + sae: 12875, + saf: 12876, + sag: 12877, + sah: 12878, + sai: 12879, + saj: 12880, + sak: 12881, + sal: 12882, + sam: 12883, + san: 12884, + sao: 12885, + sap: 12886, + saq: 12887, + sar: 12888, + sas: 12889, + sat: 12890, + sau: 12891, + sav: 12892, + saw: 12893, + sax: 12894, + say: 12895, + sbz: 12896, + sba: 12897, + sbb: 12898, + sbc: 12899, + sbd: 12900, + sbe: 12901, + sbf: 12902, + sbg: 12903, + sbh: 12904, + sbi: 12905, + sbj: 12906, + sbk: 12907, + sbl: 12908, + sbm: 12909, + sbn: 12910, + sbo: 12911, + sbp: 12912, + sbq: 12913, + sbr: 12914, + sbs: 12915, + sbt: 12916, + sbu: 12917, + sbv: 12918, + sbw: 12919, + sbx: 12920, + sby: 12921, + scz: 12922, + sca: 12923, + scb: 12924, + scc: 12925, + scd: 12926, + sce: 12927, + scf: 12928, + scg: 12929, + sch: 12930, + sci: 12931, + scj: 12932, + sck: 12933, + scl: 12934, + scm: 12935, + scn: 12936, + sco: 12937, + scp: 12938, + scq: 12939, + scr: 12940, + scs: 12941, + sct: 12942, + scu: 12943, + scv: 12944, + scw: 12945, + scx: 12946, + scy: 12947, + sdz: 12948, + sda: 12949, + sdb: 12950, + sdc: 12951, + sdd: 12952, + sde: 12953, + sdf: 12954, + sdg: 12955, + sdh: 12956, + sdi: 12957, + sdj: 12958, + sdk: 12959, + sdl: 12960, + sdm: 12961, + sdn: 12962, + sdo: 12963, + sdp: 12964, + sdq: 12965, + sdr: 12966, + sds: 12967, + sdt: 12968, + sdu: 12969, + sdv: 12970, + sdw: 12971, + sdx: 12972, + sdy: 12973, + sez: 12974, + sea: 12975, + seb: 12976, + sec: 12977, + sed: 12978, + see: 12979, + sef: 12980, + seg: 12981, + seh: 12982, + sei: 12983, + sej: 12984, + sek: 12985, + sel: 12986, + sem: 12987, + sen: 12988, + seo: 12989, + sep: 12990, + seq: 12991, + ser: 12992, + ses: 12993, + set: 12994, + seu: 12995, + sev: 12996, + sew: 12997, + sex: 12998, + sey: 12999, + sfz: 13000, + sfa: 13001, + sfb: 13002, + sfc: 13003, + sfd: 13004, + sfe: 13005, + sff: 13006, + sfg: 13007, + sfh: 13008, + sfi: 13009, + sfj: 13010, + sfk: 13011, + sfl: 13012, + sfm: 13013, + sfn: 13014, + sfo: 13015, + sfp: 13016, + sfq: 13017, + sfr: 13018, + sfs: 13019, + sft: 13020, + sfu: 13021, + sfv: 13022, + sfw: 13023, + sfx: 13024, + sfy: 13025, + sgz: 13026, + sga: 13027, + sgb: 13028, + sgc: 13029, + sgd: 13030, + sge: 13031, + sgf: 13032, + sgg: 13033, + sgh: 13034, + sgi: 13035, + sgj: 13036, + sgk: 13037, + sgl: 13038, + sgm: 13039, + sgn: 13040, + sgo: 13041, + sgp: 13042, + sgq: 13043, + sgr: 13044, + sgs: 13045, + sgt: 13046, + sgu: 13047, + sgv: 13048, + sgw: 13049, + sgx: 13050, + sgy: 13051, + shz: 13052, + sha: 13053, + shb: 13054, + shc: 13055, + shd: 13056, + she: 13057, + shf: 13058, + shg: 13059, + shh: 13060, + shi: 13061, + shj: 13062, + shk: 13063, + shl: 13064, + shm: 13065, + shn: 13066, + sho: 13067, + shp: 13068, + shq: 13069, + shr: 13070, + shs: 13071, + sht: 13072, + shu: 13073, + shv: 13074, + shw: 13075, + shx: 13076, + shy: 13077, + siz: 13078, + sia: 13079, + sib: 13080, + sic: 13081, + sid: 13082, + sie: 13083, + sif: 13084, + sig: 13085, + sih: 13086, + sii: 13087, + sij: 13088, + sik: 13089, + sil: 13090, + sim: 13091, + sin: 13092, + sio: 13093, + sip: 13094, + siq: 13095, + sir: 13096, + sis: 13097, + sit: 13098, + siu: 13099, + siv: 13100, + siw: 13101, + six: 13102, + siy: 13103, + sjz: 13104, + sja: 13105, + sjb: 13106, + sjc: 13107, + sjd: 13108, + sje: 13109, + sjf: 13110, + sjg: 13111, + sjh: 13112, + sji: 13113, + sjj: 13114, + sjk: 13115, + sjl: 13116, + sjm: 13117, + sjn: 13118, + sjo: 13119, + sjp: 13120, + sjq: 13121, + sjr: 13122, + sjs: 13123, + sjt: 13124, + sju: 13125, + sjv: 13126, + sjw: 13127, + sjx: 13128, + sjy: 13129, + skz: 13130, + ska: 13131, + skb: 13132, + skc: 13133, + skd: 13134, + ske: 13135, + skf: 13136, + skg: 13137, + skh: 13138, + ski: 13139, + skj: 13140, + skk: 13141, + skl: 13142, + skm: 13143, + skn: 13144, + sko: 13145, + skp: 13146, + skq: 13147, + skr: 13148, + sks: 13149, + skt: 13150, + sku: 13151, + skv: 13152, + skw: 13153, + skx: 13154, + sky: 13155, + slz: 13156, + sla: 13157, + slb: 13158, + slc: 13159, + sld: 13160, + sle: 13161, + slf: 13162, + slg: 13163, + slh: 13164, + sli: 13165, + slj: 13166, + slk: 13167, + sll: 13168, + slm: 13169, + sln: 13170, + slo: 13171, + slp: 13172, + slq: 13173, + slr: 13174, + sls: 13175, + slt: 13176, + slu: 13177, + slv: 13178, + slw: 13179, + slx: 13180, + sly: 13181, + smz: 13182, + sma: 13183, + smb: 13184, + smc: 13185, + smd: 13186, + sme: 13187, + smf: 13188, + smg: 13189, + smh: 13190, + smi: 13191, + smj: 13192, + smk: 13193, + sml: 13194, + smm: 13195, + smn: 13196, + smo: 13197, + smp: 13198, + smq: 13199, + smr: 13200, + sms: 13201, + smt: 13202, + smu: 13203, + smv: 13204, + smw: 13205, + smx: 13206, + smy: 13207, + snz: 13208, + sna: 13209, + snb: 13210, + snc: 13211, + snd: 13212, + sne: 13213, + snf: 13214, + sng: 13215, + snh: 13216, + sni: 13217, + snj: 13218, + snk: 13219, + snl: 13220, + snm: 13221, + snn: 13222, + sno: 13223, + snp: 13224, + snq: 13225, + snr: 13226, + sns: 13227, + snt: 13228, + snu: 13229, + snv: 13230, + snw: 13231, + snx: 13232, + sny: 13233, + soz: 13234, + soa: 13235, + sob: 13236, + soc: 13237, + sod: 13238, + soe: 13239, + sof: 13240, + sog: 13241, + soh: 13242, + soi: 13243, + soj: 13244, + sok: 13245, + sol: 13246, + som: 13247, + son: 13248, + soo: 13249, + sop: 13250, + soq: 13251, + sor: 13252, + sos: 13253, + sot: 13254, + sou: 13255, + sov: 13256, + sow: 13257, + sox: 13258, + soy: 13259, + spz: 13260, + spa: 13261, + spb: 13262, + spc: 13263, + spd: 13264, + spe: 13265, + spf: 13266, + spg: 13267, + sph: 13268, + spi: 13269, + spj: 13270, + spk: 13271, + spl: 13272, + spm: 13273, + spn: 13274, + spo: 13275, + spp: 13276, + spq: 13277, + spr: 13278, + sps: 13279, + spt: 13280, + spu: 13281, + spv: 13282, + spw: 13283, + spx: 13284, + spy: 13285, + sqz: 13286, + sqa: 13287, + sqb: 13288, + sqc: 13289, + sqd: 13290, + sqe: 13291, + sqf: 13292, + sqg: 13293, + sqh: 13294, + sqi: 13295, + sqj: 13296, + sqk: 13297, + sql: 13298, + sqm: 13299, + sqn: 13300, + sqo: 13301, + sqp: 13302, + sqq: 13303, + sqr: 13304, + sqs: 13305, + sqt: 13306, + squ: 13307, + sqv: 13308, + sqw: 13309, + sqx: 13310, + sqy: 13311, + srz: 13312, + sra: 13313, + srb: 13314, + src: 13315, + srd: 13316, + sre: 13317, + srf: 13318, + srg: 13319, + srh: 13320, + sri: 13321, + srj: 13322, + srk: 13323, + srl: 13324, + srm: 13325, + srn: 13326, + sro: 13327, + srp: 13328, + srq: 13329, + srr: 13330, + srs: 13331, + srt: 13332, + sru: 13333, + srv: 13334, + srw: 13335, + srx: 13336, + sry: 13337, + ssz: 13338, + ssa: 13339, + ssb: 13340, + ssc: 13341, + ssd: 13342, + sse: 13343, + ssf: 13344, + ssg: 13345, + ssh: 13346, + ssi: 13347, + ssj: 13348, + ssk: 13349, + ssl: 13350, + ssm: 13351, + ssn: 13352, + sso: 13353, + ssp: 13354, + ssq: 13355, + ssr: 13356, + sss: 13357, + sst: 13358, + ssu: 13359, + ssv: 13360, + ssw: 13361, + ssx: 13362, + ssy: 13363, + stz: 13364, + sta: 13365, + stb: 13366, + stc: 13367, + std: 13368, + ste: 13369, + stf: 13370, + stg: 13371, + sth: 13372, + sti: 13373, + stj: 13374, + stk: 13375, + stl: 13376, + stm: 13377, + stn: 13378, + sto: 13379, + stp: 13380, + stq: 13381, + str: 13382, + sts: 13383, + stt: 13384, + stu: 13385, + stv: 13386, + stw: 13387, + stx: 13388, + sty: 13389, + suz: 13390, + sua: 13391, + sub: 13392, + suc: 13393, + sud: 13394, + sue: 13395, + suf: 13396, + sug: 13397, + suh: 13398, + sui: 13399, + suj: 13400, + suk: 13401, + sul: 13402, + sum: 13403, + sun: 13404, + suo: 13405, + sup: 13406, + suq: 13407, + sur: 13408, + sus: 13409, + sut: 13410, + suu: 13411, + suv: 13412, + suw: 13413, + sux: 13414, + suy: 13415, + svz: 13416, + sva: 13417, + svb: 13418, + svc: 13419, + svd: 13420, + sve: 13421, + svf: 13422, + svg: 13423, + svh: 13424, + svi: 13425, + svj: 13426, + svk: 13427, + svl: 13428, + svm: 13429, + svn: 13430, + svo: 13431, + svp: 13432, + svq: 13433, + svr: 13434, + svs: 13435, + svt: 13436, + svu: 13437, + svv: 13438, + svw: 13439, + svx: 13440, + svy: 13441, + swz: 13442, + swa: 13443, + swb: 13444, + swc: 13445, + swd: 13446, + swe: 13447, + swf: 13448, + swg: 13449, + swh: 13450, + swi: 13451, + swj: 13452, + swk: 13453, + swl: 13454, + swm: 13455, + swn: 13456, + swo: 13457, + swp: 13458, + swq: 13459, + swr: 13460, + sws: 13461, + swt: 13462, + swu: 13463, + swv: 13464, + sww: 13465, + swx: 13466, + swy: 13467, + sxz: 13468, + sxa: 13469, + sxb: 13470, + sxc: 13471, + sxd: 13472, + sxe: 13473, + sxf: 13474, + sxg: 13475, + sxh: 13476, + sxi: 13477, + sxj: 13478, + sxk: 13479, + sxl: 13480, + sxm: 13481, + sxn: 13482, + sxo: 13483, + sxp: 13484, + sxq: 13485, + sxr: 13486, + sxs: 13487, + sxt: 13488, + sxu: 13489, + sxv: 13490, + sxw: 13491, + sxx: 13492, + sxy: 13493, + syz: 13494, + sya: 13495, + syb: 13496, + syc: 13497, + syd: 13498, + sye: 13499, + syf: 13500, + syg: 13501, + syh: 13502, + syi: 13503, + syj: 13504, + syk: 13505, + syl: 13506, + sym: 13507, + syn: 13508, + syo: 13509, + syp: 13510, + syq: 13511, + syr: 13512, + sys: 13513, + syt: 13514, + syu: 13515, + syv: 13516, + syw: 13517, + syx: 13518, + syy: 13519, + tzz: 13520, + tza: 13521, + tzb: 13522, + tzc: 13523, + tzd: 13524, + tze: 13525, + tzf: 13526, + tzg: 13527, + tzh: 13528, + tzi: 13529, + tzj: 13530, + tzk: 13531, + tzl: 13532, + tzm: 13533, + tzn: 13534, + tzo: 13535, + tzp: 13536, + tzq: 13537, + tzr: 13538, + tzs: 13539, + tzt: 13540, + tzu: 13541, + tzv: 13542, + tzw: 13543, + tzx: 13544, + tzy: 13545, + taz: 13546, + taa: 13547, + tab: 13548, + tac: 13549, + tad: 13550, + tae: 13551, + taf: 13552, + tag: 13553, + tah: 13554, + tai: 13555, + taj: 13556, + tak: 13557, + tal: 13558, + tam: 13559, + tan: 13560, + tao: 13561, + tap: 13562, + taq: 13563, + tar: 13564, + tas: 13565, + tat: 13566, + tau: 13567, + tav: 13568, + taw: 13569, + tax: 13570, + tay: 13571, + tbz: 13572, + tba: 13573, + tbb: 13574, + tbc: 13575, + tbd: 13576, + tbe: 13577, + tbf: 13578, + tbg: 13579, + tbh: 13580, + tbi: 13581, + tbj: 13582, + tbk: 13583, + tbl: 13584, + tbm: 13585, + tbn: 13586, + tbo: 13587, + tbp: 13588, + tbq: 13589, + tbr: 13590, + tbs: 13591, + tbt: 13592, + tbu: 13593, + tbv: 13594, + tbw: 13595, + tbx: 13596, + tby: 13597, + tcz: 13598, + tca: 13599, + tcb: 13600, + tcc: 13601, + tcd: 13602, + tce: 13603, + tcf: 13604, + tcg: 13605, + tch: 13606, + tci: 13607, + tcj: 13608, + tck: 13609, + tcl: 13610, + tcm: 13611, + tcn: 13612, + tco: 13613, + tcp: 13614, + tcq: 13615, + tcr: 13616, + tcs: 13617, + tct: 13618, + tcu: 13619, + tcv: 13620, + tcw: 13621, + tcx: 13622, + tcy: 13623, + tdz: 13624, + tda: 13625, + tdb: 13626, + tdc: 13627, + tdd: 13628, + tde: 13629, + tdf: 13630, + tdg: 13631, + tdh: 13632, + tdi: 13633, + tdj: 13634, + tdk: 13635, + tdl: 13636, + tdm: 13637, + tdn: 13638, + tdo: 13639, + tdp: 13640, + tdq: 13641, + tdr: 13642, + tds: 13643, + tdt: 13644, + tdu: 13645, + tdv: 13646, + tdw: 13647, + tdx: 13648, + tdy: 13649, + tez: 13650, + tea: 13651, + teb: 13652, + tec: 13653, + ted: 13654, + tee: 13655, + tef: 13656, + teg: 13657, + teh: 13658, + tei: 13659, + tej: 13660, + tek: 13661, + tel: 13662, + tem: 13663, + ten: 13664, + teo: 13665, + tep: 13666, + teq: 13667, + ter: 13668, + tes: 13669, + tet: 13670, + teu: 13671, + tev: 13672, + tew: 13673, + tex: 13674, + tey: 13675, + tfz: 13676, + tfa: 13677, + tfb: 13678, + tfc: 13679, + tfd: 13680, + tfe: 13681, + tff: 13682, + tfg: 13683, + tfh: 13684, + tfi: 13685, + tfj: 13686, + tfk: 13687, + tfl: 13688, + tfm: 13689, + tfn: 13690, + tfo: 13691, + tfp: 13692, + tfq: 13693, + tfr: 13694, + tfs: 13695, + tft: 13696, + tfu: 13697, + tfv: 13698, + tfw: 13699, + tfx: 13700, + tfy: 13701, + tgz: 13702, + tga: 13703, + tgb: 13704, + tgc: 13705, + tgd: 13706, + tge: 13707, + tgf: 13708, + tgg: 13709, + tgh: 13710, + tgi: 13711, + tgj: 13712, + tgk: 13713, + tgl: 13714, + tgm: 13715, + tgn: 13716, + tgo: 13717, + tgp: 13718, + tgq: 13719, + tgr: 13720, + tgs: 13721, + tgt: 13722, + tgu: 13723, + tgv: 13724, + tgw: 13725, + tgx: 13726, + tgy: 13727, + thz: 13728, + tha: 13729, + thb: 13730, + thc: 13731, + thd: 13732, + the: 13733, + thf: 13734, + thg: 13735, + thh: 13736, + thi: 13737, + thj: 13738, + thk: 13739, + thl: 13740, + thm: 13741, + thn: 13742, + tho: 13743, + thp: 13744, + thq: 13745, + thr: 13746, + ths: 13747, + tht: 13748, + thu: 13749, + thv: 13750, + thw: 13751, + thx: 13752, + thy: 13753, + tiz: 13754, + tia: 13755, + tib: 13756, + tic: 13757, + tid: 13758, + tie: 13759, + tif: 13760, + tig: 13761, + tih: 13762, + tii: 13763, + tij: 13764, + tik: 13765, + til: 13766, + tim: 13767, + tin: 13768, + tio: 13769, + tip: 13770, + tiq: 13771, + tir: 13772, + tis: 13773, + tit: 13774, + tiu: 13775, + tiv: 13776, + tiw: 13777, + tix: 13778, + tiy: 13779, + tjz: 13780, + tja: 13781, + tjb: 13782, + tjc: 13783, + tjd: 13784, + tje: 13785, + tjf: 13786, + tjg: 13787, + tjh: 13788, + tji: 13789, + tjj: 13790, + tjk: 13791, + tjl: 13792, + tjm: 13793, + tjn: 13794, + tjo: 13795, + tjp: 13796, + tjq: 13797, + tjr: 13798, + tjs: 13799, + tjt: 13800, + tju: 13801, + tjv: 13802, + tjw: 13803, + tjx: 13804, + tjy: 13805, + tkz: 13806, + tka: 13807, + tkb: 13808, + tkc: 13809, + tkd: 13810, + tke: 13811, + tkf: 13812, + tkg: 13813, + tkh: 13814, + tki: 13815, + tkj: 13816, + tkk: 13817, + tkl: 13818, + tkm: 13819, + tkn: 13820, + tko: 13821, + tkp: 13822, + tkq: 13823, + tkr: 13824, + tks: 13825, + tkt: 13826, + tku: 13827, + tkv: 13828, + tkw: 13829, + tkx: 13830, + tky: 13831, + tlz: 13832, + tla: 13833, + tlb: 13834, + tlc: 13835, + tld: 13836, + tle: 13837, + tlf: 13838, + tlg: 13839, + tlh: 13840, + tli: 13841, + tlj: 13842, + tlk: 13843, + tll: 13844, + tlm: 13845, + tln: 13846, + tlo: 13847, + tlp: 13848, + tlq: 13849, + tlr: 13850, + tls: 13851, + tlt: 13852, + tlu: 13853, + tlv: 13854, + tlw: 13855, + tlx: 13856, + tly: 13857, + tmz: 13858, + tma: 13859, + tmb: 13860, + tmc: 13861, + tmd: 13862, + tme: 13863, + tmf: 13864, + tmg: 13865, + tmh: 13866, + tmi: 13867, + tmj: 13868, + tmk: 13869, + tml: 13870, + tmm: 13871, + tmn: 13872, + tmo: 13873, + tmp: 13874, + tmq: 13875, + tmr: 13876, + tms: 13877, + tmt: 13878, + tmu: 13879, + tmv: 13880, + tmw: 13881, + tmx: 13882, + tmy: 13883, + tnz: 13884, + tna: 13885, + tnb: 13886, + tnc: 13887, + tnd: 13888, + tne: 13889, + tnf: 13890, + tng: 13891, + tnh: 13892, + tni: 13893, + tnj: 13894, + tnk: 13895, + tnl: 13896, + tnm: 13897, + tnn: 13898, + tno: 13899, + tnp: 13900, + tnq: 13901, + tnr: 13902, + tns: 13903, + tnt: 13904, + tnu: 13905, + tnv: 13906, + tnw: 13907, + tnx: 13908, + tny: 13909, + toz: 13910, + toa: 13911, + tob: 13912, + toc: 13913, + tod: 13914, + toe: 13915, + tof: 13916, + tog: 13917, + toh: 13918, + toi: 13919, + toj: 13920, + tok: 13921, + tol: 13922, + tom: 13923, + ton: 13924, + too: 13925, + top: 13926, + toq: 13927, + tor: 13928, + tos: 13929, + tot: 13930, + tou: 13931, + tov: 13932, + tow: 13933, + tox: 13934, + toy: 13935, + tpz: 13936, + tpa: 13937, + tpb: 13938, + tpc: 13939, + tpd: 13940, + tpe: 13941, + tpf: 13942, + tpg: 13943, + tph: 13944, + tpi: 13945, + tpj: 13946, + tpk: 13947, + tpl: 13948, + tpm: 13949, + tpn: 13950, + tpo: 13951, + tpp: 13952, + tpq: 13953, + tpr: 13954, + tps: 13955, + tpt: 13956, + tpu: 13957, + tpv: 13958, + tpw: 13959, + tpx: 13960, + tpy: 13961, + tqz: 13962, + tqa: 13963, + tqb: 13964, + tqc: 13965, + tqd: 13966, + tqe: 13967, + tqf: 13968, + tqg: 13969, + tqh: 13970, + tqi: 13971, + tqj: 13972, + tqk: 13973, + tql: 13974, + tqm: 13975, + tqn: 13976, + tqo: 13977, + tqp: 13978, + tqq: 13979, + tqr: 13980, + tqs: 13981, + tqt: 13982, + tqu: 13983, + tqv: 13984, + tqw: 13985, + tqx: 13986, + tqy: 13987, + trz: 13988, + tra: 13989, + trb: 13990, + trc: 13991, + trd: 13992, + tre: 13993, + trf: 13994, + trg: 13995, + trh: 13996, + tri: 13997, + trj: 13998, + trk: 13999, + trl: 14000, + trm: 14001, + trn: 14002, + tro: 14003, + trp: 14004, + trq: 14005, + trr: 14006, + trs: 14007, + trt: 14008, + tru: 14009, + trv: 14010, + trw: 14011, + trx: 14012, + try: 14013, + tsz: 14014, + tsa: 14015, + tsb: 14016, + tsc: 14017, + tsd: 14018, + tse: 14019, + tsf: 14020, + tsg: 14021, + tsh: 14022, + tsi: 14023, + tsj: 14024, + tsk: 14025, + tsl: 14026, + tsm: 14027, + tsn: 14028, + tso: 14029, + tsp: 14030, + tsq: 14031, + tsr: 14032, + tss: 14033, + tst: 14034, + tsu: 14035, + tsv: 14036, + tsw: 14037, + tsx: 14038, + tsy: 14039, + ttz: 14040, + tta: 14041, + ttb: 14042, + ttc: 14043, + ttd: 14044, + tte: 14045, + ttf: 14046, + ttg: 14047, + tth: 14048, + tti: 14049, + ttj: 14050, + ttk: 14051, + ttl: 14052, + ttm: 14053, + ttn: 14054, + tto: 14055, + ttp: 14056, + ttq: 14057, + ttr: 14058, + tts: 14059, + ttt: 14060, + ttu: 14061, + ttv: 14062, + ttw: 14063, + ttx: 14064, + tty: 14065, + tuz: 14066, + tua: 14067, + tub: 14068, + tuc: 14069, + tud: 14070, + tue: 14071, + tuf: 14072, + tug: 14073, + tuh: 14074, + tui: 14075, + tuj: 14076, + tuk: 14077, + tul: 14078, + tum: 14079, + tun: 14080, + tuo: 14081, + tup: 14082, + tuq: 14083, + tur: 14084, + tus: 14085, + tut: 14086, + tuu: 14087, + tuv: 14088, + tuw: 14089, + tux: 14090, + tuy: 14091, + tvz: 14092, + tva: 14093, + tvb: 14094, + tvc: 14095, + tvd: 14096, + tve: 14097, + tvf: 14098, + tvg: 14099, + tvh: 14100, + tvi: 14101, + tvj: 14102, + tvk: 14103, + tvl: 14104, + tvm: 14105, + tvn: 14106, + tvo: 14107, + tvp: 14108, + tvq: 14109, + tvr: 14110, + tvs: 14111, + tvt: 14112, + tvu: 14113, + tvv: 14114, + tvw: 14115, + tvx: 14116, + tvy: 14117, + twz: 14118, + twa: 14119, + twb: 14120, + twc: 14121, + twd: 14122, + twe: 14123, + twf: 14124, + twg: 14125, + twh: 14126, + twi: 14127, + twj: 14128, + twk: 14129, + twl: 14130, + twm: 14131, + twn: 14132, + two: 14133, + twp: 14134, + twq: 14135, + twr: 14136, + tws: 14137, + twt: 14138, + twu: 14139, + twv: 14140, + tww: 14141, + twx: 14142, + twy: 14143, + txz: 14144, + txa: 14145, + txb: 14146, + txc: 14147, + txd: 14148, + txe: 14149, + txf: 14150, + txg: 14151, + txh: 14152, + txi: 14153, + txj: 14154, + txk: 14155, + txl: 14156, + txm: 14157, + txn: 14158, + txo: 14159, + txp: 14160, + txq: 14161, + txr: 14162, + txs: 14163, + txt: 14164, + txu: 14165, + txv: 14166, + txw: 14167, + txx: 14168, + txy: 14169, + tyz: 14170, + tya: 14171, + tyb: 14172, + tyc: 14173, + tyd: 14174, + tye: 14175, + tyf: 14176, + tyg: 14177, + tyh: 14178, + tyi: 14179, + tyj: 14180, + tyk: 14181, + tyl: 14182, + tym: 14183, + tyn: 14184, + tyo: 14185, + typ: 14186, + tyq: 14187, + tyr: 14188, + tys: 14189, + tyt: 14190, + tyu: 14191, + tyv: 14192, + tyw: 14193, + tyx: 14194, + tyy: 14195, + uzz: 14196, + uza: 14197, + uzb: 14198, + uzc: 14199, + uzd: 14200, + uze: 14201, + uzf: 14202, + uzg: 14203, + uzh: 14204, + uzi: 14205, + uzj: 14206, + uzk: 14207, + uzl: 14208, + uzm: 14209, + uzn: 14210, + uzo: 14211, + uzp: 14212, + uzq: 14213, + uzr: 14214, + uzs: 14215, + uzt: 14216, + uzu: 14217, + uzv: 14218, + uzw: 14219, + uzx: 14220, + uzy: 14221, + uaz: 14222, + uaa: 14223, + uab: 14224, + uac: 14225, + uad: 14226, + uae: 14227, + uaf: 14228, + uag: 14229, + uah: 14230, + uai: 14231, + uaj: 14232, + uak: 14233, + ual: 14234, + uam: 14235, + uan: 14236, + uao: 14237, + uap: 14238, + uaq: 14239, + uar: 14240, + uas: 14241, + uat: 14242, + uau: 14243, + uav: 14244, + uaw: 14245, + uax: 14246, + uay: 14247, + ubz: 14248, + uba: 14249, + ubb: 14250, + ubc: 14251, + ubd: 14252, + ube: 14253, + ubf: 14254, + ubg: 14255, + ubh: 14256, + ubi: 14257, + ubj: 14258, + ubk: 14259, + ubl: 14260, + ubm: 14261, + ubn: 14262, + ubo: 14263, + ubp: 14264, + ubq: 14265, + ubr: 14266, + ubs: 14267, + ubt: 14268, + ubu: 14269, + ubv: 14270, + ubw: 14271, + ubx: 14272, + uby: 14273, + ucz: 14274, + uca: 14275, + ucb: 14276, + ucc: 14277, + ucd: 14278, + uce: 14279, + ucf: 14280, + ucg: 14281, + uch: 14282, + uci: 14283, + ucj: 14284, + uck: 14285, + ucl: 14286, + ucm: 14287, + ucn: 14288, + uco: 14289, + ucp: 14290, + ucq: 14291, + ucr: 14292, + ucs: 14293, + uct: 14294, + ucu: 14295, + ucv: 14296, + ucw: 14297, + ucx: 14298, + ucy: 14299, + udz: 14300, + uda: 14301, + udb: 14302, + udc: 14303, + udd: 14304, + ude: 14305, + udf: 14306, + udg: 14307, + udh: 14308, + udi: 14309, + udj: 14310, + udk: 14311, + udl: 14312, + udm: 14313, + udn: 14314, + udo: 14315, + udp: 14316, + udq: 14317, + udr: 14318, + uds: 14319, + udt: 14320, + udu: 14321, + udv: 14322, + udw: 14323, + udx: 14324, + udy: 14325, + uez: 14326, + uea: 14327, + ueb: 14328, + uec: 14329, + ued: 14330, + uee: 14331, + uef: 14332, + ueg: 14333, + ueh: 14334, + uei: 14335, + uej: 14336, + uek: 14337, + uel: 14338, + uem: 14339, + uen: 14340, + ueo: 14341, + uep: 14342, + ueq: 14343, + uer: 14344, + ues: 14345, + uet: 14346, + ueu: 14347, + uev: 14348, + uew: 14349, + uex: 14350, + uey: 14351, + ufz: 14352, + ufa: 14353, + ufb: 14354, + ufc: 14355, + ufd: 14356, + ufe: 14357, + uff: 14358, + ufg: 14359, + ufh: 14360, + ufi: 14361, + ufj: 14362, + ufk: 14363, + ufl: 14364, + ufm: 14365, + ufn: 14366, + ufo: 14367, + ufp: 14368, + ufq: 14369, + ufr: 14370, + ufs: 14371, + uft: 14372, + ufu: 14373, + ufv: 14374, + ufw: 14375, + ufx: 14376, + ufy: 14377, + ugz: 14378, + uga: 14379, + ugb: 14380, + ugc: 14381, + ugd: 14382, + uge: 14383, + ugf: 14384, + ugg: 14385, + ugh: 14386, + ugi: 14387, + ugj: 14388, + ugk: 14389, + ugl: 14390, + ugm: 14391, + ugn: 14392, + ugo: 14393, + ugp: 14394, + ugq: 14395, + ugr: 14396, + ugs: 14397, + ugt: 14398, + ugu: 14399, + ugv: 14400, + ugw: 14401, + ugx: 14402, + ugy: 14403, + uhz: 14404, + uha: 14405, + uhb: 14406, + uhc: 14407, + uhd: 14408, + uhe: 14409, + uhf: 14410, + uhg: 14411, + uhh: 14412, + uhi: 14413, + uhj: 14414, + uhk: 14415, + uhl: 14416, + uhm: 14417, + uhn: 14418, + uho: 14419, + uhp: 14420, + uhq: 14421, + uhr: 14422, + uhs: 14423, + uht: 14424, + uhu: 14425, + uhv: 14426, + uhw: 14427, + uhx: 14428, + uhy: 14429, + uiz: 14430, + uia: 14431, + uib: 14432, + uic: 14433, + uid: 14434, + uie: 14435, + uif: 14436, + uig: 14437, + uih: 14438, + uii: 14439, + uij: 14440, + uik: 14441, + uil: 14442, + uim: 14443, + uin: 14444, + uio: 14445, + uip: 14446, + uiq: 14447, + uir: 14448, + uis: 14449, + uit: 14450, + uiu: 14451, + uiv: 14452, + uiw: 14453, + uix: 14454, + uiy: 14455, + ujz: 14456, + uja: 14457, + ujb: 14458, + ujc: 14459, + ujd: 14460, + uje: 14461, + ujf: 14462, + ujg: 14463, + ujh: 14464, + uji: 14465, + ujj: 14466, + ujk: 14467, + ujl: 14468, + ujm: 14469, + ujn: 14470, + ujo: 14471, + ujp: 14472, + ujq: 14473, + ujr: 14474, + ujs: 14475, + ujt: 14476, + uju: 14477, + ujv: 14478, + ujw: 14479, + ujx: 14480, + ujy: 14481, + ukz: 14482, + uka: 14483, + ukb: 14484, + ukc: 14485, + ukd: 14486, + uke: 14487, + ukf: 14488, + ukg: 14489, + ukh: 14490, + uki: 14491, + ukj: 14492, + ukk: 14493, + ukl: 14494, + ukm: 14495, + ukn: 14496, + uko: 14497, + ukp: 14498, + ukq: 14499, + ukr: 14500, + uks: 14501, + ukt: 14502, + uku: 14503, + ukv: 14504, + ukw: 14505, + ukx: 14506, + uky: 14507, + ulz: 14508, + ula: 14509, + ulb: 14510, + ulc: 14511, + uld: 14512, + ule: 14513, + ulf: 14514, + ulg: 14515, + ulh: 14516, + uli: 14517, + ulj: 14518, + ulk: 14519, + ull: 14520, + ulm: 14521, + uln: 14522, + ulo: 14523, + ulp: 14524, + ulq: 14525, + ulr: 14526, + uls: 14527, + ult: 14528, + ulu: 14529, + ulv: 14530, + ulw: 14531, + ulx: 14532, + uly: 14533, + umz: 14534, + uma: 14535, + umb: 14536, + umc: 14537, + umd: 14538, + ume: 14539, + umf: 14540, + umg: 14541, + umh: 14542, + umi: 14543, + umj: 14544, + umk: 14545, + uml: 14546, + umm: 14547, + umn: 14548, + umo: 14549, + ump: 14550, + umq: 14551, + umr: 14552, + ums: 14553, + umt: 14554, + umu: 14555, + umv: 14556, + umw: 14557, + umx: 14558, + umy: 14559, + unz: 14560, + una: 14561, + unb: 14562, + unc: 14563, + und: 14564, + une: 14565, + unf: 14566, + ung: 14567, + unh: 14568, + uni: 14569, + unj: 14570, + unk: 14571, + unl: 14572, + unm: 14573, + unn: 14574, + uno: 14575, + unp: 14576, + unq: 14577, + unr: 14578, + uns: 14579, + unt: 14580, + unu: 14581, + unv: 14582, + unw: 14583, + unx: 14584, + uny: 14585, + uoz: 14586, + uoa: 14587, + uob: 14588, + uoc: 14589, + uod: 14590, + uoe: 14591, + uof: 14592, + uog: 14593, + uoh: 14594, + uoi: 14595, + uoj: 14596, + uok: 14597, + uol: 14598, + uom: 14599, + uon: 14600, + uoo: 14601, + uop: 14602, + uoq: 14603, + uor: 14604, + uos: 14605, + uot: 14606, + uou: 14607, + uov: 14608, + uow: 14609, + uox: 14610, + uoy: 14611, + upz: 14612, + upa: 14613, + upb: 14614, + upc: 14615, + upd: 14616, + upe: 14617, + upf: 14618, + upg: 14619, + uph: 14620, + upi: 14621, + upj: 14622, + upk: 14623, + upl: 14624, + upm: 14625, + upn: 14626, + upo: 14627, + upp: 14628, + upq: 14629, + upr: 14630, + ups: 14631, + upt: 14632, + upu: 14633, + upv: 14634, + upw: 14635, + upx: 14636, + upy: 14637, + uqz: 14638, + uqa: 14639, + uqb: 14640, + uqc: 14641, + uqd: 14642, + uqe: 14643, + uqf: 14644, + uqg: 14645, + uqh: 14646, + uqi: 14647, + uqj: 14648, + uqk: 14649, + uql: 14650, + uqm: 14651, + uqn: 14652, + uqo: 14653, + uqp: 14654, + uqq: 14655, + uqr: 14656, + uqs: 14657, + uqt: 14658, + uqu: 14659, + uqv: 14660, + uqw: 14661, + uqx: 14662, + uqy: 14663, + urz: 14664, + ura: 14665, + urb: 14666, + urc: 14667, + urd: 14668, + ure: 14669, + urf: 14670, + urg: 14671, + urh: 14672, + uri: 14673, + urj: 14674, + urk: 14675, + url: 14676, + urm: 14677, + urn: 14678, + uro: 14679, + urp: 14680, + urq: 14681, + urr: 14682, + urs: 14683, + urt: 14684, + uru: 14685, + urv: 14686, + urw: 14687, + urx: 14688, + ury: 14689, + usz: 14690, + usa: 14691, + usb: 14692, + usc: 14693, + usd: 14694, + use: 14695, + usf: 14696, + usg: 14697, + ush: 14698, + usi: 14699, + usj: 14700, + usk: 14701, + usl: 14702, + usm: 14703, + usn: 14704, + uso: 14705, + usp: 14706, + usq: 14707, + usr: 14708, + uss: 14709, + ust: 14710, + usu: 14711, + usv: 14712, + usw: 14713, + usx: 14714, + usy: 14715, + utz: 14716, + uta: 14717, + utb: 14718, + utc: 14719, + utd: 14720, + ute: 14721, + utf: 14722, + utg: 14723, + uth: 14724, + uti: 14725, + utj: 14726, + utk: 14727, + utl: 14728, + utm: 14729, + utn: 14730, + uto: 14731, + utp: 14732, + utq: 14733, + utr: 14734, + uts: 14735, + utt: 14736, + utu: 14737, + utv: 14738, + utw: 14739, + utx: 14740, + uty: 14741, + uuz: 14742, + uua: 14743, + uub: 14744, + uuc: 14745, + uud: 14746, + uue: 14747, + uuf: 14748, + uug: 14749, + uuh: 14750, + uui: 14751, + uuj: 14752, + uuk: 14753, + uul: 14754, + uum: 14755, + uun: 14756, + uuo: 14757, + uup: 14758, + uuq: 14759, + uur: 14760, + uus: 14761, + uut: 14762, + uuu: 14763, + uuv: 14764, + uuw: 14765, + uux: 14766, + uuy: 14767, + uvz: 14768, + uva: 14769, + uvb: 14770, + uvc: 14771, + uvd: 14772, + uve: 14773, + uvf: 14774, + uvg: 14775, + uvh: 14776, + uvi: 14777, + uvj: 14778, + uvk: 14779, + uvl: 14780, + uvm: 14781, + uvn: 14782, + uvo: 14783, + uvp: 14784, + uvq: 14785, + uvr: 14786, + uvs: 14787, + uvt: 14788, + uvu: 14789, + uvv: 14790, + uvw: 14791, + uvx: 14792, + uvy: 14793, + uwz: 14794, + uwa: 14795, + uwb: 14796, + uwc: 14797, + uwd: 14798, + uwe: 14799, + uwf: 14800, + uwg: 14801, + uwh: 14802, + uwi: 14803, + uwj: 14804, + uwk: 14805, + uwl: 14806, + uwm: 14807, + uwn: 14808, + uwo: 14809, + uwp: 14810, + uwq: 14811, + uwr: 14812, + uws: 14813, + uwt: 14814, + uwu: 14815, + uwv: 14816, + uww: 14817, + uwx: 14818, + uwy: 14819, + uxz: 14820, + uxa: 14821, + uxb: 14822, + uxc: 14823, + uxd: 14824, + uxe: 14825, + uxf: 14826, + uxg: 14827, + uxh: 14828, + uxi: 14829, + uxj: 14830, + uxk: 14831, + uxl: 14832, + uxm: 14833, + uxn: 14834, + uxo: 14835, + uxp: 14836, + uxq: 14837, + uxr: 14838, + uxs: 14839, + uxt: 14840, + uxu: 14841, + uxv: 14842, + uxw: 14843, + uxx: 14844, + uxy: 14845, + uyz: 14846, + uya: 14847, + uyb: 14848, + uyc: 14849, + uyd: 14850, + uye: 14851, + uyf: 14852, + uyg: 14853, + uyh: 14854, + uyi: 14855, + uyj: 14856, + uyk: 14857, + uyl: 14858, + uym: 14859, + uyn: 14860, + uyo: 14861, + uyp: 14862, + uyq: 14863, + uyr: 14864, + uys: 14865, + uyt: 14866, + uyu: 14867, + uyv: 14868, + uyw: 14869, + uyx: 14870, + uyy: 14871, + vzz: 14872, + vza: 14873, + vzb: 14874, + vzc: 14875, + vzd: 14876, + vze: 14877, + vzf: 14878, + vzg: 14879, + vzh: 14880, + vzi: 14881, + vzj: 14882, + vzk: 14883, + vzl: 14884, + vzm: 14885, + vzn: 14886, + vzo: 14887, + vzp: 14888, + vzq: 14889, + vzr: 14890, + vzs: 14891, + vzt: 14892, + vzu: 14893, + vzv: 14894, + vzw: 14895, + vzx: 14896, + vzy: 14897, + vaz: 14898, + vaa: 14899, + vab: 14900, + vac: 14901, + vad: 14902, + vae: 14903, + vaf: 14904, + vag: 14905, + vah: 14906, + vai: 14907, + vaj: 14908, + vak: 14909, + val: 14910, + vam: 14911, + van: 14912, + vao: 14913, + vap: 14914, + vaq: 14915, + var: 14916, + vas: 14917, + vat: 14918, + vau: 14919, + vav: 14920, + vaw: 14921, + vax: 14922, + vay: 14923, + vbz: 14924, + vba: 14925, + vbb: 14926, + vbc: 14927, + vbd: 14928, + vbe: 14929, + vbf: 14930, + vbg: 14931, + vbh: 14932, + vbi: 14933, + vbj: 14934, + vbk: 14935, + vbl: 14936, + vbm: 14937, + vbn: 14938, + vbo: 14939, + vbp: 14940, + vbq: 14941, + vbr: 14942, + vbs: 14943, + vbt: 14944, + vbu: 14945, + vbv: 14946, + vbw: 14947, + vbx: 14948, + vby: 14949, + vcz: 14950, + vca: 14951, + vcb: 14952, + vcc: 14953, + vcd: 14954, + vce: 14955, + vcf: 14956, + vcg: 14957, + vch: 14958, + vci: 14959, + vcj: 14960, + vck: 14961, + vcl: 14962, + vcm: 14963, + vcn: 14964, + vco: 14965, + vcp: 14966, + vcq: 14967, + vcr: 14968, + vcs: 14969, + vct: 14970, + vcu: 14971, + vcv: 14972, + vcw: 14973, + vcx: 14974, + vcy: 14975, + vdz: 14976, + vda: 14977, + vdb: 14978, + vdc: 14979, + vdd: 14980, + vde: 14981, + vdf: 14982, + vdg: 14983, + vdh: 14984, + vdi: 14985, + vdj: 14986, + vdk: 14987, + vdl: 14988, + vdm: 14989, + vdn: 14990, + vdo: 14991, + vdp: 14992, + vdq: 14993, + vdr: 14994, + vds: 14995, + vdt: 14996, + vdu: 14997, + vdv: 14998, + vdw: 14999, + vdx: 15000, + vdy: 15001, + vez: 15002, + vea: 15003, + veb: 15004, + vec: 15005, + ved: 15006, + vee: 15007, + vef: 15008, + veg: 15009, + veh: 15010, + vei: 15011, + vej: 15012, + vek: 15013, + vel: 15014, + vem: 15015, + ven: 15016, + veo: 15017, + vep: 15018, + veq: 15019, + ver: 15020, + ves: 15021, + vet: 15022, + veu: 15023, + vev: 15024, + vew: 15025, + vex: 15026, + vey: 15027, + vfz: 15028, + vfa: 15029, + vfb: 15030, + vfc: 15031, + vfd: 15032, + vfe: 15033, + vff: 15034, + vfg: 15035, + vfh: 15036, + vfi: 15037, + vfj: 15038, + vfk: 15039, + vfl: 15040, + vfm: 15041, + vfn: 15042, + vfo: 15043, + vfp: 15044, + vfq: 15045, + vfr: 15046, + vfs: 15047, + vft: 15048, + vfu: 15049, + vfv: 15050, + vfw: 15051, + vfx: 15052, + vfy: 15053, + vgz: 15054, + vga: 15055, + vgb: 15056, + vgc: 15057, + vgd: 15058, + vge: 15059, + vgf: 15060, + vgg: 15061, + vgh: 15062, + vgi: 15063, + vgj: 15064, + vgk: 15065, + vgl: 15066, + vgm: 15067, + vgn: 15068, + vgo: 15069, + vgp: 15070, + vgq: 15071, + vgr: 15072, + vgs: 15073, + vgt: 15074, + vgu: 15075, + vgv: 15076, + vgw: 15077, + vgx: 15078, + vgy: 15079, + vhz: 15080, + vha: 15081, + vhb: 15082, + vhc: 15083, + vhd: 15084, + vhe: 15085, + vhf: 15086, + vhg: 15087, + vhh: 15088, + vhi: 15089, + vhj: 15090, + vhk: 15091, + vhl: 15092, + vhm: 15093, + vhn: 15094, + vho: 15095, + vhp: 15096, + vhq: 15097, + vhr: 15098, + vhs: 15099, + vht: 15100, + vhu: 15101, + vhv: 15102, + vhw: 15103, + vhx: 15104, + vhy: 15105, + viz: 15106, + via: 15107, + vib: 15108, + vic: 15109, + vid: 15110, + vie: 15111, + vif: 15112, + vig: 15113, + vih: 15114, + vii: 15115, + vij: 15116, + vik: 15117, + vil: 15118, + vim: 15119, + vin: 15120, + vio: 15121, + vip: 15122, + viq: 15123, + vir: 15124, + vis: 15125, + vit: 15126, + viu: 15127, + viv: 15128, + viw: 15129, + vix: 15130, + viy: 15131, + vjz: 15132, + vja: 15133, + vjb: 15134, + vjc: 15135, + vjd: 15136, + vje: 15137, + vjf: 15138, + vjg: 15139, + vjh: 15140, + vji: 15141, + vjj: 15142, + vjk: 15143, + vjl: 15144, + vjm: 15145, + vjn: 15146, + vjo: 15147, + vjp: 15148, + vjq: 15149, + vjr: 15150, + vjs: 15151, + vjt: 15152, + vju: 15153, + vjv: 15154, + vjw: 15155, + vjx: 15156, + vjy: 15157, + vkz: 15158, + vka: 15159, + vkb: 15160, + vkc: 15161, + vkd: 15162, + vke: 15163, + vkf: 15164, + vkg: 15165, + vkh: 15166, + vki: 15167, + vkj: 15168, + vkk: 15169, + vkl: 15170, + vkm: 15171, + vkn: 15172, + vko: 15173, + vkp: 15174, + vkq: 15175, + vkr: 15176, + vks: 15177, + vkt: 15178, + vku: 15179, + vkv: 15180, + vkw: 15181, + vkx: 15182, + vky: 15183, + vlz: 15184, + vla: 15185, + vlb: 15186, + vlc: 15187, + vld: 15188, + vle: 15189, + vlf: 15190, + vlg: 15191, + vlh: 15192, + vli: 15193, + vlj: 15194, + vlk: 15195, + vll: 15196, + vlm: 15197, + vln: 15198, + vlo: 15199, + vlp: 15200, + vlq: 15201, + vlr: 15202, + vls: 15203, + vlt: 15204, + vlu: 15205, + vlv: 15206, + vlw: 15207, + vlx: 15208, + vly: 15209, + vmz: 15210, + vma: 15211, + vmb: 15212, + vmc: 15213, + vmd: 15214, + vme: 15215, + vmf: 15216, + vmg: 15217, + vmh: 15218, + vmi: 15219, + vmj: 15220, + vmk: 15221, + vml: 15222, + vmm: 15223, + vmn: 15224, + vmo: 15225, + vmp: 15226, + vmq: 15227, + vmr: 15228, + vms: 15229, + vmt: 15230, + vmu: 15231, + vmv: 15232, + vmw: 15233, + vmx: 15234, + vmy: 15235, + vnz: 15236, + vna: 15237, + vnb: 15238, + vnc: 15239, + vnd: 15240, + vne: 15241, + vnf: 15242, + vng: 15243, + vnh: 15244, + vni: 15245, + vnj: 15246, + vnk: 15247, + vnl: 15248, + vnm: 15249, + vnn: 15250, + vno: 15251, + vnp: 15252, + vnq: 15253, + vnr: 15254, + vns: 15255, + vnt: 15256, + vnu: 15257, + vnv: 15258, + vnw: 15259, + vnx: 15260, + vny: 15261, + voz: 15262, + voa: 15263, + vob: 15264, + voc: 15265, + vod: 15266, + voe: 15267, + vof: 15268, + vog: 15269, + voh: 15270, + voi: 15271, + voj: 15272, + vok: 15273, + vol: 15274, + vom: 15275, + von: 15276, + voo: 15277, + vop: 15278, + voq: 15279, + vor: 15280, + vos: 15281, + vot: 15282, + vou: 15283, + vov: 15284, + vow: 15285, + vox: 15286, + voy: 15287, + vpz: 15288, + vpa: 15289, + vpb: 15290, + vpc: 15291, + vpd: 15292, + vpe: 15293, + vpf: 15294, + vpg: 15295, + vph: 15296, + vpi: 15297, + vpj: 15298, + vpk: 15299, + vpl: 15300, + vpm: 15301, + vpn: 15302, + vpo: 15303, + vpp: 15304, + vpq: 15305, + vpr: 15306, + vps: 15307, + vpt: 15308, + vpu: 15309, + vpv: 15310, + vpw: 15311, + vpx: 15312, + vpy: 15313, + vqz: 15314, + vqa: 15315, + vqb: 15316, + vqc: 15317, + vqd: 15318, + vqe: 15319, + vqf: 15320, + vqg: 15321, + vqh: 15322, + vqi: 15323, + vqj: 15324, + vqk: 15325, + vql: 15326, + vqm: 15327, + vqn: 15328, + vqo: 15329, + vqp: 15330, + vqq: 15331, + vqr: 15332, + vqs: 15333, + vqt: 15334, + vqu: 15335, + vqv: 15336, + vqw: 15337, + vqx: 15338, + vqy: 15339, + vrz: 15340, + vra: 15341, + vrb: 15342, + vrc: 15343, + vrd: 15344, + vre: 15345, + vrf: 15346, + vrg: 15347, + vrh: 15348, + vri: 15349, + vrj: 15350, + vrk: 15351, + vrl: 15352, + vrm: 15353, + vrn: 15354, + vro: 15355, + vrp: 15356, + vrq: 15357, + vrr: 15358, + vrs: 15359, + vrt: 15360, + vru: 15361, + vrv: 15362, + vrw: 15363, + vrx: 15364, + vry: 15365, + vsz: 15366, + vsa: 15367, + vsb: 15368, + vsc: 15369, + vsd: 15370, + vse: 15371, + vsf: 15372, + vsg: 15373, + vsh: 15374, + vsi: 15375, + vsj: 15376, + vsk: 15377, + vsl: 15378, + vsm: 15379, + vsn: 15380, + vso: 15381, + vsp: 15382, + vsq: 15383, + vsr: 15384, + vss: 15385, + vst: 15386, + vsu: 15387, + vsv: 15388, + vsw: 15389, + vsx: 15390, + vsy: 15391, + vtz: 15392, + vta: 15393, + vtb: 15394, + vtc: 15395, + vtd: 15396, + vte: 15397, + vtf: 15398, + vtg: 15399, + vth: 15400, + vti: 15401, + vtj: 15402, + vtk: 15403, + vtl: 15404, + vtm: 15405, + vtn: 15406, + vto: 15407, + vtp: 15408, + vtq: 15409, + vtr: 15410, + vts: 15411, + vtt: 15412, + vtu: 15413, + vtv: 15414, + vtw: 15415, + vtx: 15416, + vty: 15417, + vuz: 15418, + vua: 15419, + vub: 15420, + vuc: 15421, + vud: 15422, + vue: 15423, + vuf: 15424, + vug: 15425, + vuh: 15426, + vui: 15427, + vuj: 15428, + vuk: 15429, + vul: 15430, + vum: 15431, + vun: 15432, + vuo: 15433, + vup: 15434, + vuq: 15435, + vur: 15436, + vus: 15437, + vut: 15438, + vuu: 15439, + vuv: 15440, + vuw: 15441, + vux: 15442, + vuy: 15443, + vvz: 15444, + vva: 15445, + vvb: 15446, + vvc: 15447, + vvd: 15448, + vve: 15449, + vvf: 15450, + vvg: 15451, + vvh: 15452, + vvi: 15453, + vvj: 15454, + vvk: 15455, + vvl: 15456, + vvm: 15457, + vvn: 15458, + vvo: 15459, + vvp: 15460, + vvq: 15461, + vvr: 15462, + vvs: 15463, + vvt: 15464, + vvu: 15465, + vvv: 15466, + vvw: 15467, + vvx: 15468, + vvy: 15469, + vwz: 15470, + vwa: 15471, + vwb: 15472, + vwc: 15473, + vwd: 15474, + vwe: 15475, + vwf: 15476, + vwg: 15477, + vwh: 15478, + vwi: 15479, + vwj: 15480, + vwk: 15481, + vwl: 15482, + vwm: 15483, + vwn: 15484, + vwo: 15485, + vwp: 15486, + vwq: 15487, + vwr: 15488, + vws: 15489, + vwt: 15490, + vwu: 15491, + vwv: 15492, + vww: 15493, + vwx: 15494, + vwy: 15495, + vxz: 15496, + vxa: 15497, + vxb: 15498, + vxc: 15499, + vxd: 15500, + vxe: 15501, + vxf: 15502, + vxg: 15503, + vxh: 15504, + vxi: 15505, + vxj: 15506, + vxk: 15507, + vxl: 15508, + vxm: 15509, + vxn: 15510, + vxo: 15511, + vxp: 15512, + vxq: 15513, + vxr: 15514, + vxs: 15515, + vxt: 15516, + vxu: 15517, + vxv: 15518, + vxw: 15519, + vxx: 15520, + vxy: 15521, + vyz: 15522, + vya: 15523, + vyb: 15524, + vyc: 15525, + vyd: 15526, + vye: 15527, + vyf: 15528, + vyg: 15529, + vyh: 15530, + vyi: 15531, + vyj: 15532, + vyk: 15533, + vyl: 15534, + vym: 15535, + vyn: 15536, + vyo: 15537, + vyp: 15538, + vyq: 15539, + vyr: 15540, + vys: 15541, + vyt: 15542, + vyu: 15543, + vyv: 15544, + vyw: 15545, + vyx: 15546, + vyy: 15547, + wzz: 15548, + wza: 15549, + wzb: 15550, + wzc: 15551, + wzd: 15552, + wze: 15553, + wzf: 15554, + wzg: 15555, + wzh: 15556, + wzi: 15557, + wzj: 15558, + wzk: 15559, + wzl: 15560, + wzm: 15561, + wzn: 15562, + wzo: 15563, + wzp: 15564, + wzq: 15565, + wzr: 15566, + wzs: 15567, + wzt: 15568, + wzu: 15569, + wzv: 15570, + wzw: 15571, + wzx: 15572, + wzy: 15573, + waz: 15574, + waa: 15575, + wab: 15576, + wac: 15577, + wad: 15578, + wae: 15579, + waf: 15580, + wag: 15581, + wah: 15582, + wai: 15583, + waj: 15584, + wak: 15585, + wal: 15586, + wam: 15587, + wan: 15588, + wao: 15589, + wap: 15590, + waq: 15591, + war: 15592, + was: 15593, + wat: 15594, + wau: 15595, + wav: 15596, + waw: 15597, + wax: 15598, + way: 15599, + wbz: 15600, + wba: 15601, + wbb: 15602, + wbc: 15603, + wbd: 15604, + wbe: 15605, + wbf: 15606, + wbg: 15607, + wbh: 15608, + wbi: 15609, + wbj: 15610, + wbk: 15611, + wbl: 15612, + wbm: 15613, + wbn: 15614, + wbo: 15615, + wbp: 15616, + wbq: 15617, + wbr: 15618, + wbs: 15619, + wbt: 15620, + wbu: 15621, + wbv: 15622, + wbw: 15623, + wbx: 15624, + wby: 15625, + wcz: 15626, + wca: 15627, + wcb: 15628, + wcc: 15629, + wcd: 15630, + wce: 15631, + wcf: 15632, + wcg: 15633, + wch: 15634, + wci: 15635, + wcj: 15636, + wck: 15637, + wcl: 15638, + wcm: 15639, + wcn: 15640, + wco: 15641, + wcp: 15642, + wcq: 15643, + wcr: 15644, + wcs: 15645, + wct: 15646, + wcu: 15647, + wcv: 15648, + wcw: 15649, + wcx: 15650, + wcy: 15651, + wdz: 15652, + wda: 15653, + wdb: 15654, + wdc: 15655, + wdd: 15656, + wde: 15657, + wdf: 15658, + wdg: 15659, + wdh: 15660, + wdi: 15661, + wdj: 15662, + wdk: 15663, + wdl: 15664, + wdm: 15665, + wdn: 15666, + wdo: 15667, + wdp: 15668, + wdq: 15669, + wdr: 15670, + wds: 15671, + wdt: 15672, + wdu: 15673, + wdv: 15674, + wdw: 15675, + wdx: 15676, + wdy: 15677, + wez: 15678, + wea: 15679, + web: 15680, + wec: 15681, + wed: 15682, + wee: 15683, + wef: 15684, + weg: 15685, + weh: 15686, + wei: 15687, + wej: 15688, + wek: 15689, + wel: 15690, + wem: 15691, + wen: 15692, + weo: 15693, + wep: 15694, + weq: 15695, + wer: 15696, + wes: 15697, + wet: 15698, + weu: 15699, + wev: 15700, + wew: 15701, + wex: 15702, + wey: 15703, + wfz: 15704, + wfa: 15705, + wfb: 15706, + wfc: 15707, + wfd: 15708, + wfe: 15709, + wff: 15710, + wfg: 15711, + wfh: 15712, + wfi: 15713, + wfj: 15714, + wfk: 15715, + wfl: 15716, + wfm: 15717, + wfn: 15718, + wfo: 15719, + wfp: 15720, + wfq: 15721, + wfr: 15722, + wfs: 15723, + wft: 15724, + wfu: 15725, + wfv: 15726, + wfw: 15727, + wfx: 15728, + wfy: 15729, + wgz: 15730, + wga: 15731, + wgb: 15732, + wgc: 15733, + wgd: 15734, + wge: 15735, + wgf: 15736, + wgg: 15737, + wgh: 15738, + wgi: 15739, + wgj: 15740, + wgk: 15741, + wgl: 15742, + wgm: 15743, + wgn: 15744, + wgo: 15745, + wgp: 15746, + wgq: 15747, + wgr: 15748, + wgs: 15749, + wgt: 15750, + wgu: 15751, + wgv: 15752, + wgw: 15753, + wgx: 15754, + wgy: 15755, + whz: 15756, + wha: 15757, + whb: 15758, + whc: 15759, + whd: 15760, + whe: 15761, + whf: 15762, + whg: 15763, + whh: 15764, + whi: 15765, + whj: 15766, + whk: 15767, + whl: 15768, + whm: 15769, + whn: 15770, + who: 15771, + whp: 15772, + whq: 15773, + whr: 15774, + whs: 15775, + wht: 15776, + whu: 15777, + whv: 15778, + whw: 15779, + whx: 15780, + why: 15781, + wiz: 15782, + wia: 15783, + wib: 15784, + wic: 15785, + wid: 15786, + wie: 15787, + wif: 15788, + wig: 15789, + wih: 15790, + wii: 15791, + wij: 15792, + wik: 15793, + wil: 15794, + wim: 15795, + win: 15796, + wio: 15797, + wip: 15798, + wiq: 15799, + wir: 15800, + wis: 15801, + wit: 15802, + wiu: 15803, + wiv: 15804, + wiw: 15805, + wix: 15806, + wiy: 15807, + wjz: 15808, + wja: 15809, + wjb: 15810, + wjc: 15811, + wjd: 15812, + wje: 15813, + wjf: 15814, + wjg: 15815, + wjh: 15816, + wji: 15817, + wjj: 15818, + wjk: 15819, + wjl: 15820, + wjm: 15821, + wjn: 15822, + wjo: 15823, + wjp: 15824, + wjq: 15825, + wjr: 15826, + wjs: 15827, + wjt: 15828, + wju: 15829, + wjv: 15830, + wjw: 15831, + wjx: 15832, + wjy: 15833, + wkz: 15834, + wka: 15835, + wkb: 15836, + wkc: 15837, + wkd: 15838, + wke: 15839, + wkf: 15840, + wkg: 15841, + wkh: 15842, + wki: 15843, + wkj: 15844, + wkk: 15845, + wkl: 15846, + wkm: 15847, + wkn: 15848, + wko: 15849, + wkp: 15850, + wkq: 15851, + wkr: 15852, + wks: 15853, + wkt: 15854, + wku: 15855, + wkv: 15856, + wkw: 15857, + wkx: 15858, + wky: 15859, + wlz: 15860, + wla: 15861, + wlb: 15862, + wlc: 15863, + wld: 15864, + wle: 15865, + wlf: 15866, + wlg: 15867, + wlh: 15868, + wli: 15869, + wlj: 15870, + wlk: 15871, + wll: 15872, + wlm: 15873, + wln: 15874, + wlo: 15875, + wlp: 15876, + wlq: 15877, + wlr: 15878, + wls: 15879, + wlt: 15880, + wlu: 15881, + wlv: 15882, + wlw: 15883, + wlx: 15884, + wly: 15885, + wmz: 15886, + wma: 15887, + wmb: 15888, + wmc: 15889, + wmd: 15890, + wme: 15891, + wmf: 15892, + wmg: 15893, + wmh: 15894, + wmi: 15895, + wmj: 15896, + wmk: 15897, + wml: 15898, + wmm: 15899, + wmn: 15900, + wmo: 15901, + wmp: 15902, + wmq: 15903, + wmr: 15904, + wms: 15905, + wmt: 15906, + wmu: 15907, + wmv: 15908, + wmw: 15909, + wmx: 15910, + wmy: 15911, + wnz: 15912, + wna: 15913, + wnb: 15914, + wnc: 15915, + wnd: 15916, + wne: 15917, + wnf: 15918, + wng: 15919, + wnh: 15920, + wni: 15921, + wnj: 15922, + wnk: 15923, + wnl: 15924, + wnm: 15925, + wnn: 15926, + wno: 15927, + wnp: 15928, + wnq: 15929, + wnr: 15930, + wns: 15931, + wnt: 15932, + wnu: 15933, + wnv: 15934, + wnw: 15935, + wnx: 15936, + wny: 15937, + woz: 15938, + woa: 15939, + wob: 15940, + woc: 15941, + wod: 15942, + woe: 15943, + wof: 15944, + wog: 15945, + woh: 15946, + woi: 15947, + woj: 15948, + wok: 15949, + wol: 15950, + wom: 15951, + won: 15952, + woo: 15953, + wop: 15954, + woq: 15955, + wor: 15956, + wos: 15957, + wot: 15958, + wou: 15959, + wov: 15960, + wow: 15961, + wox: 15962, + woy: 15963, + wpz: 15964, + wpa: 15965, + wpb: 15966, + wpc: 15967, + wpd: 15968, + wpe: 15969, + wpf: 15970, + wpg: 15971, + wph: 15972, + wpi: 15973, + wpj: 15974, + wpk: 15975, + wpl: 15976, + wpm: 15977, + wpn: 15978, + wpo: 15979, + wpp: 15980, + wpq: 15981, + wpr: 15982, + wps: 15983, + wpt: 15984, + wpu: 15985, + wpv: 15986, + wpw: 15987, + wpx: 15988, + wpy: 15989, + wqz: 15990, + wqa: 15991, + wqb: 15992, + wqc: 15993, + wqd: 15994, + wqe: 15995, + wqf: 15996, + wqg: 15997, + wqh: 15998, + wqi: 15999, + wqj: 16000, + wqk: 16001, + wql: 16002, + wqm: 16003, + wqn: 16004, + wqo: 16005, + wqp: 16006, + wqq: 16007, + wqr: 16008, + wqs: 16009, + wqt: 16010, + wqu: 16011, + wqv: 16012, + wqw: 16013, + wqx: 16014, + wqy: 16015, + wrz: 16016, + wra: 16017, + wrb: 16018, + wrc: 16019, + wrd: 16020, + wre: 16021, + wrf: 16022, + wrg: 16023, + wrh: 16024, + wri: 16025, + wrj: 16026, + wrk: 16027, + wrl: 16028, + wrm: 16029, + wrn: 16030, + wro: 16031, + wrp: 16032, + wrq: 16033, + wrr: 16034, + wrs: 16035, + wrt: 16036, + wru: 16037, + wrv: 16038, + wrw: 16039, + wrx: 16040, + wry: 16041, + wsz: 16042, + wsa: 16043, + wsb: 16044, + wsc: 16045, + wsd: 16046, + wse: 16047, + wsf: 16048, + wsg: 16049, + wsh: 16050, + wsi: 16051, + wsj: 16052, + wsk: 16053, + wsl: 16054, + wsm: 16055, + wsn: 16056, + wso: 16057, + wsp: 16058, + wsq: 16059, + wsr: 16060, + wss: 16061, + wst: 16062, + wsu: 16063, + wsv: 16064, + wsw: 16065, + wsx: 16066, + wsy: 16067, + wtz: 16068, + wta: 16069, + wtb: 16070, + wtc: 16071, + wtd: 16072, + wte: 16073, + wtf: 16074, + wtg: 16075, + wth: 16076, + wti: 16077, + wtj: 16078, + wtk: 16079, + wtl: 16080, + wtm: 16081, + wtn: 16082, + wto: 16083, + wtp: 16084, + wtq: 16085, + wtr: 16086, + wts: 16087, + wtt: 16088, + wtu: 16089, + wtv: 16090, + wtw: 16091, + wtx: 16092, + wty: 16093, + wuz: 16094, + wua: 16095, + wub: 16096, + wuc: 16097, + wud: 16098, + wue: 16099, + wuf: 16100, + wug: 16101, + wuh: 16102, + wui: 16103, + wuj: 16104, + wuk: 16105, + wul: 16106, + wum: 16107, + wun: 16108, + wuo: 16109, + wup: 16110, + wuq: 16111, + wur: 16112, + wus: 16113, + wut: 16114, + wuu: 16115, + wuv: 16116, + wuw: 16117, + wux: 16118, + wuy: 16119, + wvz: 16120, + wva: 16121, + wvb: 16122, + wvc: 16123, + wvd: 16124, + wve: 16125, + wvf: 16126, + wvg: 16127, + wvh: 16128, + wvi: 16129, + wvj: 16130, + wvk: 16131, + wvl: 16132, + wvm: 16133, + wvn: 16134, + wvo: 16135, + wvp: 16136, + wvq: 16137, + wvr: 16138, + wvs: 16139, + wvt: 16140, + wvu: 16141, + wvv: 16142, + wvw: 16143, + wvx: 16144, + wvy: 16145, + wwz: 16146, + wwa: 16147, + wwb: 16148, + wwc: 16149, + wwd: 16150, + wwe: 16151, + wwf: 16152, + wwg: 16153, + wwh: 16154, + wwi: 16155, + wwj: 16156, + wwk: 16157, + wwl: 16158, + wwm: 16159, + wwn: 16160, + wwo: 16161, + wwp: 16162, + wwq: 16163, + wwr: 16164, + wws: 16165, + wwt: 16166, + wwu: 16167, + wwv: 16168, + www: 16169, + wwx: 16170, + wwy: 16171, + wxz: 16172, + wxa: 16173, + wxb: 16174, + wxc: 16175, + wxd: 16176, + wxe: 16177, + wxf: 16178, + wxg: 16179, + wxh: 16180, + wxi: 16181, + wxj: 16182, + wxk: 16183, + wxl: 16184, + wxm: 16185, + wxn: 16186, + wxo: 16187, + wxp: 16188, + wxq: 16189, + wxr: 16190, + wxs: 16191, + wxt: 16192, + wxu: 16193, + wxv: 16194, + wxw: 16195, + wxx: 16196, + wxy: 16197, + wyz: 16198, + wya: 16199, + wyb: 16200, + wyc: 16201, + wyd: 16202, + wye: 16203, + wyf: 16204, + wyg: 16205, + wyh: 16206, + wyi: 16207, + wyj: 16208, + wyk: 16209, + wyl: 16210, + wym: 16211, + wyn: 16212, + wyo: 16213, + wyp: 16214, + wyq: 16215, + wyr: 16216, + wys: 16217, + wyt: 16218, + wyu: 16219, + wyv: 16220, + wyw: 16221, + wyx: 16222, + wyy: 16223, + xzz: 16224, + xza: 16225, + xzb: 16226, + xzc: 16227, + xzd: 16228, + xze: 16229, + xzf: 16230, + xzg: 16231, + xzh: 16232, + xzi: 16233, + xzj: 16234, + xzk: 16235, + xzl: 16236, + xzm: 16237, + xzn: 16238, + xzo: 16239, + xzp: 16240, + xzq: 16241, + xzr: 16242, + xzs: 16243, + xzt: 16244, + xzu: 16245, + xzv: 16246, + xzw: 16247, + xzx: 16248, + xzy: 16249, + xaz: 16250, + xaa: 16251, + xab: 16252, + xac: 16253, + xad: 16254, + xae: 16255, + xaf: 16256, + xag: 16257, + xah: 16258, + xai: 16259, + xaj: 16260, + xak: 16261, + xal: 16262, + xam: 16263, + xan: 16264, + xao: 16265, + xap: 16266, + xaq: 16267, + xar: 16268, + xas: 16269, + xat: 16270, + xau: 16271, + xav: 16272, + xaw: 16273, + xax: 16274, + xay: 16275, + xbz: 16276, + xba: 16277, + xbb: 16278, + xbc: 16279, + xbd: 16280, + xbe: 16281, + xbf: 16282, + xbg: 16283, + xbh: 16284, + xbi: 16285, + xbj: 16286, + xbk: 16287, + xbl: 16288, + xbm: 16289, + xbn: 16290, + xbo: 16291, + xbp: 16292, + xbq: 16293, + xbr: 16294, + xbs: 16295, + xbt: 16296, + xbu: 16297, + xbv: 16298, + xbw: 16299, + xbx: 16300, + xby: 16301, + xcz: 16302, + xca: 16303, + xcb: 16304, + xcc: 16305, + xcd: 16306, + xce: 16307, + xcf: 16308, + xcg: 16309, + xch: 16310, + xci: 16311, + xcj: 16312, + xck: 16313, + xcl: 16314, + xcm: 16315, + xcn: 16316, + xco: 16317, + xcp: 16318, + xcq: 16319, + xcr: 16320, + xcs: 16321, + xct: 16322, + xcu: 16323, + xcv: 16324, + xcw: 16325, + xcx: 16326, + xcy: 16327, + xdz: 16328, + xda: 16329, + xdb: 16330, + xdc: 16331, + xdd: 16332, + xde: 16333, + xdf: 16334, + xdg: 16335, + xdh: 16336, + xdi: 16337, + xdj: 16338, + xdk: 16339, + xdl: 16340, + xdm: 16341, + xdn: 16342, + xdo: 16343, + xdp: 16344, + xdq: 16345, + xdr: 16346, + xds: 16347, + xdt: 16348, + xdu: 16349, + xdv: 16350, + xdw: 16351, + xdx: 16352, + xdy: 16353, + xez: 16354, + xea: 16355, + xeb: 16356, + xec: 16357, + xed: 16358, + xee: 16359, + xef: 16360, + xeg: 16361, + xeh: 16362, + xei: 16363, + xej: 16364, + xek: 16365, + xel: 16366, + xem: 16367, + xen: 16368, + xeo: 16369, + xep: 16370, + xeq: 16371, + xer: 16372, + xes: 16373, + xet: 16374, + xeu: 16375, + xev: 16376, + xew: 16377, + xex: 16378, + xey: 16379, + xfz: 16380, + xfa: 16381, + xfb: 16382, + xfc: 16383, + xfd: 16384, + xfe: 16385, + xff: 16386, + xfg: 16387, + xfh: 16388, + xfi: 16389, + xfj: 16390, + xfk: 16391, + xfl: 16392, + xfm: 16393, + xfn: 16394, + xfo: 16395, + xfp: 16396, + xfq: 16397, + xfr: 16398, + xfs: 16399, + xft: 16400, + xfu: 16401, + xfv: 16402, + xfw: 16403, + xfx: 16404, + xfy: 16405, + xgz: 16406, + xga: 16407, + xgb: 16408, + xgc: 16409, + xgd: 16410, + xge: 16411, + xgf: 16412, + xgg: 16413, + xgh: 16414, + xgi: 16415, + xgj: 16416, + xgk: 16417, + xgl: 16418, + xgm: 16419, + xgn: 16420, + xgo: 16421, + xgp: 16422, + xgq: 16423, + xgr: 16424, + xgs: 16425, + xgt: 16426, + xgu: 16427, + xgv: 16428, + xgw: 16429, + xgx: 16430, + xgy: 16431, + xhz: 16432, + xha: 16433, + xhb: 16434, + xhc: 16435, + xhd: 16436, + xhe: 16437, + xhf: 16438, + xhg: 16439, + xhh: 16440, + xhi: 16441, + xhj: 16442, + xhk: 16443, + xhl: 16444, + xhm: 16445, + xhn: 16446, + xho: 16447, + xhp: 16448, + xhq: 16449, + xhr: 16450, + xhs: 16451, + xht: 16452, + xhu: 16453, + xhv: 16454, + xhw: 16455, + xhx: 16456, + xhy: 16457, + xiz: 16458, + xia: 16459, + xib: 16460, + xic: 16461, + xid: 16462, + xie: 16463, + xif: 16464, + xig: 16465, + xih: 16466, + xii: 16467, + xij: 16468, + xik: 16469, + xil: 16470, + xim: 16471, + xin: 16472, + xio: 16473, + xip: 16474, + xiq: 16475, + xir: 16476, + xis: 16477, + xit: 16478, + xiu: 16479, + xiv: 16480, + xiw: 16481, + xix: 16482, + xiy: 16483, + xjz: 16484, + xja: 16485, + xjb: 16486, + xjc: 16487, + xjd: 16488, + xje: 16489, + xjf: 16490, + xjg: 16491, + xjh: 16492, + xji: 16493, + xjj: 16494, + xjk: 16495, + xjl: 16496, + xjm: 16497, + xjn: 16498, + xjo: 16499, + xjp: 16500, + xjq: 16501, + xjr: 16502, + xjs: 16503, + xjt: 16504, + xju: 16505, + xjv: 16506, + xjw: 16507, + xjx: 16508, + xjy: 16509, + xkz: 16510, + xka: 16511, + xkb: 16512, + xkc: 16513, + xkd: 16514, + xke: 16515, + xkf: 16516, + xkg: 16517, + xkh: 16518, + xki: 16519, + xkj: 16520, + xkk: 16521, + xkl: 16522, + xkm: 16523, + xkn: 16524, + xko: 16525, + xkp: 16526, + xkq: 16527, + xkr: 16528, + xks: 16529, + xkt: 16530, + xku: 16531, + xkv: 16532, + xkw: 16533, + xkx: 16534, + xky: 16535, + xlz: 16536, + xla: 16537, + xlb: 16538, + xlc: 16539, + xld: 16540, + xle: 16541, + xlf: 16542, + xlg: 16543, + xlh: 16544, + xli: 16545, + xlj: 16546, + xlk: 16547, + xll: 16548, + xlm: 16549, + xln: 16550, + xlo: 16551, + xlp: 16552, + xlq: 16553, + xlr: 16554, + xls: 16555, + xlt: 16556, + xlu: 16557, + xlv: 16558, + xlw: 16559, + xlx: 16560, + xly: 16561, + xmz: 16562, + xma: 16563, + xmb: 16564, + xmc: 16565, + xmd: 16566, + xme: 16567, + xmf: 16568, + xmg: 16569, + xmh: 16570, + xmi: 16571, + xmj: 16572, + xmk: 16573, + xml: 16574, + xmm: 16575, + xmn: 16576, + xmo: 16577, + xmp: 16578, + xmq: 16579, + xmr: 16580, + xms: 16581, + xmt: 16582, + xmu: 16583, + xmv: 16584, + xmw: 16585, + xmx: 16586, + xmy: 16587, + xnz: 16588, + xna: 16589, + xnb: 16590, + xnc: 16591, + xnd: 16592, + xne: 16593, + xnf: 16594, + xng: 16595, + xnh: 16596, + xni: 16597, + xnj: 16598, + xnk: 16599, + xnl: 16600, + xnm: 16601, + xnn: 16602, + xno: 16603, + xnp: 16604, + xnq: 16605, + xnr: 16606, + xns: 16607, + xnt: 16608, + xnu: 16609, + xnv: 16610, + xnw: 16611, + xnx: 16612, + xny: 16613, + xoz: 16614, + xoa: 16615, + xob: 16616, + xoc: 16617, + xod: 16618, + xoe: 16619, + xof: 16620, + xog: 16621, + xoh: 16622, + xoi: 16623, + xoj: 16624, + xok: 16625, + xol: 16626, + xom: 16627, + xon: 16628, + xoo: 16629, + xop: 16630, + xoq: 16631, + xor: 16632, + xos: 16633, + xot: 16634, + xou: 16635, + xov: 16636, + xow: 16637, + xox: 16638, + xoy: 16639, + xpz: 16640, + xpa: 16641, + xpb: 16642, + xpc: 16643, + xpd: 16644, + xpe: 16645, + xpf: 16646, + xpg: 16647, + xph: 16648, + xpi: 16649, + xpj: 16650, + xpk: 16651, + xpl: 16652, + xpm: 16653, + xpn: 16654, + xpo: 16655, + xpp: 16656, + xpq: 16657, + xpr: 16658, + xps: 16659, + xpt: 16660, + xpu: 16661, + xpv: 16662, + xpw: 16663, + xpx: 16664, + xpy: 16665, + xqz: 16666, + xqa: 16667, + xqb: 16668, + xqc: 16669, + xqd: 16670, + xqe: 16671, + xqf: 16672, + xqg: 16673, + xqh: 16674, + xqi: 16675, + xqj: 16676, + xqk: 16677, + xql: 16678, + xqm: 16679, + xqn: 16680, + xqo: 16681, + xqp: 16682, + xqq: 16683, + xqr: 16684, + xqs: 16685, + xqt: 16686, + xqu: 16687, + xqv: 16688, + xqw: 16689, + xqx: 16690, + xqy: 16691, + xrz: 16692, + xra: 16693, + xrb: 16694, + xrc: 16695, + xrd: 16696, + xre: 16697, + xrf: 16698, + xrg: 16699, + xrh: 16700, + xri: 16701, + xrj: 16702, + xrk: 16703, + xrl: 16704, + xrm: 16705, + xrn: 16706, + xro: 16707, + xrp: 16708, + xrq: 16709, + xrr: 16710, + xrs: 16711, + xrt: 16712, + xru: 16713, + xrv: 16714, + xrw: 16715, + xrx: 16716, + xry: 16717, + xsz: 16718, + xsa: 16719, + xsb: 16720, + xsc: 16721, + xsd: 16722, + xse: 16723, + xsf: 16724, + xsg: 16725, + xsh: 16726, + xsi: 16727, + xsj: 16728, + xsk: 16729, + xsl: 16730, + xsm: 16731, + xsn: 16732, + xso: 16733, + xsp: 16734, + xsq: 16735, + xsr: 16736, + xss: 16737, + xst: 16738, + xsu: 16739, + xsv: 16740, + xsw: 16741, + xsx: 16742, + xsy: 16743, + xtz: 16744, + xta: 16745, + xtb: 16746, + xtc: 16747, + xtd: 16748, + xte: 16749, + xtf: 16750, + xtg: 16751, + xth: 16752, + xti: 16753, + xtj: 16754, + xtk: 16755, + xtl: 16756, + xtm: 16757, + xtn: 16758, + xto: 16759, + xtp: 16760, + xtq: 16761, + xtr: 16762, + xts: 16763, + xtt: 16764, + xtu: 16765, + xtv: 16766, + xtw: 16767, + xtx: 16768, + xty: 16769, + xuz: 16770, + xua: 16771, + xub: 16772, + xuc: 16773, + xud: 16774, + xue: 16775, + xuf: 16776, + xug: 16777, + xuh: 16778, + xui: 16779, + xuj: 16780, + xuk: 16781, + xul: 16782, + xum: 16783, + xun: 16784, + xuo: 16785, + xup: 16786, + xuq: 16787, + xur: 16788, + xus: 16789, + xut: 16790, + xuu: 16791, + xuv: 16792, + xuw: 16793, + xux: 16794, + xuy: 16795, + xvz: 16796, + xva: 16797, + xvb: 16798, + xvc: 16799, + xvd: 16800, + xve: 16801, + xvf: 16802, + xvg: 16803, + xvh: 16804, + xvi: 16805, + xvj: 16806, + xvk: 16807, + xvl: 16808, + xvm: 16809, + xvn: 16810, + xvo: 16811, + xvp: 16812, + xvq: 16813, + xvr: 16814, + xvs: 16815, + xvt: 16816, + xvu: 16817, + xvv: 16818, + xvw: 16819, + xvx: 16820, + xvy: 16821, + xwz: 16822, + xwa: 16823, + xwb: 16824, + xwc: 16825, + xwd: 16826, + xwe: 16827, + xwf: 16828, + xwg: 16829, + xwh: 16830, + xwi: 16831, + xwj: 16832, + xwk: 16833, + xwl: 16834, + xwm: 16835, + xwn: 16836, + xwo: 16837, + xwp: 16838, + xwq: 16839, + xwr: 16840, + xws: 16841, + xwt: 16842, + xwu: 16843, + xwv: 16844, + xww: 16845, + xwx: 16846, + xwy: 16847, + xxz: 16848, + xxa: 16849, + xxb: 16850, + xxc: 16851, + xxd: 16852, + xxe: 16853, + xxf: 16854, + xxg: 16855, + xxh: 16856, + xxi: 16857, + xxj: 16858, + xxk: 16859, + xxl: 16860, + xxm: 16861, + xxn: 16862, + xxo: 16863, + xxp: 16864, + xxq: 16865, + xxr: 16866, + xxs: 16867, + xxt: 16868, + xxu: 16869, + xxv: 16870, + xxw: 16871, + xxx: 16872, + xxy: 16873, + xyz: 16874, + xya: 16875, + xyb: 16876, + xyc: 16877, + xyd: 16878, + xye: 16879, + xyf: 16880, + xyg: 16881, + xyh: 16882, + xyi: 16883, + xyj: 16884, + xyk: 16885, + xyl: 16886, + xym: 16887, + xyn: 16888, + xyo: 16889, + xyp: 16890, + xyq: 16891, + xyr: 16892, + xys: 16893, + xyt: 16894, + xyu: 16895, + xyv: 16896, + xyw: 16897, + xyx: 16898, + xyy: 16899, + yzz: 16900, + yza: 16901, + yzb: 16902, + yzc: 16903, + yzd: 16904, + yze: 16905, + yzf: 16906, + yzg: 16907, + yzh: 16908, + yzi: 16909, + yzj: 16910, + yzk: 16911, + yzl: 16912, + yzm: 16913, + yzn: 16914, + yzo: 16915, + yzp: 16916, + yzq: 16917, + yzr: 16918, + yzs: 16919, + yzt: 16920, + yzu: 16921, + yzv: 16922, + yzw: 16923, + yzx: 16924, + yzy: 16925, + yaz: 16926, + yaa: 16927, + yab: 16928, + yac: 16929, + yad: 16930, + yae: 16931, + yaf: 16932, + yag: 16933, + yah: 16934, + yai: 16935, + yaj: 16936, + yak: 16937, + yal: 16938, + yam: 16939, + yan: 16940, + yao: 16941, + yap: 16942, + yaq: 16943, + yar: 16944, + yas: 16945, + yat: 16946, + yau: 16947, + yav: 16948, + yaw: 16949, + yax: 16950, + yay: 16951, + ybz: 16952, + yba: 16953, + ybb: 16954, + ybc: 16955, + ybd: 16956, + ybe: 16957, + ybf: 16958, + ybg: 16959, + ybh: 16960, + ybi: 16961, + ybj: 16962, + ybk: 16963, + ybl: 16964, + ybm: 16965, + ybn: 16966, + ybo: 16967, + ybp: 16968, + ybq: 16969, + ybr: 16970, + ybs: 16971, + ybt: 16972, + ybu: 16973, + ybv: 16974, + ybw: 16975, + ybx: 16976, + yby: 16977, + ycz: 16978, + yca: 16979, + ycb: 16980, + ycc: 16981, + ycd: 16982, + yce: 16983, + ycf: 16984, + ycg: 16985, + ych: 16986, + yci: 16987, + ycj: 16988, + yck: 16989, + ycl: 16990, + ycm: 16991, + ycn: 16992, + yco: 16993, + ycp: 16994, + ycq: 16995, + ycr: 16996, + ycs: 16997, + yct: 16998, + ycu: 16999, + ycv: 17000, + ycw: 17001, + ycx: 17002, + ycy: 17003, + ydz: 17004, + yda: 17005, + ydb: 17006, + ydc: 17007, + ydd: 17008, + yde: 17009, + ydf: 17010, + ydg: 17011, + ydh: 17012, + ydi: 17013, + ydj: 17014, + ydk: 17015, + ydl: 17016, + ydm: 17017, + ydn: 17018, + ydo: 17019, + ydp: 17020, + ydq: 17021, + ydr: 17022, + yds: 17023, + ydt: 17024, + ydu: 17025, + ydv: 17026, + ydw: 17027, + ydx: 17028, + ydy: 17029, + yez: 17030, + yea: 17031, + yeb: 17032, + yec: 17033, + yed: 17034, + yee: 17035, + yef: 17036, + yeg: 17037, + yeh: 17038, + yei: 17039, + yej: 17040, + yek: 17041, + yel: 17042, + yem: 17043, + yen: 17044, + yeo: 17045, + yep: 17046, + yeq: 17047, + yer: 17048, + yes: 17049, + yet: 17050, + yeu: 17051, + yev: 17052, + yew: 17053, + yex: 17054, + yey: 17055, + yfz: 17056, + yfa: 17057, + yfb: 17058, + yfc: 17059, + yfd: 17060, + yfe: 17061, + yff: 17062, + yfg: 17063, + yfh: 17064, + yfi: 17065, + yfj: 17066, + yfk: 17067, + yfl: 17068, + yfm: 17069, + yfn: 17070, + yfo: 17071, + yfp: 17072, + yfq: 17073, + yfr: 17074, + yfs: 17075, + yft: 17076, + yfu: 17077, + yfv: 17078, + yfw: 17079, + yfx: 17080, + yfy: 17081, + ygz: 17082, + yga: 17083, + ygb: 17084, + ygc: 17085, + ygd: 17086, + yge: 17087, + ygf: 17088, + ygg: 17089, + ygh: 17090, + ygi: 17091, + ygj: 17092, + ygk: 17093, + ygl: 17094, + ygm: 17095, + ygn: 17096, + ygo: 17097, + ygp: 17098, + ygq: 17099, + ygr: 17100, + ygs: 17101, + ygt: 17102, + ygu: 17103, + ygv: 17104, + ygw: 17105, + ygx: 17106, + ygy: 17107, + yhz: 17108, + yha: 17109, + yhb: 17110, + yhc: 17111, + yhd: 17112, + yhe: 17113, + yhf: 17114, + yhg: 17115, + yhh: 17116, + yhi: 17117, + yhj: 17118, + yhk: 17119, + yhl: 17120, + yhm: 17121, + yhn: 17122, + yho: 17123, + yhp: 17124, + yhq: 17125, + yhr: 17126, + yhs: 17127, + yht: 17128, + yhu: 17129, + yhv: 17130, + yhw: 17131, + yhx: 17132, + yhy: 17133, + yiz: 17134, + yia: 17135, + yib: 17136, + yic: 17137, + yid: 17138, + yie: 17139, + yif: 17140, + yig: 17141, + yih: 17142, + yii: 17143, + yij: 17144, + yik: 17145, + yil: 17146, + yim: 17147, + yin: 17148, + yio: 17149, + yip: 17150, + yiq: 17151, + yir: 17152, + yis: 17153, + yit: 17154, + yiu: 17155, + yiv: 17156, + yiw: 17157, + yix: 17158, + yiy: 17159, + yjz: 17160, + yja: 17161, + yjb: 17162, + yjc: 17163, + yjd: 17164, + yje: 17165, + yjf: 17166, + yjg: 17167, + yjh: 17168, + yji: 17169, + yjj: 17170, + yjk: 17171, + yjl: 17172, + yjm: 17173, + yjn: 17174, + yjo: 17175, + yjp: 17176, + yjq: 17177, + yjr: 17178, + yjs: 17179, + yjt: 17180, + yju: 17181, + yjv: 17182, + yjw: 17183, + yjx: 17184, + yjy: 17185, + ykz: 17186, + yka: 17187, + ykb: 17188, + ykc: 17189, + ykd: 17190, + yke: 17191, + ykf: 17192, + ykg: 17193, + ykh: 17194, + yki: 17195, + ykj: 17196, + ykk: 17197, + ykl: 17198, + ykm: 17199, + ykn: 17200, + yko: 17201, + ykp: 17202, + ykq: 17203, + ykr: 17204, + yks: 17205, + ykt: 17206, + yku: 17207, + ykv: 17208, + ykw: 17209, + ykx: 17210, + yky: 17211, + ylz: 17212, + yla: 17213, + ylb: 17214, + ylc: 17215, + yld: 17216, + yle: 17217, + ylf: 17218, + ylg: 17219, + ylh: 17220, + yli: 17221, + ylj: 17222, + ylk: 17223, + yll: 17224, + ylm: 17225, + yln: 17226, + ylo: 17227, + ylp: 17228, + ylq: 17229, + ylr: 17230, + yls: 17231, + ylt: 17232, + ylu: 17233, + ylv: 17234, + ylw: 17235, + ylx: 17236, + yly: 17237, + ymz: 17238, + yma: 17239, + ymb: 17240, + ymc: 17241, + ymd: 17242, + yme: 17243, + ymf: 17244, + ymg: 17245, + ymh: 17246, + ymi: 17247, + ymj: 17248, + ymk: 17249, + yml: 17250, + ymm: 17251, + ymn: 17252, + ymo: 17253, + ymp: 17254, + ymq: 17255, + ymr: 17256, + yms: 17257, + ymt: 17258, + ymu: 17259, + ymv: 17260, + ymw: 17261, + ymx: 17262, + ymy: 17263, + ynz: 17264, + yna: 17265, + ynb: 17266, + ync: 17267, + ynd: 17268, + yne: 17269, + ynf: 17270, + yng: 17271, + ynh: 17272, + yni: 17273, + ynj: 17274, + ynk: 17275, + ynl: 17276, + ynm: 17277, + ynn: 17278, + yno: 17279, + ynp: 17280, + ynq: 17281, + ynr: 17282, + yns: 17283, + ynt: 17284, + ynu: 17285, + ynv: 17286, + ynw: 17287, + ynx: 17288, + yny: 17289, + yoz: 17290, + yoa: 17291, + yob: 17292, + yoc: 17293, + yod: 17294, + yoe: 17295, + yof: 17296, + yog: 17297, + yoh: 17298, + yoi: 17299, + yoj: 17300, + yok: 17301, + yol: 17302, + yom: 17303, + yon: 17304, + yoo: 17305, + yop: 17306, + yoq: 17307, + yor: 17308, + yos: 17309, + yot: 17310, + you: 17311, + yov: 17312, + yow: 17313, + yox: 17314, + yoy: 17315, + ypz: 17316, + ypa: 17317, + ypb: 17318, + ypc: 17319, + ypd: 17320, + ype: 17321, + ypf: 17322, + ypg: 17323, + yph: 17324, + ypi: 17325, + ypj: 17326, + ypk: 17327, + ypl: 17328, + ypm: 17329, + ypn: 17330, + ypo: 17331, + ypp: 17332, + ypq: 17333, + ypr: 17334, + yps: 17335, + ypt: 17336, + ypu: 17337, + ypv: 17338, + ypw: 17339, + ypx: 17340, + ypy: 17341, + yqz: 17342, + yqa: 17343, + yqb: 17344, + yqc: 17345, + yqd: 17346, + yqe: 17347, + yqf: 17348, + yqg: 17349, + yqh: 17350, + yqi: 17351, + yqj: 17352, + yqk: 17353, + yql: 17354, + yqm: 17355, + yqn: 17356, + yqo: 17357, + yqp: 17358, + yqq: 17359, + yqr: 17360, + yqs: 17361, + yqt: 17362, + yqu: 17363, + yqv: 17364, + yqw: 17365, + yqx: 17366, + yqy: 17367, + yrz: 17368, + yra: 17369, + yrb: 17370, + yrc: 17371, + yrd: 17372, + yre: 17373, + yrf: 17374, + yrg: 17375, + yrh: 17376, + yri: 17377, + yrj: 17378, + yrk: 17379, + yrl: 17380, + yrm: 17381, + yrn: 17382, + yro: 17383, + yrp: 17384, + yrq: 17385, + yrr: 17386, + yrs: 17387, + yrt: 17388, + yru: 17389, + yrv: 17390, + yrw: 17391, + yrx: 17392, + yry: 17393, + ysz: 17394, + ysa: 17395, + ysb: 17396, + ysc: 17397, + ysd: 17398, + yse: 17399, + ysf: 17400, + ysg: 17401, + ysh: 17402, + ysi: 17403, + ysj: 17404, + ysk: 17405, + ysl: 17406, + ysm: 17407, + ysn: 17408, + yso: 17409, + ysp: 17410, + ysq: 17411, + ysr: 17412, + yss: 17413, + yst: 17414, + ysu: 17415, + ysv: 17416, + ysw: 17417, + ysx: 17418, + ysy: 17419, + ytz: 17420, + yta: 17421, + ytb: 17422, + ytc: 17423, + ytd: 17424, + yte: 17425, + ytf: 17426, + ytg: 17427, + yth: 17428, + yti: 17429, + ytj: 17430, + ytk: 17431, + ytl: 17432, + ytm: 17433, + ytn: 17434, + yto: 17435, + ytp: 17436, + ytq: 17437, + ytr: 17438, + yts: 17439, + ytt: 17440, + ytu: 17441, + ytv: 17442, + ytw: 17443, + ytx: 17444, + yty: 17445, + yuz: 17446, + yua: 17447, + yub: 17448, + yuc: 17449, + yud: 17450, + yue: 17451, + yuf: 17452, + yug: 17453, + yuh: 17454, + yui: 17455, + yuj: 17456, + yuk: 17457, + yul: 17458, + yum: 17459, + yun: 17460, + yuo: 17461, + yup: 17462, + yuq: 17463, + yur: 17464, + yus: 17465, + yut: 17466, + yuu: 17467, + yuv: 17468, + yuw: 17469, + yux: 17470, + yuy: 17471, + yvz: 17472, + yva: 17473, + yvb: 17474, + yvc: 17475, + yvd: 17476, + yve: 17477, + yvf: 17478, + yvg: 17479, + yvh: 17480, + yvi: 17481, + yvj: 17482, + yvk: 17483, + yvl: 17484, + yvm: 17485, + yvn: 17486, + yvo: 17487, + yvp: 17488, + yvq: 17489, + yvr: 17490, + yvs: 17491, + yvt: 17492, + yvu: 17493, + yvv: 17494, + yvw: 17495, + yvx: 17496, + yvy: 17497, + ywz: 17498, + ywa: 17499, + ywb: 17500, + ywc: 17501, + ywd: 17502, + ywe: 17503, + ywf: 17504, + ywg: 17505, + ywh: 17506, + ywi: 17507, + ywj: 17508, + ywk: 17509, + ywl: 17510, + ywm: 17511, + ywn: 17512, + ywo: 17513, + ywp: 17514, + ywq: 17515, + ywr: 17516, + yws: 17517, + ywt: 17518, + ywu: 17519, + ywv: 17520, + yww: 17521, + ywx: 17522, + ywy: 17523, + yxz: 17524, + yxa: 17525, + yxb: 17526, + yxc: 17527, + yxd: 17528, + yxe: 17529, + yxf: 17530, + yxg: 17531, + yxh: 17532, + yxi: 17533, + yxj: 17534, + yxk: 17535, + yxl: 17536, + yxm: 17537, + yxn: 17538, + yxo: 17539, + yxp: 17540, + yxq: 17541, + yxr: 17542, + yxs: 17543, + yxt: 17544, + yxu: 17545, + yxv: 17546, + yxw: 17547, + yxx: 17548, + yxy: 17549, + yyz: 17550, + yya: 17551, + yyb: 17552, + yyc: 17553, + yyd: 17554, + yye: 17555, + yyf: 17556, + yyg: 17557, + yyh: 17558, + yyi: 17559, + yyj: 17560, + yyk: 17561, + yyl: 17562, + yym: 17563, + yyn: 17564, + yyo: 17565, + yyp: 17566, + yyq: 17567, + yyr: 17568, + yys: 17569, + yyt: 17570, + yyu: 17571, + yyv: 17572, + 111: 111, + yyw: 17573, + yyx: 17574, + yyy: 17575, + get X() { print("getting X"); return "X"; }, + set X(value) { print("setting X"); }, +}; + +print(x.aaa); +print(x.hhh); +print(x.yyy); +print(x[111]); +print(x.X); +x.X = 0; +var keys = Object.keys(x); +print(keys.length); +print(keys[0]); +print(keys[703]); +print(keys[5624]); +print(keys[17575]); +print(keys[17576]); + diff --git a/nashorn/test/script/basic/JDK-8017084.js.EXPECTED b/nashorn/test/script/basic/JDK-8017084.js.EXPECTED new file mode 100644 index 00000000000..f57be50c00c --- /dev/null +++ b/nashorn/test/script/basic/JDK-8017084.js.EXPECTED @@ -0,0 +1,13 @@ +703 +5624 +17575 +111 +getting X +X +setting X +17577 +111 +aaa +hhh +yyy +X From dbe76b28bda5ed02436261208bdf60627526c615 Mon Sep 17 00:00:00 2001 From: Attila Szegedi Date: Fri, 5 Jul 2013 15:10:47 +0200 Subject: [PATCH 068/123] 8019819: scope symbol didn't get a slot in certain cases Reviewed-by: hannesw, jlaskey, lagergren, sundar --- .../jdk/nashorn/internal/codegen/Attr.java | 8 ++-- .../internal/codegen/CodeGenerator.java | 27 ++++------- .../internal/codegen/CompilationPhase.java | 8 ++-- .../internal/codegen/FinalizeTypes.java | 9 ++-- .../jdk/nashorn/internal/ir/FunctionNode.java | 14 +++++- .../nashorn/internal/ir/LexicalContext.java | 28 ++++++++++- .../src/jdk/nashorn/internal/ir/Symbol.java | 3 +- .../jdk/nashorn/internal/parser/Parser.java | 2 +- nashorn/test/script/basic/JDK-8019819.js | 46 +++++++++++++++++++ 9 files changed, 108 insertions(+), 37 deletions(-) create mode 100644 nashorn/test/script/basic/JDK-8019819.js diff --git a/nashorn/src/jdk/nashorn/internal/codegen/Attr.java b/nashorn/src/jdk/nashorn/internal/codegen/Attr.java index d72e6a76c72..60de425524f 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/Attr.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/Attr.java @@ -54,7 +54,6 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; - import jdk.nashorn.internal.codegen.types.Type; import jdk.nashorn.internal.ir.AccessNode; import jdk.nashorn.internal.ir.BinaryNode; @@ -343,10 +342,11 @@ final class Attr extends NodeOperatorVisitor { catchNestingLevel++; // define block-local exception variable - final Symbol def = defineSymbol(block, exception.getName(), IS_VAR | IS_LET | IS_ALWAYS_DEFINED); + final String exname = exception.getName(); + final Symbol def = defineSymbol(block, exname, IS_VAR | IS_LET | IS_ALWAYS_DEFINED); newType(def, Type.OBJECT); //we can catch anything, not just ecma exceptions - addLocalDef(exception.getName()); + addLocalDef(exname); return true; } @@ -678,7 +678,7 @@ final class Attr extends NodeOperatorVisitor { if (scopeBlock != null) { assert lc.contains(scopeBlock); - lc.setFlag(scopeBlock, Block.NEEDS_SCOPE); + lc.setBlockNeedsScope(scopeBlock); } } } diff --git a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java index fe4e3676e19..79936473fb9 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java @@ -881,9 +881,15 @@ final class CodeGenerator extends NodeOperatorVisitor= 0, like varargs. */ - if (function.needsParentScope()) { - initParentScope(); + if(method.hasScope()) { + if (function.needsParentScope()) { + method.loadCompilerConstant(CALLEE); + method.invoke(ScriptFunction.GET_SCOPE); + } else { + assert function.hasScopeBlock(); + method.loadNull(); + } + method.storeCompilerConstant(SCOPE); } if (function.needsArguments()) { initArguments(function); @@ -949,15 +955,6 @@ final class CodeGenerator extends NodeOperatorVisitor { if (!functionNode.needsCallee()) { functionNode.compilerConstant(CALLEE).setNeedsSlot(false); } - // Similar reasoning applies to __scope__ symbol: if the function doesn't need either parent scope or its - // own scope, we ensure it doesn't get a slot, but we can't determine whether it needs a scope earlier than - // this phase. - if (!(functionNode.getBody().needsScope() || functionNode.needsParentScope())) { + // Similar reasoning applies to __scope__ symbol: if the function doesn't need either parent scope and none of + // its blocks create a scope, we ensure it doesn't get a slot, but we can't determine whether it needs a scope + // earlier than this phase. + if (!(functionNode.hasScopeBlock() || functionNode.needsParentScope())) { functionNode.compilerConstant(SCOPE).setNeedsSlot(false); } diff --git a/nashorn/src/jdk/nashorn/internal/ir/FunctionNode.java b/nashorn/src/jdk/nashorn/internal/ir/FunctionNode.java index 8caff9d28fd..ec32c767308 100644 --- a/nashorn/src/jdk/nashorn/internal/ir/FunctionNode.java +++ b/nashorn/src/jdk/nashorn/internal/ir/FunctionNode.java @@ -160,6 +160,10 @@ public final class FunctionNode extends LexicalContextNode implements Flags= 0; i--) { if (stack[i] == node) { flags[i] |= flag; @@ -71,6 +74,29 @@ public class LexicalContext { assert false; } + /** + * Marks the block as one that creates a scope. Note that this method must + * be used instead of {@link #setFlag(LexicalContextNode, int)} with + * {@link Block#NEEDS_SCOPE} because it atomically also sets the + * {@link FunctionNode#HAS_SCOPE_BLOCK} flag on the block's containing + * function. + * @param block the block that needs to be marked as creating a scope. + */ + public void setBlockNeedsScope(final Block block) { + for (int i = sp - 1; i >= 0; i--) { + if (stack[i] == block) { + flags[i] |= Block.NEEDS_SCOPE; + for(int j = i - 1; j >=0; j --) { + if(stack[j] instanceof FunctionNode) { + flags[j] |= FunctionNode.HAS_SCOPE_BLOCK; + return; + } + } + } + } + assert false; + } + /** * Get the flags for a lexical context node on the stack * @param node node diff --git a/nashorn/src/jdk/nashorn/internal/ir/Symbol.java b/nashorn/src/jdk/nashorn/internal/ir/Symbol.java index 7c1839024aa..5061ab9049a 100644 --- a/nashorn/src/jdk/nashorn/internal/ir/Symbol.java +++ b/nashorn/src/jdk/nashorn/internal/ir/Symbol.java @@ -29,7 +29,6 @@ import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; - import jdk.nashorn.internal.codegen.types.Range; import jdk.nashorn.internal.codegen.types.Type; import jdk.nashorn.internal.runtime.Context; @@ -705,7 +704,7 @@ public final class Symbol implements Comparable { public static void setSymbolIsScope(final LexicalContext lc, final Symbol symbol) { symbol.setIsScope(); if (!symbol.isGlobal()) { - lc.setFlag(lc.getDefiningBlock(symbol), Block.NEEDS_SCOPE); + lc.setBlockNeedsScope(lc.getDefiningBlock(symbol)); } } diff --git a/nashorn/src/jdk/nashorn/internal/parser/Parser.java b/nashorn/src/jdk/nashorn/internal/parser/Parser.java index 4c6107d570e..fd0136e463c 100644 --- a/nashorn/src/jdk/nashorn/internal/parser/Parser.java +++ b/nashorn/src/jdk/nashorn/internal/parser/Parser.java @@ -2957,7 +2957,7 @@ loop: } else { lc.setFlag(fn, FunctionNode.HAS_NESTED_EVAL); } - lc.setFlag(lc.getFunctionBody(fn), Block.NEEDS_SCOPE); + lc.setBlockNeedsScope(lc.getFunctionBody(fn)); } } diff --git a/nashorn/test/script/basic/JDK-8019819.js b/nashorn/test/script/basic/JDK-8019819.js new file mode 100644 index 00000000000..1760ac3d333 --- /dev/null +++ b/nashorn/test/script/basic/JDK-8019819.js @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * 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. + */ + +/** + * JDK-8019819: scope symbol didn't get a slot in certain cases + * + * @test + * @run + */ +function f() { + try { + } catch(e if [].g(e)) { + with({}) { + throw e; + } + } +} + +function g() { + try { + } catch(e) { + with({}) { + throw e; + } + } +} From fa6c5ef45f829b45b542681c80ccc7401756e072 Mon Sep 17 00:00:00 2001 From: Marcus Lagergren Date: Fri, 5 Jul 2013 19:35:39 +0200 Subject: [PATCH 069/123] 8019983: Void returns combined with return with expression picked the wrong return type Reviewed-by: sundar, jlaskey --- .../jdk/nashorn/internal/codegen/Attr.java | 9 ++-- nashorn/test/script/basic/JDK-8019983.js | 42 +++++++++++++++++++ .../test/script/basic/JDK-8019983.js.EXPECTED | 1 + 3 files changed, 49 insertions(+), 3 deletions(-) create mode 100644 nashorn/test/script/basic/JDK-8019983.js create mode 100644 nashorn/test/script/basic/JDK-8019983.js.EXPECTED diff --git a/nashorn/src/jdk/nashorn/internal/codegen/Attr.java b/nashorn/src/jdk/nashorn/internal/codegen/Attr.java index 60de425524f..6dbfa6d4c9b 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/Attr.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/Attr.java @@ -749,6 +749,7 @@ final class Attr extends NodeOperatorVisitor { @Override public Node leaveReturnNode(final ReturnNode returnNode) { final Node expr = returnNode.getExpression(); + final Type returnType; if (expr != null) { //we can't do parameter specialization if we return something that hasn't been typed yet @@ -757,10 +758,12 @@ final class Attr extends NodeOperatorVisitor { symbol.setType(Type.OBJECT); } - final Type returnType = Type.widest(returnTypes.pop(), symbol.getSymbolType()); - returnTypes.push(returnType); - LOG.info("Returntype is now ", returnType); + returnType = Type.widest(returnTypes.pop(), symbol.getSymbolType()); + } else { + returnType = Type.OBJECT; //undefined } + LOG.info("Returntype is now ", returnType); + returnTypes.push(returnType); end(returnNode); diff --git a/nashorn/test/script/basic/JDK-8019983.js b/nashorn/test/script/basic/JDK-8019983.js new file mode 100644 index 00000000000..7851ab01849 --- /dev/null +++ b/nashorn/test/script/basic/JDK-8019983.js @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * 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. + */ + +/** + * JDK-8019983.js return without expression combined with return with expression should produce object + * return type (undefined) + * + * @test + * @run + */ + + +function g() { + switch(1) { + case 0: + case '': + default: + return; + } + return 10; +} +print(g()); diff --git a/nashorn/test/script/basic/JDK-8019983.js.EXPECTED b/nashorn/test/script/basic/JDK-8019983.js.EXPECTED new file mode 100644 index 00000000000..417b7b5370d --- /dev/null +++ b/nashorn/test/script/basic/JDK-8019983.js.EXPECTED @@ -0,0 +1 @@ +undefined From 0a7fda8dbe71a2af9cb4a62268f8d121cac98d0d Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Mon, 8 Jul 2013 16:33:50 +0530 Subject: [PATCH 070/123] 8020015: shared PropertyMaps should not be used without duplication Reviewed-by: hannesw, attila --- nashorn/buildtools/nasgen/build.xml | 3 +- .../internal/tools/nasgen/ClassGenerator.java | 85 +++++++++---- .../tools/nasgen/ConstructorGenerator.java | 18 +-- .../tools/nasgen/MethodGenerator.java | 5 + .../tools/nasgen/PrototypeGenerator.java | 19 +-- .../tools/nasgen/ScriptClassInstrumentor.java | 14 +-- .../tools/nasgen/StringConstants.java | 94 +++++++++----- nashorn/make/code_coverage.xml | 8 -- nashorn/make/project.properties | 3 + .../jdk/nashorn/internal/lookup/Lookup.java | 38 ------ .../internal/objects/ArrayBufferView.java | 9 +- .../jdk/nashorn/internal/objects/Global.java | 51 +++++--- .../internal/objects/NativeArguments.java | 12 +- .../internal/objects/NativeBoolean.java | 1 - .../nashorn/internal/objects/NativeDebug.java | 14 ++- .../nashorn/internal/objects/NativeError.java | 1 - .../internal/objects/NativeJSAdapter.java | 1 - .../nashorn/internal/objects/NativeJSON.java | 1 + .../nashorn/internal/objects/NativeMath.java | 1 + .../objects/NativeStrictArguments.java | 11 +- .../internal/objects/PrototypeObject.java | 10 +- .../internal/objects/ScriptFunctionImpl.java | 35 ++++-- .../internal/runtime/AccessorProperty.java | 14 +++ .../jdk/nashorn/internal/runtime/Context.java | 8 +- .../runtime/PropertyListenerManager.java | 10 ++ .../nashorn/internal/runtime/PropertyMap.java | 117 ++++++++++++------ .../internal/runtime/ScriptEnvironment.java | 8 ++ .../internal/runtime/ScriptObject.java | 2 +- .../runtime/resources/Options.properties | 16 +++ .../src/jdk/nashorn/internal/scripts/JO.java | 2 +- nashorn/src/jdk/nashorn/tools/Shell.java | 4 + 31 files changed, 385 insertions(+), 230 deletions(-) diff --git a/nashorn/buildtools/nasgen/build.xml b/nashorn/buildtools/nasgen/build.xml index bf56c1111df..6243bb2f02c 100644 --- a/nashorn/buildtools/nasgen/build.xml +++ b/nashorn/buildtools/nasgen/build.xml @@ -42,7 +42,8 @@ destdir="${build.classes.dir}" classpath="${javac.classpath}" debug="${javac.debug}" - includeantruntime="false"> + includeantruntime="false" fork="true"> + diff --git a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java index ed0eee61e60..3425e9fd0c0 100644 --- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java +++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java @@ -37,14 +37,24 @@ import static jdk.nashorn.internal.tools.nasgen.StringConstants.GETTER_PREFIX; import static jdk.nashorn.internal.tools.nasgen.StringConstants.GET_CLASS_NAME; import static jdk.nashorn.internal.tools.nasgen.StringConstants.GET_CLASS_NAME_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.INIT; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.LOOKUP_NEWPROPERTY; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.LOOKUP_NEWPROPERTY_DESC; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.LOOKUP_TYPE; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_DESC; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_FIELD_NAME; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_NEWMAP; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_NEWMAP_DESC; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_TYPE; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.ACCESSORPROPERTY_CREATE; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.ACCESSORPROPERTY_CREATE_DESC; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.ACCESSORPROPERTY_TYPE; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.LIST_DESC; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.ARRAYLIST_TYPE; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.ARRAYLIST_INIT_DESC; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTION_TYPE; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTION_ADD; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTION_ADD_DESC; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTIONS_TYPE; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTIONS_EMPTY_LIST; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DESC; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_FIELD_NAME; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_SETISSHARED; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_SETISSHARED_DESC; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_NEWMAP; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_NEWMAP_DESC; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_TYPE; import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJECT_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTIONIMPL_MAKEFUNCTION; import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTIONIMPL_MAKEFUNCTION_DESC; @@ -161,17 +171,30 @@ public class ClassGenerator { return new MethodGenerator(mv, access, name, desc); } - static void emitStaticInitPrefix(final MethodGenerator mi, final String className) { + static void emitStaticInitPrefix(final MethodGenerator mi, final String className, final int memberCount) { mi.visitCode(); - mi.pushNull(); - mi.putStatic(className, MAP_FIELD_NAME, MAP_DESC); - mi.invokeStatic(MAP_TYPE, MAP_NEWMAP, MAP_NEWMAP_DESC); - // stack: PropertyMap + if (memberCount > 0) { + // new ArrayList(int) + mi.newObject(ARRAYLIST_TYPE); + mi.dup(); + mi.push(memberCount); + mi.invokeSpecial(ARRAYLIST_TYPE, INIT, ARRAYLIST_INIT_DESC); + // stack: ArrayList + } else { + // java.util.Collections.EMPTY_LIST + mi.getStatic(COLLECTIONS_TYPE, COLLECTIONS_EMPTY_LIST, LIST_DESC); + // stack List + } } static void emitStaticInitSuffix(final MethodGenerator mi, final String className) { - // stack: PropertyMap - mi.putStatic(className, MAP_FIELD_NAME, MAP_DESC); + // stack: Collection + // pmap = PropertyMap.newMap(Collection); + mi.invokeStatic(PROPERTYMAP_TYPE, PROPERTYMAP_NEWMAP, PROPERTYMAP_NEWMAP_DESC); + // pmap.setIsShared(); + mi.invokeVirtual(PROPERTYMAP_TYPE, PROPERTYMAP_SETISSHARED, PROPERTYMAP_SETISSHARED_DESC); + // $nasgenmap$ = pmap; + mi.putStatic(className, PROPERTYMAP_FIELD_NAME, PROPERTYMAP_DESC); mi.returnVoid(); mi.computeMaxs(); mi.visitEnd(); @@ -235,9 +258,9 @@ public class ClassGenerator { } static void addMapField(final ClassVisitor cv) { - // add a MAP static field + // add a PropertyMap static field final FieldVisitor fv = cv.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, - MAP_FIELD_NAME, MAP_DESC, null, null); + PROPERTYMAP_FIELD_NAME, PROPERTYMAP_DESC, null, null); if (fv != null) { fv.visitEnd(); } @@ -278,7 +301,11 @@ public class ClassGenerator { static void linkerAddGetterSetter(final MethodGenerator mi, final String className, final MemberInfo memInfo) { final String propertyName = memInfo.getName(); - // stack: PropertyMap + // stack: Collection + // dup of Collection instance + mi.dup(); + + // property = AccessorProperty.create(key, flags, getter, setter); mi.loadLiteral(propertyName); // setup flags mi.push(memInfo.getAttributes()); @@ -292,13 +319,21 @@ public class ClassGenerator { javaName = SETTER_PREFIX + memInfo.getJavaName(); mi.visitLdcInsn(new Handle(H_INVOKEVIRTUAL, className, javaName, setterDesc(memInfo))); } - mi.invokeStatic(LOOKUP_TYPE, LOOKUP_NEWPROPERTY, LOOKUP_NEWPROPERTY_DESC); - // stack: PropertyMap + mi.invokeStatic(ACCESSORPROPERTY_TYPE, ACCESSORPROPERTY_CREATE, ACCESSORPROPERTY_CREATE_DESC); + // boolean Collection.add(property) + mi.invokeInterface(COLLECTION_TYPE, COLLECTION_ADD, COLLECTION_ADD_DESC); + // pop return value of Collection.add + mi.pop(); + // stack: Collection } static void linkerAddGetterSetter(final MethodGenerator mi, final String className, final MemberInfo getter, final MemberInfo setter) { final String propertyName = getter.getName(); - // stack: PropertyMap + // stack: Collection + // dup of Collection instance + mi.dup(); + + // property = AccessorProperty.create(key, flags, getter, setter); mi.loadLiteral(propertyName); // setup flags mi.push(getter.getAttributes()); @@ -312,8 +347,12 @@ public class ClassGenerator { mi.visitLdcInsn(new Handle(H_INVOKESTATIC, className, setter.getJavaName(), setter.getJavaDesc())); } - mi.invokeStatic(LOOKUP_TYPE, LOOKUP_NEWPROPERTY, LOOKUP_NEWPROPERTY_DESC); - // stack: PropertyMap + mi.invokeStatic(ACCESSORPROPERTY_TYPE, ACCESSORPROPERTY_CREATE, ACCESSORPROPERTY_CREATE_DESC); + // boolean Collection.add(property) + mi.invokeInterface(COLLECTION_TYPE, COLLECTION_ADD, COLLECTION_ADD_DESC); + // pop return value of Collection.add + mi.pop(); + // stack: Collection } static ScriptClassInfo getScriptClassInfo(final String fileName) throws IOException { diff --git a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ConstructorGenerator.java b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ConstructorGenerator.java index 7c59f8c3c2b..e90b53ecb81 100644 --- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ConstructorGenerator.java +++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ConstructorGenerator.java @@ -32,11 +32,11 @@ import static jdk.internal.org.objectweb.asm.Opcodes.V1_7; import static jdk.nashorn.internal.tools.nasgen.StringConstants.CONSTRUCTOR_SUFFIX; import static jdk.nashorn.internal.tools.nasgen.StringConstants.DEFAULT_INIT_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.INIT; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_DESC; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_DUPLICATE; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_DUPLICATE_DESC; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_FIELD_NAME; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_TYPE; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DESC; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DUPLICATE; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DUPLICATE_DESC; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_FIELD_NAME; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_TYPE; import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJECT_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROTOTYPEOBJECT_SETCONSTRUCTOR; import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROTOTYPEOBJECT_SETCONSTRUCTOR_DESC; @@ -129,7 +129,7 @@ public class ConstructorGenerator extends ClassGenerator { private void emitStaticInitializer() { final MethodGenerator mi = makeStaticInitializer(); - emitStaticInitPrefix(mi, className); + emitStaticInitPrefix(mi, className, memberCount); for (final MemberInfo memInfo : scriptClassInfo.getMembers()) { if (memInfo.isConstructorFunction() || memInfo.isConstructorProperty()) { @@ -170,10 +170,10 @@ public class ConstructorGenerator extends ClassGenerator { private void loadMap(final MethodGenerator mi) { if (memberCount > 0) { - mi.getStatic(className, MAP_FIELD_NAME, MAP_DESC); + mi.getStatic(className, PROPERTYMAP_FIELD_NAME, PROPERTYMAP_DESC); // make sure we use duplicated PropertyMap so that original map - // stays intact and so can be used for many globals in same context - mi.invokeVirtual(MAP_TYPE, MAP_DUPLICATE, MAP_DUPLICATE_DESC); + // stays intact and so can be used for many globals. + mi.invokeVirtual(PROPERTYMAP_TYPE, PROPERTYMAP_DUPLICATE, PROPERTYMAP_DUPLICATE_DESC); } } diff --git a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/MethodGenerator.java b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/MethodGenerator.java index c3dfd878526..475d7328c69 100644 --- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/MethodGenerator.java +++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/MethodGenerator.java @@ -57,6 +57,7 @@ import static jdk.internal.org.objectweb.asm.Opcodes.IALOAD; import static jdk.internal.org.objectweb.asm.Opcodes.IASTORE; import static jdk.internal.org.objectweb.asm.Opcodes.ICONST_0; import static jdk.internal.org.objectweb.asm.Opcodes.ILOAD; +import static jdk.internal.org.objectweb.asm.Opcodes.INVOKEINTERFACE; import static jdk.internal.org.objectweb.asm.Opcodes.INVOKESPECIAL; import static jdk.internal.org.objectweb.asm.Opcodes.INVOKESTATIC; import static jdk.internal.org.objectweb.asm.Opcodes.INVOKEVIRTUAL; @@ -347,6 +348,10 @@ public class MethodGenerator extends MethodVisitor { } // invokes, field get/sets + void invokeInterface(final String owner, final String method, final String desc) { + super.visitMethodInsn(INVOKEINTERFACE, owner, method, desc); + } + void invokeVirtual(final String owner, final String method, final String desc) { super.visitMethodInsn(INVOKEVIRTUAL, owner, method, desc); } diff --git a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/PrototypeGenerator.java b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/PrototypeGenerator.java index 17750cd1bbf..98048a294b2 100644 --- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/PrototypeGenerator.java +++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/PrototypeGenerator.java @@ -30,11 +30,11 @@ import static jdk.internal.org.objectweb.asm.Opcodes.ACC_SUPER; import static jdk.internal.org.objectweb.asm.Opcodes.V1_7; import static jdk.nashorn.internal.tools.nasgen.StringConstants.DEFAULT_INIT_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.INIT; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_DESC; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_DUPLICATE; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_DUPLICATE_DESC; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_FIELD_NAME; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_TYPE; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DESC; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DUPLICATE; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DUPLICATE_DESC; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_FIELD_NAME; +import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_TYPE; import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJECT_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROTOTYPEOBJECT_TYPE; import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROTOTYPE_SUFFIX; @@ -67,6 +67,7 @@ public class PrototypeGenerator extends ClassGenerator { // add emitStaticInitializer(); } + // add emitConstructor(); @@ -106,7 +107,7 @@ public class PrototypeGenerator extends ClassGenerator { private void emitStaticInitializer() { final MethodGenerator mi = makeStaticInitializer(); - emitStaticInitPrefix(mi, className); + emitStaticInitPrefix(mi, className, memberCount); for (final MemberInfo memInfo : scriptClassInfo.getMembers()) { if (memInfo.isPrototypeFunction() || memInfo.isPrototypeProperty()) { linkerAddGetterSetter(mi, className, memInfo); @@ -124,10 +125,10 @@ public class PrototypeGenerator extends ClassGenerator { mi.loadThis(); if (memberCount > 0) { // call "super(map$)" - mi.getStatic(className, MAP_FIELD_NAME, MAP_DESC); + mi.getStatic(className, PROPERTYMAP_FIELD_NAME, PROPERTYMAP_DESC); // make sure we use duplicated PropertyMap so that original map - // stays intact and so can be used for many globals in same context - mi.invokeVirtual(MAP_TYPE, MAP_DUPLICATE, MAP_DUPLICATE_DESC); + // stays intact and so can be used for many global. + mi.invokeVirtual(PROPERTYMAP_TYPE, PROPERTYMAP_DUPLICATE, PROPERTYMAP_DUPLICATE_DESC); mi.invokeSpecial(PROTOTYPEOBJECT_TYPE, INIT, SCRIPTOBJECT_INIT_DESC); // initialize Function type fields initFunctionFields(mi); diff --git a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ScriptClassInstrumentor.java b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ScriptClassInstrumentor.java index ffeb90bea3e..1622e02b469 100644 --- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ScriptClassInstrumentor.java +++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ScriptClassInstrumentor.java @@ -37,10 +37,7 @@ import static jdk.nashorn.internal.tools.nasgen.StringConstants.$CLINIT$; import static jdk.nashorn.internal.tools.nasgen.StringConstants.CLINIT; import static jdk.nashorn.internal.tools.nasgen.StringConstants.DEFAULT_INIT_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.INIT; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_DESC; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_FIELD_NAME; import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJECT_DESC; -import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTOBJECT_INIT_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTOBJECT_TYPE; import java.io.BufferedInputStream; @@ -159,14 +156,7 @@ public class ScriptClassInstrumentor extends ClassVisitor { public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc) { if (isConstructor && opcode == INVOKESPECIAL && INIT.equals(name) && SCRIPTOBJECT_TYPE.equals(owner)) { - - // replace call to empty super-constructor with one passing PropertyMap argument - if (DEFAULT_INIT_DESC.equals(desc)) { - super.visitFieldInsn(GETSTATIC, scriptClassInfo.getJavaName(), MAP_FIELD_NAME, MAP_DESC); - super.visitMethodInsn(INVOKESPECIAL, SCRIPTOBJECT_TYPE, INIT, SCRIPTOBJECT_INIT_DESC); - } else { - super.visitMethodInsn(opcode, owner, name, desc); - } + super.visitMethodInsn(opcode, owner, name, desc); if (memberCount > 0) { // initialize @Property fields if needed @@ -256,7 +246,7 @@ public class ScriptClassInstrumentor extends ClassVisitor { } // Now generate $clinit$ final MethodGenerator mi = ClassGenerator.makeStaticInitializer(this, $CLINIT$); - ClassGenerator.emitStaticInitPrefix(mi, className); + ClassGenerator.emitStaticInitPrefix(mi, className, memberCount); if (memberCount > 0) { for (final MemberInfo memInfo : scriptClassInfo.getMembers()) { if (memInfo.isInstanceProperty() || memInfo.isInstanceFunction()) { diff --git a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/StringConstants.java b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/StringConstants.java index d0e3168b31f..c4c1ab8d465 100644 --- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/StringConstants.java +++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/StringConstants.java @@ -27,10 +27,14 @@ package jdk.nashorn.internal.tools.nasgen; import java.lang.invoke.MethodHandle; import java.lang.reflect.Method; +import java.util.Collection; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import jdk.internal.org.objectweb.asm.Type; -import jdk.nashorn.internal.lookup.Lookup; import jdk.nashorn.internal.objects.PrototypeObject; import jdk.nashorn.internal.objects.ScriptFunctionImpl; +import jdk.nashorn.internal.runtime.AccessorProperty; import jdk.nashorn.internal.runtime.PropertyMap; import jdk.nashorn.internal.runtime.ScriptFunction; import jdk.nashorn.internal.runtime.ScriptObject; @@ -40,15 +44,41 @@ import jdk.nashorn.internal.runtime.ScriptObject; */ @SuppressWarnings("javadoc") public interface StringConstants { + // standard jdk types, methods static final Type TYPE_METHOD = Type.getType(Method.class); static final Type TYPE_METHODHANDLE = Type.getType(MethodHandle.class); static final Type TYPE_METHODHANDLE_ARRAY = Type.getType(MethodHandle[].class); static final Type TYPE_OBJECT = Type.getType(Object.class); static final Type TYPE_CLASS = Type.getType(Class.class); static final Type TYPE_STRING = Type.getType(String.class); + static final Type TYPE_COLLECTION = Type.getType(Collection.class); + static final Type TYPE_COLLECTIONS = Type.getType(Collections.class); + static final Type TYPE_ARRAYLIST = Type.getType(ArrayList.class); + static final Type TYPE_LIST = Type.getType(List.class); - // Nashorn types - static final Type TYPE_LOOKUP = Type.getType(Lookup.class); + static final String CLINIT = ""; + static final String INIT = ""; + static final String DEFAULT_INIT_DESC = Type.getMethodDescriptor(Type.VOID_TYPE); + + static final String METHODHANDLE_TYPE = TYPE_METHODHANDLE.getInternalName(); + static final String OBJECT_TYPE = TYPE_OBJECT.getInternalName(); + static final String OBJECT_DESC = TYPE_OBJECT.getDescriptor(); + static final String OBJECT_ARRAY_DESC = Type.getDescriptor(Object[].class); + static final String ARRAYLIST_TYPE = TYPE_ARRAYLIST.getInternalName(); + static final String COLLECTION_TYPE = TYPE_COLLECTION.getInternalName(); + static final String COLLECTIONS_TYPE = TYPE_COLLECTIONS.getInternalName(); + + // java.util.Collection.add(Object) + static final String COLLECTION_ADD = "add"; + static final String COLLECTION_ADD_DESC = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, TYPE_OBJECT); + // java.util.ArrayList.(int) + static final String ARRAYLIST_INIT_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE); + // java.util.Collections.EMPTY_LIST + static final String COLLECTIONS_EMPTY_LIST = "EMPTY_LIST"; + static final String LIST_DESC = TYPE_LIST.getDescriptor(); + + // Nashorn types, methods + static final Type TYPE_ACCESSORPROPERTY = Type.getType(AccessorProperty.class); static final Type TYPE_PROPERTYMAP = Type.getType(PropertyMap.class); static final Type TYPE_PROTOTYPEOBJECT = Type.getType(PrototypeObject.class); static final Type TYPE_SCRIPTFUNCTION = Type.getType(ScriptFunction.class); @@ -57,52 +87,56 @@ public interface StringConstants { static final String PROTOTYPE_SUFFIX = "$Prototype"; static final String CONSTRUCTOR_SUFFIX = "$Constructor"; + // This field name is known to Nashorn runtime (Context). // Synchronize the name change, if needed at all. - static final String MAP_FIELD_NAME = "$nasgenmap$"; + static final String PROPERTYMAP_FIELD_NAME = "$nasgenmap$"; static final String $CLINIT$ = "$clinit$"; - static final String CLINIT = ""; - static final String INIT = ""; - static final String DEFAULT_INIT_DESC = Type.getMethodDescriptor(Type.VOID_TYPE); - static final String SCRIPTOBJECT_INIT_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_PROPERTYMAP); + // AccessorProperty + static final String ACCESSORPROPERTY_TYPE = TYPE_ACCESSORPROPERTY.getInternalName(); + static final String ACCESSORPROPERTY_CREATE = "create"; + static final String ACCESSORPROPERTY_CREATE_DESC = + Type.getMethodDescriptor(TYPE_ACCESSORPROPERTY, TYPE_STRING, Type.INT_TYPE, TYPE_METHODHANDLE, TYPE_METHODHANDLE); - static final String METHODHANDLE_TYPE = TYPE_METHODHANDLE.getInternalName(); + // PropertyMap + static final String PROPERTYMAP_TYPE = TYPE_PROPERTYMAP.getInternalName(); + static final String PROPERTYMAP_DESC = TYPE_PROPERTYMAP.getDescriptor(); + static final String PROPERTYMAP_NEWMAP = "newMap"; + static final String PROPERTYMAP_NEWMAP_DESC = Type.getMethodDescriptor(TYPE_PROPERTYMAP, TYPE_COLLECTION); + static final String PROPERTYMAP_DUPLICATE = "duplicate"; + static final String PROPERTYMAP_DUPLICATE_DESC = Type.getMethodDescriptor(TYPE_PROPERTYMAP); + static final String PROPERTYMAP_SETISSHARED = "setIsShared"; + static final String PROPERTYMAP_SETISSHARED_DESC = Type.getMethodDescriptor(TYPE_PROPERTYMAP); - static final String OBJECT_TYPE = TYPE_OBJECT.getInternalName(); - static final String OBJECT_DESC = TYPE_OBJECT.getDescriptor(); - static final String OBJECT_ARRAY_DESC = Type.getDescriptor(Object[].class); + // PrototypeObject + static final String PROTOTYPEOBJECT_TYPE = TYPE_PROTOTYPEOBJECT.getInternalName(); + static final String PROTOTYPEOBJECT_SETCONSTRUCTOR = "setConstructor"; + static final String PROTOTYPEOBJECT_SETCONSTRUCTOR_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_OBJECT, TYPE_OBJECT); + // ScriptFunction static final String SCRIPTFUNCTION_TYPE = TYPE_SCRIPTFUNCTION.getInternalName(); + static final String SCRIPTFUNCTION_SETARITY = "setArity"; + static final String SCRIPTFUNCTION_SETARITY_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE); + static final String SCRIPTFUNCTION_SETPROTOTYPE = "setPrototype"; + static final String SCRIPTFUNCTION_SETPROTOTYPE_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_OBJECT); + + // ScriptFunctionImpl static final String SCRIPTFUNCTIONIMPL_TYPE = TYPE_SCRIPTFUNCTIONIMPL.getInternalName(); static final String SCRIPTFUNCTIONIMPL_MAKEFUNCTION = "makeFunction"; static final String SCRIPTFUNCTIONIMPL_MAKEFUNCTION_DESC = Type.getMethodDescriptor(TYPE_SCRIPTFUNCTION, TYPE_STRING, TYPE_METHODHANDLE); static final String SCRIPTFUNCTIONIMPL_MAKEFUNCTION_SPECS_DESC = Type.getMethodDescriptor(TYPE_SCRIPTFUNCTION, TYPE_STRING, TYPE_METHODHANDLE, TYPE_METHODHANDLE_ARRAY); - static final String SCRIPTFUNCTIONIMPL_INIT_DESC3 = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_STRING, TYPE_METHODHANDLE, TYPE_METHODHANDLE_ARRAY); static final String SCRIPTFUNCTIONIMPL_INIT_DESC4 = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_STRING, TYPE_METHODHANDLE, TYPE_PROPERTYMAP, TYPE_METHODHANDLE_ARRAY); - static final String SCRIPTFUNCTION_SETARITY = "setArity"; - static final String SCRIPTFUNCTION_SETARITY_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE); - static final String SCRIPTFUNCTION_SETPROTOTYPE = "setPrototype"; - static final String SCRIPTFUNCTION_SETPROTOTYPE_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_OBJECT); - static final String PROTOTYPEOBJECT_TYPE = TYPE_PROTOTYPEOBJECT.getInternalName(); - static final String PROTOTYPEOBJECT_SETCONSTRUCTOR = "setConstructor"; - static final String PROTOTYPEOBJECT_SETCONSTRUCTOR_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_OBJECT, TYPE_OBJECT); + + // ScriptObject static final String SCRIPTOBJECT_TYPE = TYPE_SCRIPTOBJECT.getInternalName(); - static final String MAP_TYPE = TYPE_PROPERTYMAP.getInternalName(); - static final String MAP_DESC = TYPE_PROPERTYMAP.getDescriptor(); - static final String MAP_NEWMAP = "newMap"; - static final String MAP_NEWMAP_DESC = Type.getMethodDescriptor(TYPE_PROPERTYMAP); - static final String MAP_DUPLICATE = "duplicate"; - static final String MAP_DUPLICATE_DESC = Type.getMethodDescriptor(TYPE_PROPERTYMAP); - static final String LOOKUP_TYPE = TYPE_LOOKUP.getInternalName(); - static final String LOOKUP_NEWPROPERTY = "newProperty"; - static final String LOOKUP_NEWPROPERTY_DESC = - Type.getMethodDescriptor(TYPE_PROPERTYMAP, TYPE_PROPERTYMAP, TYPE_STRING, Type.INT_TYPE, TYPE_METHODHANDLE, TYPE_METHODHANDLE); + static final String SCRIPTOBJECT_INIT_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_PROPERTYMAP); + static final String GETTER_PREFIX = "G$"; static final String SETTER_PREFIX = "S$"; diff --git a/nashorn/make/code_coverage.xml b/nashorn/make/code_coverage.xml index 3e2860f8d9d..dea03099e36 100644 --- a/nashorn/make/code_coverage.xml +++ b/nashorn/make/code_coverage.xml @@ -60,16 +60,8 @@ - - - - - - - - diff --git a/nashorn/make/project.properties b/nashorn/make/project.properties index 66bbdbebab7..dbd9efce80c 100644 --- a/nashorn/make/project.properties +++ b/nashorn/make/project.properties @@ -200,6 +200,9 @@ test262-test-sys-prop.test.failed.list.file=${build.dir}/test/failedTests # test262 test frameworks test262-test-sys-prop.test.js.framework=\ + --class-cache-size=0 \ + --no-java \ + --no-typed-arrays \ -timezone=PST \ ${test.script.dir}/test262.js \ ${test262.dir}/test/harness/framework.js \ diff --git a/nashorn/src/jdk/nashorn/internal/lookup/Lookup.java b/nashorn/src/jdk/nashorn/internal/lookup/Lookup.java index a454527aec2..e874cfd7bbe 100644 --- a/nashorn/src/jdk/nashorn/internal/lookup/Lookup.java +++ b/nashorn/src/jdk/nashorn/internal/lookup/Lookup.java @@ -124,44 +124,6 @@ public final class Lookup { throw typeError("strict.getter.setter.poison", ScriptRuntime.safeToString(self)); } - /** - * Create a new {@link Property} - * - * @param map property map - * @param key property key - * @param flags property flags - * @param propertyGetter getter for property if available, null otherwise - * @param propertySetter setter for property if available, null otherwise - * - * @return new property map, representing {@code PropertyMap} with the new property added to it - */ - @SuppressWarnings("fallthrough") - public static PropertyMap newProperty(final PropertyMap map, final String key, final int flags, final MethodHandle propertyGetter, final MethodHandle propertySetter) { - MethodHandle getter = propertyGetter; - MethodHandle setter = propertySetter; - - // TODO: this is temporary code. This code exists to support reflective - // field reader/writer handles generated by "unreflect" lookup. - - switch (getter.type().parameterCount()) { - case 0: - // A static field reader, so drop the 'self' argument. - getter = MH.dropArguments(getter, 0, Object.class); - if (setter != null) { - setter = MH.dropArguments(setter, 0, Object.class); - } - // fall through - case 1: - // standard getter that accepts 'self'. - break; - default: - // Huh!! something wrong.. - throw new IllegalArgumentException("getter/setter has wrong arguments"); - } - - return map.newProperty(key, flags, -1, getter, setter); - } - /** * This method filters primitive return types using JavaScript semantics. For example, * an (int) cast of a double in Java land is not the same thing as invoking toInt32 on it. diff --git a/nashorn/src/jdk/nashorn/internal/objects/ArrayBufferView.java b/nashorn/src/jdk/nashorn/internal/objects/ArrayBufferView.java index 60da65a113a..73969fa5cb1 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/ArrayBufferView.java +++ b/nashorn/src/jdk/nashorn/internal/objects/ArrayBufferView.java @@ -46,14 +46,17 @@ abstract class ArrayBufferView extends ScriptObject { return $nasgenmap$; } - ArrayBufferView(final NativeArrayBuffer buffer, final int byteOffset, final int elementLength) { + private ArrayBufferView(final NativeArrayBuffer buffer, final int byteOffset, final int elementLength, final Global global) { + super(global.getArrayBufferViewMap()); checkConstructorArgs(buffer, byteOffset, elementLength); - final Global global = Global.instance(); - this.setMap(global.getArrayBufferViewMap()); this.setProto(getPrototype(global)); this.setArray(factory().createArrayData(buffer, byteOffset, elementLength)); } + ArrayBufferView(final NativeArrayBuffer buffer, final int byteOffset, final int elementLength) { + this(buffer, byteOffset, elementLength, Global.instance()); + } + private void checkConstructorArgs(final NativeArrayBuffer buffer, final int byteOffset, final int elementLength) { if (byteOffset < 0 || elementLength < 0) { throw new RuntimeException("byteOffset or length must not be negative"); diff --git a/nashorn/src/jdk/nashorn/internal/objects/Global.java b/nashorn/src/jdk/nashorn/internal/objects/Global.java index a92de8e11ee..e54fbb45e6d 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/Global.java +++ b/nashorn/src/jdk/nashorn/internal/objects/Global.java @@ -43,7 +43,6 @@ import java.util.List; import java.util.Map; import jdk.internal.dynalink.linker.GuardedInvocation; import jdk.internal.dynalink.linker.LinkRequest; -import jdk.nashorn.internal.lookup.MethodHandleFactory; import jdk.nashorn.internal.objects.annotations.Attribute; import jdk.nashorn.internal.objects.annotations.Property; import jdk.nashorn.internal.objects.annotations.ScriptClass; @@ -389,6 +388,7 @@ public final class Global extends ScriptObject implements GlobalObject, Scope { private PropertyMap prototypeObjectMap; private PropertyMap objectMap; private PropertyMap functionMap; + private PropertyMap anonymousFunctionMap; private PropertyMap strictFunctionMap; private PropertyMap boundFunctionMap; @@ -409,7 +409,6 @@ public final class Global extends ScriptObject implements GlobalObject, Scope { private static final MethodHandle EXIT = findOwnMH("exit", Object.class, Object.class, Object.class); // initialized by nasgen - @SuppressWarnings("unused") private static PropertyMap $nasgenmap$; /** @@ -418,14 +417,14 @@ public final class Global extends ScriptObject implements GlobalObject, Scope { * @param context the context */ public Global(final Context context) { - this.setContext(context); - this.setIsScope(); /* * Duplicate global's map and use it. This way the initial Map filled * by nasgen (referenced from static field in this class) is retained - * 'as is'. This allows multiple globals to be used within a context. + * 'as is' (as that one is process wide singleton. */ - this.setMap(getMap().duplicate()); + super($nasgenmap$.duplicate()); + this.setContext(context); + this.setIsScope(); final int cacheSize = context.getEnv()._class_cache_size; if (cacheSize > 0) { @@ -1018,6 +1017,10 @@ public final class Global extends ScriptObject implements GlobalObject, Scope { return functionMap; } + PropertyMap getAnonymousFunctionMap() { + return anonymousFunctionMap; + } + PropertyMap getStrictFunctionMap() { return strictFunctionMap; } @@ -1538,7 +1541,7 @@ public final class Global extends ScriptObject implements GlobalObject, Scope { final ScriptEnvironment env = getContext().getEnv(); // duplicate PropertyMaps of Native* classes - copyInitialMaps(); + copyInitialMaps(env); // initialize Function and Object constructor initFunctionAndObject(); @@ -1599,12 +1602,16 @@ public final class Global extends ScriptObject implements GlobalObject, Scope { initErrorObjects(); // java access - initJavaAccess(); + if (! env._no_java) { + initJavaAccess(); + } - initTypedArray(); + if (! env._no_typed_arrays) { + initTypedArray(); + } if (env._scripting) { - initScripting(); + initScripting(env); } if (Context.DEBUG && System.getSecurityManager() == null) { @@ -1685,7 +1692,7 @@ public final class Global extends ScriptObject implements GlobalObject, Scope { this.builtinJavaApi = initConstructor("Java"); } - private void initScripting() { + private void initScripting(final ScriptEnvironment scriptEnv) { Object value; value = ScriptFunctionImpl.makeFunction("readLine", ScriptingFunctions.READLINE); addOwnProperty("readLine", Attribute.NOT_ENUMERABLE, value); @@ -1704,7 +1711,6 @@ public final class Global extends ScriptObject implements GlobalObject, Scope { // Nashorn extension: global.$OPTIONS (scripting-mode-only) final ScriptObject options = newObject(); - final ScriptEnvironment scriptEnv = getContext().getEnv(); copyOptions(options, scriptEnv); addOwnProperty("$OPTIONS", Attribute.NOT_ENUMERABLE, options); @@ -1857,20 +1863,17 @@ public final class Global extends ScriptObject implements GlobalObject, Scope { } } - private void copyInitialMaps() { + private void copyInitialMaps(final ScriptEnvironment env) { this.accessorPropertyDescriptorMap = AccessorPropertyDescriptor.getInitialMap().duplicate(); - this.arrayBufferViewMap = ArrayBufferView.getInitialMap().duplicate(); this.dataPropertyDescriptorMap = DataPropertyDescriptor.getInitialMap().duplicate(); this.genericPropertyDescriptorMap = GenericPropertyDescriptor.getInitialMap().duplicate(); this.nativeArgumentsMap = NativeArguments.getInitialMap().duplicate(); this.nativeArrayMap = NativeArray.getInitialMap().duplicate(); - this.nativeArrayBufferMap = NativeArrayBuffer.getInitialMap().duplicate(); this.nativeBooleanMap = NativeBoolean.getInitialMap().duplicate(); this.nativeDateMap = NativeDate.getInitialMap().duplicate(); this.nativeErrorMap = NativeError.getInitialMap().duplicate(); this.nativeEvalErrorMap = NativeEvalError.getInitialMap().duplicate(); this.nativeJSAdapterMap = NativeJSAdapter.getInitialMap().duplicate(); - this.nativeJavaImporterMap = NativeJavaImporter.getInitialMap().duplicate(); this.nativeNumberMap = NativeNumber.getInitialMap().duplicate(); this.nativeRangeErrorMap = NativeRangeError.getInitialMap().duplicate(); this.nativeReferenceErrorMap = NativeReferenceError.getInitialMap().duplicate(); @@ -1883,9 +1886,21 @@ public final class Global extends ScriptObject implements GlobalObject, Scope { this.nativeURIErrorMap = NativeURIError.getInitialMap().duplicate(); this.prototypeObjectMap = PrototypeObject.getInitialMap().duplicate(); this.objectMap = JO.getInitialMap().duplicate(); - this.functionMap = ScriptFunctionImpl.getInitialMap(); + this.functionMap = ScriptFunctionImpl.getInitialMap().duplicate(); + this.anonymousFunctionMap = ScriptFunctionImpl.getInitialAnonymousMap().duplicate(); this.strictFunctionMap = ScriptFunctionImpl.getInitialStrictMap().duplicate(); this.boundFunctionMap = ScriptFunctionImpl.getInitialBoundMap().duplicate(); + + // java + if (! env._no_java) { + this.nativeJavaImporterMap = NativeJavaImporter.getInitialMap().duplicate(); + } + + // typed arrays + if (! env._no_typed_arrays) { + this.arrayBufferViewMap = ArrayBufferView.getInitialMap().duplicate(); + this.nativeArrayBufferMap = NativeArrayBuffer.getInitialMap().duplicate(); + } } // Function and Object constructors are inter-dependent. Also, @@ -1899,7 +1914,7 @@ public final class Global extends ScriptObject implements GlobalObject, Scope { this.builtinFunction = (ScriptFunction)initConstructor("Function"); // create global anonymous function - final ScriptFunction anon = ScriptFunctionImpl.newAnonymousFunction(); + final ScriptFunction anon = ScriptFunctionImpl.newAnonymousFunction(this); // need to copy over members of Function.prototype to anon function anon.addBoundProperties(getFunctionPrototype()); diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeArguments.java b/nashorn/src/jdk/nashorn/internal/objects/NativeArguments.java index 4a5b5986197..3bd74d523d8 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeArguments.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeArguments.java @@ -31,8 +31,10 @@ import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; +import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; +import jdk.nashorn.internal.runtime.AccessorProperty; import jdk.nashorn.internal.runtime.Property; import jdk.nashorn.internal.runtime.PropertyDescriptor; import jdk.nashorn.internal.runtime.PropertyMap; @@ -41,8 +43,6 @@ import jdk.nashorn.internal.runtime.ScriptObject; import jdk.nashorn.internal.runtime.ScriptRuntime; import jdk.nashorn.internal.runtime.arrays.ArrayData; import jdk.nashorn.internal.runtime.arrays.ArrayIndex; -import jdk.nashorn.internal.lookup.Lookup; -import jdk.nashorn.internal.lookup.MethodHandleFactory; /** * ECMA 10.6 Arguments Object. @@ -64,10 +64,10 @@ public final class NativeArguments extends ScriptObject { private static final PropertyMap map$; static { - PropertyMap map = PropertyMap.newMap(); - map = Lookup.newProperty(map, "length", Property.NOT_ENUMERABLE, G$LENGTH, S$LENGTH); - map = Lookup.newProperty(map, "callee", Property.NOT_ENUMERABLE, G$CALLEE, S$CALLEE); - map$ = map; + final ArrayList properties = new ArrayList<>(2); + properties.add(AccessorProperty.create("length", Property.NOT_ENUMERABLE, G$LENGTH, S$LENGTH)); + properties.add(AccessorProperty.create("callee", Property.NOT_ENUMERABLE, G$CALLEE, S$CALLEE)); + map$ = PropertyMap.newMap(properties).setIsShared(); } static PropertyMap getInitialMap() { diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeBoolean.java b/nashorn/src/jdk/nashorn/internal/objects/NativeBoolean.java index 962086c491e..bb57cc71a39 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeBoolean.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeBoolean.java @@ -40,7 +40,6 @@ import jdk.nashorn.internal.runtime.JSType; import jdk.nashorn.internal.runtime.PropertyMap; import jdk.nashorn.internal.runtime.ScriptObject; import jdk.nashorn.internal.runtime.ScriptRuntime; -import jdk.nashorn.internal.lookup.MethodHandleFactory; import jdk.nashorn.internal.runtime.linker.PrimitiveLookup; /** diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeDebug.java b/nashorn/src/jdk/nashorn/internal/objects/NativeDebug.java index 43106eeb7b8..30a4228958e 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeDebug.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeDebug.java @@ -49,6 +49,7 @@ import jdk.nashorn.internal.runtime.linker.LinkerCallSite; public final class NativeDebug extends ScriptObject { // initialized by nasgen + @SuppressWarnings("unused") private static PropertyMap $nasgenmap$; private NativeDebug() { @@ -144,7 +145,7 @@ public final class NativeDebug extends ScriptObject { */ @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) public static Object equals(final Object self, final Object obj1, final Object obj2) { - return (obj1 != null) ? obj1.equals(obj2) : false; + return Objects.equals(obj1, obj2); } /** @@ -176,6 +177,15 @@ public final class NativeDebug extends ScriptObject { return obj.getClass() + "@" + Integer.toHexString(hash); } + /** + * Returns the property listener count for a script object + * @return listener count + */ + @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) + public static Object getListenerCount(final Object self, final Object obj) { + return (obj instanceof ScriptObject)? ((ScriptObject)obj).getListenerCount() : 0; + } + /** * Dump all Nashorn debug mode counters. Calling this may be better if * you want to print all counters. This way you can avoid too many callsites @@ -197,6 +207,8 @@ public final class NativeDebug extends ScriptObject { out.println("ScriptFunction allocations " + ScriptFunction.getAllocations()); out.println("PropertyMap count " + PropertyMap.getCount()); out.println("PropertyMap cloned " + PropertyMap.getClonedCount()); + out.println("PropertyMap shared " + PropertyMap.getSharedCount()); + out.println("PropertyMap duplicated " + PropertyMap.getDuplicatedCount()); out.println("PropertyMap history hit " + PropertyMap.getHistoryHit()); out.println("PropertyMap proto invalidations " + PropertyMap.getProtoInvalidations()); out.println("PropertyMap proto history hit " + PropertyMap.getProtoHistoryHit()); diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeError.java b/nashorn/src/jdk/nashorn/internal/objects/NativeError.java index 0f233f18b17..dc6aef906d9 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeError.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeError.java @@ -31,7 +31,6 @@ import static jdk.nashorn.internal.lookup.Lookup.MH; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import jdk.nashorn.api.scripting.NashornException; -import jdk.nashorn.internal.lookup.MethodHandleFactory; import jdk.nashorn.internal.objects.annotations.Attribute; import jdk.nashorn.internal.objects.annotations.Constructor; import jdk.nashorn.internal.objects.annotations.Function; diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeJSAdapter.java b/nashorn/src/jdk/nashorn/internal/objects/NativeJSAdapter.java index 8e98f4e1825..1fda3767874 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeJSAdapter.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeJSAdapter.java @@ -48,7 +48,6 @@ import jdk.nashorn.internal.runtime.ScriptObject; import jdk.nashorn.internal.runtime.ScriptRuntime; import jdk.nashorn.internal.runtime.arrays.ArrayLikeIterator; import jdk.nashorn.internal.lookup.Lookup; -import jdk.nashorn.internal.lookup.MethodHandleFactory; import jdk.nashorn.internal.scripts.JO; /** diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeJSON.java b/nashorn/src/jdk/nashorn/internal/objects/NativeJSON.java index 0fdb170f44b..863d531bda9 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeJSON.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeJSON.java @@ -60,6 +60,7 @@ public final class NativeJSON extends ScriptObject { ScriptFunction.class, ScriptObject.class, Object.class, Object.class); // initialized by nasgen + @SuppressWarnings("unused") private static PropertyMap $nasgenmap$; private NativeJSON() { diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeMath.java b/nashorn/src/jdk/nashorn/internal/objects/NativeMath.java index c952bd1d295..cc50fbb4f00 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeMath.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeMath.java @@ -43,6 +43,7 @@ import jdk.nashorn.internal.runtime.ScriptObject; public final class NativeMath extends ScriptObject { // initialized by nasgen + @SuppressWarnings("unused") private static PropertyMap $nasgenmap$; private NativeMath() { diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeStrictArguments.java b/nashorn/src/jdk/nashorn/internal/objects/NativeStrictArguments.java index df2d17dd054..de6e4b51435 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeStrictArguments.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeStrictArguments.java @@ -30,14 +30,14 @@ import static jdk.nashorn.internal.lookup.Lookup.MH; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; +import java.util.ArrayList; import java.util.Arrays; +import jdk.nashorn.internal.runtime.AccessorProperty; import jdk.nashorn.internal.runtime.Property; import jdk.nashorn.internal.runtime.PropertyMap; import jdk.nashorn.internal.runtime.ScriptFunction; import jdk.nashorn.internal.runtime.ScriptObject; import jdk.nashorn.internal.runtime.arrays.ArrayData; -import jdk.nashorn.internal.lookup.Lookup; -import jdk.nashorn.internal.lookup.MethodHandleFactory; /** * ECMA 10.6 Arguments Object. @@ -54,14 +54,15 @@ public final class NativeStrictArguments extends ScriptObject { private static final PropertyMap map$; static { - PropertyMap map = PropertyMap.newMap(); - map = Lookup.newProperty(map, "length", Property.NOT_ENUMERABLE, G$LENGTH, S$LENGTH); + final ArrayList properties = new ArrayList<>(1); + properties.add(AccessorProperty.create("length", Property.NOT_ENUMERABLE, G$LENGTH, S$LENGTH)); + PropertyMap map = PropertyMap.newMap(properties); // In strict mode, the caller and callee properties should throw TypeError // Need to add properties directly to map since slots are assigned speculatively by newUserAccessors. final int flags = Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE; map = map.addProperty(map.newUserAccessors("caller", flags)); map = map.addProperty(map.newUserAccessors("callee", flags)); - map$ = map; + map$ = map.setIsShared(); } static PropertyMap getInitialMap() { diff --git a/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java b/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java index 64af421598f..837fee8b789 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java +++ b/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java @@ -30,12 +30,12 @@ import static jdk.nashorn.internal.lookup.Lookup.MH; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import jdk.nashorn.internal.runtime.AccessorProperty; import jdk.nashorn.internal.runtime.Property; import jdk.nashorn.internal.runtime.PropertyMap; import jdk.nashorn.internal.runtime.ScriptFunction; import jdk.nashorn.internal.runtime.ScriptObject; -import jdk.nashorn.internal.lookup.Lookup; -import jdk.nashorn.internal.lookup.MethodHandleFactory; /** * Instances of this class serve as "prototype" object for script functions. @@ -52,9 +52,9 @@ public class PrototypeObject extends ScriptObject { private static final MethodHandle SET_CONSTRUCTOR = findOwnMH("setConstructor", void.class, Object.class, Object.class); static { - PropertyMap map = PropertyMap.newMap(); - map = Lookup.newProperty(map, "constructor", Property.NOT_ENUMERABLE, GET_CONSTRUCTOR, SET_CONSTRUCTOR); - map$ = map; + final ArrayList properties = new ArrayList<>(1); + properties.add(AccessorProperty.create("constructor", Property.NOT_ENUMERABLE, GET_CONSTRUCTOR, SET_CONSTRUCTOR)); + map$ = PropertyMap.newMap(properties).setIsShared(); } static PropertyMap getInitialMap() { diff --git a/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java b/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java index 921073d4484..643d9acddf3 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java +++ b/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java @@ -28,6 +28,7 @@ package jdk.nashorn.internal.objects; import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED; import java.lang.invoke.MethodHandle; +import java.util.ArrayList; import jdk.nashorn.internal.runtime.GlobalFunctions; import jdk.nashorn.internal.runtime.Property; import jdk.nashorn.internal.runtime.PropertyMap; @@ -36,6 +37,7 @@ import jdk.nashorn.internal.runtime.ScriptFunction; import jdk.nashorn.internal.runtime.ScriptFunctionData; import jdk.nashorn.internal.runtime.ScriptObject; import jdk.nashorn.internal.lookup.Lookup; +import jdk.nashorn.internal.runtime.AccessorProperty; /** * Concrete implementation of ScriptFunction. This sets correct map for the @@ -57,6 +59,10 @@ public class ScriptFunctionImpl extends ScriptFunction { return map$; } + static PropertyMap getInitialAnonymousMap() { + return AnonymousFunction.getInitialMap(); + } + static PropertyMap getInitialStrictMap() { return strictmodemap$; } @@ -149,13 +155,18 @@ public class ScriptFunctionImpl extends ScriptFunction { } static { - PropertyMap map = PropertyMap.newMap(); - map = Lookup.newProperty(map, "prototype", Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE, G$PROTOTYPE, S$PROTOTYPE); - map = Lookup.newProperty(map, "length", Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE | Property.NOT_WRITABLE, G$LENGTH, null); - map = Lookup.newProperty(map, "name", Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE | Property.NOT_WRITABLE, G$NAME, null); - map$ = map; + final ArrayList properties = new ArrayList<>(3); + properties.add(AccessorProperty.create("prototype", Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE, G$PROTOTYPE, S$PROTOTYPE)); + properties.add(AccessorProperty.create("length", Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE | Property.NOT_WRITABLE, G$LENGTH, null)); + properties.add(AccessorProperty.create("name", Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE | Property.NOT_WRITABLE, G$NAME, null)); + map$ = PropertyMap.newMap(properties); strictmodemap$ = createStrictModeMap(map$); boundfunctionmap$ = createBoundFunctionMap(strictmodemap$); + // There are order dependencies between normal map, struct map and bound map + // We can make these 'shared' only after initialization of all three. + map$.setIsShared(); + strictmodemap$.setIsShared(); + boundfunctionmap$.setIsShared(); } // function object representing TypeErrorThrower @@ -201,15 +212,19 @@ public class ScriptFunctionImpl extends ScriptFunction { // Instance of this class is used as global anonymous function which // serves as Function.prototype object. private static class AnonymousFunction extends ScriptFunctionImpl { - private static final PropertyMap nasgenmap$$ = PropertyMap.newMap(); + private static final PropertyMap map$ = PropertyMap.newMap().setIsShared(); - AnonymousFunction() { - super("", GlobalFunctions.ANONYMOUS, nasgenmap$$, null); + static PropertyMap getInitialMap() { + return map$; + } + + AnonymousFunction(final Global global) { + super("", GlobalFunctions.ANONYMOUS, global.getAnonymousFunctionMap(), null); } } - static ScriptFunctionImpl newAnonymousFunction() { - return new AnonymousFunction(); + static ScriptFunctionImpl newAnonymousFunction(final Global global) { + return new AnonymousFunction(global); } /** diff --git a/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java b/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java index 6840d458c4e..f7ece9df533 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java @@ -107,6 +107,20 @@ public class AccessorProperty extends Property { SPILL_ELEMENT_SETTER = MH.filterArguments(MH.arrayElementSetter(Object[].class), 0, spillGetter); } + /** + * Create a new accessor property. Factory method used by nasgen generated code. + * + * @param key {@link Property} key. + * @param propertyFlags {@link Property} flags. + * @param getter {@link Property} get accessor method. + * @param setter {@link Property} set accessor method. + * + * @return New {@link AccessorProperty} created. + */ + public static AccessorProperty create(final String key, final int propertyFlags, final MethodHandle getter, final MethodHandle setter) { + return new AccessorProperty(key, propertyFlags, -1, getter, setter); + } + /** Seed getter for the primitive version of this field (in -Dnashorn.fields.dual=true mode) */ private MethodHandle primitiveGetter; diff --git a/nashorn/src/jdk/nashorn/internal/runtime/Context.java b/nashorn/src/jdk/nashorn/internal/runtime/Context.java index 218be74e3bd..8f00d52127e 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/Context.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/Context.java @@ -253,13 +253,7 @@ public final class Context { this.env = new ScriptEnvironment(options, out, err); this._strict = env._strict; this.appLoader = appLoader; - this.scriptLoader = (ScriptLoader)AccessController.doPrivileged( - new PrivilegedAction() { - @Override - public ClassLoader run() { - return new ScriptLoader(sharedLoader, Context.this); - } - }); + this.scriptLoader = env._loader_per_compile? null : createNewLoader(); this.errors = errors; // if user passed -classpath option, make a class loader with that and set it as diff --git a/nashorn/src/jdk/nashorn/internal/runtime/PropertyListenerManager.java b/nashorn/src/jdk/nashorn/internal/runtime/PropertyListenerManager.java index 34db0cb3877..1ce18b63d8f 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/PropertyListenerManager.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/PropertyListenerManager.java @@ -41,6 +41,7 @@ public class PropertyListenerManager implements PropertyListener { private static int listenersRemoved; /** + * Return aggregate listeners added to all PropertyListenerManagers * @return the listenersAdded */ public static int getListenersAdded() { @@ -48,12 +49,21 @@ public class PropertyListenerManager implements PropertyListener { } /** + * Return aggregate listeners removed from all PropertyListenerManagers * @return the listenersRemoved */ public static int getListenersRemoved() { return listenersRemoved; } + /** + * Return listeners added to this PropertyListenerManager. + * @return the listener count + */ + public final int getListenerCount() { + return listeners != null? listeners.size() : 0; + } + // Property listener management methods /** diff --git a/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java b/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java index f8d9b437c07..05e8dc78235 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java @@ -25,11 +25,8 @@ package jdk.nashorn.internal.runtime; -import jdk.nashorn.internal.scripts.JO; - import static jdk.nashorn.internal.runtime.PropertyHashMap.EMPTY_HASHMAP; -import java.lang.invoke.MethodHandle; import java.lang.invoke.SwitchPoint; import java.lang.ref.WeakReference; import java.util.Arrays; @@ -57,9 +54,8 @@ public final class PropertyMap implements Iterable, PropertyListener { private static final int CLONEABLE_FLAGS_MASK = 0b0000_1111; /** Has a listener been added to this property map. This flag is not copied when cloning a map. See {@link PropertyListener} */ public static final int IS_LISTENER_ADDED = 0b0001_0000; - - /** Empty map used for seed map for JO$ objects */ - private static final PropertyMap EMPTY_MAP = new PropertyMap(EMPTY_HASHMAP); + /** Is this process wide "shared" map?. This flag is not copied when cloning a map */ + public static final int IS_SHARED = 0b0010_0000; /** Map status flags. */ private int flags; @@ -145,16 +141,17 @@ public final class PropertyMap implements Iterable, PropertyListener { } /** - * Duplicates this PropertyMap instance. This is used by nasgen generated - * prototype and constructor classes. {@link PropertyMap} used for singletons - * like these (and global instance) are duplicated using this method and used. - * The original filled map referenced by static fields of prototype and - * constructor classes are not touched. This allows multiple independent global - * instances to be used within a single context instance. + * Duplicates this PropertyMap instance. This is used to duplicate 'shared' + * maps {@link PropertyMap} used as process wide singletons. Shared maps are + * duplicated for every global scope object. That way listeners, proto and property + * histories are scoped within a global scope. * * @return Duplicated {@link PropertyMap}. */ public PropertyMap duplicate() { + if (Context.DEBUG) { + duplicatedCount++; + } return new PropertyMap(this.properties); } @@ -172,6 +169,15 @@ public final class PropertyMap implements Iterable, PropertyListener { return new PropertyMap(newProperties, fieldCount, fieldMaximum, spillLength); } + /** + * Public property map allocator. Used by nasgen generated code. + * @param properties Collection of initial properties. + * @return New {@link PropertyMap}. + */ + public static PropertyMap newMap(final Collection properties) { + return (properties == null || properties.isEmpty())? newMap() : newMap(properties, 0, 0, 0); + } + /** * Return a sharable empty map. * @@ -199,6 +205,8 @@ public final class PropertyMap implements Iterable, PropertyListener { * @return A shared {@link SwitchPoint} for the property. */ public SwitchPoint getProtoGetSwitchPoint(final ScriptObject proto, final String key) { + assert !isShared() : "proto SwitchPoint from a shared PropertyMap"; + if (proto == null) { return null; } @@ -227,6 +235,8 @@ public final class PropertyMap implements Iterable, PropertyListener { * @param property {@link Property} to invalidate. */ private void invalidateProtoGetSwitchPoint(final Property property) { + assert !isShared() : "proto invalidation on a shared PropertyMap"; + if (protoGetSwitches != null) { final String key = property.getKey(); final SwitchPoint sp = protoGetSwitches.get(key); @@ -240,17 +250,6 @@ public final class PropertyMap implements Iterable, PropertyListener { } } - /** - * Add a property to the map. - * - * @param property {@link Property} being added. - * - * @return New {@link PropertyMap} with {@link Property} added. - */ - public PropertyMap newProperty(final Property property) { - return addProperty(property); - } - /** * Add a property to the map, re-binding its getters and setters, * if available, to a given receiver. This is typically the global scope. See @@ -261,23 +260,8 @@ public final class PropertyMap implements Iterable, PropertyListener { * * @return New {@link PropertyMap} with {@link Property} added. */ - PropertyMap newPropertyBind(final AccessorProperty property, final ScriptObject bindTo) { - return newProperty(new AccessorProperty(property, bindTo)); - } - - /** - * Add a new accessor property to the map. - * - * @param key {@link Property} key. - * @param propertyFlags {@link Property} flags. - * @param slot {@link Property} slot. - * @param getter {@link Property} get accessor method. - * @param setter {@link Property} set accessor method. - * - * @return New {@link PropertyMap} with {@link AccessorProperty} added. - */ - public PropertyMap newProperty(final String key, final int propertyFlags, final int slot, final MethodHandle getter, final MethodHandle setter) { - return newProperty(new AccessorProperty(key, propertyFlags, slot, getter, setter)); + PropertyMap addPropertyBind(final AccessorProperty property, final ScriptObject bindTo) { + return addProperty(new AccessorProperty(property, bindTo)); } /** @@ -478,6 +462,28 @@ public final class PropertyMap implements Iterable, PropertyListener { return newMap; } + /** + * Make this property map 'shared' one. Shared property map instances are + * process wide singleton objects. A shaped map should never be added as a listener + * to a proto object. Nor it should have history or proto history. A shared map + * is just a template that is meant to be duplicated before use. All nasgen initialized + * property maps are shared. + * + * @return this map after making it as shared + */ + public PropertyMap setIsShared() { + assert !isListenerAdded() : "making PropertyMap shared after listener added"; + assert protoHistory == null : "making PropertyMap shared after associating a proto with it"; + if (Context.DEBUG) { + sharedCount++; + } + + flags |= IS_SHARED; + // clear any history on this PropertyMap, won't be used. + history = null; + return this; + } + /** * Check for any configurable properties. * @@ -544,6 +550,8 @@ public final class PropertyMap implements Iterable, PropertyListener { * @param newMap {@link PropertyMap} associated with prototype. */ private void addToProtoHistory(final ScriptObject newProto, final PropertyMap newMap) { + assert !isShared() : "proto history modified on a shared PropertyMap"; + if (protoHistory == null) { protoHistory = new WeakHashMap<>(); } @@ -558,6 +566,8 @@ public final class PropertyMap implements Iterable, PropertyListener { * @param newMap Modified {@link PropertyMap}. */ private void addToHistory(final Property property, final PropertyMap newMap) { + assert !isShared() : "history modified on a shared PropertyMap"; + if (!properties.isEmpty()) { if (history == null) { history = new LinkedHashMap<>(); @@ -682,6 +692,15 @@ public final class PropertyMap implements Iterable, PropertyListener { return (flags & IS_LISTENER_ADDED) != 0; } + /** + * Check if this map shared or not. + * + * @return true if this map is shared. + */ + public boolean isShared() { + return (flags & IS_SHARED) != 0; + } + /** * Test to see if {@link PropertyMap} is extensible. * @@ -745,6 +764,8 @@ public final class PropertyMap implements Iterable, PropertyListener { * @return New {@link PropertyMap} with prototype changed. */ PropertyMap changeProto(final ScriptObject oldProto, final ScriptObject newProto) { + assert !isShared() : "proto associated with a shared PropertyMap"; + if (oldProto == newProto) { return this; } @@ -860,6 +881,8 @@ public final class PropertyMap implements Iterable, PropertyListener { // counters updated only in debug mode private static int count; private static int clonedCount; + private static int sharedCount; + private static int duplicatedCount; private static int historyHit; private static int protoInvalidations; private static int protoHistoryHit; @@ -879,6 +902,20 @@ public final class PropertyMap implements Iterable, PropertyListener { return clonedCount; } + /** + * @return The number of maps that are shared. + */ + public static int getSharedCount() { + return sharedCount; + } + + /** + * @return The number of maps that are duplicated. + */ + public static int getDuplicatedCount() { + return duplicatedCount; + } + /** * @return The number of times history was successfully used. */ diff --git a/nashorn/src/jdk/nashorn/internal/runtime/ScriptEnvironment.java b/nashorn/src/jdk/nashorn/internal/runtime/ScriptEnvironment.java index f04dedf05c9..a2f1f4a0880 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptEnvironment.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptEnvironment.java @@ -119,9 +119,15 @@ public final class ScriptEnvironment { /** Create a new class loaded for each compilation */ public final boolean _loader_per_compile; + /** Do not support Java support extensions. */ + public final boolean _no_java; + /** Do not support non-standard syntax extensions. */ public final boolean _no_syntax_extensions; + /** Do not support typed arrays. */ + public final boolean _no_typed_arrays; + /** Package to which generated class files are added */ public final String _package; @@ -207,7 +213,9 @@ public final class ScriptEnvironment { _fx = options.getBoolean("fx"); _lazy_compilation = options.getBoolean("lazy.compilation"); _loader_per_compile = options.getBoolean("loader.per.compile"); + _no_java = options.getBoolean("no.java"); _no_syntax_extensions = options.getBoolean("no.syntax.extensions"); + _no_typed_arrays = options.getBoolean("no.typed.arrays"); _package = options.getString("package"); _parse_only = options.getBoolean("parse.only"); _print_ast = options.getBoolean("print.ast"); diff --git a/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java b/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java index e4eaf77e581..c56c32c7257 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java @@ -213,7 +213,7 @@ public abstract class ScriptObject extends PropertyListenerManager implements Pr final UserAccessorProperty prop = this.newUserAccessors(key, property.getFlags(), property.getGetterFunction(source), property.getSetterFunction(source)); newMap = newMap.addProperty(prop); } else { - newMap = newMap.newPropertyBind((AccessorProperty)property, source); + newMap = newMap.addPropertyBind((AccessorProperty)property, source); } } } diff --git a/nashorn/src/jdk/nashorn/internal/runtime/resources/Options.properties b/nashorn/src/jdk/nashorn/internal/runtime/resources/Options.properties index 4d7be62b2de..452ae88c928 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/resources/Options.properties +++ b/nashorn/src/jdk/nashorn/internal/runtime/resources/Options.properties @@ -192,6 +192,14 @@ nashorn.option.loader.per.compile = { \ default=true \ } +nashorn.option.no.java = { \ + name="--no-java", \ + short_name="-nj", \ + is_undocumented=true, \ + desc="No Java support", \ + default=false \ +} + nashorn.option.no.syntax.extensions = { \ name="--no-syntax-extensions", \ short_name="-nse", \ @@ -200,6 +208,14 @@ nashorn.option.no.syntax.extensions = { \ default=false \ } +nashorn.option.no.typed.arrays = { \ + name="--no-typed-arrays", \ + short_name="-nta", \ + is_undocumented=true, \ + desc="No Typed arrays support", \ + default=false \ +} + nashorn.option.package = { \ name="--package", \ is_undocumented=true, \ diff --git a/nashorn/src/jdk/nashorn/internal/scripts/JO.java b/nashorn/src/jdk/nashorn/internal/scripts/JO.java index d6173918933..f2f000625d9 100644 --- a/nashorn/src/jdk/nashorn/internal/scripts/JO.java +++ b/nashorn/src/jdk/nashorn/internal/scripts/JO.java @@ -33,7 +33,7 @@ import jdk.nashorn.internal.runtime.ScriptObject; */ public class JO extends ScriptObject { - private static final PropertyMap map$ = PropertyMap.newMap(); + private static final PropertyMap map$ = PropertyMap.newMap().setIsShared(); /** * Returns the initial property map to be used. diff --git a/nashorn/src/jdk/nashorn/tools/Shell.java b/nashorn/src/jdk/nashorn/tools/Shell.java index 914c7b6e5cc..55840078e64 100644 --- a/nashorn/src/jdk/nashorn/tools/Shell.java +++ b/nashorn/src/jdk/nashorn/tools/Shell.java @@ -435,6 +435,10 @@ public class Shell { break; } + if (source.isEmpty()) { + continue; + } + Object res; try { res = context.eval(global, source, global, "", env._strict); From 1e0c0dc73ec40a8ec91e881e47682a5ab418a472 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Mon, 8 Jul 2013 18:36:10 +0530 Subject: [PATCH 071/123] 8020035: nashorn jdk buildfile BuildNashorn.gmk still renamed jdk.nashorn.internal.objects package Reviewed-by: attila, jlaskey --- nashorn/makefiles/BuildNashorn.gmk | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/nashorn/makefiles/BuildNashorn.gmk b/nashorn/makefiles/BuildNashorn.gmk index d08f7e8fa6f..96bedf44ac4 100644 --- a/nashorn/makefiles/BuildNashorn.gmk +++ b/nashorn/makefiles/BuildNashorn.gmk @@ -71,7 +71,6 @@ $(eval $(call SetupJavaCompilation,BUILD_NASGEN,\ $(BUILD_NASGEN): $(BUILD_NASHORN) # Copy classes to final classes dir and run nasgen to modify classes in jdk.nashorn.internal.objects package -# Finally rename classes in jdk.nashorn.internal.objects package $(NASHORN_OUTPUTDIR)/classes/_the.nasgen.run: $(BUILD_NASGEN) $(ECHO) Running nasgen $(MKDIR) -p $(@D) @@ -80,9 +79,6 @@ $(NASHORN_OUTPUTDIR)/classes/_the.nasgen.run: $(BUILD_NASGEN) $(FIXPATH) $(JAVA) \ -cp "$(NASHORN_OUTPUTDIR)/nasgen_classes$(PATH_SEP)$(NASHORN_OUTPUTDIR)/nashorn_classes" \ jdk.nashorn.internal.tools.nasgen.Main $(@D) jdk.nashorn.internal.objects $(@D) - for f in `$(FIND) $(@D)/jdk/nashorn/internal/objects/ -name "*.class"`; do \ - mv "$$f" `$(ECHO) "$$f" | $(SED) "s/\.class$$/\.clazz/"`; \ - done $(TOUCH) $@ # Version file needs to be processed with version numbers @@ -104,7 +100,7 @@ $(eval $(call SetupArchive,BUILD_NASHORN_JAR,\ $(NASHORN_OUTPUTDIR)/classes/_the.nasgen.run \ $(VERSION_FILE),\ SRCS:=$(NASHORN_OUTPUTDIR)/classes,\ - SUFFIXES:=.class .clazz .js .properties Factory,\ + SUFFIXES:=.class .js .properties Factory,\ MANIFEST:=$(NASHORN_TOPDIR)/src/META-INF/MANIFEST.MF,\ EXTRA_MANIFEST_ATTR:=$(MANIFEST_ATTRIBUTES),\ SKIP_METAINF:=true,\ From 007e944455c195c9a82efb6f3b61e9b2a2b42ad5 Mon Sep 17 00:00:00 2001 From: Leonid Romanov Date: Mon, 8 Jul 2013 19:47:40 +0400 Subject: [PATCH 072/123] 8019265: [macosx] apple.laf.useScreenMenuBar regression comparing with jdk6 Reviewed-by: anthony --- jdk/src/macosx/native/sun/awt/CMenuItem.m | 9 +++++++-- .../ActionListenerCalledTwiceTest.java | 5 +++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/jdk/src/macosx/native/sun/awt/CMenuItem.m b/jdk/src/macosx/native/sun/awt/CMenuItem.m index eaabb3e06ab..0d1ade68ab6 100644 --- a/jdk/src/macosx/native/sun/awt/CMenuItem.m +++ b/jdk/src/macosx/native/sun/awt/CMenuItem.m @@ -82,8 +82,13 @@ JNF_COCOA_ENTER(env); // 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]) { diff --git a/jdk/test/javax/swing/JMenuItem/ActionListenerCalledTwice/ActionListenerCalledTwiceTest.java b/jdk/test/javax/swing/JMenuItem/ActionListenerCalledTwice/ActionListenerCalledTwiceTest.java index 4cf1c750da5..d9cedf423e6 100644 --- a/jdk/test/javax/swing/JMenuItem/ActionListenerCalledTwice/ActionListenerCalledTwiceTest.java +++ b/jdk/test/javax/swing/JMenuItem/ActionListenerCalledTwice/ActionListenerCalledTwiceTest.java @@ -35,10 +35,11 @@ import java.awt.event.*; import javax.swing.*; public class ActionListenerCalledTwiceTest { - static String menuItems[] = { "Item1", "Item2" }; + static String menuItems[] = { "Item1", "Item2", "Item3" }; static KeyStroke keyStrokes[] = { KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.META_MASK), - KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0) + KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), + KeyStroke.getKeyStroke(KeyEvent.VK_UP, InputEvent.SHIFT_MASK), }; static volatile int listenerCallCounter = 0; From 4e011cfb8c0805708981bbccb01d5e5b42878610 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hannes=20Walln=C3=B6fer?= Date: Mon, 8 Jul 2013 19:34:55 +0200 Subject: [PATCH 073/123] 8019963: empty char range in regex Reviewed-by: jlaskey, sundar --- .../runtime/regexp/joni/CodeRangeBuffer.java | 2 +- .../internal/runtime/regexp/joni/Parser.java | 57 ++-------------- nashorn/test/script/basic/JDK-8019963.js | 66 +++++++++++++++++++ .../test/script/basic/JDK-8019963.js.EXPECTED | 29 ++++++++ 4 files changed, 102 insertions(+), 52 deletions(-) create mode 100644 nashorn/test/script/basic/JDK-8019963.js create mode 100644 nashorn/test/script/basic/JDK-8019963.js.EXPECTED diff --git a/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/CodeRangeBuffer.java b/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/CodeRangeBuffer.java index 87e0f8e1fc3..d6c2a61e23a 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/CodeRangeBuffer.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/CodeRangeBuffer.java @@ -183,7 +183,7 @@ public final class CodeRangeBuffer { // add_code_range, be aware of it returning null! public static CodeRangeBuffer addCodeRange(CodeRangeBuffer pbuf, ScanEnvironment env, int from, int to) { - if (from >to) { + if (from > to) { if (env.syntax.allowEmptyRangeInCC()) { return pbuf; } else { diff --git a/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/Parser.java b/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/Parser.java index 03c99a3c03c..45c8838e5d4 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/Parser.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/Parser.java @@ -125,32 +125,8 @@ class Parser extends Lexer { break; case RAW_BYTE: - if (token.base != 0) { /* tok->base != 0 : octal or hexadec. */ - byte[] buf = new byte[4]; - int psave = p; - int base = token.base; - buf[0] = (byte)token.getC(); - int i; - for (i=1; i<4; i++) { - fetchTokenInCC(); - if (token.type != TokenType.RAW_BYTE || token.base != base) { - fetched = true; - break; - } - buf[i] = (byte)token.getC(); - } - - if (i == 1) { - arg.v = buf[0] & 0xff; - arg.inType = CCVALTYPE.SB; // goto raw_single - } else { - arg.v = EncodingHelper.mbcToCode(buf, 0, buf.length); - arg.inType = CCVALTYPE.CODE_POINT; - } - } else { - arg.v = token.getC(); - arg.inType = CCVALTYPE.SB; // raw_single: - } + arg.v = token.getC(); + arg.inType = CCVALTYPE.SB; // raw_single: arg.vIsRaw = true; parseCharClassValEntry2(cc, arg); // goto val_entry2 break; @@ -615,31 +591,10 @@ class Parser extends Lexer { StringNode node = new StringNode((char)token.getC()); node.setRaw(); - int len = 1; - while (true) { - if (len >= 1) { - if (len == 1) { - fetchToken(); - node.clearRaw(); - // !goto string_end;! - return parseExpRepeat(node, group); - } - } - - fetchToken(); - if (token.type != TokenType.RAW_BYTE) { - /* Don't use this, it is wrong for little endian encodings. */ - // USE_PAD_TO_SHORT_BYTE_CHAR ... - - newValueException(ERR_TOO_SHORT_MULTI_BYTE_STRING); - } - - // important: we don't use 0xff mask here neither in the compiler - // (in the template string) so we won't have to mask target - // strings when comparing against them in the matcher - node.cat((char)token.getC()); - len++; - } // while + fetchToken(); + node.clearRaw(); + // !goto string_end;! + return parseExpRepeat(node, group); } private Node parseExpRepeat(Node target, boolean group) { diff --git a/nashorn/test/script/basic/JDK-8019963.js b/nashorn/test/script/basic/JDK-8019963.js new file mode 100644 index 00000000000..5767a414a49 --- /dev/null +++ b/nashorn/test/script/basic/JDK-8019963.js @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * 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. + */ + +/** + * JDK-8019963: empty char range in regex + * + * @test + * @run + */ + +var re1 = /[\x00-\x08\x0B\x0C\x0E-\x9F\uD800-\uDFFF\uFFFE\uFFFF]/; + +print(re1.test("\x00")); +print(re1.test("\x04")); +print(re1.test("\x08")); +print(re1.test("\x0a")); +print(re1.test("\x0B")); +print(re1.test("\x0C")); +print(re1.test("\x0E")); +print(re1.test("\x10")); +print(re1.test("\x1A")); +print(re1.test("\x2F")); +print(re1.test("\x8E")); +print(re1.test("\x8F")); +print(re1.test("\x9F")); +print(re1.test("\xA0")); +print(re1.test("\xAF")); +print(re1.test("\uD800")); +print(re1.test("\xDA00")); +print(re1.test("\xDCFF")); +print(re1.test("\xDFFF")); +print(re1.test("\xFFFE")); +print(re1.test("\xFFFF")); + +var re2 = /[\x1F\x7F-\x84\x86]/; + +print(re2.test("\x1F")); +print(re2.test("\x2F")); +print(re2.test("\x3F")); +print(re2.test("\x7F")); +print(re2.test("\x80")); +print(re2.test("\x84")); +print(re2.test("\x85")); +print(re2.test("\x86")); + +var re3 = /^([\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})*$/; diff --git a/nashorn/test/script/basic/JDK-8019963.js.EXPECTED b/nashorn/test/script/basic/JDK-8019963.js.EXPECTED new file mode 100644 index 00000000000..ffde31fe38d --- /dev/null +++ b/nashorn/test/script/basic/JDK-8019963.js.EXPECTED @@ -0,0 +1,29 @@ +true +true +true +false +true +true +true +true +true +true +true +true +true +false +false +true +true +true +true +true +true +true +false +false +true +true +true +false +true From 3300eed0bb0f2305736da92f8be6cc6919e4be0d Mon Sep 17 00:00:00 2001 From: Vinnie Ryan Date: Fri, 12 Jul 2013 20:44:34 +0100 Subject: [PATCH 074/123] 8019627: RuntimeException gets obscured during OCSP cert revocation checking Reviewed-by: mullan --- .../provider/certpath/RevocationChecker.java | 8 ++----- .../CertPathValidator/OCSP/FailoverToCRL.java | 24 ++----------------- 2 files changed, 4 insertions(+), 28 deletions(-) diff --git a/jdk/src/share/classes/sun/security/provider/certpath/RevocationChecker.java b/jdk/src/share/classes/sun/security/provider/certpath/RevocationChecker.java index 05b517892fe..98d8a9d2272 100644 --- a/jdk/src/share/classes/sun/security/provider/certpath/RevocationChecker.java +++ b/jdk/src/share/classes/sun/security/provider/certpath/RevocationChecker.java @@ -675,12 +675,8 @@ class RevocationChecker extends PKIXRevocationChecker { responderURI, respCert, params.date(), ocspExtensions); } - } catch (Exception e) { - if (e instanceof CertPathValidatorException) { - throw (CertPathValidatorException) e; - } else { - throw new CertPathValidatorException(e); - } + } catch (IOException e) { + throw new CertPathValidatorException(e); } RevocationStatus rs = diff --git a/jdk/test/java/security/cert/CertPathValidator/OCSP/FailoverToCRL.java b/jdk/test/java/security/cert/CertPathValidator/OCSP/FailoverToCRL.java index 25eaab56eea..29abf024e9f 100644 --- a/jdk/test/java/security/cert/CertPathValidator/OCSP/FailoverToCRL.java +++ b/jdk/test/java/security/cert/CertPathValidator/OCSP/FailoverToCRL.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,7 @@ /** * @test - * @bug 6383095 8019259 + * @bug 6383095 * @summary CRL revoked certificate failures masked by OCSP failures * * Note that the certificate validity is from Mar 16 14:55:35 2009 GMT to @@ -254,32 +254,12 @@ public class FailoverToCRL { CertPathValidator validator = CertPathValidator.getInstance("PKIX"); try { - System.out.println("Validating cert via OCSP: no responder URL"); validator.validate(path, params); } catch (CertPathValidatorException cpve) { if (cpve.getReason() != BasicReason.REVOKED) { throw new Exception( "unexpected exception, should be a REVOKED CPVE", cpve); } - System.out.println(" successful failover to using CRLs"); - } - - java.security.cert.PKIXRevocationChecker revocationChecker = - (java.security.cert.PKIXRevocationChecker) - validator.getRevocationChecker(); - revocationChecker.setOCSPResponder( - new java.net.URI("bad_ocsp_responder_url")); - params.addCertPathChecker(revocationChecker); - - try { - System.out.println("Validating cert via OCSP: bad responder URL"); - validator.validate(path, params); - } catch (CertPathValidatorException cpve) { - if (cpve.getReason() != BasicReason.REVOKED) { - throw new Exception( - "unexpected exception, should be a REVOKED CPVE", cpve); - } - System.out.println(" successful failover to using CRLs"); } } } From ace3a4d196546d2bfaa21f58e50f3222085f880e Mon Sep 17 00:00:00 2001 From: Brian Goetz Date: Fri, 12 Jul 2013 15:01:08 -0700 Subject: [PATCH 075/123] 8015320: Pull spliterator() up from Collection to Iterable Reviewed-by: psandoz, mduigou --- jdk/src/share/classes/java/lang/Iterable.java | 27 +++++++++++++++++++ .../share/classes/java/util/Collection.java | 1 + .../util/ConcurrentModificationException.java | 1 + .../Spliterator/SpliteratorCollisions.java | 9 +++---- ...SpliteratorTraversingAndSplittingTest.java | 15 +++++++++++ 5 files changed, 48 insertions(+), 5 deletions(-) diff --git a/jdk/src/share/classes/java/lang/Iterable.java b/jdk/src/share/classes/java/lang/Iterable.java index 8d46dbfe5ff..fe9086f6874 100644 --- a/jdk/src/share/classes/java/lang/Iterable.java +++ b/jdk/src/share/classes/java/lang/Iterable.java @@ -26,6 +26,8 @@ package java.lang; 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 @@ public interface Iterable { action.accept(t); } } + + /** + * Creates a {@link Spliterator} over the elements described by this + * {@code Iterable}. + * + * @implSpec + * The default implementation creates an + * early-binding + * spliterator from the iterable's {@code Iterator}. The spliterator + * inherits the fail-fast 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 spliterator() { + return Spliterators.spliteratorUnknownSize(iterator(), 0); + } } diff --git a/jdk/src/share/classes/java/util/Collection.java b/jdk/src/share/classes/java/util/Collection.java index d42ba3e8a6e..17ab7347dc0 100644 --- a/jdk/src/share/classes/java/util/Collection.java +++ b/jdk/src/share/classes/java/util/Collection.java @@ -537,6 +537,7 @@ public interface Collection extends Iterable { * @return a {@code Spliterator} over the elements in this collection * @since 1.8 */ + @Override default Spliterator spliterator() { return Spliterators.spliterator(this, 0); } diff --git a/jdk/src/share/classes/java/util/ConcurrentModificationException.java b/jdk/src/share/classes/java/util/ConcurrentModificationException.java index 3683fb399cf..d5256538f04 100644 --- a/jdk/src/share/classes/java/util/ConcurrentModificationException.java +++ b/jdk/src/share/classes/java/util/ConcurrentModificationException.java @@ -57,6 +57,7 @@ package java.util; * @author Josh Bloch * @see Collection * @see Iterator + * @see Spliterator * @see ListIterator * @see Vector * @see LinkedList diff --git a/jdk/test/java/util/Spliterator/SpliteratorCollisions.java b/jdk/test/java/util/Spliterator/SpliteratorCollisions.java index 604d90b9f20..e40ef916d46 100644 --- a/jdk/test/java/util/Spliterator/SpliteratorCollisions.java +++ b/jdk/test/java/util/Spliterator/SpliteratorCollisions.java @@ -48,7 +48,6 @@ import java.util.Spliterator; import java.util.TreeSet; import java.util.function.Consumer; import java.util.function.Function; -import java.util.function.LongConsumer; import java.util.function.Supplier; import java.util.function.UnaryOperator; @@ -677,11 +676,11 @@ public class SpliteratorCollisions { private static Map toBoxedMultiset(Iterable c) { Map result = new HashMap<>(); - c.forEach((Consumer) e -> { - if (result.containsKey((T)e)) { - result.put((T)e, new HashableInteger(((HashableInteger)result.get(e)).value + 1, 10)); + c.forEach(e -> { + if (result.containsKey(e)) { + result.put(e, new HashableInteger(result.get(e).value + 1, 10)); } else { - result.put((T)e, new HashableInteger(1, 10)); + result.put(e, new HashableInteger(1, 10)); } }); return result; diff --git a/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java b/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java index d58c2b9d544..6da6214e1ca 100644 --- a/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java +++ b/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java @@ -321,6 +321,21 @@ public class SpliteratorTraversingAndSplittingTest { db.addCollection( c -> new AbstractSortedSetImpl(c)); + class IterableWrapper implements Iterable { + final Iterable it; + + IterableWrapper(Iterable it) { + this.it = it; + } + + @Override + public Iterator iterator() { + return it.iterator(); + } + } + db.add("new Iterable.spliterator()", + () -> new IterableWrapper(exp).spliterator()); + // db.add("Arrays.asList().spliterator()", From 50a242e51061f9406523fe5fb7d347d67b928be7 Mon Sep 17 00:00:00 2001 From: Brian Goetz Date: Mon, 8 Jul 2013 15:46:26 -0400 Subject: [PATCH 076/123] 8020062: Nest StreamBuilder interfaces inside relevant Stream interfaces Reviewed-by: psandoz, mduigou --- .../java/util/stream/DoubleStream.java | 59 +++- .../classes/java/util/stream/IntStream.java | 59 +++- .../classes/java/util/stream/LongStream.java | 59 +++- .../classes/java/util/stream/Stream.java | 63 ++++- .../java/util/stream/StreamBuilder.java | 265 ------------------ .../classes/java/util/stream/Streams.java | 10 +- .../java/util/stream/StreamBuilderTest.java | 33 ++- 7 files changed, 257 insertions(+), 291 deletions(-) delete mode 100644 jdk/src/share/classes/java/util/stream/StreamBuilder.java diff --git a/jdk/src/share/classes/java/util/stream/DoubleStream.java b/jdk/src/share/classes/java/util/stream/DoubleStream.java index 225de5e03b6..50c9666befd 100644 --- a/jdk/src/share/classes/java/util/stream/DoubleStream.java +++ b/jdk/src/share/classes/java/util/stream/DoubleStream.java @@ -662,7 +662,7 @@ public interface DoubleStream extends BaseStream { * * @return a stream builder */ - public static StreamBuilder.OfDouble builder() { + public static Builder builder() { return new Streams.DoubleStreamBuilderImpl(); } @@ -766,4 +766,61 @@ public interface DoubleStream extends BaseStream { a.spliterator(), b.spliterator()); return StreamSupport.doubleStream(split, a.isParallel() || b.isParallel()); } + + /** + * A mutable builder for a {@code DoubleStream}. + * + *

    A stream builder has a lifecycle, where it starts in a building + * phase, during which elements can be added, and then transitions to a + * built phase, after which elements may not be added. The built phase + * begins when the {@link #build()} method is called, which creates an + * ordered stream whose elements are the elements that were added to the + * stream builder, in the order they were added. + * + * @see DoubleStream#builder() + * @since 1.8 + */ + public interface Builder extends DoubleConsumer { + + /** + * Adds an element to the stream being built. + * + * @throws IllegalStateException if the builder has already transitioned + * to the built state + */ + @Override + void accept(double t); + + /** + * Adds an element to the stream being built. + * + * @implSpec + * The default implementation behaves as if: + *

    {@code
    +         *     accept(t)
    +         *     return this;
    +         * }
    + * + * @param t the element to add + * @return {@code this} builder + * @throws IllegalStateException if the builder has already transitioned + * to the built state + */ + default Builder add(double t) { + accept(t); + return this; + } + + /** + * Builds the stream, transitioning this builder to the built state. + * An {@code IllegalStateException} is thrown if there are further + * attempts to operate on the builder after it has entered the built + * state. + * + * @return the built stream + * @throws IllegalStateException if the builder has already transitioned + * to the built state + */ + DoubleStream build(); + } } diff --git a/jdk/src/share/classes/java/util/stream/IntStream.java b/jdk/src/share/classes/java/util/stream/IntStream.java index 2ef55e15f9c..ce515e992a6 100644 --- a/jdk/src/share/classes/java/util/stream/IntStream.java +++ b/jdk/src/share/classes/java/util/stream/IntStream.java @@ -664,7 +664,7 @@ public interface IntStream extends BaseStream { * * @return a stream builder */ - public static StreamBuilder.OfInt builder() { + public static Builder builder() { return new Streams.IntStreamBuilderImpl(); } @@ -820,4 +820,61 @@ public interface IntStream extends BaseStream { a.spliterator(), b.spliterator()); return StreamSupport.intStream(split, a.isParallel() || b.isParallel()); } + + /** + * A mutable builder for an {@code IntStream}. + * + *

    A stream builder has a lifecycle, where it starts in a building + * phase, during which elements can be added, and then transitions to a + * built phase, after which elements may not be added. The built phase + * begins when the {@link #build()} method is called, which creates an + * ordered stream whose elements are the elements that were added to the + * stream builder, in the order they were added. + * + * @see IntStream#builder() + * @since 1.8 + */ + public interface Builder extends IntConsumer { + + /** + * Adds an element to the stream being built. + * + * @throws IllegalStateException if the builder has already transitioned + * to the built state + */ + @Override + void accept(int t); + + /** + * Adds an element to the stream being built. + * + * @implSpec + * The default implementation behaves as if: + *

    {@code
    +         *     accept(t)
    +         *     return this;
    +         * }
    + * + * @param t the element to add + * @return {@code this} builder + * @throws IllegalStateException if the builder has already transitioned + * to the built state + */ + default Builder add(int t) { + accept(t); + return this; + } + + /** + * Builds the stream, transitioning this builder to the built state. + * An {@code IllegalStateException} is thrown if there are further + * attempts to operate on the builder after it has entered the built + * state. + * + * @return the built stream + * @throws IllegalStateException if the builder has already transitioned to + * the built state + */ + IntStream build(); + } } diff --git a/jdk/src/share/classes/java/util/stream/LongStream.java b/jdk/src/share/classes/java/util/stream/LongStream.java index 8d1c7eae8fd..39c4e1bb7bc 100644 --- a/jdk/src/share/classes/java/util/stream/LongStream.java +++ b/jdk/src/share/classes/java/util/stream/LongStream.java @@ -655,7 +655,7 @@ public interface LongStream extends BaseStream { * * @return a stream builder */ - public static StreamBuilder.OfLong builder() { + public static Builder builder() { return new Streams.LongStreamBuilderImpl(); } @@ -826,4 +826,61 @@ public interface LongStream extends BaseStream { a.spliterator(), b.spliterator()); return StreamSupport.longStream(split, a.isParallel() || b.isParallel()); } + + /** + * A mutable builder for a {@code LongStream}. + * + *

    A stream builder has a lifecycle, where it starts in a building + * phase, during which elements can be added, and then transitions to a + * built phase, after which elements may not be added. The built phase + * begins when the {@link #build()} method is called, which creates an + * ordered stream whose elements are the elements that were added to the + * stream builder, in the order they were added. + * + * @see LongStream#builder() + * @since 1.8 + */ + public interface Builder extends LongConsumer { + + /** + * Adds an element to the stream being built. + * + * @throws IllegalStateException if the builder has already transitioned + * to the built state + */ + @Override + void accept(long t); + + /** + * Adds an element to the stream being built. + * + * @implSpec + * The default implementation behaves as if: + *

    {@code
    +         *     accept(t)
    +         *     return this;
    +         * }
    + * + * @param t the element to add + * @return {@code this} builder + * @throws IllegalStateException if the builder has already transitioned + * to the built state + */ + default Builder add(long t) { + accept(t); + return this; + } + + /** + * Builds the stream, transitioning this builder to the built state. + * An {@code IllegalStateException} is thrown if there are further + * attempts to operate on the builder after it has entered the built + * state. + * + * @return the built stream + * @throws IllegalStateException if the builder has already transitioned + * to the built state + */ + LongStream build(); + } } diff --git a/jdk/src/share/classes/java/util/stream/Stream.java b/jdk/src/share/classes/java/util/stream/Stream.java index ea166bdca36..a5f36841f4a 100644 --- a/jdk/src/share/classes/java/util/stream/Stream.java +++ b/jdk/src/share/classes/java/util/stream/Stream.java @@ -794,7 +794,7 @@ public interface Stream extends BaseStream> { * @param type of elements * @return a stream builder */ - public static StreamBuilder builder() { + public static Builder builder() { return new Streams.StreamBuilderImpl<>(); } @@ -906,4 +906,65 @@ public interface Stream extends BaseStream> { (Spliterator) a.spliterator(), (Spliterator) b.spliterator()); return StreamSupport.stream(split, a.isParallel() || b.isParallel()); } + + /** + * A mutable builder for a {@code Stream}. This allows the creation of a + * {@code Stream} by generating elements individually and adding them to the + * {@code Builder} (without the copying overhead that comes from using + * an {@code ArrayList} as a temporary buffer.) + * + *

    A {@code Stream.Builder} has a lifecycle, where it starts in a building + * phase, during which elements can be added, and then transitions to a built + * phase, after which elements may not be added. The built phase begins + * when the {@link #build()} method is called, which creates an ordered + * {@code Stream} whose elements are the elements that were added to the stream + * builder, in the order they were added. + * + * @param the type of stream elements + * @see Stream#builder() + * @since 1.8 + */ + public interface Builder extends Consumer { + + /** + * Adds an element to the stream being built. + * + * @throws IllegalStateException if the builder has already transitioned to + * the built state + */ + @Override + void accept(T t); + + /** + * Adds an element to the stream being built. + * + * @implSpec + * The default implementation behaves as if: + *

    {@code
    +         *     accept(t)
    +         *     return this;
    +         * }
    + * + * @param t the element to add + * @return {@code this} builder + * @throws IllegalStateException if the builder has already transitioned to + * the built state + */ + default Builder add(T t) { + accept(t); + return this; + } + + /** + * Builds the stream, transitioning this builder to the built state. + * An {@code IllegalStateException} is thrown if there are further attempts + * to operate on the builder after it has entered the built state. + * + * @return the built stream + * @throws IllegalStateException if the builder has already transitioned to + * the built state + */ + Stream build(); + + } } diff --git a/jdk/src/share/classes/java/util/stream/StreamBuilder.java b/jdk/src/share/classes/java/util/stream/StreamBuilder.java deleted file mode 100644 index 66baa84cdfe..00000000000 --- a/jdk/src/share/classes/java/util/stream/StreamBuilder.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package java.util.stream; - -import java.util.function.Consumer; -import java.util.function.DoubleConsumer; -import java.util.function.IntConsumer; -import java.util.function.LongConsumer; - -/** - * A mutable builder for a {@code Stream}. This allows the creation of a - * {@code Stream} by generating elements individually and adding them to the - * {@code StreamBuilder} (without the copying overhead that comes from using - * an {@code ArrayList} as a temporary buffer.) - * - *

    A {@code StreamBuilder} has a lifecycle, where it starts in a building - * phase, during which elements can be added, and then transitions to a built - * phase, after which elements may not be added. The built phase begins - * when the {@link #build()} method is called, which creates an ordered - * {@code Stream} whose elements are the elements that were added to the stream - * builder, in the order they were added. - * - *

    Primitive specializations of {@code StreamBuilder} are provided - * for {@link OfInt int}, {@link OfLong long}, and {@link OfDouble double} - * values. - * - * @param the type of stream elements - * @see Stream#builder() - * @since 1.8 - */ -public interface StreamBuilder extends Consumer { - - /** - * Adds an element to the stream being built. - * - * @throws IllegalStateException if the builder has already transitioned to - * the built state - */ - @Override - void accept(T t); - - /** - * Adds an element to the stream being built. - * - * @implSpec - * The default implementation behaves as if: - *

    {@code
    -     *     accept(t)
    -     *     return this;
    -     * }
    - * - * @param t the element to add - * @return {@code this} builder - * @throws IllegalStateException if the builder has already transitioned to - * the built state - */ - default StreamBuilder add(T t) { - accept(t); - return this; - } - - /** - * Builds the stream, transitioning this builder to the built state. - * An {@code IllegalStateException} is thrown if there are further attempts - * to operate on the builder after it has entered the built state. - * - * @return the built stream - * @throws IllegalStateException if the builder has already transitioned to - * the built state - */ - Stream build(); - - /** - * A mutable builder for an {@code IntStream}. - * - *

    A stream builder has a lifecycle, where it starts in a building - * phase, during which elements can be added, and then transitions to a - * built phase, after which elements may not be added. The built phase - * begins when the {@link #build()} method is called, which creates an - * ordered stream whose elements are the elements that were added to the - * stream builder, in the order they were added. - * - * @see IntStream#builder() - * @since 1.8 - */ - interface OfInt extends IntConsumer { - - /** - * Adds an element to the stream being built. - * - * @throws IllegalStateException if the builder has already transitioned - * to the built state - */ - @Override - void accept(int t); - - /** - * Adds an element to the stream being built. - * - * @implSpec - * The default implementation behaves as if: - *

    {@code
    -         *     accept(t)
    -         *     return this;
    -         * }
    - * - * @param t the element to add - * @return {@code this} builder - * @throws IllegalStateException if the builder has already transitioned - * to the built state - */ - default StreamBuilder.OfInt add(int t) { - accept(t); - return this; - } - - /** - * Builds the stream, transitioning this builder to the built state. - * An {@code IllegalStateException} is thrown if there are further - * attempts to operate on the builder after it has entered the built - * state. - * - * @return the built stream - * @throws IllegalStateException if the builder has already transitioned to - * the built state - */ - IntStream build(); - } - - /** - * A mutable builder for a {@code LongStream}. - * - *

    A stream builder has a lifecycle, where it starts in a building - * phase, during which elements can be added, and then transitions to a - * built phase, after which elements may not be added. The built phase - * begins when the {@link #build()} method is called, which creates an - * ordered stream whose elements are the elements that were added to the - * stream builder, in the order they were added. - * - * @see LongStream#builder() - * @since 1.8 - */ - interface OfLong extends LongConsumer { - - /** - * Adds an element to the stream being built. - * - * @throws IllegalStateException if the builder has already transitioned - * to the built state - */ - @Override - void accept(long t); - - /** - * Adds an element to the stream being built. - * - * @implSpec - * The default implementation behaves as if: - *

    {@code
    -         *     accept(t)
    -         *     return this;
    -         * }
    - * - * @param t the element to add - * @return {@code this} builder - * @throws IllegalStateException if the builder has already transitioned - * to the built state - */ - default StreamBuilder.OfLong add(long t) { - accept(t); - return this; - } - - /** - * Builds the stream, transitioning this builder to the built state. - * An {@code IllegalStateException} is thrown if there are further - * attempts to operate on the builder after it has entered the built - * state. - * - * @return the built stream - * @throws IllegalStateException if the builder has already transitioned - * to the built state - */ - LongStream build(); - } - - /** - * A mutable builder for a {@code DoubleStream}. - * - *

    A stream builder has a lifecycle, where it starts in a building - * phase, during which elements can be added, and then transitions to a - * built phase, after which elements may not be added. The built phase - * begins when the {@link #build()} method is called, which creates an - * ordered stream whose elements are the elements that were added to the - * stream builder, in the order they were added. - * - * @see LongStream#builder() - * @since 1.8 - */ - interface OfDouble extends DoubleConsumer { - - /** - * Adds an element to the stream being built. - * - * @throws IllegalStateException if the builder has already transitioned - * to the built state - */ - @Override - void accept(double t); - - /** - * Adds an element to the stream being built. - * - * @implSpec - * The default implementation behaves as if: - *

    {@code
    -         *     accept(t)
    -         *     return this;
    -         * }
    - * - * @param t the element to add - * @return {@code this} builder - * @throws IllegalStateException if the builder has already transitioned - * to the built state - */ - default StreamBuilder.OfDouble add(double t) { - accept(t); - return this; - } - - /** - * Builds the stream, transitioning this builder to the built state. - * An {@code IllegalStateException} is thrown if there are further - * attempts to operate on the builder after it has entered the built - * state. - * - * @return the built stream - * @throws IllegalStateException if the builder has already transitioned - * to the built state - */ - DoubleStream build(); - } -} diff --git a/jdk/src/share/classes/java/util/stream/Streams.java b/jdk/src/share/classes/java/util/stream/Streams.java index 21fe2706280..7bf3123af65 100644 --- a/jdk/src/share/classes/java/util/stream/Streams.java +++ b/jdk/src/share/classes/java/util/stream/Streams.java @@ -317,7 +317,7 @@ final class Streams { static final class StreamBuilderImpl extends AbstractStreamBuilderImpl> - implements StreamBuilder { + implements Stream.Builder { // The first element in the stream // valid if count == 1 T first; @@ -363,7 +363,7 @@ final class Streams { } } - public StreamBuilder add(T t) { + public Stream.Builder add(T t) { accept(t); return this; } @@ -409,7 +409,7 @@ final class Streams { static final class IntStreamBuilderImpl extends AbstractStreamBuilderImpl - implements StreamBuilder.OfInt, Spliterator.OfInt { + implements IntStream.Builder, Spliterator.OfInt { // The first element in the stream // valid if count == 1 int first; @@ -496,7 +496,7 @@ final class Streams { static final class LongStreamBuilderImpl extends AbstractStreamBuilderImpl - implements StreamBuilder.OfLong, Spliterator.OfLong { + implements LongStream.Builder, Spliterator.OfLong { // The first element in the stream // valid if count == 1 long first; @@ -583,7 +583,7 @@ final class Streams { static final class DoubleStreamBuilderImpl extends AbstractStreamBuilderImpl - implements StreamBuilder.OfDouble, Spliterator.OfDouble { + implements DoubleStream.Builder, Spliterator.OfDouble { // The first element in the stream // valid if count == 1 double first; diff --git a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamBuilderTest.java b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamBuilderTest.java index 5a2760872fa..cbf87b1e779 100644 --- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamBuilderTest.java +++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamBuilderTest.java @@ -35,7 +35,6 @@ import java.util.stream.LambdaTestHelpers; import java.util.stream.LongStream; import java.util.stream.OpTestCase; import java.util.stream.Stream; -import java.util.stream.StreamBuilder; import java.util.stream.TestData; import static java.util.stream.Collectors.toList; @@ -89,7 +88,7 @@ public class StreamBuilderTest extends OpTestCase { @Test(dataProvider = "sizes") public void testAfterBuilding(int size) { - StreamBuilder sb = Stream.builder(); + Stream.Builder sb = Stream.builder(); IntStream.range(0, size).boxed().forEach(sb); sb.build(); @@ -101,15 +100,15 @@ public class StreamBuilderTest extends OpTestCase { @Test(dataProvider = "sizes") public void testStreamBuilder(int size) { testStreamBuilder(size, (s) -> { - StreamBuilder sb = Stream.builder(); + Stream.Builder sb = Stream.builder(); IntStream.range(0, s).boxed().forEach(sb); return sb.build(); }); testStreamBuilder(size, (s) -> { - StreamBuilder sb = Stream.builder(); + Stream.Builder sb = Stream.builder(); IntStream.range(0, s).boxed().forEach(i -> { - StreamBuilder _sb = sb.add(i); + Stream.Builder _sb = sb.add(i); assertTrue(sb == _sb); }); return sb.build(); @@ -151,7 +150,7 @@ public class StreamBuilderTest extends OpTestCase { @Test(dataProvider = "sizes") public void testIntAfterBuilding(int size) { - StreamBuilder.OfInt sb = IntStream.builder(); + IntStream.Builder sb = IntStream.builder(); IntStream.range(0, size).forEach(sb); sb.build(); @@ -163,15 +162,15 @@ public class StreamBuilderTest extends OpTestCase { @Test(dataProvider = "sizes") public void testIntStreamBuilder(int size) { testIntStreamBuilder(size, (s) -> { - StreamBuilder.OfInt sb = IntStream.builder(); + IntStream.Builder sb = IntStream.builder(); IntStream.range(0, s).forEach(sb); return sb.build(); }); testIntStreamBuilder(size, (s) -> { - StreamBuilder.OfInt sb = IntStream.builder(); + IntStream.Builder sb = IntStream.builder(); IntStream.range(0, s).forEach(i -> { - StreamBuilder.OfInt _sb = sb.add(i); + IntStream.Builder _sb = sb.add(i); assertTrue(sb == _sb); }); return sb.build(); @@ -213,7 +212,7 @@ public class StreamBuilderTest extends OpTestCase { @Test(dataProvider = "sizes") public void testLongAfterBuilding(int size) { - StreamBuilder.OfLong sb = LongStream.builder(); + LongStream.Builder sb = LongStream.builder(); LongStream.range(0, size).forEach(sb); sb.build(); @@ -225,15 +224,15 @@ public class StreamBuilderTest extends OpTestCase { @Test(dataProvider = "sizes") public void testLongStreamBuilder(int size) { testLongStreamBuilder(size, (s) -> { - StreamBuilder.OfLong sb = LongStream.builder(); + LongStream.Builder sb = LongStream.builder(); LongStream.range(0, s).forEach(sb); return sb.build(); }); testLongStreamBuilder(size, (s) -> { - StreamBuilder.OfLong sb = LongStream.builder(); + LongStream.Builder sb = LongStream.builder(); LongStream.range(0, s).forEach(i -> { - StreamBuilder.OfLong _sb = sb.add(i); + LongStream.Builder _sb = sb.add(i); assertTrue(sb == _sb); }); return sb.build(); @@ -274,7 +273,7 @@ public class StreamBuilderTest extends OpTestCase { @Test(dataProvider = "sizes") public void testDoubleAfterBuilding(int size) { - StreamBuilder.OfDouble sb = DoubleStream.builder(); + DoubleStream.Builder sb = DoubleStream.builder(); IntStream.range(0, size).asDoubleStream().forEach(sb); sb.build(); @@ -286,15 +285,15 @@ public class StreamBuilderTest extends OpTestCase { @Test(dataProvider = "sizes") public void testDoubleStreamBuilder(int size) { testDoubleStreamBuilder(size, (s) -> { - StreamBuilder.OfDouble sb = DoubleStream.builder(); + DoubleStream.Builder sb = DoubleStream.builder(); IntStream.range(0, s).asDoubleStream().forEach(sb); return sb.build(); }); testDoubleStreamBuilder(size, (s) -> { - StreamBuilder.OfDouble sb = DoubleStream.builder(); + DoubleStream.Builder sb = DoubleStream.builder(); IntStream.range(0, s).asDoubleStream().forEach(i -> { - StreamBuilder.OfDouble _sb = sb.add(i); + DoubleStream.Builder _sb = sb.add(i); assertTrue(sb == _sb); }); return sb.build(); From 3e0c71b6c11e9b87e6e510915e8ecbe0b1e90bbf Mon Sep 17 00:00:00 2001 From: Attila Szegedi Date: Tue, 9 Jul 2013 13:57:24 +0200 Subject: [PATCH 077/123] 8009758: reactivate the 8006529 test Reviewed-by: jlaskey, sundar --- .../jdk/nashorn/internal/codegen/Attr.java | 18 ++- .../internal/codegen/CompilerConstants.java | 4 +- .../codegen/ObjectClassGenerator.java | 4 +- .../nashorn/internal/codegen/types/Type.java | 66 ++++----- .../internal/runtime/AccessorProperty.java | 7 +- .../internal/runtime/FunctionScope.java | 4 +- .../JDK-8006529.js | 131 +++++++++++------- 7 files changed, 134 insertions(+), 100 deletions(-) rename nashorn/test/script/{currently-failing => trusted}/JDK-8006529.js (68%) diff --git a/nashorn/src/jdk/nashorn/internal/codegen/Attr.java b/nashorn/src/jdk/nashorn/internal/codegen/Attr.java index 6dbfa6d4c9b..e076825dfe0 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/Attr.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/Attr.java @@ -94,7 +94,6 @@ import jdk.nashorn.internal.runtime.DebugLogger; import jdk.nashorn.internal.runtime.JSType; import jdk.nashorn.internal.runtime.Property; import jdk.nashorn.internal.runtime.PropertyMap; -import jdk.nashorn.internal.runtime.ScriptObject; /** * This is the attribution pass of the code generator. Attr takes Lowered IR, @@ -166,19 +165,19 @@ final class Attr extends NodeOperatorVisitor { } private void initFunctionWideVariables(final FunctionNode functionNode, final Block body) { - initCompileConstant(CALLEE, body, IS_PARAM | IS_INTERNAL, FunctionNode.FUNCTION_TYPE); + initCompileConstant(CALLEE, body, IS_PARAM | IS_INTERNAL); initCompileConstant(THIS, body, IS_PARAM | IS_THIS, Type.OBJECT); if (functionNode.isVarArg()) { - initCompileConstant(VARARGS, body, IS_PARAM | IS_INTERNAL, Type.OBJECT_ARRAY); + initCompileConstant(VARARGS, body, IS_PARAM | IS_INTERNAL); if (functionNode.needsArguments()) { - initCompileConstant(ARGUMENTS, body, IS_VAR | IS_INTERNAL | IS_ALWAYS_DEFINED, Type.typeFor(ScriptObject.class)); + initCompileConstant(ARGUMENTS, body, IS_VAR | IS_INTERNAL | IS_ALWAYS_DEFINED); addLocalDef(ARGUMENTS.symbolName()); } } initParameters(functionNode, body); - initCompileConstant(SCOPE, body, IS_VAR | IS_INTERNAL | IS_ALWAYS_DEFINED, Type.typeFor(ScriptObject.class)); + initCompileConstant(SCOPE, body, IS_VAR | IS_INTERNAL | IS_ALWAYS_DEFINED); initCompileConstant(RETURN, body, IS_VAR | IS_INTERNAL | IS_ALWAYS_DEFINED, Type.OBJECT); } @@ -1424,9 +1423,16 @@ final class Attr extends NodeOperatorVisitor { return end(ensureSymbol(type, ternaryNode)); } + private void initCompileConstant(final CompilerConstants cc, final Block block, final int flags) { + final Class type = cc.type(); + // Must not call this method for constants with no explicit types; use the one with (..., Type) signature instead. + assert type != null; + initCompileConstant(cc, block, flags, Type.typeFor(type)); + } + private void initCompileConstant(final CompilerConstants cc, final Block block, final int flags, final Type type) { final Symbol symbol = defineSymbol(block, cc.symbolName(), flags); - newType(symbol, type); + symbol.setTypeOverride(type); symbol.setNeedsSlot(true); } diff --git a/nashorn/src/jdk/nashorn/internal/codegen/CompilerConstants.java b/nashorn/src/jdk/nashorn/internal/codegen/CompilerConstants.java index 3deff98c00a..c8ccc1cedc1 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/CompilerConstants.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/CompilerConstants.java @@ -100,10 +100,10 @@ public enum CompilerConstants { CALLEE(":callee", ScriptFunction.class), /** the varargs variable when necessary */ - VARARGS(":varargs"), + VARARGS(":varargs", Object[].class), /** the arguments vector when necessary and the slot */ - ARGUMENTS("arguments", Object.class, 2), + ARGUMENTS("arguments", ScriptObject.class, 2), /** prefix for iterators for for (x in ...) */ ITERATOR_PREFIX(":i", Iterator.class), diff --git a/nashorn/src/jdk/nashorn/internal/codegen/ObjectClassGenerator.java b/nashorn/src/jdk/nashorn/internal/codegen/ObjectClassGenerator.java index 7d61db1f691..fa3d19e5d05 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/ObjectClassGenerator.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/ObjectClassGenerator.java @@ -435,13 +435,13 @@ public final class ObjectClassGenerator { * @return Open method emitter. */ private static MethodEmitter newInitScopeWithArgumentsMethod(final ClassEmitter classEmitter) { - final MethodEmitter init = classEmitter.init(PropertyMap.class, ScriptObject.class, Object.class); + final MethodEmitter init = classEmitter.init(PropertyMap.class, ScriptObject.class, ScriptObject.class); init.begin(); init.load(Type.OBJECT, JAVA_THIS.slot()); init.load(Type.OBJECT, INIT_MAP.slot()); init.load(Type.OBJECT, INIT_SCOPE.slot()); init.load(Type.OBJECT, INIT_ARGUMENTS.slot()); - init.invoke(constructorNoLookup(FunctionScope.class, PropertyMap.class, ScriptObject.class, Object.class)); + init.invoke(constructorNoLookup(FunctionScope.class, PropertyMap.class, ScriptObject.class, ScriptObject.class)); return init; } diff --git a/nashorn/src/jdk/nashorn/internal/codegen/types/Type.java b/nashorn/src/jdk/nashorn/internal/codegen/types/Type.java index ab32a779703..c1e8bfbb432 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/types/Type.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/types/Type.java @@ -47,9 +47,8 @@ import static jdk.internal.org.objectweb.asm.Opcodes.T_INT; import static jdk.internal.org.objectweb.asm.Opcodes.T_LONG; import java.lang.invoke.MethodHandle; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import jdk.internal.org.objectweb.asm.MethodVisitor; import jdk.nashorn.internal.codegen.CompilerConstants.Call; @@ -548,19 +547,19 @@ public abstract class Type implements Comparable, BytecodeOps { * @return the Type representing this class */ public static Type typeFor(final Class clazz) { - Type type = cache.get(clazz); - - if (type == null) { - assert !clazz.isPrimitive() || clazz == void.class; - if (clazz.isArray()) { - type = new ArrayType(clazz); - } else { - type = new ObjectType(clazz); - } - cache.put(clazz, type); + final Type type = cache.get(clazz); + if(type != null) { + return type; } - - return type; + assert !clazz.isPrimitive() || clazz == void.class; + final Type newType; + if (clazz.isArray()) { + newType = new ArrayType(clazz); + } else { + newType = new ObjectType(clazz); + } + final Type existingType = cache.putIfAbsent(clazz, newType); + return existingType == null ? newType : existingType; } @Override @@ -663,35 +662,38 @@ public abstract class Type implements Comparable, BytecodeOps { } } + /** Mappings between java classes and their Type singletons */ + private static final ConcurrentMap, Type> cache = new ConcurrentHashMap<>(); + /** * This is the boolean singleton, used for all boolean types */ - public static final Type BOOLEAN = new BooleanType(); + public static final Type BOOLEAN = putInCache(new BooleanType()); /** * This is an integer type, i.e INT, INT32. */ - public static final Type INT = new IntType(); + public static final Type INT = putInCache(new IntType()); /** * This is the number singleton, used for all number types */ - public static final Type NUMBER = new NumberType(); + public static final Type NUMBER = putInCache(new NumberType()); /** * This is the long singleton, used for all long types */ - public static final Type LONG = new LongType(); + public static final Type LONG = putInCache(new LongType()); /** * A string singleton */ - public static final Type STRING = new ObjectType(String.class); + public static final Type STRING = putInCache(new ObjectType(String.class)); /** * This is the object singleton, used for all object types */ - public static final Type OBJECT = new ObjectType(); + public static final Type OBJECT = putInCache(new ObjectType()); /** * This is the singleton for integer arrays @@ -775,13 +777,13 @@ public abstract class Type implements Comparable, BytecodeOps { }; /** Singleton for method handle arrays used for properties etc. */ - public static final ArrayType METHODHANDLE_ARRAY = new ArrayType(MethodHandle[].class); + public static final ArrayType METHODHANDLE_ARRAY = putInCache(new ArrayType(MethodHandle[].class)); /** This is the singleton for string arrays */ - public static final ArrayType STRING_ARRAY = new ArrayType(String[].class); + public static final ArrayType STRING_ARRAY = putInCache(new ArrayType(String[].class)); /** This is the singleton for object arrays */ - public static final ArrayType OBJECT_ARRAY = new ArrayType(Object[].class); + public static final ArrayType OBJECT_ARRAY = putInCache(new ArrayType(Object[].class)); /** This type, always an object type, just a toString override */ public static final Type THIS = new ObjectType() { @@ -855,18 +857,8 @@ public abstract class Type implements Comparable, BytecodeOps { } }; - /** Mappings between java classes and their Type singletons */ - private static final Map, Type> cache = Collections.synchronizedMap(new HashMap, Type>()); - - //TODO may need to be cleared, as all types are retained throughout code generation - static { - cache.put(BOOLEAN.getTypeClass(), BOOLEAN); - cache.put(INT.getTypeClass(), INT); - cache.put(LONG.getTypeClass(), LONG); - cache.put(NUMBER.getTypeClass(), NUMBER); - cache.put(STRING.getTypeClass(), STRING); - cache.put(OBJECT.getTypeClass(), OBJECT); - cache.put(OBJECT_ARRAY.getTypeClass(), OBJECT_ARRAY); + private static T putInCache(T type) { + cache.put(type.getTypeClass(), type); + return type; } - } diff --git a/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java b/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java index f7ece9df533..f1f0ebe33c0 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java @@ -248,11 +248,10 @@ public class AccessorProperty extends Property { primitiveSetter = null; if (isParameter() && hasArguments()) { - final MethodHandle arguments = MH.getter(lookup, structure, "arguments", Object.class); - final MethodHandle argumentsSO = MH.asType(arguments, arguments.type().changeReturnType(ScriptObject.class)); + final MethodHandle arguments = MH.getter(lookup, structure, "arguments", ScriptObject.class); - objectGetter = MH.asType(MH.insertArguments(MH.filterArguments(ScriptObject.GET_ARGUMENT.methodHandle(), 0, argumentsSO), 1, slot), Lookup.GET_OBJECT_TYPE); - objectSetter = MH.asType(MH.insertArguments(MH.filterArguments(ScriptObject.SET_ARGUMENT.methodHandle(), 0, argumentsSO), 1, slot), Lookup.SET_OBJECT_TYPE); + objectGetter = MH.asType(MH.insertArguments(MH.filterArguments(ScriptObject.GET_ARGUMENT.methodHandle(), 0, arguments), 1, slot), Lookup.GET_OBJECT_TYPE); + objectSetter = MH.asType(MH.insertArguments(MH.filterArguments(ScriptObject.SET_ARGUMENT.methodHandle(), 0, arguments), 1, slot), Lookup.SET_OBJECT_TYPE); } else { final GettersSetters gs = GETTERS_SETTERS.get(structure); objectGetter = gs.getters[slot]; diff --git a/nashorn/src/jdk/nashorn/internal/runtime/FunctionScope.java b/nashorn/src/jdk/nashorn/internal/runtime/FunctionScope.java index 59a9d5ede03..b3872c45cd7 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/FunctionScope.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/FunctionScope.java @@ -41,7 +41,7 @@ package jdk.nashorn.internal.runtime; public class FunctionScope extends ScriptObject implements Scope { /** Area to store scope arguments. (public for access from scripts.) */ - public final Object arguments; + public final ScriptObject arguments; /** Flag to indicate that a split method issued a return statement */ private int splitState = -1; @@ -53,7 +53,7 @@ public class FunctionScope extends ScriptObject implements Scope { * @param callerScope caller scope * @param arguments arguments */ - public FunctionScope(final PropertyMap map, final ScriptObject callerScope, final Object arguments) { + public FunctionScope(final PropertyMap map, final ScriptObject callerScope, final ScriptObject arguments) { super(callerScope, map); this.arguments = arguments; setIsScope(); diff --git a/nashorn/test/script/currently-failing/JDK-8006529.js b/nashorn/test/script/trusted/JDK-8006529.js similarity index 68% rename from nashorn/test/script/currently-failing/JDK-8006529.js rename to nashorn/test/script/trusted/JDK-8006529.js index ca21f0b9c48..378cd6cf7a6 100644 --- a/nashorn/test/script/currently-failing/JDK-8006529.js +++ b/nashorn/test/script/trusted/JDK-8006529.js @@ -39,30 +39,35 @@ * and FunctionNode because of package-access check and so reflective calls. */ -var Parser = Java.type("jdk.nashorn.internal.parser.Parser") -var Compiler = Java.type("jdk.nashorn.internal.codegen.Compiler") -var Context = Java.type("jdk.nashorn.internal.runtime.Context") -var ScriptEnvironment = Java.type("jdk.nashorn.internal.runtime.ScriptEnvironment") -var Source = Java.type("jdk.nashorn.internal.runtime.Source") -var FunctionNode = Java.type("jdk.nashorn.internal.ir.FunctionNode") -var ThrowErrorManager = Java.type("jdk.nashorn.internal.runtime.Context$ThrowErrorManager"); +var forName = java.lang.Class["forName(String)"] + +var Parser = forName("jdk.nashorn.internal.parser.Parser").static +var Compiler = forName("jdk.nashorn.internal.codegen.Compiler").static +var Context = forName("jdk.nashorn.internal.runtime.Context").static +var ScriptEnvironment = forName("jdk.nashorn.internal.runtime.ScriptEnvironment").static +var Source = forName("jdk.nashorn.internal.runtime.Source").static +var FunctionNode = forName("jdk.nashorn.internal.ir.FunctionNode").static +var Block = forName("jdk.nashorn.internal.ir.Block").static +var VarNode = forName("jdk.nashorn.internal.ir.VarNode").static +var ExecuteNode = forName("jdk.nashorn.internal.ir.ExecuteNode").static +var UnaryNode = forName("jdk.nashorn.internal.ir.UnaryNode").static +var BinaryNode = forName("jdk.nashorn.internal.ir.BinaryNode").static +var ThrowErrorManager = forName("jdk.nashorn.internal.runtime.Context$ThrowErrorManager").static +var Debug = forName("jdk.nashorn.internal.runtime.Debug").static -// Compiler class methods and fields var parseMethod = Parser.class.getMethod("parse"); -var compileMethod = Compiler.class.getMethod("compile"); - -// NOTE: private field. But this is a trusted test! -// Compiler.functionNode -var functionNodeField = Compiler.class.getDeclaredField("functionNode"); -functionNodeField.setAccessible(true); - -// FunctionNode methods - -// FunctionNode.getFunctions method -var getFunctionsMethod = FunctionNode.class.getMethod("getFunctions"); +var compileMethod = Compiler.class.getMethod("compile", FunctionNode.class); +var getBodyMethod = FunctionNode.class.getMethod("getBody"); +var getStatementsMethod = Block.class.getMethod("getStatements"); +var getInitMethod = VarNode.class.getMethod("getInit"); +var getExpressionMethod = ExecuteNode.class.getMethod("getExpression") +var rhsMethod = UnaryNode.class.getMethod("rhs") +var lhsMethod = BinaryNode.class.getMethod("lhs") +var binaryRhsMethod = BinaryNode.class.getMethod("rhs") +var debugIdMethod = Debug.class.getMethod("id", java.lang.Object.class) // These are method names of methods in FunctionNode class -var allAssertionList = ['isVarArg', 'needsParentScope', 'needsCallee', 'needsScope', 'needsSelfSymbol', 'isSplit', 'hasEval', 'hasWith', 'hasDeepWithOrEval', 'allVarsInScope', 'isStrictMode'] +var allAssertionList = ['isVarArg', 'needsParentScope', 'needsCallee', 'hasScopeBlock', 'needsSelfSymbol', 'isSplit', 'hasEval', 'allVarsInScope', 'isStrict'] // corresponding Method objects of FunctionNode class var functionNodeMethods = {}; @@ -74,30 +79,54 @@ var functionNodeMethods = {}; } })(); -// returns "script" functionNode from Compiler instance -function getScriptNode(compiler) { - // compiler.functionNode - return functionNodeField.get(compiler); +// returns functionNode.getBody().getStatements().get(0) +function getFirstFunction(functionNode) { + var f = findFunction(getBodyMethod.invoke(functionNode)) + if (f == null) { + throw new Error(); + } + return f; } -// returns functionNode.getFunctions().get(0) -function getFirstFunction(functionNode) { - // functionNode.getFunctions().get(0) - return getFunctionsMethod.invoke(functionNode).get(0); +function findFunction(node) { + if(node instanceof Block) { + var stmts = getStatementsMethod.invoke(node) + for(var i = 0; i < stmts.size(); ++i) { + var retval = findFunction(stmts.get(i)) + if(retval != null) { + return retval; + } + } + } else if(node instanceof VarNode) { + return findFunction(getInitMethod.invoke(node)) + } else if(node instanceof UnaryNode) { + return findFunction(rhsMethod.invoke(node)) + } else if(node instanceof BinaryNode) { + return findFunction(lhsMethod.invoke(node)) || findFunction(binaryRhsMethod.invoke(node)) + } else if(node instanceof ExecuteNode) { + return findFunction(getExpressionMethod.invoke(node)) + } else if(node instanceof FunctionNode) { + return node + } } +var getContextMethod = Context.class.getMethod("getContext") +var getEnvMethod = Context.class.getMethod("getEnv") + // compile(script) -- compiles a script specified as a string with its // source code, returns a jdk.nashorn.internal.ir.FunctionNode object // representing it. function compile(source) { var source = new Source("", source); - var parser = new Parser(Context.getContext().getEnv(), source, new ThrowErrorManager()); + + var env = getEnvMethod.invoke(getContextMethod.invoke(null)) + + var parser = new Parser(env, source, new ThrowErrorManager()); var func = parseMethod.invoke(parser); - var compiler = new Compiler(Context.getContext().getEnv(), func); - compileMethod.invoke(compiler); + var compiler = new Compiler(env); - return getScriptNode(compiler); + return compileMethod.invoke(compiler, func); }; var allAssertions = (function() { @@ -122,8 +151,9 @@ function test(f) { } for(var assertion in allAssertions) { var expectedValue = !!assertions[assertion] - if(functionNodeMethods[assertion].invoke(f) !== expectedValue) { - throw "Expected " + assertion + " === " + expectedValue + " for " + f; + var actualValue = functionNodeMethods[assertion].invoke(f) + if(actualValue !== expectedValue) { + throw "Expected " + assertion + " === " + expectedValue + ", got " + actualValue + " for " + f + ":" + debugIdMethod.invoke(null, f); } } } @@ -152,7 +182,7 @@ testFirstFn("function f() { arguments }", 'needsCallee', 'isVarArg') // A function referencing "arguments" will have to be vararg. If it is // strict, it will not have to have a callee, though. -testFirstFn("function f() {'use strict'; arguments }", 'isVarArg', 'isStrictMode') +testFirstFn("function f() {'use strict'; arguments }", 'isVarArg', 'isStrict') // A function defining "arguments" as a parameter will not be vararg. testFirstFn("function f(arguments) { arguments }") @@ -173,11 +203,11 @@ testFirstFn("(function f() { f() })", 'needsCallee', 'needsSelfSymbol') // A child function accessing parent's variable triggers the need for scope // in parent -testFirstFn("(function f() { var x; function g() { x } })", 'needsScope') +testFirstFn("(function f() { var x; function g() { x } })", 'hasScopeBlock') // A child function accessing parent's parameter triggers the need for scope // in parent -testFirstFn("(function f(x) { function g() { x } })", 'needsScope') +testFirstFn("(function f(x) { function g() { x } })", 'hasScopeBlock') // A child function accessing a global variable triggers the need for parent // scope in parent @@ -187,22 +217,29 @@ testFirstFn("(function f() { function g() { x } })", 'needsParentScope', 'needsC // affect the parent function in any way testFirstFn("(function f() { var x; function g() { var x; x } })") -// Using "with" unleashes a lot of needs: parent scope, callee, own scope, -// and all variables in scope. Actually, we could make "with" less wasteful, -// and only put those variables in scope that it actually references, similar -// to what nested functions do with variables in their parents. -testFirstFn("(function f() { var o; with(o) {} })", 'needsParentScope', 'needsCallee', 'needsScope', 'hasWith', 'hasDeepWithOrEval', 'allVarsInScope') +// Using "with" on its own doesn't do much. +testFirstFn("(function f() { var o; with(o) {} })") -// Using "eval" is as bad as using "with" with the added requirement of -// being vararg, 'cause we don't know if eval will be using "arguments". -testFirstFn("(function f() { eval() })", 'needsParentScope', 'needsCallee', 'needsScope', 'hasEval', 'isVarArg', 'hasDeepWithOrEval', 'allVarsInScope') +// "with" referencing a local variable triggers scoping. +testFirstFn("(function f() { var x; var y; with(x) { y } })", 'hasScopeBlock') + +// "with" referencing a non-local variable triggers parent scope. +testFirstFn("(function f() { var x; with(x) { y } })", 'needsCallee', 'needsParentScope') // Nested function using "with" is pretty much the same as the parent // function needing with. -testFirstFn("(function f() { function g() { var o; with(o) {} } })", 'needsParentScope', 'needsCallee', 'needsScope', 'hasDeepWithOrEval', 'allVarsInScope') +testFirstFn("(function f() { function g() { var o; with(o) {} } })") + +// Nested function using "with" referencing a local variable. +testFirstFn("(function f() { var x; function g() { var o; with(o) { x } } })", 'hasScopeBlock') + +// Using "eval" triggers pretty much everything. The function even needs to be +// vararg, 'cause we don't know if eval will be using "arguments". +testFirstFn("(function f() { eval() })", 'needsParentScope', 'needsCallee', 'hasScopeBlock', 'hasEval', 'isVarArg', 'allVarsInScope') + // Nested function using "eval" is almost the same as parent function using // eval, but at least the parent doesn't have to be vararg. -testFirstFn("(function f() { function g() { eval() } })", 'needsParentScope', 'needsCallee', 'needsScope', 'hasDeepWithOrEval', 'allVarsInScope') +testFirstFn("(function f() { function g() { eval() } })", 'needsParentScope', 'needsCallee', 'hasScopeBlock', 'allVarsInScope') // Function with 250 named parameters is ordinary testFirstFn("function f(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26, p27, p28, p29, p30, p31, p32, p33, p34, p35, p36, p37, p38, p39, p40, p41, p42, p43, p44, p45, p46, p47, p48, p49, p50, p51, p52, p53, p54, p55, p56, p57, p58, p59, p60, p61, p62, p63, p64, p65, p66, p67, p68, p69, p70, p71, p72, p73, p74, p75, p76, p77, p78, p79, p80, p81, p82, p83, p84, p85, p86, p87, p88, p89, p90, p91, p92, p93, p94, p95, p96, p97, p98, p99, p100, p101, p102, p103, p104, p105, p106, p107, p108, p109, p110, p111, p112, p113, p114, p115, p116, p117, p118, p119, p120, p121, p122, p123, p124, p125, p126, p127, p128, p129, p130, p131, p132, p133, p134, p135, p136, p137, p138, p139, p140, p141, p142, p143, p144, p145, p146, p147, p148, p149, p150, p151, p152, p153, p154, p155, p156, p157, p158, p159, p160, p161, p162, p163, p164, p165, p166, p167, p168, p169, p170, p171, p172, p173, p174, p175, p176, p177, p178, p179, p180, p181, p182, p183, p184, p185, p186, p187, p188, p189, p190, p191, p192, p193, p194, p195, p196, p197, p198, p199, p200, p201, p202, p203, p204, p205, p206, p207, p208, p209, p210, p211, p212, p213, p214, p215, p216, p217, p218, p219, p220, p221, p222, p223, p224, p225, p226, p227, p228, p229, p230, p231, p232, p233, p234, p235, p236, p237, p238, p239, p240, p241, p242, p243, p244, p245, p246, p247, p248, p249, p250) { p250 = p249 }") From 8854b24a3034df1b4751789d403ae7a8205abf23 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Tue, 9 Jul 2013 17:37:46 +0530 Subject: [PATCH 078/123] 8014785: Ability to extend global instance by binding properties of another object Reviewed-by: attila, hannesw, jlaskey, lagergren --- .../internal/objects/NativeObject.java | 116 ++++++++++++++++++ .../internal/runtime/AccessorProperty.java | 4 +- .../jdk/nashorn/internal/runtime/Context.java | 8 +- .../nashorn/internal/runtime/PropertyMap.java | 2 +- .../internal/runtime/ScriptObject.java | 32 ++++- .../internal/runtime/linker/InvokeByName.java | 2 +- nashorn/test/script/basic/JDK-8014785.js | 62 ++++++++++ .../test/script/basic/JDK-8014785.js.EXPECTED | 8 ++ 8 files changed, 224 insertions(+), 10 deletions(-) create mode 100644 nashorn/test/script/basic/JDK-8014785.js create mode 100644 nashorn/test/script/basic/JDK-8014785.js.EXPECTED diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java b/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java index 6e4791bd20c..c8bff8b0203 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java @@ -27,18 +27,24 @@ package jdk.nashorn.internal.objects; import static jdk.nashorn.internal.runtime.ECMAErrors.typeError; import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED; + +import java.lang.invoke.MethodHandle; +import java.util.ArrayList; import jdk.nashorn.api.scripting.ScriptObjectMirror; import jdk.nashorn.internal.objects.annotations.Attribute; import jdk.nashorn.internal.objects.annotations.Constructor; import jdk.nashorn.internal.objects.annotations.Function; import jdk.nashorn.internal.objects.annotations.ScriptClass; import jdk.nashorn.internal.objects.annotations.Where; +import jdk.nashorn.internal.runtime.AccessorProperty; import jdk.nashorn.internal.runtime.ECMAException; import jdk.nashorn.internal.runtime.JSType; +import jdk.nashorn.internal.runtime.Property; import jdk.nashorn.internal.runtime.PropertyMap; import jdk.nashorn.internal.runtime.ScriptFunction; import jdk.nashorn.internal.runtime.ScriptObject; import jdk.nashorn.internal.runtime.ScriptRuntime; +import jdk.nashorn.internal.runtime.linker.Bootstrap; import jdk.nashorn.internal.runtime.linker.InvokeByName; /** @@ -471,4 +477,114 @@ public final class NativeObject { return false; } + + /** + * Nashorn extension: Object.bindProperties + * + * Binds the source object's properties to the target object. Binding + * properties allows two-way read/write for the properties of the source object. + * + * Example: + *
    +     * var obj = { x: 34, y: 100 };
    +     * var foo = {}
    +     *
    +     * // bind properties of "obj" to "foo" object
    +     * Object.bindProperties(foo, obj);
    +     *
    +     * // now, we can access/write on 'foo' properties
    +     * print(foo.x); // prints obj.x which is 34
    +     *
    +     * // update obj.x via foo.x
    +     * foo.x = "hello";
    +     * print(obj.x); // prints "hello" now
    +     *
    +     * obj.x = 42;   // foo.x also becomes 42
    +     * print(foo.x); // prints 42
    +     * 
    + *

    + * The source object bound can be a ScriptObject or a ScriptOjectMirror. + * null or undefined source object results in TypeError being thrown. + *

    + * Example: + *
    +     * var obj = loadWithNewGlobal({
    +     *    name: "test",
    +     *    script: "obj = { x: 33, y: 'hello' }"
    +     * });
    +     *
    +     * // bind 'obj's properties to global scope 'this'
    +     * Object.bindProperties(this, obj);
    +     * print(x);         // prints 33
    +     * print(y);         // prints "hello"
    +     * x = Math.PI;      // changes obj.x to Math.PI
    +     * print(obj.x);     // prints Math.PI
    +     * 
    + * + * Limitations of property binding: + *
      + *
    • Only enumerable, immediate (not proto inherited) properties of the source object are bound. + *
    • If the target object already contains a property called "foo", the source's "foo" is skipped (not bound). + *
    • Properties added to the source object after binding to the target are not bound. + *
    • Property configuration changes on the source object (or on the target) is not propagated. + *
    • Delete of property on the target (or the source) is not propagated - + * only the property value is set to 'undefined' if the property happens to be a data property. + *
    + *

    + * It is recommended that the bound properties be treated as non-configurable + * properties to avoid surprises. + *

    + * + * @param self self reference + * @param target the target object to which the source object's properties are bound + * @param source the source object whose properties are bound to the target + * @return the target object after property binding + */ + @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) + public static Object bindProperties(final Object self, final Object target, final Object source) { + // target object has to be a ScriptObject + Global.checkObject(target); + // check null or undefined source object + Global.checkObjectCoercible(source); + + final ScriptObject targetObj = (ScriptObject)target; + + if (source instanceof ScriptObject) { + final ScriptObject sourceObj = (ScriptObject)source; + final Property[] properties = sourceObj.getMap().getProperties(); + + // filter non-enumerable properties + final ArrayList propList = new ArrayList<>(); + for (Property prop : properties) { + if (prop.isEnumerable()) { + propList.add(prop); + } + } + + if (! propList.isEmpty()) { + targetObj.addBoundProperties(sourceObj, propList.toArray(new Property[propList.size()])); + } + } else if (source instanceof ScriptObjectMirror) { + // get enumerable, immediate properties of mirror + final ScriptObjectMirror mirror = (ScriptObjectMirror)source; + final String[] keys = mirror.getOwnKeys(false); + if (keys.length == 0) { + // nothing to bind + return target; + } + + // make accessor properties using dynamic invoker getters and setters + final AccessorProperty[] props = new AccessorProperty[keys.length]; + for (int idx = 0; idx < keys.length; idx++) { + final String name = keys[idx]; + final MethodHandle getter = Bootstrap.createDynamicInvoker("dyn:getMethod|getProp|getElem:" + name, Object.class, ScriptObjectMirror.class); + final MethodHandle setter = Bootstrap.createDynamicInvoker("dyn:setProp|setElem:" + name, Object.class, ScriptObjectMirror.class, Object.class); + props[idx] = (AccessorProperty.create(name, 0, getter, setter)); + } + + targetObj.addBoundProperties(source, props); + } + + return target; + } } diff --git a/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java b/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java index f1f0ebe33c0..c9d2a04229f 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java @@ -147,9 +147,9 @@ public class AccessorProperty extends Property { * and are thus rebound with that as receiver * * @param property accessor property to rebind - * @param delegate delegate script object to rebind receiver to + * @param delegate delegate object to rebind receiver to */ - public AccessorProperty(final AccessorProperty property, final ScriptObject delegate) { + public AccessorProperty(final AccessorProperty property, final Object delegate) { super(property); this.primitiveGetter = bindTo(property.primitiveGetter, delegate); diff --git a/nashorn/src/jdk/nashorn/internal/runtime/Context.java b/nashorn/src/jdk/nashorn/internal/runtime/Context.java index 8f00d52127e..7d639cd31c3 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/Context.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/Context.java @@ -199,6 +199,7 @@ public final class Context { private static final ClassLoader myLoader = Context.class.getClassLoader(); private static final StructureLoader sharedLoader; + private static final AccessControlContext NO_PERMISSIONS_CONTEXT; static { sharedLoader = AccessController.doPrivileged(new PrivilegedAction() { @@ -207,6 +208,7 @@ public final class Context { return new StructureLoader(myLoader, null); } }); + NO_PERMISSIONS_CONTEXT = new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, new Permissions()) }); } /** @@ -564,7 +566,7 @@ public final class Context { sm.checkPackageAccess(fullName.substring(0, index)); return null; } - }, createNoPermissionsContext()); + }, NO_PERMISSIONS_CONTEXT); } } @@ -707,10 +709,6 @@ public final class Context { return (context != null) ? context : Context.getContextTrusted(); } - private static AccessControlContext createNoPermissionsContext() { - return new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, new Permissions()) }); - } - private Object evaluateSource(final Source source, final ScriptObject scope, final ScriptObject thiz) { ScriptFunction script = null; diff --git a/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java b/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java index 05e8dc78235..511ff666cd5 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java @@ -260,7 +260,7 @@ public final class PropertyMap implements Iterable, PropertyListener { * * @return New {@link PropertyMap} with {@link Property} added. */ - PropertyMap addPropertyBind(final AccessorProperty property, final ScriptObject bindTo) { + PropertyMap addPropertyBind(final AccessorProperty property, final Object bindTo) { return addProperty(new AccessorProperty(property, bindTo)); } diff --git a/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java b/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java index c56c32c7257..f770bd65a6f 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java @@ -203,9 +203,19 @@ public abstract class ScriptObject extends PropertyListenerManager implements Pr * @param source The source object to copy from. */ public void addBoundProperties(final ScriptObject source) { + addBoundProperties(source, source.getMap().getProperties()); + } + + /** + * Copy all properties from the array with their receiver bound to the source. + * + * @param source The source object to copy from. + * @param properties The array of properties to copy. + */ + public void addBoundProperties(final ScriptObject source, final Property[] properties) { PropertyMap newMap = this.getMap(); - for (final Property property : source.getMap().getProperties()) { + for (final Property property : properties) { final String key = property.getKey(); if (newMap.findProperty(key) == null) { @@ -221,6 +231,26 @@ public abstract class ScriptObject extends PropertyListenerManager implements Pr this.setMap(newMap); } + /** + * Copy all properties from the array with their receiver bound to the source. + * + * @param source The source object to copy from. + * @param properties The collection of accessor properties to copy. + */ + public void addBoundProperties(final Object source, final AccessorProperty[] properties) { + PropertyMap newMap = this.getMap(); + + for (final AccessorProperty property : properties) { + final String key = property.getKey(); + + if (newMap.findProperty(key) == null) { + newMap = newMap.addPropertyBind(property, source); + } + } + + this.setMap(newMap); + } + /** * Bind the method handle to the specified receiver, while preserving its original type (it will just ignore the * first argument in lieu of the bound argument). diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/InvokeByName.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/InvokeByName.java index 4bfb6851c08..efec5b44738 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/linker/InvokeByName.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/InvokeByName.java @@ -83,7 +83,7 @@ public class InvokeByName { */ public InvokeByName(final String name, final Class targetClass, final Class rtype, final Class... ptypes) { this.name = name; - getter = Bootstrap.createDynamicInvoker("dyn:getMethod|getProp|getItem:" + name, Object.class, targetClass); + getter = Bootstrap.createDynamicInvoker("dyn:getMethod|getProp|getElem:" + name, Object.class, targetClass); final Class[] finalPtypes; final int plength = ptypes.length; diff --git a/nashorn/test/script/basic/JDK-8014785.js b/nashorn/test/script/basic/JDK-8014785.js new file mode 100644 index 00000000000..27b05bd1f32 --- /dev/null +++ b/nashorn/test/script/basic/JDK-8014785.js @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * 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. + */ + +/** + * JDK-8014785: Ability to extend global instance by binding properties of another object + * + * @test + * @run + */ + +var obj = { x: 34, y: 100 }; +var foo = {} + +// bind properties of "obj" to "foo" obj +Object.bindProperties(foo, obj); + +// now we can access/write on foo properties +print("foo.x = " + foo.x); // prints obj.x which is 34 + +// update obj.x via foo.x +foo.x = "hello"; +print("obj.x = " + obj.x); // prints "hello" now + +obj.x = 42; // foo.x also becomes 42 +print("obj.x = " + obj.x); // prints 42 +print("foo.x = " + foo.x); // prints 42 + +// now bind a mirror object to an object +var obj = loadWithNewGlobal({ + name: "test", + script: "obj = { x: 33, y: 'hello' }" +}); + +Object.bindProperties(this, obj); +print("x = " + x); // prints 33 +print("y = " + y); // prints "hello" + +x = Math.PI; // changes obj.x to Math.PI +print("obj.x = " +obj.x); // prints Math.PI + +obj.y = 32; +print("y = " + y); // should print 32 diff --git a/nashorn/test/script/basic/JDK-8014785.js.EXPECTED b/nashorn/test/script/basic/JDK-8014785.js.EXPECTED new file mode 100644 index 00000000000..cb2b154cffe --- /dev/null +++ b/nashorn/test/script/basic/JDK-8014785.js.EXPECTED @@ -0,0 +1,8 @@ +foo.x = 34 +obj.x = hello +obj.x = 42 +foo.x = 42 +x = 33 +y = hello +obj.x = 3.141592653589793 +y = 32 From cfbe70e2231e591d8888d654f2148cac5168e147 Mon Sep 17 00:00:00 2001 From: Marcus Lagergren Date: Tue, 9 Jul 2013 15:56:59 +0200 Subject: [PATCH 079/123] 8020124: In the case of an eval switch, we might need explicit conversions of the tag store, as it was not known in the surrounding environment Reviewed-by: sundar, jlaskey --- .../internal/codegen/CodeGenerator.java | 2 ++ nashorn/test/script/basic/JDK-8020124.js | 32 +++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 nashorn/test/script/basic/JDK-8020124.js diff --git a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java index 79936473fb9..250c44c1541 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java @@ -1869,6 +1869,8 @@ final class CodeGenerator extends NodeOperatorVisitor Date: Tue, 9 Jul 2013 18:01:58 +0400 Subject: [PATCH 080/123] 6707231: Wrong read Method returned for boolen properties Reviewed-by: alexsch --- .../classes/java/beans/Introspector.java | 5 +- .../java/beans/Introspector/Test6707231.java | 80 +++++++++++++++++++ 2 files changed, 83 insertions(+), 2 deletions(-) create mode 100644 jdk/test/java/beans/Introspector/Test6707231.java diff --git a/jdk/src/share/classes/java/beans/Introspector.java b/jdk/src/share/classes/java/beans/Introspector.java index 65d95eb4e80..783fcbef315 100644 --- a/jdk/src/share/classes/java/beans/Introspector.java +++ b/jdk/src/share/classes/java/beans/Introspector.java @@ -652,11 +652,12 @@ public class Introspector { } } 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 { diff --git a/jdk/test/java/beans/Introspector/Test6707231.java b/jdk/test/java/beans/Introspector/Test6707231.java new file mode 100644 index 00000000000..67f935d6ec1 --- /dev/null +++ b/jdk/test/java/beans/Introspector/Test6707231.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.beans.PropertyDescriptor; + +/* + * @test + * @bug 6707231 + * @summary Tests the boolean getter + * @author Sergey Malenkov + */ + +public class Test6707231 { + public static void main(String[] args) throws Exception { + test(Bean.class, Bean.class); + test(Public.class, Public.class); + test(Private.class, Bean.class); + } + + public static class Bean { + private boolean value; + + public boolean isValue() { + return this.value; + } + + public void setValue(boolean value) { + this.value = value; + } + } + + public static class Public extends Bean { + public boolean isValue() { + return super.isValue(); + } + + public void setValue(boolean value) { + super.setValue(value); + } + } + + private static class Private extends Bean { + public boolean isValue() { + return super.isValue(); + } + + public void setValue(boolean value) { + super.setValue(value); + } + } + + private static void test(Class actual, Class expected) { + PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(actual, "value"); + Class getter = pd.getReadMethod().getDeclaringClass(); + Class setter = pd.getWriteMethod().getDeclaringClass(); + if ((getter != expected) || (setter != expected)) { + throw new Error(actual.getName()); + } + } +} From b2b2d519cafa52436bd15425cd9592991a1d2b69 Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Tue, 9 Jul 2013 21:21:55 +0400 Subject: [PATCH 081/123] 8019587: [macosx] Possibility to set the same frame for the different screens Reviewed-by: art, anthony --- .../classes/java/awt/GraphicsDevice.java | 6 ++ .../IncorrectDisplayModeExitFullscreen.java | 94 +++++++++++++++++++ 2 files changed, 100 insertions(+) create mode 100644 jdk/test/java/awt/GraphicsDevice/IncorrectDisplayModeExitFullscreen.java diff --git a/jdk/src/share/classes/java/awt/GraphicsDevice.java b/jdk/src/share/classes/java/awt/GraphicsDevice.java index b99d7ef8def..c619a2aee19 100644 --- a/jdk/src/share/classes/java/awt/GraphicsDevice.java +++ b/jdk/src/share/classes/java/awt/GraphicsDevice.java @@ -296,6 +296,12 @@ public abstract class GraphicsDevice { 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 diff --git a/jdk/test/java/awt/GraphicsDevice/IncorrectDisplayModeExitFullscreen.java b/jdk/test/java/awt/GraphicsDevice/IncorrectDisplayModeExitFullscreen.java new file mode 100644 index 00000000000..1d42db8f47d --- /dev/null +++ b/jdk/test/java/awt/GraphicsDevice/IncorrectDisplayModeExitFullscreen.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +import java.awt.Color; +import java.awt.DisplayMode; +import java.awt.Frame; +import java.awt.GraphicsDevice; +import java.awt.GraphicsEnvironment; +import java.awt.Toolkit; + +import sun.awt.SunToolkit; + +/** + * @test + * @bug 8019587 + * @author Sergey Bylokhov + */ +public class IncorrectDisplayModeExitFullscreen { + + public static void main(final String[] args) { + + final GraphicsDevice[] devices = + GraphicsEnvironment.getLocalGraphicsEnvironment() + .getScreenDevices(); + if (devices.length < 2 || devices[0].getDisplayModes().length < 2 + || !devices[0].isFullScreenSupported() + || !devices[1].isFullScreenSupported()) { + System.err.println("Testcase is not applicable"); + return; + } + final DisplayMode defaultDM = devices[0].getDisplayMode(); + final DisplayMode[] dms = devices[0].getDisplayModes(); + DisplayMode nonDefaultDM = null; + + for (final DisplayMode dm : dms) { + if (!dm.equals(defaultDM)) { + nonDefaultDM = dm; + break; + } + } + if (nonDefaultDM == null) { + System.err.println("Testcase is not applicable"); + return; + } + + final Frame frame = new Frame(); + frame.setBackground(Color.GREEN); + frame.setUndecorated(true); + try { + devices[0].setFullScreenWindow(frame); + sleep(); + devices[0].setDisplayMode(nonDefaultDM); + sleep(); + devices[1].setFullScreenWindow(frame); + sleep(); + if (!defaultDM.equals(devices[0].getDisplayMode())) { + throw new RuntimeException("DisplayMode is not restored"); + } + } finally { + // cleaning up + devices[0].setFullScreenWindow(null); + devices[1].setFullScreenWindow(null); + frame.dispose(); + } + } + private static void sleep() { + ((SunToolkit) Toolkit.getDefaultToolkit()).realSync(); + try { + Thread.sleep(1500); + } catch (InterruptedException ignored) { + } + } +} From 41c47ddf53a1337f7809796bd6ef6e115d97a37b Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Wed, 10 Jul 2013 13:25:07 +0530 Subject: [PATCH 082/123] 8020224: LinkageError: attempted duplicate class definition when --loader-per-compiler=false Reviewed-by: hannesw --- .../nashorn/internal/codegen/Compiler.java | 5 +- .../internal/runtime/CodeInstaller.java | 6 +++ .../jdk/nashorn/internal/runtime/Context.java | 12 +++++ .../runtime/TrustedScriptEngineTest.java | 51 +++++++++++++++++++ 4 files changed, 73 insertions(+), 1 deletion(-) diff --git a/nashorn/src/jdk/nashorn/internal/codegen/Compiler.java b/nashorn/src/jdk/nashorn/internal/codegen/Compiler.java index 72fcf178bea..e40986d4e4a 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/Compiler.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/Compiler.java @@ -528,7 +528,7 @@ public final class Compiler { return this.env; } - private static String safeSourceName(final Source source) { + private String safeSourceName(final Source source) { String baseName = new File(source.getName()).getName(); final int index = baseName.lastIndexOf(".js"); @@ -537,6 +537,9 @@ public final class Compiler { } baseName = baseName.replace('.', '_').replace('-', '_'); + if (! env._loader_per_compile) { + baseName = baseName + installer.getUniqueScriptId(); + } final String mangled = NameCodec.encode(baseName); return mangled != null ? mangled : baseName; diff --git a/nashorn/src/jdk/nashorn/internal/runtime/CodeInstaller.java b/nashorn/src/jdk/nashorn/internal/runtime/CodeInstaller.java index 80fac179cb0..be9976e7d84 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/CodeInstaller.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/CodeInstaller.java @@ -62,4 +62,10 @@ public interface CodeInstaller { * @param code bytecode to verify */ public void verify(final byte[] code); + + /** + * Get next unique script id + * @return unique script id + */ + public long getUniqueScriptId(); } diff --git a/nashorn/src/jdk/nashorn/internal/runtime/Context.java b/nashorn/src/jdk/nashorn/internal/runtime/Context.java index 7d639cd31c3..dae27cd9e42 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/Context.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/Context.java @@ -96,6 +96,11 @@ public final class Context { public void verify(final byte[] code) { context.verify(code); } + + @Override + public long getUniqueScriptId() { + return context.getUniqueScriptId(); + } } /** Is Context global debug mode enabled ? */ @@ -197,6 +202,9 @@ public final class Context { /** Current error manager. */ private final ErrorManager errors; + /** Unique id for script. Used only when --loader-per-compile=false */ + private long uniqueScriptId; + private static final ClassLoader myLoader = Context.class.getClassLoader(); private static final StructureLoader sharedLoader; private static final AccessControlContext NO_PERMISSIONS_CONTEXT; @@ -816,4 +824,8 @@ public final class Context { private ScriptObject newGlobalTrusted() { return new Global(this); } + + private synchronized long getUniqueScriptId() { + return uniqueScriptId++; + } } diff --git a/nashorn/test/src/jdk/nashorn/internal/runtime/TrustedScriptEngineTest.java b/nashorn/test/src/jdk/nashorn/internal/runtime/TrustedScriptEngineTest.java index 0f740a483c6..f7f7c6ae298 100644 --- a/nashorn/test/src/jdk/nashorn/internal/runtime/TrustedScriptEngineTest.java +++ b/nashorn/test/src/jdk/nashorn/internal/runtime/TrustedScriptEngineTest.java @@ -145,4 +145,55 @@ public class TrustedScriptEngineTest { fail("Cannot find nashorn factory!"); } + + @Test + /** + * Test repeated evals with --loader-per-compile=false + * We used to get "class redefinition error". + */ + public void noLoaderPerCompilerTest() { + final ScriptEngineManager sm = new ScriptEngineManager(); + for (ScriptEngineFactory fac : sm.getEngineFactories()) { + if (fac instanceof NashornScriptEngineFactory) { + final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac; + final String[] options = new String[] { "--loader-per-compile=false" }; + final ScriptEngine e = nfac.getScriptEngine(options); + try { + e.eval("2 + 3"); + e.eval("4 + 4"); + } catch (final ScriptException se) { + se.printStackTrace(); + fail(se.getMessage()); + } + return; + } + } + fail("Cannot find nashorn factory!"); + } + + @Test + /** + * Test that we can use same script name in repeated evals with --loader-per-compile=false + * We used to get "class redefinition error" as name was derived from script name. + */ + public void noLoaderPerCompilerWithSameNameTest() { + final ScriptEngineManager sm = new ScriptEngineManager(); + for (ScriptEngineFactory fac : sm.getEngineFactories()) { + if (fac instanceof NashornScriptEngineFactory) { + final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac; + final String[] options = new String[] { "--loader-per-compile=false" }; + final ScriptEngine e = nfac.getScriptEngine(options); + e.put(ScriptEngine.FILENAME, "test.js"); + try { + e.eval("2 + 3"); + e.eval("4 + 4"); + } catch (final ScriptException se) { + se.printStackTrace(); + fail(se.getMessage()); + } + return; + } + } + fail("Cannot find nashorn factory!"); + } } From 652b0209056637422dc9b76f479a558487e6cfc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hannes=20Walln=C3=B6fer?= Date: Wed, 10 Jul 2013 10:54:19 +0200 Subject: [PATCH 083/123] 8016681: regex capture behaves differently than on V8 Reviewed-by: lagergren, sundar --- .../runtime/regexp/RegExpScanner.java | 58 ++++++++++--------- nashorn/test/script/basic/JDK-8016681.js | 42 ++++++++++++++ .../test/script/basic/JDK-8016681.js.EXPECTED | 15 +++++ 3 files changed, 87 insertions(+), 28 deletions(-) create mode 100644 nashorn/test/script/basic/JDK-8016681.js create mode 100644 nashorn/test/script/basic/JDK-8016681.js.EXPECTED diff --git a/nashorn/src/jdk/nashorn/internal/runtime/regexp/RegExpScanner.java b/nashorn/src/jdk/nashorn/internal/runtime/regexp/RegExpScanner.java index 52829fac099..68df99f3af3 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/regexp/RegExpScanner.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/regexp/RegExpScanner.java @@ -57,7 +57,10 @@ final class RegExpScanner extends Scanner { private final LinkedList forwardReferences = new LinkedList<>(); /** Current level of zero-width negative lookahead assertions. */ - private int negativeLookaheadLevel; + private int negLookaheadLevel; + + /** Sequential id of current top-level zero-width negative lookahead assertion. */ + private int negLookaheadGroup; /** Are we currently inside a character class? */ private boolean inCharClass = false; @@ -68,17 +71,18 @@ final class RegExpScanner extends Scanner { private static final String NON_IDENT_ESCAPES = "$^*+(){}[]|\\.?-"; private static class Capture { - /** - * Zero-width negative lookaheads enclosing the capture. - */ - private final int negativeLookaheadLevel; + /** Zero-width negative lookaheads enclosing the capture. */ + private final int negLookaheadLevel; + /** Sequential id of top-level negative lookaheads containing the capture. */ + private final int negLookaheadGroup; - Capture(final int negativeLookaheadLevel) { - this.negativeLookaheadLevel = negativeLookaheadLevel; + Capture(final int negLookaheadGroup, final int negLookaheadLevel) { + this.negLookaheadGroup = negLookaheadGroup; + this.negLookaheadLevel = negLookaheadLevel; } - public int getNegativeLookaheadLevel() { - return negativeLookaheadLevel; + boolean isContained(final int group, final int level) { + return group == this.negLookaheadGroup && level >= this.negLookaheadLevel; } } @@ -152,7 +156,7 @@ final class RegExpScanner extends Scanner { BitVector vec = null; for (int i = 0; i < caps.size(); i++) { final Capture cap = caps.get(i); - if (cap.getNegativeLookaheadLevel() > 0) { + if (cap.negLookaheadLevel > 0) { if (vec == null) { vec = new BitVector(caps.size() + 1); } @@ -311,11 +315,14 @@ final class RegExpScanner extends Scanner { commit(3); if (isNegativeLookahead) { - negativeLookaheadLevel++; + if (negLookaheadLevel == 0) { + negLookaheadGroup++; + } + negLookaheadLevel++; } disjunction(); if (isNegativeLookahead) { - negativeLookaheadLevel--; + negLookaheadLevel--; } if (ch0 == ')') { @@ -432,20 +439,17 @@ final class RegExpScanner extends Scanner { } if (ch0 == '(') { - boolean capturingParens = true; commit(1); if (ch0 == '?' && ch1 == ':') { - capturingParens = false; commit(2); + } else { + caps.add(new Capture(negLookaheadGroup, negLookaheadLevel)); } disjunction(); if (ch0 == ')') { commit(1); - if (capturingParens) { - caps.add(new Capture(negativeLookaheadLevel)); - } return true; } } @@ -675,24 +679,22 @@ final class RegExpScanner extends Scanner { sb.setLength(sb.length() - 1); octalOrLiteral(Integer.toString(decimalValue), sb); - } else if (decimalValue <= caps.size() && caps.get(decimalValue - 1).getNegativeLookaheadLevel() > 0) { - // Captures that live inside a negative lookahead are dead after the - // lookahead and will be undefined if referenced from outside. - if (caps.get(decimalValue - 1).getNegativeLookaheadLevel() > negativeLookaheadLevel) { + } else if (decimalValue <= caps.size()) { + // Captures inside a negative lookahead are undefined when referenced from the outside. + if (!caps.get(decimalValue - 1).isContained(negLookaheadGroup, negLookaheadLevel)) { + // Reference to capture in negative lookahead, omit from output buffer. sb.setLength(sb.length() - 1); } else { + // Append backreference to output buffer. sb.append(decimalValue); } - } else if (decimalValue > caps.size()) { - // Forward reference to a capture group. Forward references are always undefined so we can omit - // it from the output buffer. However, if the target capture does not exist, we need to rewrite - // the reference as hex escape or literal string, so register the reference for later processing. + } else { + // Forward references to a capture group are always undefined so we can omit it from the output buffer. + // However, if the target capture does not exist, we need to rewrite the reference as hex escape + // or literal string, so register the reference for later processing. sb.setLength(sb.length() - 1); forwardReferences.add(decimalValue); forwardReferences.add(sb.length()); - } else { - // Append as backreference - sb.append(decimalValue); } } diff --git a/nashorn/test/script/basic/JDK-8016681.js b/nashorn/test/script/basic/JDK-8016681.js new file mode 100644 index 00000000000..9596b0ddbd3 --- /dev/null +++ b/nashorn/test/script/basic/JDK-8016681.js @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * 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. + */ + +/** + * JDK-8016681: regex capture behaves differently than on V8 + * + * @test + * @run + */ + +// regexp similar to the one used in marked.js +/^((?:[^\n]+\n?(?!( *[-*_]){3,} *(?:\n+|$)| *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)|([^\n]+)\n *(=|-){3,} *\n*))+)\n*/ + .exec("a\n\nb") + .forEach(function(e) { print(e); }); + +// simplified regexp +/(x(?!(a))(?!(b))y)/ + .exec("xy") + .forEach(function(e) { print(e); }); + +// should not match as cross-negative-lookeahead backreference \2 should be undefined +print(/(x(?!(a))(?!(b)\2))/.exec("xbc")); diff --git a/nashorn/test/script/basic/JDK-8016681.js.EXPECTED b/nashorn/test/script/basic/JDK-8016681.js.EXPECTED new file mode 100644 index 00000000000..06b855074ea --- /dev/null +++ b/nashorn/test/script/basic/JDK-8016681.js.EXPECTED @@ -0,0 +1,15 @@ +a + + +a + +undefined +undefined +undefined +undefined +undefined +xy +xy +undefined +undefined +null From 48c4649f17a8ce482c8b5a442d695b4d3fa3df94 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Wed, 10 Jul 2013 19:08:04 +0530 Subject: [PATCH 084/123] 8020276: interface checks in Invocable.getInterface implementation Reviewed-by: jlaskey, hannesw, attila --- .../api/scripting/NashornScriptEngine.java | 19 +++++++ .../jdk/nashorn/internal/runtime/Context.java | 15 ++++-- .../runtime/linker/JavaAdapterFactory.java | 11 +++++ .../api/scripting/ScriptEngineTest.java | 49 +++++++++++++++++++ 4 files changed, 90 insertions(+), 4 deletions(-) diff --git a/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java b/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java index d38e63c88b8..64574229d0a 100644 --- a/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java +++ b/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java @@ -33,6 +33,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.lang.reflect.Method; +import java.lang.reflect.Modifier; import java.net.URL; import java.nio.charset.Charset; import java.security.AccessController; @@ -184,6 +185,23 @@ public final class NashornScriptEngine extends AbstractScriptEngine implements C } private T getInterfaceInner(final Object self, final Class clazz) { + if (clazz == null || !clazz.isInterface()) { + throw new IllegalArgumentException("interface Class expected"); + } + + // perform security access check as early as possible + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + if (! Modifier.isPublic(clazz.getModifiers())) { + throw new SecurityException("attempt to implement non-public interfce: " + clazz); + } + final String fullName = clazz.getName(); + final int index = fullName.lastIndexOf('.'); + if (index != -1) { + sm.checkPackageAccess(fullName.substring(0, index)); + } + } + final ScriptObject realSelf; final ScriptObject ctxtGlobal = getNashornGlobalFrom(context); if(self == null) { @@ -193,6 +211,7 @@ public final class NashornScriptEngine extends AbstractScriptEngine implements C } else { realSelf = (ScriptObject)self; } + try { final ScriptObject oldGlobal = getNashornGlobal(); try { diff --git a/nashorn/src/jdk/nashorn/internal/runtime/Context.java b/nashorn/src/jdk/nashorn/internal/runtime/Context.java index dae27cd9e42..fb362b1725e 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/Context.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/Context.java @@ -36,6 +36,7 @@ import java.io.IOException; import java.io.PrintWriter; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; +import java.util.concurrent.atomic.AtomicLong; import java.net.MalformedURLException; import java.net.URL; import java.security.AccessControlContext; @@ -203,7 +204,7 @@ public final class Context { private final ErrorManager errors; /** Unique id for script. Used only when --loader-per-compile=false */ - private long uniqueScriptId; + private final AtomicLong uniqueScriptId; private static final ClassLoader myLoader = Context.class.getClassLoader(); private static final StructureLoader sharedLoader; @@ -263,7 +264,13 @@ public final class Context { this.env = new ScriptEnvironment(options, out, err); this._strict = env._strict; this.appLoader = appLoader; - this.scriptLoader = env._loader_per_compile? null : createNewLoader(); + if (env._loader_per_compile) { + this.scriptLoader = null; + this.uniqueScriptId = null; + } else { + this.scriptLoader = createNewLoader(); + this.uniqueScriptId = new AtomicLong(); + } this.errors = errors; // if user passed -classpath option, make a class loader with that and set it as @@ -825,7 +832,7 @@ public final class Context { return new Global(this); } - private synchronized long getUniqueScriptId() { - return uniqueScriptId++; + private long getUniqueScriptId() { + return uniqueScriptId.getAndIncrement(); } } diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java index f207d37cf66..77dcc695a0a 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java @@ -99,6 +99,17 @@ public final class JavaAdapterFactory { */ public static StaticClass getAdapterClassFor(final Class[] types, ScriptObject classOverrides) { assert types != null && types.length > 0; + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + for (Class type : types) { + // check for restricted package access + final String fullName = type.getName(); + final int index = fullName.lastIndexOf('.'); + if (index != -1) { + sm.checkPackageAccess(fullName.substring(0, index)); + } + } + } return getAdapterInfo(types).getAdapterClassFor(classOverrides); } diff --git a/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java b/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java index a6c015a1e54..73572502605 100644 --- a/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java +++ b/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java @@ -36,6 +36,7 @@ import java.io.StringWriter; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.concurrent.Callable; import javax.script.Bindings; import javax.script.Compilable; @@ -344,6 +345,23 @@ public class ScriptEngineTest { foo2.bar2(); } + @Test + /** + * Try passing non-interface Class object for interface implementation. + */ + public void getNonInterfaceGetInterfaceTest() { + final ScriptEngineManager manager = new ScriptEngineManager(); + final ScriptEngine engine = manager.getEngineByName("nashorn"); + try { + log(Objects.toString(((Invocable)engine).getInterface(Object.class))); + fail("Should have thrown IllegalArgumentException"); + } catch (final Exception exp) { + if (! (exp instanceof IllegalArgumentException)) { + fail("IllegalArgumentException expected, got " + exp); + } + } + } + @Test public void accessGlobalTest() { final ScriptEngineManager m = new ScriptEngineManager(); @@ -927,4 +945,35 @@ public class ScriptEngineTest { Assert.assertEquals(itf.test1(42, "a", "b"), "i == 42, strings instanceof java.lang.String[] == true, strings == [a, b]"); Assert.assertEquals(itf.test2(44, "c", "d", "e"), "arguments[0] == 44, arguments[1] instanceof java.lang.String[] == true, arguments[1] == [c, d, e]"); } + + @Test + /** + * Check that script can't implement sensitive package interfaces. + */ + public void checkSensitiveInterfaceImplTest() throws ScriptException { + final ScriptEngineManager m = new ScriptEngineManager(); + final ScriptEngine e = m.getEngineByName("nashorn"); + final Object[] holder = new Object[1]; + e.put("holder", holder); + // put an empty script object into array + e.eval("holder[0] = {}"); + // holder[0] is an object of some subclass of ScriptObject + Class ScriptObjectClass = holder[0].getClass().getSuperclass(); + Class PropertyAccessClass = ScriptObjectClass.getInterfaces()[0]; + // implementation methods for PropertyAccess class + e.eval("function set() {}; function get() {}; function getInt(){} " + + "function getDouble(){}; function getLong() {}; " + + "this.delete = function () {}; function has() {}; " + + "function hasOwnProperty() {}"); + + // get implementation of a restricted package interface + try { + log(Objects.toString(((Invocable)e).getInterface(PropertyAccessClass))); + fail("should have thrown SecurityException"); + } catch (final Exception exp) { + if (! (exp instanceof SecurityException)) { + fail("SecurityException expected, got " + exp); + } + } + } } From 701d77dfd1192fd17cc2cb9242262eabbb16ebc5 Mon Sep 17 00:00:00 2001 From: Jennifer Godinez Date: Wed, 10 Jul 2013 11:49:04 -0700 Subject: [PATCH 085/123] 8016737: After clicking on "Print UNCOLLATED" button, the print out come in order 'Page 1', 'Page 2', 'Page 1' Reviewed-by: jchen, prr --- .../solaris/classes/sun/print/IPPPrintService.java | 11 ++++++++++- .../classes/sun/print/UnixPrintServiceLookup.java | 4 ++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/jdk/src/solaris/classes/sun/print/IPPPrintService.java b/jdk/src/solaris/classes/sun/print/IPPPrintService.java index 1c441bd197e..dea62374103 100644 --- a/jdk/src/solaris/classes/sun/print/IPPPrintService.java +++ b/jdk/src/solaris/classes/sun/print/IPPPrintService.java @@ -1029,7 +1029,16 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { // now supports collation and that most OS has a way // of setting it, it is a safe assumption to just always // include SheetCollate as supported attribute. - catList.add(SheetCollate.class); + + /* + In Linux, we use Postscript for rendering but Linux still + has issues in propagating Postscript-embedded setpagedevice + setting like collation. Therefore, we temporarily exclude + Linux. + */ + if (!UnixPrintServiceLookup.isLinux()) { + catList.add(SheetCollate.class); + } } // With the assumption that Chromaticity is equivalent to diff --git a/jdk/src/solaris/classes/sun/print/UnixPrintServiceLookup.java b/jdk/src/solaris/classes/sun/print/UnixPrintServiceLookup.java index c682634b7b6..2c2a6406293 100644 --- a/jdk/src/solaris/classes/sun/print/UnixPrintServiceLookup.java +++ b/jdk/src/solaris/classes/sun/print/UnixPrintServiceLookup.java @@ -123,6 +123,10 @@ public class UnixPrintServiceLookup extends PrintServiceLookup return osname.equals("SunOS"); } + static boolean isLinux() { + return (osname.equals("Linux")); + } + static boolean isBSD() { return (osname.equals("Linux") || osname.contains("OS X")); From 0f82640543629c9264c216ffabf5a6e4553e5ee2 Mon Sep 17 00:00:00 2001 From: Bengt Rutisson Date: Thu, 11 Jul 2013 11:33:27 +0200 Subject: [PATCH 086/123] 8020155: PSR:PERF G1 not collecting old regions when humongous allocations interfer Take _last_young_gc into account when deciding on starting a concurrent mark. Also reviewed-by: per.liden@oracle.com. Reviewed-by: tschatzl, johnc --- .../src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp index 3bd04281955..4c6d2bbf877 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp @@ -873,7 +873,7 @@ bool G1CollectorPolicy::need_to_start_conc_mark(const char* source, size_t alloc 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 @@ void G1CollectorPolicy::record_collection_pause_end(double pause_time_ms, Evacua 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. From f0144d9d93a3b2907573437f448ecf45d8bb2858 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Thu, 11 Jul 2013 16:34:55 +0530 Subject: [PATCH 087/123] 8020325: static property does not work on accessible, public classes Reviewed-by: attila, hannesw, lagergren --- nashorn/make/build.xml | 6 ++- .../api/scripting/NashornScriptEngine.java | 6 +-- .../internal/codegen/CodeGenerator.java | 2 +- .../nashorn/internal/codegen/Compiler.java | 4 +- .../jdk/nashorn/internal/lookup/Lookup.java | 2 - .../nashorn/internal/objects/NativeDebug.java | 3 ++ .../internal/objects/NativeNumber.java | 1 - .../internal/objects/ScriptFunctionImpl.java | 4 +- .../jdk/nashorn/internal/runtime/Context.java | 34 ++++++++--------- .../runtime/linker/JavaAdapterFactory.java | 9 ++--- .../runtime/linker/ReflectionCheckLinker.java | 23 +++++++++++ nashorn/test/script/basic/JDK-8020325.js | 38 +++++++++++++++++++ .../test/script/basic/JDK-8020325.js.EXPECTED | 4 ++ nashorn/test/script/trusted/JDK-8006529.js | 28 +++++++------- .../api/scripting/ScriptEngineTest.java | 2 +- 15 files changed, 111 insertions(+), 55 deletions(-) create mode 100644 nashorn/test/script/basic/JDK-8020325.js create mode 100644 nashorn/test/script/basic/JDK-8020325.js.EXPECTED diff --git a/nashorn/make/build.xml b/nashorn/make/build.xml index da2ded1ea1d..2bda503fd88 100644 --- a/nashorn/make/build.xml +++ b/nashorn/make/build.xml @@ -219,8 +219,10 @@ target="${javac.target}" debug="${javac.debug}" encoding="${javac.encoding}" - includeantruntime="false"> - + includeantruntime="false" fork="true"> + + + diff --git a/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java b/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java index 64574229d0a..682975a85d5 100644 --- a/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java +++ b/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java @@ -195,11 +195,7 @@ public final class NashornScriptEngine extends AbstractScriptEngine implements C if (! Modifier.isPublic(clazz.getModifiers())) { throw new SecurityException("attempt to implement non-public interfce: " + clazz); } - final String fullName = clazz.getName(); - final int index = fullName.lastIndexOf('.'); - if (index != -1) { - sm.checkPackageAccess(fullName.substring(0, index)); - } + Context.checkPackageAccess(clazz.getName()); } final ScriptObject realSelf; diff --git a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java index 250c44c1541..b9d35682458 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java @@ -1313,7 +1313,7 @@ final class CodeGenerator extends NodeOperatorVisitor literalNode) { assert literalNode.getSymbol() != null : literalNode + " has no symbol"; load(literalNode).store(literalNode.getSymbol()); return false; diff --git a/nashorn/src/jdk/nashorn/internal/codegen/Compiler.java b/nashorn/src/jdk/nashorn/internal/codegen/Compiler.java index e40986d4e4a..a31358f6503 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/Compiler.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/Compiler.java @@ -528,8 +528,8 @@ public final class Compiler { return this.env; } - private String safeSourceName(final Source source) { - String baseName = new File(source.getName()).getName(); + private String safeSourceName(final Source src) { + String baseName = new File(src.getName()).getName(); final int index = baseName.lastIndexOf(".js"); if (index != -1) { diff --git a/nashorn/src/jdk/nashorn/internal/lookup/Lookup.java b/nashorn/src/jdk/nashorn/internal/lookup/Lookup.java index e874cfd7bbe..0dd2741e00c 100644 --- a/nashorn/src/jdk/nashorn/internal/lookup/Lookup.java +++ b/nashorn/src/jdk/nashorn/internal/lookup/Lookup.java @@ -32,8 +32,6 @@ import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import jdk.nashorn.internal.runtime.JSType; -import jdk.nashorn.internal.runtime.Property; -import jdk.nashorn.internal.runtime.PropertyMap; import jdk.nashorn.internal.runtime.ScriptRuntime; /** diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeDebug.java b/nashorn/src/jdk/nashorn/internal/objects/NativeDebug.java index 30a4228958e..82757cbae51 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeDebug.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeDebug.java @@ -179,6 +179,9 @@ public final class NativeDebug extends ScriptObject { /** * Returns the property listener count for a script object + * + * @param self self reference + * @param obj script object whose listener count is returned * @return listener count */ @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeNumber.java b/nashorn/src/jdk/nashorn/internal/objects/NativeNumber.java index c69478967f4..d9d568b7e38 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/NativeNumber.java +++ b/nashorn/src/jdk/nashorn/internal/objects/NativeNumber.java @@ -48,7 +48,6 @@ import jdk.nashorn.internal.runtime.JSType; import jdk.nashorn.internal.runtime.PropertyMap; import jdk.nashorn.internal.runtime.ScriptObject; import jdk.nashorn.internal.runtime.ScriptRuntime; -import jdk.nashorn.internal.lookup.MethodHandleFactory; import jdk.nashorn.internal.runtime.linker.PrimitiveLookup; /** diff --git a/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java b/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java index 643d9acddf3..88421a70bd1 100644 --- a/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java +++ b/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java @@ -212,10 +212,10 @@ public class ScriptFunctionImpl extends ScriptFunction { // Instance of this class is used as global anonymous function which // serves as Function.prototype object. private static class AnonymousFunction extends ScriptFunctionImpl { - private static final PropertyMap map$ = PropertyMap.newMap().setIsShared(); + private static final PropertyMap anonmap$ = PropertyMap.newMap().setIsShared(); static PropertyMap getInitialMap() { - return map$; + return anonmap$; } AnonymousFunction(final Global global) { diff --git a/nashorn/src/jdk/nashorn/internal/runtime/Context.java b/nashorn/src/jdk/nashorn/internal/runtime/Context.java index fb362b1725e..9d603c66b72 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/Context.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/Context.java @@ -39,13 +39,10 @@ import java.lang.invoke.MethodHandles; import java.util.concurrent.atomic.AtomicLong; import java.net.MalformedURLException; import java.net.URL; -import java.security.AccessControlContext; import java.security.AccessController; import java.security.CodeSigner; import java.security.CodeSource; -import java.security.Permissions; import java.security.PrivilegedAction; -import java.security.ProtectionDomain; import java.util.Map; import jdk.internal.org.objectweb.asm.ClassReader; import jdk.internal.org.objectweb.asm.util.CheckClassAdapter; @@ -208,7 +205,6 @@ public final class Context { private static final ClassLoader myLoader = Context.class.getClassLoader(); private static final StructureLoader sharedLoader; - private static final AccessControlContext NO_PERMISSIONS_CONTEXT; static { sharedLoader = AccessController.doPrivileged(new PrivilegedAction() { @@ -217,7 +213,6 @@ public final class Context { return new StructureLoader(myLoader, null); } }); - NO_PERMISSIONS_CONTEXT = new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, new Permissions()) }); } /** @@ -559,6 +554,21 @@ public final class Context { return Class.forName(fullName, true, sharedLoader); } + /** + * Checks that the given package can be accessed from current call stack. + * + * @param fullName fully qualified package name + */ + public static void checkPackageAccess(final String fullName) { + final int index = fullName.lastIndexOf('.'); + if (index != -1) { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPackageAccess(fullName.substring(0, index)); + } + } + } + /** * Lookup a Java class. This is used for JSR-223 stuff linking in from * {@code jdk.nashorn.internal.objects.NativeJava} and {@code jdk.nashorn.internal.runtime.NativeJavaPackage} @@ -571,19 +581,7 @@ public final class Context { */ public Class findClass(final String fullName) throws ClassNotFoundException { // check package access as soon as possible! - final int index = fullName.lastIndexOf('.'); - if (index != -1) { - final SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - sm.checkPackageAccess(fullName.substring(0, index)); - return null; - } - }, NO_PERMISSIONS_CONTEXT); - } - } + checkPackageAccess(fullName); // try the script -classpath loader, if that is set if (classPathLoader != null) { diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java index 77dcc695a0a..472b8dcd727 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java @@ -43,6 +43,7 @@ import java.util.Map; import jdk.internal.dynalink.beans.StaticClass; import jdk.internal.dynalink.support.LinkRequestImpl; import jdk.nashorn.internal.objects.NativeJava; +import jdk.nashorn.internal.runtime.Context; import jdk.nashorn.internal.runtime.ECMAException; import jdk.nashorn.internal.runtime.ScriptFunction; import jdk.nashorn.internal.runtime.ScriptObject; @@ -101,13 +102,9 @@ public final class JavaAdapterFactory { assert types != null && types.length > 0; final SecurityManager sm = System.getSecurityManager(); if (sm != null) { - for (Class type : types) { + for (Class type : types) { // check for restricted package access - final String fullName = type.getName(); - final int index = fullName.lastIndexOf('.'); - if (index != -1) { - sm.checkPackageAccess(fullName.substring(0, index)); - } + Context.checkPackageAccess(type.getName()); } } return getAdapterInfo(types).getAdapterClassFor(classOverrides); diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/ReflectionCheckLinker.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/ReflectionCheckLinker.java index eb8837a8d70..53c652cab15 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/linker/ReflectionCheckLinker.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/ReflectionCheckLinker.java @@ -25,10 +25,14 @@ package jdk.nashorn.internal.runtime.linker; +import java.lang.reflect.Modifier; +import jdk.internal.dynalink.CallSiteDescriptor; import jdk.internal.dynalink.linker.GuardedInvocation; import jdk.internal.dynalink.linker.LinkRequest; import jdk.internal.dynalink.linker.LinkerServices; import jdk.internal.dynalink.linker.TypeBasedGuardingDynamicLinker; +import jdk.internal.dynalink.support.CallSiteDescriptorFactory; +import jdk.nashorn.internal.runtime.Context; /** * Check java reflection permission for java reflective and java.lang.invoke access from scripts @@ -52,6 +56,25 @@ final class ReflectionCheckLinker implements TypeBasedGuardingDynamicLinker{ throws Exception { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { + final LinkRequest requestWithoutContext = origRequest.withoutRuntimeContext(); // Nashorn has no runtime context + final Object self = requestWithoutContext.getReceiver(); + // allow 'static' access on Class objects representing public classes of non-restricted packages + if ((self instanceof Class) && Modifier.isPublic(((Class)self).getModifiers())) { + final CallSiteDescriptor desc = requestWithoutContext.getCallSiteDescriptor(); + final String operator = CallSiteDescriptorFactory.tokenizeOperators(desc).get(0); + // check for 'get' on 'static' property + switch (operator) { + case "getProp": + case "getMethod": { + if ("static".equals(desc.getNameToken(CallSiteDescriptor.NAME_OPERAND))) { + Context.checkPackageAccess(((Class)self).getName()); + // let bean linker do the actual linking part + return null; + } + } + break; + } // fall through for all other stuff + } sm.checkPermission(new RuntimePermission("nashorn.JavaReflection")); } // let the next linker deal with actual linking diff --git a/nashorn/test/script/basic/JDK-8020325.js b/nashorn/test/script/basic/JDK-8020325.js new file mode 100644 index 00000000000..5c8e64f530d --- /dev/null +++ b/nashorn/test/script/basic/JDK-8020325.js @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * 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. + */ + +/** + * JDK-8020325: static property does not work on accessible, public classes + * + * @test + * @run + */ + +function printStatic(obj) { + print(obj.getClass().static); +} + +printStatic(new java.util.ArrayList()); +printStatic(new java.util.HashMap()); +printStatic(new java.lang.Object()); +printStatic(new (Java.type("java.lang.Object[]"))(0)); diff --git a/nashorn/test/script/basic/JDK-8020325.js.EXPECTED b/nashorn/test/script/basic/JDK-8020325.js.EXPECTED new file mode 100644 index 00000000000..96542b75cf3 --- /dev/null +++ b/nashorn/test/script/basic/JDK-8020325.js.EXPECTED @@ -0,0 +1,4 @@ +[JavaClass java.util.ArrayList] +[JavaClass java.util.HashMap] +[JavaClass java.lang.Object] +[JavaClass [Ljava.lang.Object;] diff --git a/nashorn/test/script/trusted/JDK-8006529.js b/nashorn/test/script/trusted/JDK-8006529.js index 378cd6cf7a6..6837fcd8d83 100644 --- a/nashorn/test/script/trusted/JDK-8006529.js +++ b/nashorn/test/script/trusted/JDK-8006529.js @@ -39,21 +39,19 @@ * and FunctionNode because of package-access check and so reflective calls. */ -var forName = java.lang.Class["forName(String)"] - -var Parser = forName("jdk.nashorn.internal.parser.Parser").static -var Compiler = forName("jdk.nashorn.internal.codegen.Compiler").static -var Context = forName("jdk.nashorn.internal.runtime.Context").static -var ScriptEnvironment = forName("jdk.nashorn.internal.runtime.ScriptEnvironment").static -var Source = forName("jdk.nashorn.internal.runtime.Source").static -var FunctionNode = forName("jdk.nashorn.internal.ir.FunctionNode").static -var Block = forName("jdk.nashorn.internal.ir.Block").static -var VarNode = forName("jdk.nashorn.internal.ir.VarNode").static -var ExecuteNode = forName("jdk.nashorn.internal.ir.ExecuteNode").static -var UnaryNode = forName("jdk.nashorn.internal.ir.UnaryNode").static -var BinaryNode = forName("jdk.nashorn.internal.ir.BinaryNode").static -var ThrowErrorManager = forName("jdk.nashorn.internal.runtime.Context$ThrowErrorManager").static -var Debug = forName("jdk.nashorn.internal.runtime.Debug").static +var Parser = Java.type("jdk.nashorn.internal.parser.Parser") +var Compiler = Java.type("jdk.nashorn.internal.codegen.Compiler") +var Context = Java.type("jdk.nashorn.internal.runtime.Context") +var ScriptEnvironment = Java.type("jdk.nashorn.internal.runtime.ScriptEnvironment") +var Source = Java.type("jdk.nashorn.internal.runtime.Source") +var FunctionNode = Java.type("jdk.nashorn.internal.ir.FunctionNode") +var Block = Java.type("jdk.nashorn.internal.ir.Block") +var VarNode = Java.type("jdk.nashorn.internal.ir.VarNode") +var ExecuteNode = Java.type("jdk.nashorn.internal.ir.ExecuteNode") +var UnaryNode = Java.type("jdk.nashorn.internal.ir.UnaryNode") +var BinaryNode = Java.type("jdk.nashorn.internal.ir.BinaryNode") +var ThrowErrorManager = Java.type("jdk.nashorn.internal.runtime.Context$ThrowErrorManager") +var Debug = Java.type("jdk.nashorn.internal.runtime.Debug") var parseMethod = Parser.class.getMethod("parse"); var compileMethod = Compiler.class.getMethod("compile", FunctionNode.class); diff --git a/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java b/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java index 73572502605..1ba08657a6f 100644 --- a/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java +++ b/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java @@ -968,7 +968,7 @@ public class ScriptEngineTest { // get implementation of a restricted package interface try { - log(Objects.toString(((Invocable)e).getInterface(PropertyAccessClass))); + log(Objects.toString(((Invocable)e).getInterface((Class)PropertyAccessClass))); fail("should have thrown SecurityException"); } catch (final Exception exp) { if (! (exp instanceof SecurityException)) { From f22f9eb04b4f8b9e0b2b3c7c3a756664ed1d15ee Mon Sep 17 00:00:00 2001 From: Petr Pchelko Date: Thu, 11 Jul 2013 16:42:13 +0400 Subject: [PATCH 088/123] 8020210: [macosx] JVM crashes in CWrapper$NSWindow.screen(long) Reviewed-by: anthony, art --- .../sun/lwawt/macosx/CPlatformWindow.java | 22 ++-- .../classes/sun/lwawt/macosx/CWrapper.java | 8 -- jdk/src/macosx/native/sun/awt/CWrapper.m | 111 ------------------ .../MaximizeOffscreenTest.java | 67 +++++++++++ 4 files changed, 76 insertions(+), 132 deletions(-) create mode 100644 jdk/test/java/awt/Window/MaximizeOffscreen/MaximizeOffscreenTest.java diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java index 7230b2eeeb5..dc711c28f0e 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java @@ -479,12 +479,14 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo 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 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo // 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); } diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java index 67d3ea1cf1f..7dc421e26b1 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java @@ -71,8 +71,6 @@ public final class CWrapper { 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 final class CWrapper { 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(); } diff --git a/jdk/src/macosx/native/sun/awt/CWrapper.m b/jdk/src/macosx/native/sun/awt/CWrapper.m index bef1d47cb9f..ccc688e802d 100644 --- a/jdk/src/macosx/native/sun/awt/CWrapper.m +++ b/jdk/src/macosx/native/sun/awt/CWrapper.m @@ -396,31 +396,6 @@ JNF_COCOA_ENTER(env); JNF_COCOA_EXIT(env); } -/* - * 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_ENTER(env); 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 diff --git a/jdk/test/java/awt/Window/MaximizeOffscreen/MaximizeOffscreenTest.java b/jdk/test/java/awt/Window/MaximizeOffscreen/MaximizeOffscreenTest.java new file mode 100644 index 00000000000..014637acec0 --- /dev/null +++ b/jdk/test/java/awt/Window/MaximizeOffscreen/MaximizeOffscreenTest.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test @summary JVM crash if the frame maximized from offscreen + * @author Petr Pchelko + * @library ../../regtesthelpers + * @build Util + * @compile MaximizeOffscreenTest.java + * @run main/othervm MaximizeOffscreenTest + */ + +import test.java.awt.regtesthelpers.Util; + +import javax.swing.*; +import java.awt.*; + +public class MaximizeOffscreenTest { + + private static JFrame frame; + + public static void main(String[] args) throws Throwable { + + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + constructTestUI(); + } + }); + + Util.waitForIdle(null); + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + frame.setExtendedState(Frame.MAXIMIZED_BOTH); + } + }); + Util.waitForIdle(null); + } + + private static void constructTestUI() { + frame = new JFrame("Test frame"); + frame.setUndecorated(true); + frame.setBounds(-1000, -1000, 100, 100); + frame.setVisible(true); + } +} From 80f5124f23fb0e7288b03382aede08ff87f4d3ac Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Thu, 11 Jul 2013 18:23:13 +0530 Subject: [PATCH 089/123] 8020380: __noSuchProperty__ defined in mozilla_compat.js script should be non-enumerable Reviewed-by: jlaskey, hannesw, attila --- .../runtime/resources/mozilla_compat.js | 7 +++- nashorn/test/script/basic/JDK-8020380.js | 36 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 nashorn/test/script/basic/JDK-8020380.js diff --git a/nashorn/src/jdk/nashorn/internal/runtime/resources/mozilla_compat.js b/nashorn/src/jdk/nashorn/internal/runtime/resources/mozilla_compat.js index 206a193f7fa..8a9fcc7de0c 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/resources/mozilla_compat.js +++ b/nashorn/src/jdk/nashorn/internal/runtime/resources/mozilla_compat.js @@ -48,7 +48,7 @@ Object.defineProperty(this, "importPackage", { var _packages = []; var global = this; var oldNoSuchProperty = global.__noSuchProperty__; - global.__noSuchProperty__ = function(name) { + var __noSuchProperty__ = function(name) { 'use strict'; for (var i in _packages) { try { @@ -69,6 +69,11 @@ Object.defineProperty(this, "importPackage", { } } + Object.defineProperty(global, "__noSuchProperty__", { + writable: true, configurable: true, enumerable: false, + value: __noSuchProperty__ + }); + var prefix = "[JavaPackage "; return function() { for (var i in arguments) { diff --git a/nashorn/test/script/basic/JDK-8020380.js b/nashorn/test/script/basic/JDK-8020380.js new file mode 100644 index 00000000000..90357fa7606 --- /dev/null +++ b/nashorn/test/script/basic/JDK-8020380.js @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * 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. + */ + +/** + * JDK-8020380: __noSuchProperty__ defined in mozilla_compat.js script should be non-enumerable + * + * @test + * @run + */ + +load("nashorn:mozilla_compat.js"); + +var desc = Object.getOwnPropertyDescriptor(this, "__noSuchProperty__"); +if (typeof desc.enumerable != 'boolean' || desc.enumerable != false) { + fail("__noSuchProperty__ is enumerable"); +} From b3a5f0ec3878822c8c23d0c183702d7ce8d50217 Mon Sep 17 00:00:00 2001 From: Leonid Romanov Date: Thu, 11 Jul 2013 18:23:15 +0400 Subject: [PATCH 090/123] 8020038: [macosx] Incorrect usage of invokeLater() and likes in callbacks called via JNI from AppKit thread Reviewed-by: art, anthony --- .../com/apple/eawt/FullScreenHandler.java | 3 +- .../com/apple/eawt/_AppEventHandler.java | 100 ++++++++++++------ .../com/apple/eawt/event/GestureHandler.java | 4 +- .../classes/com/apple/laf/ScreenMenu.java | 9 +- .../sun/lwawt/macosx/CCheckboxMenuItem.java | 4 +- .../sun/lwawt/macosx/CViewEmbeddedFrame.java | 4 +- 6 files changed, 80 insertions(+), 44 deletions(-) diff --git a/jdk/src/macosx/classes/com/apple/eawt/FullScreenHandler.java b/jdk/src/macosx/classes/com/apple/eawt/FullScreenHandler.java index f5a843bcdbf..64e81b08a00 100644 --- a/jdk/src/macosx/classes/com/apple/eawt/FullScreenHandler.java +++ b/jdk/src/macosx/classes/com/apple/eawt/FullScreenHandler.java @@ -32,6 +32,7 @@ import java.util.List; import javax.swing.RootPaneContainer; import com.apple.eawt.AppEvent.FullScreenEvent; +import sun.awt.SunToolkit; import java.lang.annotation.Native; @@ -75,7 +76,7 @@ final class FullScreenHandler { 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); diff --git a/jdk/src/macosx/classes/com/apple/eawt/_AppEventHandler.java b/jdk/src/macosx/classes/com/apple/eawt/_AppEventHandler.java index a380e8412fd..b98d5739510 100644 --- a/jdk/src/macosx/classes/com/apple/eawt/_AppEventHandler.java +++ b/jdk/src/macosx/classes/com/apple/eawt/_AppEventHandler.java @@ -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.io.File; 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 _AppEventHandler { } class _AppReOpenedDispatcher extends _AppEventMultiplexor { - void performOnListeners(final List 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 @@ class _AppEventHandler { } abstract class _AppEventMultiplexor { - final List _listeners = new ArrayList(0); + private final Map listenerToAppContext = + new IdentityHashMap(); boolean nativeListenerRegistered; // called from AppKit Thread-0 void dispatch(final _NativeEvent event, final Object... args) { - // grab a local ref to the listeners - final List localListeners; + // grab a local ref to the listeners and its contexts as an array of the map's entries + final ArrayList> localEntries; synchronized (this) { - if (_listeners.size() == 0) return; - localListeners = new ArrayList(_listeners); + if (listenerToAppContext.size() == 0) { + return; + } + localEntries = new ArrayList>(listenerToAppContext.size()); + localEntries.addAll(listenerToAppContext.entrySet()); } - EventQueue.invokeLater(new Runnable() { - public void run() { - performOnListeners(localListeners, event); - } - }); + for (final Map.Entry 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 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 extends _AppEventMultiplexor { @Override - void performOnListeners(final List 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 @@ class _AppEventHandler { */ abstract class _AppEventDispatcher { 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 @@ class _AppEventHandler { 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 extends _AppEventDispatcher { @@ -531,6 +561,8 @@ class _AppEventHandler { 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 diff --git a/jdk/src/macosx/classes/com/apple/eawt/event/GestureHandler.java b/jdk/src/macosx/classes/com/apple/eawt/event/GestureHandler.java index 1378a2c808e..4514da90ca9 100644 --- a/jdk/src/macosx/classes/com/apple/eawt/event/GestureHandler.java +++ b/jdk/src/macosx/classes/com/apple/eawt/event/GestureHandler.java @@ -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 @@ final class GestureHandler { 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); diff --git a/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java b/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java index 23c55c8d2a1..5f78ff6e061 100644 --- a/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java +++ b/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java @@ -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 java.util.Hashtable; import javax.swing.*; +import sun.awt.SunToolkit; import sun.lwawt.LWToolkit; import sun.lwawt.macosx.*; @@ -144,7 +145,7 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S updateItems(); fItemBounds = new Rectangle[invoker.getMenuComponentCount()]; } - }, null); + }, invoker); } catch (final Exception e) { System.err.println(e); e.printStackTrace(); @@ -172,7 +173,7 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S fItemBounds = null; } - }, null); + }, invoker); } catch (final Exception e) { e.printStackTrace(); } @@ -200,7 +201,7 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S if (kind == 0) return; if (fItemBounds == null) return; - SwingUtilities.invokeLater(new Runnable() { + SunToolkit.executeOnEventHandlerThread(fInvoker, new Runnable() { @Override public void run() { Component target = null; diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CCheckboxMenuItem.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CCheckboxMenuItem.java index 9b59ceaef9b..da53c302ad5 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CCheckboxMenuItem.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CCheckboxMenuItem.java @@ -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 class CCheckboxMenuItem extends CMenuItem implements CheckboxMenuItemPeer 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); } diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CViewEmbeddedFrame.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CViewEmbeddedFrame.java index 306cfb1e12e..28acc26f6cc 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CViewEmbeddedFrame.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CViewEmbeddedFrame.java @@ -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 @@ public class CViewEmbeddedFrame extends EmbeddedFrame { validate(); setVisible(true); } - }, null); + }, this); } catch (InterruptedException | InvocationTargetException ex) {} } } From 4eb5c9e3a42cdda2c0bf7d79920844f8b8c9d1ee Mon Sep 17 00:00:00 2001 From: Attila Szegedi Date: Thu, 11 Jul 2013 18:33:33 +0200 Subject: [PATCH 091/123] 8013925: Remove symbol fields from nodes that don't need them Reviewed-by: jlaskey, lagergren --- .../jdk/nashorn/internal/codegen/Attr.java | 113 ++++----- .../internal/codegen/BranchOptimizer.java | 14 +- .../internal/codegen/CodeGenerator.java | 236 +++++++++--------- .../internal/codegen/CompilationPhase.java | 26 +- .../internal/codegen/FinalizeTypes.java | 81 +++--- .../internal/codegen/FoldConstants.java | 8 +- .../internal/codegen/FunctionSignature.java | 8 +- .../jdk/nashorn/internal/codegen/Lower.java | 69 ++--- .../internal/codegen/RangeAnalyzer.java | 11 +- .../internal/codegen/SpillObjectCreator.java | 17 +- .../nashorn/internal/codegen/Splitter.java | 6 +- .../nashorn/internal/codegen/WeighNodes.java | 7 +- .../jdk/nashorn/internal/ir/AccessNode.java | 8 +- .../jdk/nashorn/internal/ir/Assignment.java | 4 +- .../src/jdk/nashorn/internal/ir/BaseNode.java | 11 +- .../jdk/nashorn/internal/ir/BinaryNode.java | 26 +- .../src/jdk/nashorn/internal/ir/Block.java | 36 ++- .../nashorn/internal/ir/BlockStatement.java | 115 +++++++++ .../nashorn/internal/ir/BreakableNode.java | 47 +--- .../internal/ir/BreakableStatement.java | 91 +++++++ .../src/jdk/nashorn/internal/ir/CallNode.java | 57 +++-- .../src/jdk/nashorn/internal/ir/CaseNode.java | 12 +- .../jdk/nashorn/internal/ir/CatchNode.java | 12 +- .../jdk/nashorn/internal/ir/Expression.java | 99 ++++++++ ...cuteNode.java => ExpressionStatement.java} | 20 +- .../src/jdk/nashorn/internal/ir/ForNode.java | 28 +-- .../jdk/nashorn/internal/ir/FunctionNode.java | 17 +- .../jdk/nashorn/internal/ir/IdentNode.java | 3 +- .../src/jdk/nashorn/internal/ir/IfNode.java | 12 +- .../jdk/nashorn/internal/ir/IndexNode.java | 16 +- .../jdk/nashorn/internal/ir/LabelNode.java | 2 +- .../nashorn/internal/ir/LexicalContext.java | 9 +- .../internal/ir/LexicalContextExpression.java | 59 +++++ .../internal/ir/LexicalContextNode.java | 53 +--- .../internal/ir/LexicalContextStatement.java | 55 ++++ .../jdk/nashorn/internal/ir/LiteralNode.java | 28 +-- .../src/jdk/nashorn/internal/ir/LoopNode.java | 13 +- nashorn/src/jdk/nashorn/internal/ir/Node.java | 55 ---- .../jdk/nashorn/internal/ir/ObjectNode.java | 2 +- .../jdk/nashorn/internal/ir/PropertyNode.java | 16 +- .../jdk/nashorn/internal/ir/ReturnNode.java | 13 +- .../jdk/nashorn/internal/ir/RuntimeNode.java | 25 +- .../jdk/nashorn/internal/ir/SplitNode.java | 7 +- .../jdk/nashorn/internal/ir/SwitchNode.java | 15 +- .../nashorn/internal/ir/TemporarySymbols.java | 2 +- .../jdk/nashorn/internal/ir/TernaryNode.java | 120 ++++----- .../jdk/nashorn/internal/ir/ThrowNode.java | 12 +- .../jdk/nashorn/internal/ir/UnaryNode.java | 23 +- .../src/jdk/nashorn/internal/ir/VarNode.java | 22 +- .../jdk/nashorn/internal/ir/WhileNode.java | 12 +- .../src/jdk/nashorn/internal/ir/WithNode.java | 12 +- .../nashorn/internal/ir/debug/ASTWriter.java | 22 +- .../nashorn/internal/ir/debug/JSONWriter.java | 29 ++- .../internal/ir/debug/PrintVisitor.java | 16 +- .../ir/visitor/NodeOperatorVisitor.java | 2 - .../internal/ir/visitor/NodeVisitor.java | 39 ++- .../nashorn/internal/parser/JSONParser.java | 13 +- .../jdk/nashorn/internal/parser/Parser.java | 170 +++++++------ .../linker/NashornCallSiteDescriptor.java | 3 +- nashorn/test/script/trusted/JDK-8006529.js | 30 +-- 60 files changed, 1236 insertions(+), 853 deletions(-) create mode 100644 nashorn/src/jdk/nashorn/internal/ir/BlockStatement.java create mode 100644 nashorn/src/jdk/nashorn/internal/ir/BreakableStatement.java create mode 100644 nashorn/src/jdk/nashorn/internal/ir/Expression.java rename nashorn/src/jdk/nashorn/internal/ir/{ExecuteNode.java => ExpressionStatement.java} (78%) create mode 100644 nashorn/src/jdk/nashorn/internal/ir/LexicalContextExpression.java create mode 100644 nashorn/src/jdk/nashorn/internal/ir/LexicalContextStatement.java diff --git a/nashorn/src/jdk/nashorn/internal/codegen/Attr.java b/nashorn/src/jdk/nashorn/internal/codegen/Attr.java index e076825dfe0..f56a881def6 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/Attr.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/Attr.java @@ -61,6 +61,7 @@ import jdk.nashorn.internal.ir.Block; import jdk.nashorn.internal.ir.CallNode; import jdk.nashorn.internal.ir.CaseNode; import jdk.nashorn.internal.ir.CatchNode; +import jdk.nashorn.internal.ir.Expression; import jdk.nashorn.internal.ir.ForNode; import jdk.nashorn.internal.ir.FunctionNode; import jdk.nashorn.internal.ir.FunctionNode.CompilationState; @@ -72,7 +73,6 @@ import jdk.nashorn.internal.ir.LiteralNode; import jdk.nashorn.internal.ir.LiteralNode.ArrayLiteralNode; import jdk.nashorn.internal.ir.Node; import jdk.nashorn.internal.ir.ObjectNode; -import jdk.nashorn.internal.ir.PropertyNode; import jdk.nashorn.internal.ir.ReturnNode; import jdk.nashorn.internal.ir.RuntimeNode; import jdk.nashorn.internal.ir.RuntimeNode.Request; @@ -512,7 +512,6 @@ final class Attr extends NodeOperatorVisitor { assert nameSymbol != null; selfInit = selfInit.setName((IdentNode)name.setSymbol(lc, nameSymbol)); - selfInit = (VarNode)selfInit.setSymbol(lc, nameSymbol); newStatements.add(selfInit); newStatements.addAll(body.getStatements()); @@ -739,15 +738,9 @@ final class Attr extends NodeOperatorVisitor { return end(ensureSymbol(Type.OBJECT, objectNode)); } - @Override - public Node leavePropertyNode(final PropertyNode propertyNode) { - // assign a pseudo symbol to property name, see NASHORN-710 - return propertyNode.setSymbol(lc, new Symbol(propertyNode.getKeyName(), 0, Type.OBJECT)); - } - @Override public Node leaveReturnNode(final ReturnNode returnNode) { - final Node expr = returnNode.getExpression(); + final Expression expr = returnNode.getExpression(); final Type returnType; if (expr != null) { @@ -784,7 +777,7 @@ final class Attr extends NodeOperatorVisitor { final LiteralNode lit = (LiteralNode)test; if (lit.isNumeric() && !(lit.getValue() instanceof Integer)) { if (JSType.isRepresentableAsInt(lit.getNumber())) { - newCaseNode = caseNode.setTest(LiteralNode.newInstance(lit, lit.getInt32()).accept(this)); + newCaseNode = caseNode.setTest((Expression)LiteralNode.newInstance(lit, lit.getInt32()).accept(this)); } } } else { @@ -847,19 +840,18 @@ final class Attr extends NodeOperatorVisitor { @Override public Node leaveVarNode(final VarNode varNode) { - VarNode newVarNode = varNode; + final Expression init = varNode.getInit(); + final IdentNode ident = varNode.getName(); + final String name = ident.getName(); - final Node init = newVarNode.getInit(); - final IdentNode ident = newVarNode.getName(); - final String name = ident.getName(); - - final Symbol symbol = findSymbol(lc.getCurrentBlock(), ident.getName()); + final Symbol symbol = findSymbol(lc.getCurrentBlock(), name); + assert ident.getSymbol() == symbol; if (init == null) { // var x; with no init will be treated like a use of x by // leaveIdentNode unless we remove the name from the localdef list. removeLocalDef(name); - return end(newVarNode.setSymbol(lc, symbol)); + return end(varNode); } addLocalDef(name); @@ -868,8 +860,7 @@ final class Attr extends NodeOperatorVisitor { final IdentNode newIdent = (IdentNode)ident.setSymbol(lc, symbol); - newVarNode = newVarNode.setName(newIdent); - newVarNode = (VarNode)newVarNode.setSymbol(lc, symbol); + final VarNode newVarNode = varNode.setName(newIdent); final boolean isScript = lc.getDefiningFunction(symbol).isProgram(); //see NASHORN-56 if ((init.getType().isNumeric() || init.getType().isBoolean()) && !isScript) { @@ -879,7 +870,7 @@ final class Attr extends NodeOperatorVisitor { newType(symbol, Type.OBJECT); } - assert newVarNode.hasType() : newVarNode + " has no type"; + assert newVarNode.getName().hasType() : newVarNode + " has no type"; return end(newVarNode); } @@ -907,11 +898,11 @@ final class Attr extends NodeOperatorVisitor { public Node leaveDELETE(final UnaryNode unaryNode) { final FunctionNode currentFunctionNode = lc.getCurrentFunction(); final boolean strictMode = currentFunctionNode.isStrict(); - final Node rhs = unaryNode.rhs(); - final Node strictFlagNode = LiteralNode.newInstance(unaryNode, strictMode).accept(this); + final Expression rhs = unaryNode.rhs(); + final Expression strictFlagNode = (Expression)LiteralNode.newInstance(unaryNode, strictMode).accept(this); Request request = Request.DELETE; - final List args = new ArrayList<>(); + final List args = new ArrayList<>(); if (rhs instanceof IdentNode) { // If this is a declared variable or a function parameter, delete always fails (except for globals). @@ -922,7 +913,7 @@ final class Attr extends NodeOperatorVisitor { if (failDelete && rhs.getSymbol().isThis()) { return LiteralNode.newInstance(unaryNode, true).accept(this); } - final Node literalNode = LiteralNode.newInstance(unaryNode, name).accept(this); + final Expression literalNode = (Expression)LiteralNode.newInstance(unaryNode, name).accept(this); if (!failDelete) { args.add(compilerConstant(SCOPE)); @@ -934,16 +925,17 @@ final class Attr extends NodeOperatorVisitor { request = Request.FAIL_DELETE; } } else if (rhs instanceof AccessNode) { - final Node base = ((AccessNode)rhs).getBase(); - final IdentNode property = ((AccessNode)rhs).getProperty(); + final Expression base = ((AccessNode)rhs).getBase(); + final IdentNode property = ((AccessNode)rhs).getProperty(); args.add(base); - args.add(LiteralNode.newInstance(unaryNode, property.getName()).accept(this)); + args.add((Expression)LiteralNode.newInstance(unaryNode, property.getName()).accept(this)); args.add(strictFlagNode); } else if (rhs instanceof IndexNode) { - final Node base = ((IndexNode)rhs).getBase(); - final Node index = ((IndexNode)rhs).getIndex(); + final IndexNode indexNode = (IndexNode)rhs; + final Expression base = indexNode.getBase(); + final Expression index = indexNode.getIndex(); args.add(base); args.add(index); @@ -998,15 +990,15 @@ final class Attr extends NodeOperatorVisitor { @Override public Node leaveTYPEOF(final UnaryNode unaryNode) { - final Node rhs = unaryNode.rhs(); + final Expression rhs = unaryNode.rhs(); - List args = new ArrayList<>(); + List args = new ArrayList<>(); if (rhs instanceof IdentNode && !rhs.getSymbol().isParam() && !rhs.getSymbol().isVar()) { args.add(compilerConstant(SCOPE)); - args.add(LiteralNode.newInstance(rhs, ((IdentNode)rhs).getName()).accept(this)); //null + args.add((Expression)LiteralNode.newInstance(rhs, ((IdentNode)rhs).getName()).accept(this)); //null } else { args.add(rhs); - args.add(LiteralNode.newInstance(unaryNode).accept(this)); //null, do not reuse token of identifier rhs, it can be e.g. 'this' + args.add((Expression)LiteralNode.newInstance(unaryNode).accept(this)); //null, do not reuse token of identifier rhs, it can be e.g. 'this' } RuntimeNode runtimeNode = new RuntimeNode(unaryNode, Request.TYPEOF, args); @@ -1040,8 +1032,8 @@ final class Attr extends NodeOperatorVisitor { */ @Override public Node leaveADD(final BinaryNode binaryNode) { - final Node lhs = binaryNode.lhs(); - final Node rhs = binaryNode.rhs(); + final Expression lhs = binaryNode.lhs(); + final Expression rhs = binaryNode.rhs(); ensureTypeNotUnknown(lhs); ensureTypeNotUnknown(rhs); @@ -1096,8 +1088,8 @@ final class Attr extends NodeOperatorVisitor { private Node leaveAssignmentNode(final BinaryNode binaryNode) { BinaryNode newBinaryNode = binaryNode; - final Node lhs = binaryNode.lhs(); - final Node rhs = binaryNode.rhs(); + final Expression lhs = binaryNode.lhs(); + final Expression rhs = binaryNode.rhs(); final Type type; if (rhs.getType().isNumeric()) { @@ -1133,8 +1125,8 @@ final class Attr extends NodeOperatorVisitor { @Override public Node leaveASSIGN_ADD(final BinaryNode binaryNode) { - final Node lhs = binaryNode.lhs(); - final Node rhs = binaryNode.rhs(); + final Expression lhs = binaryNode.lhs(); + final Expression rhs = binaryNode.rhs(); final Type widest = Type.widest(lhs.getType(), rhs.getType()); //Type.NUMBER if we can't prove that the add doesn't overflow. todo @@ -1413,13 +1405,13 @@ final class Attr extends NodeOperatorVisitor { @Override public Node leaveTernaryNode(final TernaryNode ternaryNode) { - final Node lhs = ternaryNode.rhs(); - final Node rhs = ternaryNode.third(); + final Expression trueExpr = ternaryNode.getTrueExpression(); + final Expression falseExpr = ternaryNode.getFalseExpression(); - ensureTypeNotUnknown(lhs); - ensureTypeNotUnknown(rhs); + ensureTypeNotUnknown(trueExpr); + ensureTypeNotUnknown(falseExpr); - final Type type = Type.widest(lhs.getType(), rhs.getType()); + final Type type = Type.widest(trueExpr.getType(), falseExpr.getType()); return end(ensureSymbol(type, ternaryNode)); } @@ -1537,7 +1529,7 @@ final class Attr extends NodeOperatorVisitor { } } - private static void ensureTypeNotUnknown(final Node node) { + private static void ensureTypeNotUnknown(final Expression node) { final Symbol symbol = node.getSymbol(); @@ -1594,13 +1586,13 @@ final class Attr extends NodeOperatorVisitor { * * @param assignmentDest the destination node of the assignment, e.g. lhs for binary nodes */ - private Node ensureAssignmentSlots(final Node assignmentDest) { + private Expression ensureAssignmentSlots(final Expression assignmentDest) { final LexicalContext attrLexicalContext = lc; - return assignmentDest.accept(new NodeVisitor(new LexicalContext()) { + return (Expression)assignmentDest.accept(new NodeVisitor(new LexicalContext()) { @Override public Node leaveIndexNode(final IndexNode indexNode) { assert indexNode.getSymbol().isTemp(); - final Node index = indexNode.getIndex(); + final Expression index = indexNode.getIndex(); //only temps can be set as needing slots. the others will self resolve //it is illegal to take a scope var and force it to be a slot, that breaks Symbol indexSymbol = index.getSymbol(); @@ -1642,7 +1634,7 @@ final class Attr extends NodeOperatorVisitor { changed.clear(); final FunctionNode newFunctionNode = (FunctionNode)currentFunctionNode.accept(new NodeVisitor(new LexicalContext()) { - private Node widen(final Node node, final Type to) { + private Expression widen(final Expression node, final Type to) { if (node instanceof LiteralNode) { return node; } @@ -1654,7 +1646,7 @@ final class Attr extends NodeOperatorVisitor { symbol = temporarySymbols.getTypedTemporarySymbol(to); } newType(symbol, to); - final Node newNode = node.setSymbol(lc, symbol); + final Expression newNode = node.setSymbol(lc, symbol); changed.add(newNode); return newNode; } @@ -1709,7 +1701,7 @@ final class Attr extends NodeOperatorVisitor { private Node leaveSelfModifyingAssignmentNode(final BinaryNode binaryNode, final Type destType) { //e.g. for -=, Number, no wider, destType (binaryNode.getWidestOperationType()) is the coerce type - final Node lhs = binaryNode.lhs(); + final Expression lhs = binaryNode.lhs(); newType(lhs.getSymbol(), destType); //may not narrow if dest is already wider than destType // ensureSymbol(destType, binaryNode); //for OP= nodes, the node can carry a narrower types than its lhs rhs. This is perfectly fine @@ -1717,9 +1709,9 @@ final class Attr extends NodeOperatorVisitor { return end(ensureSymbol(destType, ensureAssignmentSlots(binaryNode))); } - private Node ensureSymbol(final Type type, final Node node) { + private Expression ensureSymbol(final Type type, final Expression expr) { LOG.info("New TEMPORARY added to ", lc.getCurrentFunction().getName(), " type=", type); - return temporarySymbols.ensureSymbol(lc, type, node); + return temporarySymbols.ensureSymbol(lc, type, expr); } private Symbol newInternal(final String name, final Type type) { @@ -1841,11 +1833,11 @@ final class Attr extends NodeOperatorVisitor { return true; } - private Node end(final Node node) { + private T end(final T node) { return end(node, true); } - private Node end(final Node node, final boolean printNode) { + private T end(final T node, final boolean printNode) { if(node instanceof Statement) { // If we're done with a statement, all temporaries can be reused. temporarySymbols.reuse(); @@ -1860,10 +1852,13 @@ final class Attr extends NodeOperatorVisitor { append(" in '"). append(lc.getCurrentFunction().getName()); - if (node.getSymbol() == null) { - sb.append(" "); - } else { - sb.append(" '); + if(node instanceof Expression) { + final Symbol symbol = ((Expression)node).getSymbol(); + if (symbol == null) { + sb.append(" "); + } else { + sb.append(" '); + } } LOG.unindent(); diff --git a/nashorn/src/jdk/nashorn/internal/codegen/BranchOptimizer.java b/nashorn/src/jdk/nashorn/internal/codegen/BranchOptimizer.java index ee922115d15..02ea95f17e6 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/BranchOptimizer.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/BranchOptimizer.java @@ -34,7 +34,7 @@ import static jdk.nashorn.internal.codegen.Condition.NE; import jdk.nashorn.internal.codegen.types.Type; import jdk.nashorn.internal.ir.BinaryNode; -import jdk.nashorn.internal.ir.Node; +import jdk.nashorn.internal.ir.Expression; import jdk.nashorn.internal.ir.TernaryNode; import jdk.nashorn.internal.ir.UnaryNode; @@ -52,16 +52,16 @@ final class BranchOptimizer { this.method = method; } - void execute(final Node node, final Label label, final boolean state) { + void execute(final Expression node, final Label label, final boolean state) { branchOptimizer(node, label, state); } - private void load(final Node node) { + private void load(final Expression node) { codegen.load(node); } private void branchOptimizer(final UnaryNode unaryNode, final Label label, final boolean state) { - final Node rhs = unaryNode.rhs(); + final Expression rhs = unaryNode.rhs(); switch (unaryNode.tokenType()) { case NOT: @@ -88,8 +88,8 @@ final class BranchOptimizer { } private void branchOptimizer(final BinaryNode binaryNode, final Label label, final boolean state) { - final Node lhs = binaryNode.lhs(); - final Node rhs = binaryNode.rhs(); + final Expression lhs = binaryNode.lhs(); + final Expression rhs = binaryNode.rhs(); switch (binaryNode.tokenType()) { case AND: @@ -173,7 +173,7 @@ final class BranchOptimizer { } } - private void branchOptimizer(final Node node, final Label label, final boolean state) { + private void branchOptimizer(final Expression node, final Label label, final boolean state) { if (!(node instanceof TernaryNode)) { if (node instanceof BinaryNode) { diff --git a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java index b9d35682458..b6c6f3a13e9 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java @@ -69,6 +69,7 @@ import jdk.nashorn.internal.ir.AccessNode; import jdk.nashorn.internal.ir.BaseNode; import jdk.nashorn.internal.ir.BinaryNode; import jdk.nashorn.internal.ir.Block; +import jdk.nashorn.internal.ir.BlockStatement; import jdk.nashorn.internal.ir.BreakNode; import jdk.nashorn.internal.ir.BreakableNode; import jdk.nashorn.internal.ir.CallNode; @@ -76,7 +77,8 @@ import jdk.nashorn.internal.ir.CaseNode; import jdk.nashorn.internal.ir.CatchNode; import jdk.nashorn.internal.ir.ContinueNode; import jdk.nashorn.internal.ir.EmptyNode; -import jdk.nashorn.internal.ir.ExecuteNode; +import jdk.nashorn.internal.ir.Expression; +import jdk.nashorn.internal.ir.ExpressionStatement; import jdk.nashorn.internal.ir.ForNode; import jdk.nashorn.internal.ir.FunctionNode; import jdk.nashorn.internal.ir.FunctionNode.CompilationState; @@ -350,11 +352,11 @@ final class CodeGenerator extends NodeOperatorVisitor args) { + private int loadArgs(final List args) { return loadArgs(args, null, false, args.size()); } - private int loadArgs(final List args, final String signature, final boolean isVarArg, final int argCount) { + private int loadArgs(final List args, final String signature, final boolean isVarArg, final int argCount) { // arg have already been converted to objects here. if (isVarArg || argCount > LinkerCallSite.ARGLIMIT) { loadArgsArray(args); @@ -553,7 +555,7 @@ final class CodeGenerator extends NodeOperatorVisitor= argCount) { @@ -574,13 +576,13 @@ final class CodeGenerator extends NodeOperatorVisitor args = callNode.getArgs(); - final Node function = callNode.getFunction(); - final Block currentBlock = lc.getCurrentBlock(); + final List args = callNode.getArgs(); + final Expression function = callNode.getFunction(); + final Block currentBlock = lc.getCurrentBlock(); final CodeGeneratorLexicalContext codegenLexicalContext = lc; - final Type callNodeType = callNode.getType(); + final Type callNodeType = callNode.getType(); function.accept(new NodeVisitor(new LexicalContext()) { @@ -771,11 +773,19 @@ final class CodeGenerator extends NodeOperatorVisitor(init) { + new Store(init) { @Override protected void storeNonDiscard() { return; @@ -1047,7 +1051,7 @@ final class CodeGenerator extends NodeOperatorVisitor type = arrayType.getTypeClass(); @@ -1166,11 +1173,11 @@ final class CodeGenerator extends NodeOperatorVisitor args) { + private MethodEmitter loadArgsArray(final List args) { final Object[] array = new Object[args.size()]; loadConstant(array); @@ -1323,16 +1330,16 @@ final class CodeGenerator extends NodeOperatorVisitor elements = objectNode.getElements(); - final List keys = new ArrayList<>(); - final List symbols = new ArrayList<>(); - final List values = new ArrayList<>(); + final List keys = new ArrayList<>(); + final List symbols = new ArrayList<>(); + final List values = new ArrayList<>(); boolean hasGettersSetters = false; for (PropertyNode propertyNode: elements) { - final Node value = propertyNode.getValue(); + final Expression value = propertyNode.getValue(); final String key = propertyNode.getKeyName(); - final Symbol symbol = value == null ? null : propertyNode.getSymbol(); + final Symbol symbol = value == null ? null : propertyNode.getKey().getSymbol(); if (value == null) { hasGettersSetters = true; @@ -1346,9 +1353,9 @@ final class CodeGenerator extends NodeOperatorVisitor OBJECT_SPILL_THRESHOLD) { new SpillObjectCreator(this, keys, symbols, values).makeObject(method); } else { - new FieldObjectCreator(this, keys, symbols, values) { + new FieldObjectCreator(this, keys, symbols, values) { @Override - protected void loadValue(final Node node) { + protected void loadValue(final Expression node) { load(node); } @@ -1419,7 +1426,7 @@ final class CodeGenerator extends NodeOperatorVisitor && ((LiteralNode) node).isNull(); } - private boolean nullCheck(final RuntimeNode runtimeNode, final List args, final String signature) { + private boolean nullCheck(final RuntimeNode runtimeNode, final List args, final String signature) { final Request request = runtimeNode.getRequest(); if (!Request.isEQ(request) && !Request.isNE(request)) { @@ -1444,11 +1451,11 @@ final class CodeGenerator extends NodeOperatorVisitor args) { + private boolean specializationCheck(final RuntimeNode.Request request, final Expression node, final List args) { if (!request.canSpecialize()) { return false; } @@ -1555,10 +1562,11 @@ final class CodeGenerator extends NodeOperatorVisitor args = runtimeNode.getArgs(); if (runtimeNode.isPrimitive() && !runtimeNode.isFinal() && isReducible(runtimeNode.getRequest())) { - final Node lhs = runtimeNode.getArgs().get(0); - assert runtimeNode.getArgs().size() > 1 : runtimeNode + " must have two args"; - final Node rhs = runtimeNode.getArgs().get(1); + final Expression lhs = args.get(0); + assert args.size() > 1 : runtimeNode + " must have two args"; + final Expression rhs = args.get(1); final Type type = runtimeNode.getType(); final Symbol symbol = runtimeNode.getSymbol(); @@ -1595,9 +1603,6 @@ final class CodeGenerator extends NodeOperatorVisitor args = runtimeNode.getArgs(); - if (nullCheck(runtimeNode, args, new FunctionSignature(false, false, runtimeNode.getType(), args).toString())) { return false; } @@ -1606,7 +1611,7 @@ final class CodeGenerator extends NodeOperatorVisitor cases = switchNode.getCases(); @@ -1875,7 +1878,7 @@ final class CodeGenerator extends NodeOperatorVisitor(exception) { @Override @@ -2038,7 +2041,7 @@ final class CodeGenerator extends NodeOperatorVisitor args = callNode.getArgs(); + final List args = callNode.getArgs(); // Load function reference. load(callNode.getFunction()).convert(Type.OBJECT); // must detect type error @@ -2302,7 +2303,7 @@ final class CodeGenerator extends NodeOperatorVisitor */ - private abstract class SelfModifyingStore extends Store { - protected SelfModifyingStore(final T assignNode, final Node target) { + private abstract class SelfModifyingStore extends Store { + protected SelfModifyingStore(final T assignNode, final Expression target) { super(assignNode, target); } @@ -2939,13 +2939,13 @@ final class CodeGenerator extends NodeOperatorVisitor { + private abstract class Store { /** An assignment node, e.g. x += y */ protected final T assignNode; /** The target node to store to, e.g. x */ - private final Node target; + private final Expression target; /** How deep on the stack do the arguments go if this generates an indy call */ private int depth; @@ -2959,7 +2959,7 @@ final class CodeGenerator extends NodeOperatorVisitor { * strings etc as well. */ @Override - public Node leaveADD(final BinaryNode binaryNode) { - final Node lhs = binaryNode.lhs(); - final Node rhs = binaryNode.rhs(); + public Expression leaveADD(final BinaryNode binaryNode) { + final Expression lhs = binaryNode.lhs(); + final Expression rhs = binaryNode.rhs(); final Type type = binaryNode.getType(); @@ -240,7 +241,7 @@ final class FinalizeTypes extends NodeOperatorVisitor { return leaveASSIGN(binaryNode); } - private boolean symbolIsInteger(Node node) { + private boolean symbolIsInteger(final Expression node) { final Symbol symbol = node.getSymbol(); assert symbol != null && symbol.getSymbolType().isInteger() : "int coercion expected: " + Debug.id(symbol) + " " + symbol + " " + lc.getCurrentFunction().getSource(); return true; @@ -372,7 +373,7 @@ final class FinalizeTypes extends NodeOperatorVisitor { @Override public Node leaveCatchNode(final CatchNode catchNode) { - final Node exceptionCondition = catchNode.getExceptionCondition(); + final Expression exceptionCondition = catchNode.getExceptionCondition(); if (exceptionCondition != null) { return catchNode.setExceptionCondition(convert(exceptionCondition, Type.BOOLEAN)); } @@ -380,16 +381,16 @@ final class FinalizeTypes extends NodeOperatorVisitor { } @Override - public Node leaveExecuteNode(final ExecuteNode executeNode) { + public Node leaveExpressionStatement(final ExpressionStatement expressionStatement) { temporarySymbols.reuse(); - return executeNode.setExpression(discard(executeNode.getExpression())); + return expressionStatement.setExpression(discard(expressionStatement.getExpression())); } @Override public Node leaveForNode(final ForNode forNode) { - final Node init = forNode.getInit(); - final Node test = forNode.getTest(); - final Node modify = forNode.getModify(); + final Expression init = forNode.getInit(); + final Expression test = forNode.getTest(); + final Expression modify = forNode.getModify(); if (forNode.isForIn()) { return forNode.setModify(lc, convert(forNode.getModify(), Type.OBJECT)); // NASHORN-400 @@ -439,13 +440,13 @@ final class FinalizeTypes extends NodeOperatorVisitor { public boolean enterLiteralNode(final LiteralNode literalNode) { if (literalNode instanceof ArrayLiteralNode) { final ArrayLiteralNode arrayLiteralNode = (ArrayLiteralNode)literalNode; - final Node[] array = arrayLiteralNode.getValue(); + final Expression[] array = arrayLiteralNode.getValue(); final Type elementType = arrayLiteralNode.getElementType(); for (int i = 0; i < array.length; i++) { final Node element = array[i]; if (element != null) { - array[i] = convert(element.accept(this), elementType); + array[i] = convert((Expression)element.accept(this), elementType); } } } @@ -455,7 +456,7 @@ final class FinalizeTypes extends NodeOperatorVisitor { @Override public Node leaveReturnNode(final ReturnNode returnNode) { - final Node expr = returnNode.getExpression(); + final Expression expr = returnNode.getExpression(); if (expr != null) { return returnNode.setExpression(convert(expr, lc.getCurrentFunction().getReturnType())); } @@ -464,8 +465,8 @@ final class FinalizeTypes extends NodeOperatorVisitor { @Override public Node leaveRuntimeNode(final RuntimeNode runtimeNode) { - final List args = runtimeNode.getArgs(); - for (final Node arg : args) { + final List args = runtimeNode.getArgs(); + for (final Expression arg : args) { assert !arg.getType().isUnknown(); } return runtimeNode; @@ -479,12 +480,12 @@ final class FinalizeTypes extends NodeOperatorVisitor { return switchNode; } - final Node expression = switchNode.getExpression(); + final Expression expression = switchNode.getExpression(); final List cases = switchNode.getCases(); final List newCases = new ArrayList<>(); for (final CaseNode caseNode : cases) { - final Node test = caseNode.getTest(); + final Expression test = caseNode.getTest(); newCases.add(test != null ? caseNode.setTest(convert(test, Type.OBJECT)) : caseNode); } @@ -495,7 +496,7 @@ final class FinalizeTypes extends NodeOperatorVisitor { @Override public Node leaveTernaryNode(final TernaryNode ternaryNode) { - return ternaryNode.setLHS(convert(ternaryNode.lhs(), Type.BOOLEAN)); + return ternaryNode.setTest(convert(ternaryNode.getTest(), Type.BOOLEAN)); } @Override @@ -505,16 +506,16 @@ final class FinalizeTypes extends NodeOperatorVisitor { @Override public Node leaveVarNode(final VarNode varNode) { - final Node init = varNode.getInit(); + final Expression init = varNode.getInit(); if (init != null) { final SpecializedNode specialized = specialize(varNode); final VarNode specVarNode = (VarNode)specialized.node; Type destType = specialized.type; if (destType == null) { - destType = specVarNode.getType(); + destType = specVarNode.getName().getType(); } - assert specVarNode.hasType() : specVarNode + " doesn't have a type"; - final Node convertedInit = convert(init, destType); + assert specVarNode.getName().hasType() : specVarNode + " doesn't have a type"; + final Expression convertedInit = convert(init, destType); temporarySymbols.reuse(); return specVarNode.setInit(convertedInit); } @@ -524,7 +525,7 @@ final class FinalizeTypes extends NodeOperatorVisitor { @Override public Node leaveWhileNode(final WhileNode whileNode) { - final Node test = whileNode.getTest(); + final Expression test = whileNode.getTest(); if (test != null) { return whileNode.setTest(lc, convert(test, Type.BOOLEAN)); } @@ -599,8 +600,8 @@ final class FinalizeTypes extends NodeOperatorVisitor { */ @SuppressWarnings("fallthrough") private Node leaveCmp(final BinaryNode binaryNode, final RuntimeNode.Request request) { - final Node lhs = binaryNode.lhs(); - final Node rhs = binaryNode.rhs(); + final Expression lhs = binaryNode.lhs(); + final Expression rhs = binaryNode.rhs(); Type widest = Type.widest(lhs.getType(), rhs.getType()); @@ -696,10 +697,10 @@ final class FinalizeTypes extends NodeOperatorVisitor { } } - SpecializedNode specialize(final Assignment assignment) { + SpecializedNode specialize(final Assignment assignment) { final Node node = ((Node)assignment); final T lhs = assignment.getAssignmentDest(); - final Node rhs = assignment.getAssignmentSource(); + final Expression rhs = assignment.getAssignmentSource(); if (!canHaveCallSiteType(lhs)) { return new SpecializedNode(node, null); @@ -718,8 +719,16 @@ final class FinalizeTypes extends NodeOperatorVisitor { } final Node newNode = assignment.setAssignmentDest(setTypeOverride(lhs, to)); - final Node typePropagatedNode = propagateType(newNode, to); - + final Node typePropagatedNode; + if(newNode instanceof Expression) { + typePropagatedNode = propagateType((Expression)newNode, to); + } else if(newNode instanceof VarNode) { + // VarNode, being a statement, doesn't have its own symbol; it uses the symbol of its name instead. + final VarNode varNode = (VarNode)newNode; + typePropagatedNode = varNode.setName((IdentNode)propagateType(varNode.getName(), to)); + } else { + throw new AssertionError(); + } return new SpecializedNode(typePropagatedNode, to); } @@ -759,7 +768,7 @@ final class FinalizeTypes extends NodeOperatorVisitor { * @param to new type */ @SuppressWarnings("unchecked") - T setTypeOverride(final T node, final Type to) { + T setTypeOverride(final T node, final Type to) { final Type from = node.getType(); if (!node.getType().equals(to)) { LOG.info("Changing call override type for '", node, "' from ", node.getType(), " to ", to); @@ -788,7 +797,7 @@ final class FinalizeTypes extends NodeOperatorVisitor { * @param to destination type * @return conversion node */ - private Node convert(final Node node, final Type to) { + private Expression convert(final Expression node, final Type to) { assert !to.isUnknown() : "unknown type for " + node + " class=" + node.getClass(); assert node != null : "node is null"; assert node.getSymbol() != null : "node " + node + " " + node.getClass() + " has no symbol! " + lc.getCurrentFunction(); @@ -804,7 +813,7 @@ final class FinalizeTypes extends NodeOperatorVisitor { return node; } - Node resultNode = node; + Expression resultNode = node; if (node instanceof LiteralNode && !(node instanceof ArrayLiteralNode) && !to.isObject()) { final LiteralNode newNode = new LiteralNodeConstantEvaluator((LiteralNode)node, to).eval(); @@ -828,9 +837,9 @@ final class FinalizeTypes extends NodeOperatorVisitor { return temporarySymbols.ensureSymbol(lc, to, resultNode); } - private static Node discard(final Node node) { + private static Expression discard(final Expression node) { if (node.getSymbol() != null) { - final Node discard = new UnaryNode(Token.recast(node.getToken(), TokenType.DISCARD), node); + final UnaryNode discard = new UnaryNode(Token.recast(node.getToken(), TokenType.DISCARD), node); //discard never has a symbol in the discard node - then it would be a nop assert !node.isTerminal(); return discard; @@ -853,7 +862,7 @@ final class FinalizeTypes extends NodeOperatorVisitor { * @param node * @param to */ - private Node propagateType(final Node node, final Type to) { + private Expression propagateType(final Expression node, final Type to) { Symbol symbol = node.getSymbol(); if (symbol.isTemp() && symbol.getSymbolType() != to) { symbol = symbol.setTypeOverrideShared(to, temporarySymbols); diff --git a/nashorn/src/jdk/nashorn/internal/codegen/FoldConstants.java b/nashorn/src/jdk/nashorn/internal/codegen/FoldConstants.java index 2331cf7570d..49dfbb324b7 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/FoldConstants.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/FoldConstants.java @@ -28,8 +28,8 @@ package jdk.nashorn.internal.codegen; import jdk.nashorn.internal.codegen.types.Type; import jdk.nashorn.internal.ir.BinaryNode; import jdk.nashorn.internal.ir.Block; +import jdk.nashorn.internal.ir.BlockStatement; import jdk.nashorn.internal.ir.EmptyNode; -import jdk.nashorn.internal.ir.ExecuteNode; import jdk.nashorn.internal.ir.FunctionNode; import jdk.nashorn.internal.ir.FunctionNode.CompilationState; import jdk.nashorn.internal.ir.IfNode; @@ -91,7 +91,7 @@ final class FoldConstants extends NodeVisitor { if (test instanceof LiteralNode) { final Block shortCut = ((LiteralNode)test).isTrue() ? ifNode.getPass() : ifNode.getFail(); if (shortCut != null) { - return new ExecuteNode(shortCut.getLineNumber(), shortCut.getToken(), shortCut.getFinish(), shortCut); + return new BlockStatement(ifNode.getLineNumber(), shortCut); } return new EmptyNode(ifNode); } @@ -100,9 +100,9 @@ final class FoldConstants extends NodeVisitor { @Override public Node leaveTernaryNode(final TernaryNode ternaryNode) { - final Node test = ternaryNode.lhs(); + final Node test = ternaryNode.getTest(); if (test instanceof LiteralNode) { - return ((LiteralNode)test).isTrue() ? ternaryNode.rhs() : ternaryNode.third(); + return ((LiteralNode)test).isTrue() ? ternaryNode.getTrueExpression() : ternaryNode.getFalseExpression(); } return ternaryNode; } diff --git a/nashorn/src/jdk/nashorn/internal/codegen/FunctionSignature.java b/nashorn/src/jdk/nashorn/internal/codegen/FunctionSignature.java index 057d2d4e454..1c1b5f7469f 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/FunctionSignature.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/FunctionSignature.java @@ -31,8 +31,8 @@ import java.lang.invoke.MethodType; import java.util.ArrayList; import java.util.List; import jdk.nashorn.internal.codegen.types.Type; +import jdk.nashorn.internal.ir.Expression; import jdk.nashorn.internal.ir.FunctionNode; -import jdk.nashorn.internal.ir.Node; import jdk.nashorn.internal.runtime.ScriptFunction; import jdk.nashorn.internal.runtime.linker.LinkerCallSite; @@ -63,7 +63,7 @@ public final class FunctionSignature { * @param retType what is the return type * @param args argument list of AST Nodes */ - public FunctionSignature(final boolean hasSelf, final boolean hasCallee, final Type retType, final List args) { + public FunctionSignature(final boolean hasSelf, final boolean hasCallee, final Type retType, final List args) { this(hasSelf, hasCallee, retType, FunctionSignature.typeArray(args)); } @@ -167,7 +167,7 @@ public final class FunctionSignature { * * @return the array of types */ - private static Type[] typeArray(final List args) { + private static Type[] typeArray(final List args) { if (args == null) { return null; } @@ -175,7 +175,7 @@ public final class FunctionSignature { final Type[] typeArray = new Type[args.size()]; int pos = 0; - for (final Node arg : args) { + for (final Expression arg : args) { typeArray[pos++] = arg.getType(); } diff --git a/nashorn/src/jdk/nashorn/internal/codegen/Lower.java b/nashorn/src/jdk/nashorn/internal/codegen/Lower.java index 880fea67640..cc109695d38 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/Lower.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/Lower.java @@ -37,12 +37,14 @@ import jdk.nashorn.internal.ir.BaseNode; import jdk.nashorn.internal.ir.BinaryNode; import jdk.nashorn.internal.ir.Block; import jdk.nashorn.internal.ir.BlockLexicalContext; +import jdk.nashorn.internal.ir.BlockStatement; import jdk.nashorn.internal.ir.BreakNode; import jdk.nashorn.internal.ir.CallNode; import jdk.nashorn.internal.ir.CatchNode; import jdk.nashorn.internal.ir.ContinueNode; import jdk.nashorn.internal.ir.EmptyNode; -import jdk.nashorn.internal.ir.ExecuteNode; +import jdk.nashorn.internal.ir.Expression; +import jdk.nashorn.internal.ir.ExpressionStatement; import jdk.nashorn.internal.ir.ForNode; import jdk.nashorn.internal.ir.FunctionNode; import jdk.nashorn.internal.ir.FunctionNode.CompilationState; @@ -138,7 +140,7 @@ final class Lower extends NodeOperatorVisitor { public boolean enterBlock(final Block block) { final FunctionNode function = lc.getCurrentFunction(); if (lc.isFunctionBody() && function.isProgram() && !function.hasDeclaredFunctions()) { - new ExecuteNode(block.getLineNumber(), block.getToken(), block.getFinish(), LiteralNode.newInstance(block, ScriptRuntime.UNDEFINED)).accept(this); + new ExpressionStatement(function.getLineNumber(), block.getToken(), block.getFinish(), LiteralNode.newInstance(block, ScriptRuntime.UNDEFINED)).accept(this); } return true; } @@ -154,7 +156,7 @@ final class Lower extends NodeOperatorVisitor { final boolean isProgram = currentFunction.isProgram(); final Statement last = lc.getLastStatement(); final ReturnNode returnNode = new ReturnNode( - last == null ? block.getLineNumber() : last.getLineNumber(), //TODO? + last == null ? currentFunction.getLineNumber() : last.getLineNumber(), //TODO? currentFunction.getToken(), currentFunction.getFinish(), isProgram ? @@ -195,29 +197,32 @@ final class Lower extends NodeOperatorVisitor { } @Override - public Node leaveExecuteNode(final ExecuteNode executeNode) { - final Node expr = executeNode.getExpression(); - ExecuteNode node = executeNode; + public Node leaveExpressionStatement(final ExpressionStatement expressionStatement) { + final Expression expr = expressionStatement.getExpression(); + ExpressionStatement node = expressionStatement; final FunctionNode currentFunction = lc.getCurrentFunction(); if (currentFunction.isProgram()) { - if (!(expr instanceof Block) || expr instanceof FunctionNode) { // it's not a block, but can be a function - if (!isInternalExpression(expr) && !isEvalResultAssignment(expr)) { - node = executeNode.setExpression( - new BinaryNode( - Token.recast( - executeNode.getToken(), - TokenType.ASSIGN), - compilerConstant(RETURN), - expr)); - } + if (!isInternalExpression(expr) && !isEvalResultAssignment(expr)) { + node = expressionStatement.setExpression( + new BinaryNode( + Token.recast( + expressionStatement.getToken(), + TokenType.ASSIGN), + compilerConstant(RETURN), + expr)); } } return addStatement(node); } + @Override + public Node leaveBlockStatement(BlockStatement blockStatement) { + return addStatement(blockStatement); + } + @Override public Node leaveForNode(final ForNode forNode) { ForNode newForNode = forNode; @@ -302,11 +307,11 @@ final class Lower extends NodeOperatorVisitor { final IdentNode exception = new IdentNode(token, finish, lc.getCurrentFunction().uniqueName("catch_all")); - final Block catchBody = new Block(lineNumber, token, finish, new ThrowNode(lineNumber, token, finish, new IdentNode(exception), ThrowNode.IS_SYNTHETIC_RETHROW)). + final Block catchBody = new Block(token, finish, new ThrowNode(lineNumber, token, finish, new IdentNode(exception), ThrowNode.IS_SYNTHETIC_RETHROW)). setIsTerminal(lc, true); //ends with throw, so terminal final CatchNode catchAllNode = new CatchNode(lineNumber, token, finish, new IdentNode(exception), null, catchBody, CatchNode.IS_SYNTHETIC_RETHROW); - final Block catchAllBlock = new Block(lineNumber, token, finish, catchAllNode); + final Block catchAllBlock = new Block(token, finish, catchAllNode); //catchallblock -> catchallnode (catchnode) -> exception -> throw @@ -355,14 +360,14 @@ final class Lower extends NodeOperatorVisitor { if (!isTerminal(newStatements)) { newStatements.add(throwNode); } - return new Block(throwNode.getLineNumber(), throwNode.getToken(), throwNode.getFinish(), newStatements); + return BlockStatement.createReplacement(throwNode, newStatements); } return throwNode; } @Override public Node leaveBreakNode(final BreakNode breakNode) { - return copy(breakNode, Lower.this.lc.getBreakable(breakNode.getLabel())); + return copy(breakNode, (Node)Lower.this.lc.getBreakable(breakNode.getLabel())); } @Override @@ -372,15 +377,15 @@ final class Lower extends NodeOperatorVisitor { @Override public Node leaveReturnNode(final ReturnNode returnNode) { - final Node expr = returnNode.getExpression(); + final Expression expr = returnNode.getExpression(); final List newStatements = new ArrayList<>(); - final Node resultNode; + final Expression resultNode; if (expr != null) { //we need to evaluate the result of the return in case it is complex while //still in the try block, store it in a result value and return it afterwards resultNode = new IdentNode(Lower.this.compilerConstant(RETURN)); - newStatements.add(new ExecuteNode(returnNode.getLineNumber(), returnNode.getToken(), returnNode.getFinish(), new BinaryNode(Token.recast(returnNode.getToken(), TokenType.ASSIGN), resultNode, expr))); + newStatements.add(new ExpressionStatement(returnNode.getLineNumber(), returnNode.getToken(), returnNode.getFinish(), new BinaryNode(Token.recast(returnNode.getToken(), TokenType.ASSIGN), resultNode, expr))); } else { resultNode = null; } @@ -390,7 +395,7 @@ final class Lower extends NodeOperatorVisitor { newStatements.add(expr == null ? returnNode : returnNode.setExpression(resultNode)); } - return new ExecuteNode(returnNode.getLineNumber(), returnNode.getToken(), returnNode.getFinish(), new Block(returnNode.getLineNumber(), returnNode.getToken(), lc.getCurrentBlock().getFinish(), newStatements)); + return BlockStatement.createReplacement(returnNode, lc.getCurrentBlock().getFinish(), newStatements); } private Node copy(final Statement endpoint, final Node targetNode) { @@ -399,7 +404,7 @@ final class Lower extends NodeOperatorVisitor { if (!isTerminal(newStatements)) { newStatements.add(endpoint); } - return new ExecuteNode(endpoint.getLineNumber(), endpoint.getToken(), endpoint.getFinish(), new Block(endpoint.getLineNumber(), endpoint.getToken(), finish, newStatements)); + return BlockStatement.createReplacement(endpoint, finish, newStatements); } return endpoint; } @@ -461,7 +466,7 @@ final class Lower extends NodeOperatorVisitor { if (tryNode.getCatchBlocks().isEmpty()) { newTryNode = tryNode.setFinallyBody(null); } else { - Block outerBody = new Block(tryNode.getLineNumber(), tryNode.getToken(), tryNode.getFinish(), new ArrayList(Arrays.asList(tryNode.setFinallyBody(null)))); + Block outerBody = new Block(tryNode.getToken(), tryNode.getFinish(), new ArrayList(Arrays.asList(tryNode.setFinallyBody(null)))); newTryNode = tryNode.setBody(outerBody).setCatchBlocks(null); } @@ -478,7 +483,7 @@ final class Lower extends NodeOperatorVisitor { public Node leaveVarNode(final VarNode varNode) { addStatement(varNode); if (varNode.getFlag(VarNode.IS_LAST_FUNCTION_DECLARATION) && lc.getCurrentFunction().isProgram()) { - new ExecuteNode(varNode.getLineNumber(), varNode.getToken(), varNode.getFinish(), new IdentNode(varNode.getName())).accept(this); + new ExpressionStatement(varNode.getLineNumber(), varNode.getToken(), varNode.getFinish(), new IdentNode(varNode.getName())).accept(this); } return varNode; } @@ -511,7 +516,7 @@ final class Lower extends NodeOperatorVisitor { * @param function function called by a CallNode * @return transformed node to marker function or identity if not ident/access/indexnode */ - private static Node markerFunction(final Node function) { + private static Expression markerFunction(final Expression function) { if (function instanceof IdentNode) { return ((IdentNode)function).setIsFunction(); } else if (function instanceof BaseNode) { @@ -553,15 +558,15 @@ final class Lower extends NodeOperatorVisitor { private CallNode checkEval(final CallNode callNode) { if (callNode.getFunction() instanceof IdentNode) { - final List args = callNode.getArgs(); - final IdentNode callee = (IdentNode)callNode.getFunction(); + final List args = callNode.getArgs(); + final IdentNode callee = (IdentNode)callNode.getFunction(); // 'eval' call with at least one argument if (args.size() >= 1 && EVAL.symbolName().equals(callee.getName())) { final FunctionNode currentFunction = lc.getCurrentFunction(); return callNode.setEvalArgs( new CallNode.EvalArgs( - ensureUniqueNamesIn(args.get(0)).accept(this), + (Expression)ensureUniqueNamesIn(args.get(0)).accept(this), compilerConstant(THIS), evalLocation(callee), currentFunction.isStrict())); @@ -630,7 +635,7 @@ final class Lower extends NodeOperatorVisitor { * @param expression expression to check for internal symbol * @return true if internal, false otherwise */ - private static boolean isInternalExpression(final Node expression) { + private static boolean isInternalExpression(final Expression expression) { final Symbol symbol = expression.getSymbol(); return symbol != null && symbol.isInternal(); } diff --git a/nashorn/src/jdk/nashorn/internal/codegen/RangeAnalyzer.java b/nashorn/src/jdk/nashorn/internal/codegen/RangeAnalyzer.java index ab61d374818..4056ec0c2bd 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/RangeAnalyzer.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/RangeAnalyzer.java @@ -28,11 +28,11 @@ package jdk.nashorn.internal.codegen; import java.util.HashMap; import java.util.HashSet; import java.util.Map; - import jdk.nashorn.internal.codegen.types.Range; import jdk.nashorn.internal.codegen.types.Type; import jdk.nashorn.internal.ir.Assignment; import jdk.nashorn.internal.ir.BinaryNode; +import jdk.nashorn.internal.ir.Expression; import jdk.nashorn.internal.ir.ForNode; import jdk.nashorn.internal.ir.IdentNode; import jdk.nashorn.internal.ir.LexicalContext; @@ -87,7 +87,7 @@ final class RangeAnalyzer extends NodeOperatorVisitor { } //destination visited - private Symbol setRange(final Node dest, final Range range) { + private Symbol setRange(final Expression dest, final Range range) { if (range.isUnknown()) { return null; } @@ -352,7 +352,6 @@ final class RangeAnalyzer extends NodeOperatorVisitor { range = range.isUnknown() ? Range.createGenericRange() : range; setRange(node.getName(), range); - setRange(node, range); } return node; @@ -438,12 +437,12 @@ final class RangeAnalyzer extends NodeOperatorVisitor { * @return */ private static Symbol findLoopCounter(final LoopNode node) { - final Node test = node.getTest(); + final Expression test = node.getTest(); if (test != null && test.isComparison()) { final BinaryNode binaryNode = (BinaryNode)test; - final Node lhs = binaryNode.lhs(); - final Node rhs = binaryNode.rhs(); + final Expression lhs = binaryNode.lhs(); + final Expression rhs = binaryNode.rhs(); //detect ident cmp int_literal if (lhs instanceof IdentNode && rhs instanceof LiteralNode && ((LiteralNode)rhs).getType().isInteger()) { diff --git a/nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java b/nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java index 33e1d432ac3..08dfedf1a9f 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java @@ -25,26 +25,25 @@ package jdk.nashorn.internal.codegen; +import static jdk.nashorn.internal.codegen.CompilerConstants.constructorNoLookup; +import static jdk.nashorn.internal.codegen.types.Type.OBJECT; + +import java.util.List; import jdk.nashorn.internal.codegen.types.Type; +import jdk.nashorn.internal.ir.Expression; import jdk.nashorn.internal.ir.LiteralNode; -import jdk.nashorn.internal.ir.Node; import jdk.nashorn.internal.ir.Symbol; import jdk.nashorn.internal.runtime.Property; import jdk.nashorn.internal.runtime.PropertyMap; import jdk.nashorn.internal.runtime.ScriptObject; import jdk.nashorn.internal.scripts.JO; -import java.util.List; - -import static jdk.nashorn.internal.codegen.CompilerConstants.constructorNoLookup; -import static jdk.nashorn.internal.codegen.types.Type.OBJECT; - /** * An object creator that uses spill properties. */ public class SpillObjectCreator extends ObjectCreator { - private final List values; + private final List values; /** * Constructor @@ -54,7 +53,7 @@ public class SpillObjectCreator extends ObjectCreator { * @param symbols symbols for fields in object * @param values list of values corresponding to keys */ - protected SpillObjectCreator(final CodeGenerator codegen, final List keys, final List symbols, final List values) { + protected SpillObjectCreator(final CodeGenerator codegen, final List keys, final List symbols, final List values) { super(codegen, keys, symbols, false, false); this.values = values; makeMap(); @@ -107,7 +106,7 @@ public class SpillObjectCreator extends ObjectCreator { for (int i = 0; i < length; i++) { final String key = keys.get(i); final Property property = propertyMap.findProperty(key); - final Node value = values.get(i); + final Expression value = values.get(i); if (property == null && value != null) { method.dup(); diff --git a/nashorn/src/jdk/nashorn/internal/codegen/Splitter.java b/nashorn/src/jdk/nashorn/internal/codegen/Splitter.java index e724ce261c3..a35c6dfdcf1 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/Splitter.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/Splitter.java @@ -31,7 +31,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import jdk.nashorn.internal.ir.Block; import jdk.nashorn.internal.ir.FunctionNode; import jdk.nashorn.internal.ir.FunctionNode.CompilationState; @@ -221,14 +220,13 @@ final class Splitter extends NodeVisitor { * @return New split node. */ private SplitNode createBlockSplitNode(final Block parent, final FunctionNode function, final List statements, final long weight) { - final int lineNumber = parent.getLineNumber(); final long token = parent.getToken(); final int finish = parent.getFinish(); final String name = function.uniqueName(SPLIT_PREFIX.symbolName()); - final Block newBlock = new Block(lineNumber, token, finish, statements); + final Block newBlock = new Block(token, finish, statements); - return new SplitNode(lineNumber, name, newBlock, compiler.findUnit(weight + WeighNodes.FUNCTION_WEIGHT)); + return new SplitNode(name, newBlock, compiler.findUnit(weight + WeighNodes.FUNCTION_WEIGHT)); } @Override diff --git a/nashorn/src/jdk/nashorn/internal/codegen/WeighNodes.java b/nashorn/src/jdk/nashorn/internal/codegen/WeighNodes.java index 1adef12bb3c..57b3bafa797 100644 --- a/nashorn/src/jdk/nashorn/internal/codegen/WeighNodes.java +++ b/nashorn/src/jdk/nashorn/internal/codegen/WeighNodes.java @@ -27,7 +27,6 @@ package jdk.nashorn.internal.codegen; import java.util.List; import java.util.Map; - import jdk.nashorn.internal.codegen.types.Type; import jdk.nashorn.internal.ir.AccessNode; import jdk.nashorn.internal.ir.BinaryNode; @@ -36,7 +35,7 @@ import jdk.nashorn.internal.ir.BreakNode; import jdk.nashorn.internal.ir.CallNode; import jdk.nashorn.internal.ir.CatchNode; import jdk.nashorn.internal.ir.ContinueNode; -import jdk.nashorn.internal.ir.ExecuteNode; +import jdk.nashorn.internal.ir.ExpressionStatement; import jdk.nashorn.internal.ir.ForNode; import jdk.nashorn.internal.ir.FunctionNode; import jdk.nashorn.internal.ir.IdentNode; @@ -158,8 +157,8 @@ final class WeighNodes extends NodeOperatorVisitor { } @Override - public Node leaveExecuteNode(final ExecuteNode executeNode) { - return executeNode; + public Node leaveExpressionStatement(final ExpressionStatement expressionStatement) { + return expressionStatement; } @Override diff --git a/nashorn/src/jdk/nashorn/internal/ir/AccessNode.java b/nashorn/src/jdk/nashorn/internal/ir/AccessNode.java index eecc5713541..55b0aa3feb3 100644 --- a/nashorn/src/jdk/nashorn/internal/ir/AccessNode.java +++ b/nashorn/src/jdk/nashorn/internal/ir/AccessNode.java @@ -45,12 +45,12 @@ public final class AccessNode extends BaseNode { * @param base base node * @param property property */ - public AccessNode(final long token, final int finish, final Node base, final IdentNode property) { + public AccessNode(final long token, final int finish, final Expression base, final IdentNode property) { super(token, finish, base, false, false); this.property = property.setIsPropertyName(); } - private AccessNode(final AccessNode accessNode, final Node base, final IdentNode property, final boolean isFunction, final boolean hasCallSiteType) { + private AccessNode(final AccessNode accessNode, final Expression base, final IdentNode property, final boolean isFunction, final boolean hasCallSiteType) { super(accessNode, base, isFunction, hasCallSiteType); this.property = property; } @@ -63,7 +63,7 @@ public final class AccessNode extends BaseNode { public Node accept(final NodeVisitor visitor) { if (visitor.enterAccessNode(this)) { return visitor.leaveAccessNode( - setBase(base.accept(visitor)). + setBase((Expression)base.accept(visitor)). setProperty((IdentNode)property.accept(visitor))); } return this; @@ -103,7 +103,7 @@ public final class AccessNode extends BaseNode { return property; } - private AccessNode setBase(final Node base) { + private AccessNode setBase(final Expression base) { if (this.base == base) { return this; } diff --git a/nashorn/src/jdk/nashorn/internal/ir/Assignment.java b/nashorn/src/jdk/nashorn/internal/ir/Assignment.java index 0c531bc2906..093b0d80a7d 100644 --- a/nashorn/src/jdk/nashorn/internal/ir/Assignment.java +++ b/nashorn/src/jdk/nashorn/internal/ir/Assignment.java @@ -31,7 +31,7 @@ package jdk.nashorn.internal.ir; * * @param the destination type */ -public interface Assignment { +public interface Assignment { /** * Get assignment destination @@ -45,7 +45,7 @@ public interface Assignment { * * @return get the assignment source node */ - public Node getAssignmentSource(); + public Expression getAssignmentSource(); /** * Set assignment destination node. diff --git a/nashorn/src/jdk/nashorn/internal/ir/BaseNode.java b/nashorn/src/jdk/nashorn/internal/ir/BaseNode.java index a1b7c0eed7d..f945ef35711 100644 --- a/nashorn/src/jdk/nashorn/internal/ir/BaseNode.java +++ b/nashorn/src/jdk/nashorn/internal/ir/BaseNode.java @@ -26,6 +26,7 @@ package jdk.nashorn.internal.ir; import static jdk.nashorn.internal.codegen.ObjectClassGenerator.DEBUG_FIELDS; + import jdk.nashorn.internal.codegen.ObjectClassGenerator; import jdk.nashorn.internal.codegen.types.Type; import jdk.nashorn.internal.ir.annotations.Immutable; @@ -37,10 +38,10 @@ import jdk.nashorn.internal.ir.annotations.Immutable; * @see IndexNode */ @Immutable -public abstract class BaseNode extends Node implements FunctionCall, TypeOverride { +public abstract class BaseNode extends Expression implements FunctionCall, TypeOverride { /** Base Node. */ - protected final Node base; + protected final Expression base; private final boolean isFunction; @@ -55,7 +56,7 @@ public abstract class BaseNode extends Node implements FunctionCall, TypeOverrid * @param isFunction is this a function * @param hasCallSiteType does this access have a callsite type */ - public BaseNode(final long token, final int finish, final Node base, final boolean isFunction, final boolean hasCallSiteType) { + public BaseNode(final long token, final int finish, final Expression base, final boolean isFunction, final boolean hasCallSiteType) { super(token, base.getStart(), finish); this.base = base; this.isFunction = isFunction; @@ -69,7 +70,7 @@ public abstract class BaseNode extends Node implements FunctionCall, TypeOverrid * @param isFunction is this a function * @param hasCallSiteType does this access have a callsite type */ - protected BaseNode(final BaseNode baseNode, final Node base, final boolean isFunction, final boolean hasCallSiteType) { + protected BaseNode(final BaseNode baseNode, final Expression base, final boolean isFunction, final boolean hasCallSiteType) { super(baseNode); this.base = base; this.isFunction = isFunction; @@ -80,7 +81,7 @@ public abstract class BaseNode extends Node implements FunctionCall, TypeOverrid * Get the base node for this access * @return the base node */ - public Node getBase() { + public Expression getBase() { return base; } diff --git a/nashorn/src/jdk/nashorn/internal/ir/BinaryNode.java b/nashorn/src/jdk/nashorn/internal/ir/BinaryNode.java index 4afa1945eae..1576fb9316e 100644 --- a/nashorn/src/jdk/nashorn/internal/ir/BinaryNode.java +++ b/nashorn/src/jdk/nashorn/internal/ir/BinaryNode.java @@ -34,11 +34,11 @@ import jdk.nashorn.internal.parser.TokenType; * BinaryNode nodes represent two operand operations. */ @Immutable -public final class BinaryNode extends Node implements Assignment { +public final class BinaryNode extends Expression implements Assignment { /** Left hand side argument. */ - private final Node lhs; + private final Expression lhs; - private final Node rhs; + private final Expression rhs; /** * Constructor @@ -47,13 +47,13 @@ public final class BinaryNode extends Node implements Assignment { * @param lhs left hand side * @param rhs right hand side */ - public BinaryNode(final long token, final Node lhs, final Node rhs) { + public BinaryNode(final long token, final Expression lhs, final Expression rhs) { super(token, lhs.getStart(), rhs.getFinish()); this.lhs = lhs; this.rhs = rhs; } - private BinaryNode(final BinaryNode binaryNode, final Node lhs, final Node rhs) { + private BinaryNode(final BinaryNode binaryNode, final Expression lhs, final Expression rhs) { super(binaryNode); this.lhs = lhs; this.rhs = rhs; @@ -141,17 +141,17 @@ public final class BinaryNode extends Node implements Assignment { } @Override - public Node getAssignmentDest() { + public Expression getAssignmentDest() { return isAssignment() ? lhs() : null; } @Override - public Node setAssignmentDest(Node n) { + public BinaryNode setAssignmentDest(Expression n) { return setLHS(n); } @Override - public Node getAssignmentSource() { + public Expression getAssignmentSource() { return rhs(); } @@ -162,7 +162,7 @@ public final class BinaryNode extends Node implements Assignment { @Override public Node accept(final NodeVisitor visitor) { if (visitor.enterBinaryNode(this)) { - return visitor.leaveBinaryNode(setLHS(lhs.accept(visitor)).setRHS(rhs.accept(visitor))); + return visitor.leaveBinaryNode(setLHS((Expression)lhs.accept(visitor)).setRHS((Expression)rhs.accept(visitor))); } return this; @@ -218,7 +218,7 @@ public final class BinaryNode extends Node implements Assignment { * Get the left hand side expression for this node * @return the left hand side expression */ - public Node lhs() { + public Expression lhs() { return lhs; } @@ -226,7 +226,7 @@ public final class BinaryNode extends Node implements Assignment { * Get the right hand side expression for this node * @return the left hand side expression */ - public Node rhs() { + public Expression rhs() { return rhs; } @@ -235,7 +235,7 @@ public final class BinaryNode extends Node implements Assignment { * @param lhs new left hand side expression * @return a node equivalent to this one except for the requested change. */ - public BinaryNode setLHS(final Node lhs) { + public BinaryNode setLHS(final Expression lhs) { if (this.lhs == lhs) { return this; } @@ -247,7 +247,7 @@ public final class BinaryNode extends Node implements Assignment { * @param rhs new left hand side expression * @return a node equivalent to this one except for the requested change. */ - public BinaryNode setRHS(final Node rhs) { + public BinaryNode setRHS(final Expression rhs) { if (this.rhs == rhs) { return this; } diff --git a/nashorn/src/jdk/nashorn/internal/ir/Block.java b/nashorn/src/jdk/nashorn/internal/ir/Block.java index 71692144167..c411401e710 100644 --- a/nashorn/src/jdk/nashorn/internal/ir/Block.java +++ b/nashorn/src/jdk/nashorn/internal/ir/Block.java @@ -38,11 +38,10 @@ import jdk.nashorn.internal.ir.annotations.Immutable; import jdk.nashorn.internal.ir.visitor.NodeVisitor; /** - * IR representation for a list of statements and functions. All provides the - * basis for script body. + * IR representation for a list of statements. */ @Immutable -public class Block extends BreakableNode implements Flags { +public class Block extends Node implements BreakableNode, Flags { /** List of statements */ protected final List statements; @@ -52,6 +51,9 @@ public class Block extends BreakableNode implements Flags { /** Entry label. */ protected final Label entryLabel; + /** Break label. */ + private final Label breakLabel; + /** Does the block/function need a new scope? */ protected final int flags; @@ -76,17 +78,17 @@ public class Block extends BreakableNode implements Flags { /** * Constructor * - * @param lineNumber line number * @param token token * @param finish finish * @param statements statements */ - public Block(final int lineNumber, final long token, final int finish, final Statement... statements) { - super(lineNumber, token, finish, new Label("block_break")); + public Block(final long token, final int finish, final Statement... statements) { + super(token, finish); this.statements = Arrays.asList(statements); this.symbols = new LinkedHashMap<>(); this.entryLabel = new Label("block_entry"); + this.breakLabel = new Label("block_break"); this.flags = 0; } @@ -98,8 +100,8 @@ public class Block extends BreakableNode implements Flags { * @param finish finish * @param statements statements */ - public Block(final int lineNumber, final long token, final int finish, final List statements) { - this(lineNumber, token, finish, statements.toArray(new Statement[statements.size()])); + public Block(final long token, final int finish, final List statements) { + this(token, finish, statements.toArray(new Statement[statements.size()])); } private Block(final Block block, final int finish, final List statements, final int flags, final Map symbols) { @@ -108,6 +110,7 @@ public class Block extends BreakableNode implements Flags { this.flags = flags; this.symbols = new LinkedHashMap<>(symbols); //todo - symbols have no dependencies on any IR node and can as far as we understand it be shallow copied now this.entryLabel = new Label(block.entryLabel); + this.breakLabel = new Label(block.breakLabel); this.finish = finish; } @@ -223,6 +226,11 @@ public class Block extends BreakableNode implements Flags { return entryLabel; } + @Override + public Label getBreakLabel() { + return breakLabel; + } + /** * Get the list of statements in this block * @@ -322,7 +330,17 @@ public class Block extends BreakableNode implements Flags { } @Override - protected boolean isBreakableWithoutLabel() { + public boolean isBreakableWithoutLabel() { return false; } + + @Override + public List