changeset 697:06c5f60e40e9

Merge
author alanb
date Tue, 07 Oct 2008 14:11:10 +0100
parents 437a9b4af951 2f38da01dcf4
children cbf58d8a3fec
files make/java/nio/FILES_java.gmk make/mksample/nio/Makefile src/share/classes/java/nio/Bits.java src/share/classes/java/nio/channels/DatagramChannel.java src/share/classes/java/nio/channels/ServerSocketChannel.java src/share/classes/java/nio/channels/SocketChannel.java src/share/classes/java/nio/channels/exceptions src/share/classes/java/nio/channels/package-info.java src/share/classes/org/jcp/xml/dsig/internal/package.html src/share/classes/sun/misc/SharedSecrets.java src/share/classes/sun/nio/ch/DatagramChannelImpl.java src/share/classes/sun/nio/ch/DatagramSocketAdaptor.java src/share/classes/sun/nio/ch/Net.java src/share/classes/sun/nio/ch/ServerSocketAdaptor.java src/share/classes/sun/nio/ch/ServerSocketChannelImpl.java src/share/classes/sun/nio/ch/SocketChannelImpl.java src/solaris/classes/sun/nio/ch/DevPollSelectorImpl.java src/solaris/classes/sun/nio/ch/EPollArrayWrapper.java src/solaris/classes/sun/nio/ch/EPollSelectorImpl.java src/solaris/native/java/net/net_util_md.c src/solaris/native/sun/nio/ch/DatagramChannelImpl.c src/solaris/native/sun/nio/ch/Net.c src/solaris/native/sun/nio/ch/ServerSocketChannelImpl.c src/solaris/native/sun/nio/ch/SocketChannelImpl.c src/windows/native/sun/nio/ch/Net.c test/sun/net/www/http/ChunkedInputStream/test.txt
diffstat 506 files changed, 9893 insertions(+), 8413 deletions(-) [+]
line wrap: on
line diff
--- a/make/com/sun/inputmethods/indicim/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/com/sun/inputmethods/indicim/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2002-2006 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2002-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/com/sun/inputmethods/thaiim/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/com/sun/inputmethods/thaiim/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2002-2006 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2002-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/com/sun/java/pack/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/com/sun/java/pack/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2003-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/com/sun/security/auth/module/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/com/sun/security/auth/module/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2000-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/common/BuildToolJar.gmk	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/common/BuildToolJar.gmk	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1998-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/common/Demo.gmk	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/common/Demo.gmk	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2004-2006 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2004-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/common/Library.gmk	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/common/Library.gmk	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1995-2007 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1995-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/common/internal/ImportComponents.gmk	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/common/internal/ImportComponents.gmk	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/common/shared/Defs-java.gmk	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/common/shared/Defs-java.gmk	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/common/shared/Defs-windows.gmk	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/common/shared/Defs-windows.gmk	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2005-2007 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/java/fdlibm/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/java/fdlibm/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1998-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/java/hpi/windows/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/java/hpi/windows/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1999-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/java/java/FILES_java.gmk	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/java/java/FILES_java.gmk	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1996-2007 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1996-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/java/java_crw_demo/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/java/java_crw_demo/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2004-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2004-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/java/java_hprof_demo/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/java/java_hprof_demo/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2003-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/java/management/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/java/management/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2003-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/java/net/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/java/net/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1995-2007 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1995-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/java/net/mapfile-vers	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/java/net/mapfile-vers	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1997-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/java/nio/FILES_java.gmk	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/java/nio/FILES_java.gmk	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2000-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/java/nio/genCoder.sh	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/java/nio/genCoder.sh	Tue Oct 07 14:11:10 2008 +0100
@@ -1,7 +1,7 @@
 #! /bin/sh
 
 #
-# Copyright 2000-2001 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/java/npt/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/java/npt/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2004-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2004-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/java/zip/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/java/zip/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1996-2006 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1996-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/javax/swing/beaninfo/SwingBeans.gmk	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/javax/swing/beaninfo/SwingBeans.gmk	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1998-2006 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/jpda/back/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/jpda/back/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1998-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/jpda/transport/shmem/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/jpda/transport/shmem/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1999-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/jpda/transport/socket/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/jpda/transport/socket/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1998-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/jprt.properties	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/jprt.properties	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2006-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/mksample/nio/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/mksample/nio/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2004-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2004-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/mksample/nio/multicast/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/mksample/nio/multicast/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/netbeans/jconsole/build.properties	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/netbeans/jconsole/build.properties	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
 #
 # Redistribution and use in source and binary forms, with or without
 # modification, are permitted provided that the following conditions
--- a/make/netbeans/jconsole/build.xml	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/netbeans/jconsole/build.xml	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 <!--
- Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved.
+ Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
 
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
--- a/make/sun/cmm/kcms/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/sun/cmm/kcms/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/sun/font/t2k/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/sun/font/t2k/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/sun/image/generic/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/sun/image/generic/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1998-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/sun/image/vis/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/sun/image/vis/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1998-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/sun/jconsole/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/sun/jconsole/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2004-2006 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2004-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/sun/jdbc/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/sun/jdbc/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1996-2007 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1996-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/sun/jpeg/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/sun/jpeg/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 1995-2007 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1995-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/sun/net/spi/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/sun/net/spi/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -23,10 +23,6 @@
 # have any questions.
 #
 
-#
-# Makefile for building com/sun
-#
-
 BUILDDIR = ../../..
 include $(BUILDDIR)/common/Defs.gmk
 
--- a/make/sun/net/spi/nameservice/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/sun/net/spi/nameservice/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -23,10 +23,6 @@
 # have any questions.
 #
 
-#
-# Makefile for building com/sun
-#
-
 BUILDDIR = ../../../..
 include $(BUILDDIR)/common/Defs.gmk
 
--- a/make/sun/net/spi/nameservice/dns/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/sun/net/spi/nameservice/dns/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2000-2006 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -24,7 +24,7 @@
 #
 
 #
-# Makefile for building JNDI service provider toolkit
+# Makefile for building JNDI DNS name service provider
 #
 
 BUILDDIR = ../../../../..
--- a/make/sun/text/Makefile	Fri Oct 03 19:14:15 2008 +0100
+++ b/make/sun/text/Makefile	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2001-2006 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/src/share/back/ThreadReferenceImpl.c	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/back/ThreadReferenceImpl.c	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/back/eventFilter.c	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/back/eventFilter.c	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/back/transport.c	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/back/transport.c	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/bin/java.h	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/bin/java.h	Tue Oct 07 14:11:10 2008 +0100
@@ -188,7 +188,8 @@
  */
 typedef jclass (JNICALL FindClassFromBootLoader_t(JNIEnv *env,
                                                 const char *name,
+                                                jboolean init,
+                                                jobject loader,
                                                 jboolean throwError));
-
 jclass FindBootStrapClass(JNIEnv *env, const char *classname);
 #endif /* _JAVA_H_ */
--- a/src/share/classes/com/sun/jmx/defaults/JmxProperties.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/defaults/JmxProperties.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/event/DaemonThreadFactory.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/event/DaemonThreadFactory.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/event/EventBuffer.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/event/EventBuffer.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/event/EventClientFactory.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/event/EventClientFactory.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/event/EventConnection.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/event/EventConnection.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2002-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/event/EventParams.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/event/EventParams.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/event/LeaseManager.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/event/LeaseManager.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/event/LeaseRenewer.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/event/LeaseRenewer.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/event/ReceiverBuffer.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/event/ReceiverBuffer.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/event/RepeatedSingletonJob.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/event/RepeatedSingletonJob.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/mbeanserver/DynamicMBean2.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/mbeanserver/DynamicMBean2.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/mbeanserver/MBeanInjector.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/mbeanserver/MBeanInjector.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/mbeanserver/NotifySupport.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/mbeanserver/NotifySupport.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/mbeanserver/PerThreadGroupPool.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/mbeanserver/PerThreadGroupPool.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/mbeanserver/StandardMBeanIntrospector.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/mbeanserver/StandardMBeanIntrospector.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/mbeanserver/SunJmxMBeanServer.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/mbeanserver/SunJmxMBeanServer.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/remote/internal/ClientCommunicatorAdmin.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/remote/internal/ClientCommunicatorAdmin.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/remote/internal/ProxyInputStream.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/remote/internal/ProxyInputStream.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/remote/internal/ProxyRef.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/remote/internal/ProxyRef.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/remote/util/EnvHelp.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/remote/util/EnvHelp.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/remote/util/EventClientConnection.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/remote/util/EventClientConnection.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/jmx/snmp/tasks/ThreadService.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/jmx/snmp/tasks/ThreadService.java	Tue Oct 07 14:11:10 2008 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2002-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/Init.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/Init.java	Tue Oct 07 14:11:10 2008 +0100
@@ -20,12 +20,9 @@
  */
 package com.sun.org.apache.xml.internal.security;
 
-
-
 import java.io.InputStream;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
-
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 
@@ -51,7 +48,7 @@
  * done by calling {@link Init#init} which should be done in any static block
  * of the files of this library. We ensure that this call is only executed once.
  *
- * @author $Author: raul $
+ * @author $Author: mullan $
  */
 public final class Init {
 
@@ -113,20 +110,19 @@
             dbf.setValidating(false);
 
             DocumentBuilder db = dbf.newDocumentBuilder();
-
             // We don't allow users to override the Apache XML Security
             // configuration in the JRE. Users should use the standard security
             // provider mechanism instead if implementing their own
             // transform or canonicalization algorithms.
-            // String cfile = System.getProperty("com.sun.org.apache.xml.internal.security.resource.config");
-            // InputStream is =
-            //     Class.forName("com.sun.org.apache.xml.internal.security.Init")
-            //     .getResourceAsStream(cfile != null ? cfile : "resource/config.xml");
+            // InputStream is = Class.forName("com.sun.org.apache.xml.internal.security.Init").getResourceAsStream("resource/config.xml");
             InputStream is = (InputStream) AccessController.doPrivileged(
                 new PrivilegedAction() {
                     public Object run() {
+//                        String cfile = System.getProperty
+//                            ("com.sun.org.apache.xml.internal.security.resource.config");
                         return getClass().getResourceAsStream
-                                ("resource/config.xml");
+//                            (cfile != null ? cfile : "resource/config.xml");
+                            ("resource/config.xml");
                     }
                 });
 
@@ -167,7 +163,7 @@
 //
 //            if (tag.equals("ResourceBundles")){
 //                XX_configure_i18n_start = System.currentTimeMillis();
-//              Element resource=(Element)el;
+//                Element resource=(Element)el;
 //               /* configure internationalization */
 //               Attr langAttr = resource.getAttributeNode("defaultLanguageCode");
 //               Attr countryAttr = resource.getAttributeNode("defaultCountryCode");
@@ -202,11 +198,11 @@
 
                         if (currMeth.getDeclaringClass().getName()
                                 .equals(JAVACLASS)) {
-                           log.log(java.util.logging.Level.FINE, currMeth.getDeclaringClass().toString());
+                           log.log(java.util.logging.Level.FINE, currMeth.getDe claringClass().toString());
                         }
                      }*/
-                      if (true)
-                        if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "Canonicalizer.register(" + URI + ", "
+                      if (log.isLoggable(java.util.logging.Level.FINE))
+                        log.log(java.util.logging.Level.FINE, "Canonicalizer.register(" + URI + ", "
                             + JAVACLASS + ")");
                      Canonicalizer.register(URI, JAVACLASS);
                   } catch (ClassNotFoundException e) {
@@ -233,9 +229,8 @@
                         "JAVACLASS");
                   try {
                      Class.forName(JAVACLASS);
-                     if (true)
-                        if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "Transform.register(" + URI + ", " + JAVACLASS
-                            + ")");
+                     if (log.isLoggable(java.util.logging.Level.FINE))
+                        log.log(java.util.logging.Level.FINE, "Transform.register(" + URI + ", " + JAVACLASS + ")");
                      Transform.register(URI, JAVACLASS);
                   } catch (ClassNotFoundException e) {
                      Object exArgs[] = { URI, JAVACLASS };
@@ -284,12 +279,11 @@
 //
 //                        if (currMeth.getDeclaringClass().getName()
 //                                .equals(JAVACLASS)) {
-//                           log.log(java.util.logging.Level.FINE, currMeth.getDeclaringClass().toString());
+//                           log.log(java.util.logging.Level.FINE, currMeth.getDe claringClass().toString());
 //                        }
 //                     }
-                      if (true)
-                        if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "SignatureAlgorithm.register(" + URI + ", "
-                            + JAVACLASS + ")");
+                      if (log.isLoggable(java.util.logging.Level.FINE))
+                        log.log(java.util.logging.Level.FINE, "SignatureAlgorithm.register(" + URI + ", " + JAVACLASS + ")");
                      SignatureAlgorithm.register(URI, JAVACLASS);
                   } catch (ClassNotFoundException e) {
                      Object exArgs[] = { URI, JAVACLASS };
@@ -320,13 +314,11 @@
                         "DESCRIPTION");
 
                   if ((Description != null) && (Description.length() > 0)) {
-                    if (true)
-                        if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": "
-                               + Description);
+                    if (log.isLoggable(java.util.logging.Level.FINE))
+                        log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": " + Description);
                   } else {
-                    if (true)
-                        if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS
-                               + ": For unknown purposes");
+                    if (log.isLoggable(java.util.logging.Level.FINE))
+                        log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": For unknown purposes");
                   }
                                   try {
                                           ResourceResolver.register(JAVACLASS);
@@ -359,13 +351,11 @@
                         "DESCRIPTION");
 
                   if ((Description != null) && (Description.length() > 0)) {
-                    if (true)
-                        if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": "
-                               + Description);
+                    if (log.isLoggable(java.util.logging.Level.FINE))
+                        log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": " + Description);
                   } else {
-                    if (true)
-                        if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS
-                               + ": For unknown purposes");
+                    if (log.isLoggable(java.util.logging.Level.FINE))
+                        log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": For unknown purposes");
                   }
 
                   KeyResolver.register(JAVACLASS);
@@ -376,8 +366,8 @@
 
             if (tag.equals("PrefixMappings")){
                 XX_configure_reg_prefixes_start = System.currentTimeMillis();
-                if (true)
-                        if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "Now I try to bind prefixes:");
+                if (log.isLoggable(java.util.logging.Level.FINE))
+                    log.log(java.util.logging.Level.FINE, "Now I try to bind prefixes:");
 
                Element[] nl = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS,"PrefixMapping");
 
@@ -386,8 +376,8 @@
                                         "namespace");
                   String prefix = nl[i].getAttributeNS(null,
                                      "prefix");
-                  if (true)
-                        if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "Now I try to bind " + prefix + " to " + namespace);
+                  if (log.isLoggable(java.util.logging.Level.FINE))
+                      log.log(java.util.logging.Level.FINE, "Now I try to bind " + prefix + " to " + namespace);
                   com.sun.org.apache.xml.internal.security.utils.ElementProxy
                      .setDefaultPrefix(namespace, prefix);
                }
@@ -398,19 +388,19 @@
             long XX_init_end = System.currentTimeMillis();
 
             //J-
-            if (true) {
-                if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "XX_init                             " + ((int)(XX_init_end - XX_init_start)) + " ms");
-                if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "  XX_prng                           " + ((int)(XX_prng_end - XX_prng_start)) + " ms");
-                if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "  XX_parsing                        " + ((int)(XX_parsing_end - XX_parsing_start)) + " ms");
-                if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "  XX_configure_i18n                 " + ((int)(XX_configure_i18n_end- XX_configure_i18n_start)) + " ms");
-                if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "  XX_configure_reg_c14n             " + ((int)(XX_configure_reg_c14n_end- XX_configure_reg_c14n_start)) + " ms");
-                if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "  XX_configure_reg_jcemapper        " + ((int)(XX_configure_reg_jcemapper_end- XX_configure_reg_jcemapper_start)) + " ms");
-                if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "  XX_configure_reg_keyInfo          " + ((int)(XX_configure_reg_keyInfo_end- XX_configure_reg_keyInfo_start)) + " ms");
-                if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "  XX_configure_reg_keyResolver      " + ((int)(XX_configure_reg_keyResolver_end- XX_configure_reg_keyResolver_start)) + " ms");
-                if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "  XX_configure_reg_prefixes         " + ((int)(XX_configure_reg_prefixes_end- XX_configure_reg_prefixes_start)) + " ms");
-                if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "  XX_configure_reg_resourceresolver " + ((int)(XX_configure_reg_resourceresolver_end- XX_configure_reg_resourceresolver_start)) + " ms");
-                if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "  XX_configure_reg_sigalgos         " + ((int)(XX_configure_reg_sigalgos_end- XX_configure_reg_sigalgos_start)) + " ms");
-                if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "  XX_configure_reg_transforms       " + ((int)(XX_configure_reg_transforms_end- XX_configure_reg_transforms_start)) + " ms");
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "XX_init                             " + ((int)(XX_init_end - XX_init_start)) + " ms");
+                log.log(java.util.logging.Level.FINE, "  XX_prng                           " + ((int)(XX_prng_end - XX_prng_start)) + " ms");
+                log.log(java.util.logging.Level.FINE, "  XX_parsing                        " + ((int)(XX_parsing_end - XX_parsing_start)) + " ms");
+                log.log(java.util.logging.Level.FINE, "  XX_configure_i18n                 " + ((int)(XX_configure_i18n_end- XX_configure_i18n_start)) + " ms");
+                log.log(java.util.logging.Level.FINE, "  XX_configure_reg_c14n             " + ((int)(XX_configure_reg_c14n_end- XX_configure_reg_c14n_start)) + " ms");
+                log.log(java.util.logging.Level.FINE, "  XX_configure_reg_jcemapper        " + ((int)(XX_configure_reg_jcemapper_end- XX_configure_reg_jcemapper_start)) + " ms");
+                log.log(java.util.logging.Level.FINE, "  XX_configure_reg_keyInfo          " + ((int)(XX_configure_reg_keyInfo_end- XX_configure_reg_keyInfo_start)) + " ms");
+                log.log(java.util.logging.Level.FINE, "  XX_configure_reg_keyResolver      " + ((int)(XX_configure_reg_keyResolver_end- XX_configure_reg_keyResolver_start)) + " ms");
+                log.log(java.util.logging.Level.FINE, "  XX_configure_reg_prefixes         " + ((int)(XX_configure_reg_prefixes_end- XX_configure_reg_prefixes_start)) + " ms");
+                log.log(java.util.logging.Level.FINE, "  XX_configure_reg_resourceresolver " + ((int)(XX_configure_reg_resourceresolver_end- XX_configure_reg_resourceresolver_start)) + " ms");
+                log.log(java.util.logging.Level.FINE, "  XX_configure_reg_sigalgos         " + ((int)(XX_configure_reg_sigalgos_end- XX_configure_reg_sigalgos_start)) + " ms");
+                log.log(java.util.logging.Level.FINE, "  XX_configure_reg_transforms       " + ((int)(XX_configure_reg_transforms_end- XX_configure_reg_transforms_start)) + " ms");
             }
          } catch (Exception e) {
             log.log(java.util.logging.Level.SEVERE, "Bad: ", e);
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java	Tue Oct 07 14:11:10 2008 +0100
@@ -24,7 +24,7 @@
 
 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.ElementProxy;
+import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
@@ -33,11 +33,7 @@
  * The Algorithm class which stores the Algorithm URI as a string.
  *
  */
-public abstract class Algorithm extends ElementProxy {
-
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(Algorithm.class.getName());
+public abstract class Algorithm extends SignatureElementProxy {
 
    /**
     *
@@ -79,7 +75,7 @@
     */
    protected void setAlgorithmURI(String algorithmURI) {
 
-      if ((this._state == MODE_CREATE) && (algorithmURI != null)) {
+      if ( (algorithmURI != null)) {
          this._constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM,
                                                 algorithmURI);
       }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java	Tue Oct 07 14:11:10 2008 +0100
@@ -35,7 +35,7 @@
 /**
  * This class maps algorithm identifier URIs to JAVA JCE class names.
  *
- * @author $Author: raul $
+ * @author $Author: mullan $
  */
 public class JCEMapper {
 
@@ -45,9 +45,9 @@
 
 
 
-   private static Map uriToJCEName = new HashMap();
+   private static Map uriToJCEName;
 
-   private static Map algorithmsMap = new HashMap();
+   private static Map algorithmsMap;
 
    private static String providerName = null;
    /**
@@ -63,6 +63,8 @@
 
    static void loadAlgorithms( Element algorithmsEl) {
        Element[] algorithms = XMLUtils.selectNodes(algorithmsEl.getFirstChild(),Init.CONF_NS,"Algorithm");
+       uriToJCEName = new HashMap( algorithms.length * 2);
+       algorithmsMap = new HashMap( algorithms.length * 2);
        for (int i = 0 ;i < algorithms.length ;i ++) {
            Element el = algorithms[i];
            String id = el.getAttribute("URI");
@@ -70,6 +72,7 @@
            uriToJCEName.put(id, jceName);
            algorithmsMap.put(id, new Algorithm(el));
        }
+
    }
 
    static Algorithm getAlgorithmMapping(String algoURI) {
@@ -84,8 +87,8 @@
     *
     */
    public static String translateURItoJCEID(String AlgorithmURI) {
-      if (true)
-          if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "Request for URI " + AlgorithmURI);
+      if (log.isLoggable(java.util.logging.Level.FINE))
+          log.log(java.util.logging.Level.FINE, "Request for URI " + AlgorithmURI);
 
       String jceName = (String) uriToJCEName.get(AlgorithmURI);
       return jceName;
@@ -100,8 +103,8 @@
     *
     */
    public static String getAlgorithmClassFromURI(String AlgorithmURI) {
-       if (true)
-           if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "Request for URI " + AlgorithmURI);
+       if (log.isLoggable(java.util.logging.Level.FINE))
+           log.log(java.util.logging.Level.FINE, "Request for URI " + AlgorithmURI);
 
        return ((Algorithm) algorithmsMap.get(AlgorithmURI)).algorithmClass;
    }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java	Tue Oct 07 14:11:10 2008 +0100
@@ -20,10 +20,10 @@
  */
 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;
@@ -41,11 +41,6 @@
  */
 public class MessageDigestAlgorithm extends Algorithm {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(
-                    MessageDigestAlgorithm.class.getName());
-
     /** Message Digest - NOT RECOMMENDED MD5*/
    public static final String ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5 = Constants.MoreAlgorithmsSpecNS + "md5";
    /** Digest - Required SHA1*/
@@ -76,6 +71,12 @@
       this.algorithm = messageDigest;
    }
 
+   static ThreadLocal instances=new ThreadLocal() {
+           protected Object initialValue() {
+                   return new HashMap();
+           };
+   };
+
    /**
     * Factory method for constructing a message digest algorithm by name.
     *
@@ -86,8 +87,15 @@
     */
    public static MessageDigestAlgorithm getInstance(
            Document doc, String algorithmURI) throws XMLSignatureException {
+          MessageDigest md = getDigestInstance(algorithmURI);
+      return new MessageDigestAlgorithm(doc, md, algorithmURI);
+   }
 
-      String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI);
+private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException {
+        MessageDigest result=(MessageDigest) ((Map)instances.get()).get(algorithmURI);
+        if (result!=null)
+                return result;
+    String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI);
 
           if (algorithmID == null) {
                   Object[] exArgs = { algorithmURI };
@@ -113,8 +121,9 @@
 
         throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
         }
-      return new MessageDigestAlgorithm(doc, md, algorithmURI);
-   }
+      ((Map)instances.get()).put(algorithmURI, md);
+        return md;
+}
 
    /**
     * Returns the actual {@link java.security.MessageDigest} algorithm object
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java	Tue Oct 07 14:11:10 2008 +0100
@@ -25,6 +25,7 @@
 import java.security.SecureRandom;
 import java.security.spec.AlgorithmParameterSpec;
 import java.util.HashMap;
+import java.util.Map;
 
 import com.sun.org.apache.xml.internal.security.algorithms.implementations.IntegrityHmac;
 import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
@@ -52,9 +53,35 @@
    /** All available algorithm classes are registered here */
    static HashMap _algorithmHash = null;
 
+   static ThreadLocal instancesSigning=new ThreadLocal() {
+           protected Object initialValue() {
+                   return new HashMap();
+           };
+   };
+
+   static ThreadLocal instancesVerify=new ThreadLocal() {
+           protected Object initialValue() {
+                   return new HashMap();
+           };
+   };
+
+   static ThreadLocal keysSigning=new ThreadLocal() {
+           protected Object initialValue() {
+                   return new HashMap();
+           };
+   };
+   static ThreadLocal keysVerify=new ThreadLocal() {
+           protected Object initialValue() {
+                   return new HashMap();
+           };
+   };
+//   boolean isForSigning=false;
+
    /** Field _signatureAlgorithm */
    protected SignatureAlgorithmSpi _signatureAlgorithm = null;
 
+   private String algorithmURI;
+
    /**
     * Constructor SignatureAlgorithm
     *
@@ -64,18 +91,49 @@
     */
    public SignatureAlgorithm(Document doc, String algorithmURI)
            throws XMLSecurityException {
+      super(doc, algorithmURI);
+      this.algorithmURI = algorithmURI;
+   }
 
-      super(doc, algorithmURI);
 
-      try {
+   private void initializeAlgorithm(boolean isForSigning) throws XMLSignatureException {
+           if (_signatureAlgorithm!=null) {
+                   return;
+           }
+           _signatureAlgorithm=isForSigning ? getInstanceForSigning(algorithmURI) : getInstanceForVerify(algorithmURI);
+                this._signatureAlgorithm
+                      .engineGetContextFromElement(this._constructionElement);
+   }
+   private static SignatureAlgorithmSpi getInstanceForSigning(String algorithmURI) throws XMLSignatureException {
+           SignatureAlgorithmSpi result=(SignatureAlgorithmSpi) ((Map)instancesSigning.get()).get(algorithmURI);
+           if (result!=null) {
+                   result.reset();
+                   return result;
+           }
+           result=buildSigner(algorithmURI, result);
+           ((Map)instancesSigning.get()).put(algorithmURI,result);
+           return result;
+   }
+   private static SignatureAlgorithmSpi getInstanceForVerify(String algorithmURI) throws XMLSignatureException {
+           SignatureAlgorithmSpi result=(SignatureAlgorithmSpi) ((Map)instancesVerify.get()).get(algorithmURI);
+           if (result!=null) {
+                   result.reset();
+                   return result;
+           }
+           result=buildSigner(algorithmURI, result);
+           ((Map)instancesVerify.get()).put(algorithmURI,result);
+           return result;
+   }
+
+   private static SignatureAlgorithmSpi buildSigner(String algorithmURI, SignatureAlgorithmSpi result) throws XMLSignatureException {
+        try {
          Class implementingClass =
             SignatureAlgorithm.getImplementingClass(algorithmURI);
-         if (true)
-                if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \""
+         if (log.isLoggable(java.util.logging.Level.FINE))
+                log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \""
                    + implementingClass + "\"");
-
-         this._signatureAlgorithm =
-            (SignatureAlgorithmSpi) implementingClass.newInstance();
+         result=(SignatureAlgorithmSpi) implementingClass.newInstance();
+         return   result;
       }  catch (IllegalAccessException ex) {
          Object exArgs[] = { algorithmURI, ex.getMessage() };
 
@@ -92,7 +150,7 @@
          throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs,
                                          ex);
       }
-   }
+}
 
    /**
     * Constructor SignatureAlgorithm
@@ -107,7 +165,8 @@
               throws XMLSecurityException {
 
       this(doc, algorithmURI);
-
+      this.algorithmURI=algorithmURI;
+      initializeAlgorithm(true);
       this._signatureAlgorithm.engineSetHMACOutputLength(HMACOutputLength);
       ((IntegrityHmac)this._signatureAlgorithm)
          .engineAddContextToElement(this._constructionElement);
@@ -124,37 +183,7 @@
            throws XMLSecurityException {
 
       super(element, BaseURI);
-
-      String algorithmURI = this.getURI();
-
-      try {
-         Class implementingClass =
-            SignatureAlgorithm.getImplementingClass(algorithmURI);
-         if (true)
-                if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \""
-                   + implementingClass + "\"");
-
-         this._signatureAlgorithm =
-            (SignatureAlgorithmSpi) implementingClass.newInstance();
-
-         this._signatureAlgorithm
-            .engineGetContextFromElement(this._constructionElement);
-      }  catch (IllegalAccessException ex) {
-         Object exArgs[] = { algorithmURI, ex.getMessage() };
-
-         throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs,
-                                         ex);
-      } catch (InstantiationException ex) {
-         Object exArgs[] = { algorithmURI, ex.getMessage() };
-
-         throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs,
-                                         ex);
-      } catch (NullPointerException ex) {
-         Object exArgs[] = { algorithmURI, ex.getMessage() };
-
-         throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs,
-                                         ex);
-      }
+      algorithmURI = this.getURI();
    }
 
    /**
@@ -175,7 +204,12 @@
     * @return the result of the {@link java.security.Signature#getAlgorithm} method
     */
    public String getJCEAlgorithmString() {
-      return this._signatureAlgorithm.engineGetJCEAlgorithmString();
+      try {
+                return getInstanceForVerify(algorithmURI).engineGetJCEAlgorithmString();
+        } catch (XMLSignatureException e) {
+                //Ignore.
+                return null;
+        }
    }
 
    /**
@@ -184,7 +218,11 @@
     * @return The Provider of this Signature Alogrithm
     */
    public String getJCEProviderName() {
-      return this._signatureAlgorithm.engineGetJCEProviderName();
+      try {
+                return getInstanceForVerify(algorithmURI).engineGetJCEProviderName();
+        } catch (XMLSignatureException e) {
+                return null;
+        }
    }
 
    /**
@@ -231,7 +269,13 @@
     * @throws XMLSignatureException
     */
    public void initSign(Key signingKey) throws XMLSignatureException {
-      this._signatureAlgorithm.engineInitSign(signingKey);
+           initializeAlgorithm(true);
+           Map map=(Map)keysSigning.get();
+       if (map.get(this.algorithmURI)==signingKey) {
+           return;
+       }
+       map.put(this.algorithmURI,signingKey);
+           this._signatureAlgorithm.engineInitSign(signingKey);
    }
 
    /**
@@ -244,6 +288,7 @@
     */
    public void initSign(Key signingKey, SecureRandom secureRandom)
            throws XMLSignatureException {
+           initializeAlgorithm(true);
       this._signatureAlgorithm.engineInitSign(signingKey, secureRandom);
    }
 
@@ -258,6 +303,7 @@
    public void initSign(
            Key signingKey, AlgorithmParameterSpec algorithmParameterSpec)
               throws XMLSignatureException {
+           initializeAlgorithm(true);
       this._signatureAlgorithm.engineInitSign(signingKey,
                                               algorithmParameterSpec);
    }
@@ -282,7 +328,13 @@
     * @throws XMLSignatureException
     */
    public void initVerify(Key verificationKey) throws XMLSignatureException {
-      this._signatureAlgorithm.engineInitVerify(verificationKey);
+           initializeAlgorithm(false);
+           Map map=(Map)keysVerify.get();
+           if (map.get(this.algorithmURI)==verificationKey) {
+           return;
+       }
+           map.put(this.algorithmURI,verificationKey);
+           this._signatureAlgorithm.engineInitVerify(verificationKey);
    }
 
    /**
@@ -320,7 +372,7 @@
                .getLogger(SignatureAlgorithm.class.getName());
       }
 
-      if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "Init() called");
+      log.log(java.util.logging.Level.FINE, "Init() called");
 
       if (!SignatureAlgorithm._alreadyInitialized) {
          SignatureAlgorithm._algorithmHash = new HashMap(10);
@@ -340,8 +392,8 @@
            throws AlgorithmAlreadyRegisteredException,XMLSignatureException {
 
       {
-         if (true)
-                if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass);
+         if (log.isLoggable(java.util.logging.Level.FINE))
+                log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass);
 
          // are we already registered?
          Class registeredClassClass =
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java	Tue Oct 07 14:11:10 2008 +0100
@@ -20,27 +20,20 @@
  */
 package com.sun.org.apache.xml.internal.security.algorithms;
 
-
-
 import java.security.Key;
 import java.security.SecureRandom;
 import java.security.spec.AlgorithmParameterSpec;
 
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
 
 /**
  *
- * @author $Author: raul $
+ * @author $Author: mullan $
  */
 public abstract class SignatureAlgorithmSpi {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(SignatureAlgorithmSpi.class.getName());
-
    /**
     * Returns the URI representation of <code>Transformation algorithm</code>
     *
@@ -167,20 +160,6 @@
    protected abstract void engineSetParameter(AlgorithmParameterSpec params)
       throws XMLSignatureException;
 
-   /** Field _doc */
-   Document _doc = null;
-
-   /**
-    * Method engineSetDocument
-    *
-    * @param doc
-    */
-   protected void engineSetDocument(Document doc) {
-      this._doc = doc;
-   }
-
-   /** Field _constructionElement */
-   Element _constructionElement = null;
 
    /**
     * Method engineGetContextFromElement
@@ -188,7 +167,6 @@
     * @param element
     */
    protected void engineGetContextFromElement(Element element) {
-      this._constructionElement = element;
    }
 
    /**
@@ -199,4 +177,7 @@
     */
    protected abstract void engineSetHMACOutputLength(int HMACOutputLength)
       throws XMLSignatureException;
+
+    public void reset() {
+        }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java	Tue Oct 07 14:11:10 2008 +0100
@@ -45,7 +45,7 @@
 
 /**
  *
- * @author $Author: raul $
+ * @author $Author: mullan $
  */
 public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
 
@@ -74,8 +74,8 @@
    public IntegrityHmac() throws XMLSignatureException {
 
       String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
-      if (true)
-        if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID);
+      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);
@@ -99,6 +99,10 @@
       throw new XMLSignatureException("empty");
    }
 
+   public void reset() {
+           _HMACOutputLength=0;
+   }
+
    /**
     * Proxy method for {@link java.security.Signature#verify(byte[])}
     * which is executed on the internal {@link java.security.Signature} object.
@@ -145,7 +149,20 @@
       try {
          this._macAlgorithm.init(secretKey);
       } catch (InvalidKeyException ex) {
-         throw new XMLSignatureException("empty", 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;
+            try {
+                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;
+            }
+            throw new XMLSignatureException("empty", ex);
       }
    }
 
@@ -323,7 +340,7 @@
     */
    protected String engineGetJCEAlgorithmString() {
 
-      if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "engineGetJCEAlgorithmString()");
+      log.log(java.util.logging.Level.FINE, "engineGetJCEAlgorithmString()");
 
       return this._macAlgorithm.getAlgorithm();
    }
@@ -397,7 +414,8 @@
    /**
     * Class IntegrityHmacSHA1
     *
-    * @author $Author: raul $
+    * @author $Author: mullan $
+    * @version $Revision: 1.5 $
     */
    public static class IntegrityHmacSHA1 extends IntegrityHmac {
 
@@ -423,7 +441,8 @@
    /**
     * Class IntegrityHmacSHA256
     *
-    * @author $Author: raul $
+    * @author $Author: mullan $
+    * @version $Revision: 1.5 $
     */
    public static class IntegrityHmacSHA256 extends IntegrityHmac {
 
@@ -449,7 +468,8 @@
    /**
     * Class IntegrityHmacSHA384
     *
-    * @author $Author: raul $
+    * @author $Author: mullan $
+    * @version $Revision: 1.5 $
     */
    public static class IntegrityHmacSHA384 extends IntegrityHmac {
 
@@ -475,7 +495,8 @@
    /**
     * Class IntegrityHmacSHA512
     *
-    * @author $Author: raul $
+    * @author $Author: mullan $
+    * @version $Revision: 1.5 $
     */
    public static class IntegrityHmacSHA512 extends IntegrityHmac {
 
@@ -501,7 +522,8 @@
    /**
     * Class IntegrityHmacRIPEMD160
     *
-    * @author $Author: raul $
+    * @author $Author: mullan $
+    * @version $Revision: 1.5 $
     */
    public static class IntegrityHmacRIPEMD160 extends IntegrityHmac {
 
@@ -527,7 +549,8 @@
    /**
     * Class IntegrityHmacMD5
     *
-    * @author $Author: raul $
+    * @author $Author: mullan $
+    * @version $Revision: 1.5 $
     */
    public static class IntegrityHmacMD5 extends IntegrityHmac {
 
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java	Tue Oct 07 14:11:10 2008 +0100
@@ -3,7 +3,7 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright  1999-2004 The Apache Software Foundation.
+ * Copyright  1999-2007 The Apache Software Foundation.
  *
  *  Licensed under the Apache License, Version 2.0 (the "License");
  *  you may not use this file except in compliance with the License.
@@ -20,8 +20,6 @@
  */
 package com.sun.org.apache.xml.internal.security.algorithms.implementations;
 
-
-
 import java.security.InvalidAlgorithmParameterException;
 import java.security.InvalidKeyException;
 import java.security.Key;
@@ -38,329 +36,344 @@
 import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
 
-
 /**
  *
- * @author $Author: raul $
+ * @author $Author: mullan $
  */
 public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
 
-   /** {@link java.util.logging} logging facility */
+    /** {@link java.util.logging} logging facility */
     static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(SignatureBaseRSA.class.getName());
+        java.util.logging.Logger.getLogger
+        (SignatureBaseRSA.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;
 
-   /**
-    * Constructor SignatureRSA
-    *
-    * @throws XMLSignatureException
-    */
-   public SignatureBaseRSA() throws XMLSignatureException {
+    /**
+     * Constructor SignatureRSA
+     *
+     * @throws XMLSignatureException
+     */
+    public SignatureBaseRSA() throws XMLSignatureException {
 
-      String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
+        String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
 
-      if (true)
-        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) {
+        if (log.isLoggable(java.util.logging.Level.FINE))
+            log.log(java.util.logging.Level.FINE, "Created SignatureRSA using " + algorithmID);
+        String provider=JCEMapper.getProviderId();
+        try {
+            if (provider==null) {
                 this._signatureAlgorithm = Signature.getInstance(algorithmID);
-         } else {
+            } else {
                 this._signatureAlgorithm = Signature.getInstance(algorithmID,provider);
-         }
-      } catch (java.security.NoSuchAlgorithmException ex) {
-         Object[] exArgs = { algorithmID,
-                             ex.getLocalizedMessage() };
+            }
+        } 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);
+        } catch (NoSuchProviderException ex) {
+            Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
 
-         throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
+            throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
         }
-   }
+    }
 
-   /** @inheritDoc */
-   protected void engineSetParameter(AlgorithmParameterSpec params)
-           throws XMLSignatureException {
+    /** @inheritDoc */
+    protected void engineSetParameter(AlgorithmParameterSpec params)
+        throws XMLSignatureException {
 
-      try {
-         this._signatureAlgorithm.setParameter(params);
-      } catch (InvalidAlgorithmParameterException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+        try {
+            this._signatureAlgorithm.setParameter(params);
+        } catch (InvalidAlgorithmParameterException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /** @inheritDoc */
-   protected boolean engineVerify(byte[] signature)
-           throws XMLSignatureException {
+    /** @inheritDoc */
+    protected boolean engineVerify(byte[] signature)
+        throws XMLSignatureException {
 
-      try {
-         return this._signatureAlgorithm.verify(signature);
-      } catch (SignatureException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+        try {
+            return this._signatureAlgorithm.verify(signature);
+        } catch (SignatureException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /** @inheritDoc */
-   protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
+    /** @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 };
+        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);
-      } catch (InvalidKeyException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+        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;
+            try {
+                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;
+            }
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /** @inheritDoc */
-   protected byte[] engineSign() throws XMLSignatureException {
+    /** @inheritDoc */
+    protected byte[] engineSign() throws XMLSignatureException {
+        try {
+            return this._signatureAlgorithm.sign();
+        } catch (SignatureException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-      try {
-         return this._signatureAlgorithm.sign();
-      } catch (SignatureException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /** @inheritDoc */
+    protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
+        throws XMLSignatureException {
 
-   /** @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 };
 
-      if (!(privateKey instanceof PrivateKey)) {
-         String supplied = privateKey.getClass().getName();
-         String needed = PrivateKey.class.getName();
-         Object exArgs[] = { supplied, needed };
+            throw new XMLSignatureException
+                ("algorithms.WrongKeyForThisOperation", exArgs);
+        }
 
-         throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
-                                         exArgs);
-      }
+        try {
+            this._signatureAlgorithm.initSign
+                ((PrivateKey) privateKey, secureRandom);
+        } catch (InvalidKeyException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-      try {
-         this._signatureAlgorithm.initSign((PrivateKey) privateKey,
-                                           secureRandom);
-      } catch (InvalidKeyException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /** @inheritDoc */
+    protected void engineInitSign(Key privateKey) throws XMLSignatureException {
 
-   /** @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 };
 
-      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);
+        } catch (InvalidKeyException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-      try {
-         this._signatureAlgorithm.initSign((PrivateKey) privateKey);
-      } catch (InvalidKeyException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /** @inheritDoc */
+    protected void engineUpdate(byte[] input) throws XMLSignatureException {
+        try {
+            this._signatureAlgorithm.update(input);
+        } catch (SignatureException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /** @inheritDoc */
-   protected void engineUpdate(byte[] input) throws XMLSignatureException {
+    /** @inheritDoc */
+    protected void engineUpdate(byte input) throws XMLSignatureException {
+        try {
+            this._signatureAlgorithm.update(input);
+        } catch (SignatureException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-      try {
-         this._signatureAlgorithm.update(input);
-      } catch (SignatureException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /** @inheritDoc */
+    protected void engineUpdate(byte buf[], int offset, int len)
+        throws XMLSignatureException {
+        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 buf[], int offset, int len)
-           throws XMLSignatureException {
+    /** @inheritDoc */
+    protected void engineSetHMACOutputLength(int HMACOutputLength)
+        throws XMLSignatureException {
+        throw new XMLSignatureException
+            ("algorithms.HMACOutputLengthOnlyForHMAC");
+    }
 
-      try {
-         this._signatureAlgorithm.update(buf, offset, len);
-      } 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 String engineGetJCEAlgorithmString() {
-      return this._signatureAlgorithm.getAlgorithm();
-   }
+    /**
+     * Class SignatureRSASHA1
+     *
+     * @author $Author: mullan $
+     * @version $Revision: 1.5 $
+     */
+    public static class SignatureRSASHA1 extends SignatureBaseRSA {
 
-   /** @inheritDoc */
-   protected String engineGetJCEProviderName() {
-      return this._signatureAlgorithm.getProvider().getName();
-   }
+        /**
+         * Constructor SignatureRSASHA1
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureRSASHA1() 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_RSA_SHA1;
+        }
+    }
 
-   /** @inheritDoc */
-   protected void engineInitSign(
-           Key signingKey, AlgorithmParameterSpec algorithmParameterSpec)
-              throws XMLSignatureException {
-      throw new XMLSignatureException(
-         "algorithms.CannotUseAlgorithmParameterSpecOnRSA");
-   }
+    /**
+     * Class SignatureRSASHA256
+     *
+     * @author $Author: mullan $
+     * @version $Revision: 1.5 $
+     */
+    public static class SignatureRSASHA256 extends SignatureBaseRSA {
 
-   /**
-    * Class SignatureRSASHA1
-    *
-    * @author $Author: raul $
-    */
-   public static class SignatureRSASHA1 extends SignatureBaseRSA {
+        /**
+         * Constructor SignatureRSASHA256
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureRSASHA256() throws XMLSignatureException {
+            super();
+        }
 
-      /**
-       * Constructor SignatureRSASHA1
-       *
-       * @throws XMLSignatureException
-       */
-      public SignatureRSASHA1() throws XMLSignatureException {
-         super();
-      }
+        /** @inheritDoc */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256;
+        }
+    }
 
-      /** @inheritDoc */
-      public String engineGetURI() {
-         return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
-      }
-   }
+    /**
+     * Class SignatureRSASHA384
+     *
+     * @author $Author: mullan $
+     * @version $Revision: 1.5 $
+     */
+    public static class SignatureRSASHA384 extends SignatureBaseRSA {
 
-   /**
-    * Class SignatureRSASHA256
-    *
-    * @author $Author: raul $
-    */
-   public static class SignatureRSASHA256 extends SignatureBaseRSA {
+        /**
+         * Constructor SignatureRSASHA384
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureRSASHA384() throws XMLSignatureException {
+            super();
+        }
 
-      /**
-       * Constructor SignatureRSASHA256
-       *
-       * @throws XMLSignatureException
-       */
-      public SignatureRSASHA256() throws XMLSignatureException {
-         super();
-      }
+        /** @inheritDoc */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384;
+        }
+    }
 
-      /** @inheritDoc */
-      public String engineGetURI() {
-         return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256;
-      }
-   }
+    /**
+     * Class SignatureRSASHA512
+     *
+     * @author $Author: mullan $
+     * @version $Revision: 1.5 $
+     */
+    public static class SignatureRSASHA512 extends SignatureBaseRSA {
 
-   /**
-    * Class SignatureRSASHA384
-    *
-    * @author $Author: raul $
-    */
-   public static class SignatureRSASHA384 extends SignatureBaseRSA {
+        /**
+         * Constructor SignatureRSASHA512
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureRSASHA512() throws XMLSignatureException {
+            super();
+        }
 
-      /**
-       * Constructor SignatureRSASHA384
-       *
-       * @throws XMLSignatureException
-       */
-      public SignatureRSASHA384() throws XMLSignatureException {
-         super();
-      }
+        /** @inheritDoc */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512;
+        }
+    }
 
-      /** @inheritDoc */
-      public String engineGetURI() {
-         return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384;
-      }
-   }
+    /**
+     * Class SignatureRSARIPEMD160
+     *
+     * @author $Author: mullan $
+     * @version $Revision: 1.5 $
+     */
+    public static class SignatureRSARIPEMD160 extends SignatureBaseRSA {
 
-   /**
-    * Class SignatureRSASHA512
-    *
-    * @author $Author: raul $
-    */
-   public static class SignatureRSASHA512 extends SignatureBaseRSA {
+        /**
+         * Constructor SignatureRSARIPEMD160
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureRSARIPEMD160() throws XMLSignatureException {
+            super();
+        }
 
-      /**
-       * Constructor SignatureRSASHA512
-       *
-       * @throws XMLSignatureException
-       */
-      public SignatureRSASHA512() throws XMLSignatureException {
-         super();
-      }
+        /** @inheritDoc */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160;
+        }
+    }
 
-      /** @inheritDoc */
-      public String engineGetURI() {
-         return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512;
-      }
-   }
+    /**
+     * Class SignatureRSAMD5
+     *
+     * @author $Author: mullan $
+     * @version $Revision: 1.5 $
+     */
+    public static class SignatureRSAMD5 extends SignatureBaseRSA {
 
-   /**
-    * Class SignatureRSARIPEMD160
-    *
-    * @author $Author: raul $
-    */
-   public static class SignatureRSARIPEMD160 extends SignatureBaseRSA {
+        /**
+         * Constructor SignatureRSAMD5
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureRSAMD5() throws XMLSignatureException {
+            super();
+        }
 
-      /**
-       * Constructor SignatureRSARIPEMD160
-       *
-       * @throws XMLSignatureException
-       */
-      public SignatureRSARIPEMD160() throws XMLSignatureException {
-         super();
-      }
-
-      /** @inheritDoc */
-      public String engineGetURI() {
-         return XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160;
-      }
-   }
-
-   /**
-    * Class SignatureRSAMD5
-    *
-    * @author $Author: raul $
-    */
-   public static class SignatureRSAMD5 extends SignatureBaseRSA {
-
-      /**
-       * Constructor SignatureRSAMD5
-       *
-       * @throws XMLSignatureException
-       */
-      public SignatureRSAMD5() throws XMLSignatureException {
-         super();
-      }
-
-      /** @inheritDoc */
-      public String engineGetURI() {
-         return XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5;
-      }
-   }
+        /** @inheritDoc */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5;
+        }
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java	Tue Oct 07 14:11:10 2008 +0100
@@ -20,8 +20,6 @@
  */
 package com.sun.org.apache.xml.internal.security.algorithms.implementations;
 
-
-
 import java.io.IOException;
 import java.security.InvalidAlgorithmParameterException;
 import java.security.InvalidKeyException;
@@ -39,342 +37,359 @@
 import com.sun.org.apache.xml.internal.security.utils.Base64;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 
-
 /**
  *
- * @author $Author: vishal $
+ * @author $Author: mullan $
  */
 public class SignatureDSA extends SignatureAlgorithmSpi {
 
-   /** {@link java.util.logging} logging facility */
+    /** {@link java.util.logging} logging facility */
     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;
+    /** Field algorithm */
+    private java.security.Signature _signatureAlgorithm = null;
 
-   /**
-    * Method engineGetURI
-    *
-    * @inheritDoc
-    */
-   protected String engineGetURI() {
-      return SignatureDSA._URI;
-   }
+    /**
+     * Method engineGetURI
+     *
+     * @inheritDoc
+     */
+    protected String engineGetURI() {
+        return SignatureDSA._URI;
+    }
 
-   /**
-    * Constructor SignatureDSA
-    *
-    * @throws XMLSignatureException
-    */
-   public SignatureDSA() throws XMLSignatureException {
+    /**
+     * Constructor SignatureDSA
+     *
+     * @throws XMLSignatureException
+     */
+    public SignatureDSA() throws XMLSignatureException {
 
-      String algorithmID = JCEMapper.translateURItoJCEID(SignatureDSA._URI);
-      if (true)
-        if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "Created SignatureDSA using " + algorithmID);
+        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);
 
-      try {
-         this._signatureAlgorithm = Signature.getInstance(algorithmID);
-      } catch (java.security.NoSuchAlgorithmException ex) {
-         Object[] exArgs = { algorithmID,
-                             ex.getLocalizedMessage() };
+        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 (java.security.NoSuchProviderException ex) {
+            Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
+            throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
+        }
+    }
 
-         throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
-      }
-   }
+    /**
+     * @inheritDoc
+     */
+    protected void engineSetParameter(AlgorithmParameterSpec params)
+        throws XMLSignatureException {
 
-   /**
-    * @inheritDoc
-    */
-   protected void engineSetParameter(AlgorithmParameterSpec params)
+        try {
+            this._signatureAlgorithm.setParameter(params);
+        } catch (InvalidAlgorithmParameterException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
+
+    /**
+     * @inheritDoc
+     */
+    protected boolean engineVerify(byte[] signature)
            throws XMLSignatureException {
 
-      try {
-         this._signatureAlgorithm.setParameter(params);
-      } catch (InvalidAlgorithmParameterException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+        try {
+            if (log.isLoggable(java.util.logging.Level.FINE))
+                log.log(java.util.logging.Level.FINE, "Called DSA.verify() on " + Base64.encode(signature));
 
-   /**
-    * @inheritDoc
-    */
-   protected boolean engineVerify(byte[] signature)
+            byte[] jcebytes = SignatureDSA.convertXMLDSIGtoASN1(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;
+            try {
+                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;
+            }
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
+
+    /**
+     * @inheritDoc
+     */
+    protected byte[] engineSign() throws XMLSignatureException {
+
+        try {
+            byte jcebytes[] = this._signatureAlgorithm.sign();
+
+            return SignatureDSA.convertASN1toXMLDSIG(jcebytes);
+        } catch (IOException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (SignatureException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
+
+    /**
+     * @inheritDoc
+     */
+    protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
            throws XMLSignatureException {
 
-      try {
-         if (true)
-                if (log.isLoggable(java.util.logging.Level.FINE))                                     log.log(java.util.logging.Level.FINE, "Called DSA.verify() on " + Base64.encode(signature));
+        if (!(privateKey instanceof PrivateKey)) {
+            String supplied = privateKey.getClass().getName();
+            String needed = PrivateKey.class.getName();
+            Object exArgs[] = { supplied, needed };
 
-         byte[] jcebytes = SignatureDSA.convertXMLDSIGtoASN1(signature);
+            throw new XMLSignatureException
+                ("algorithms.WrongKeyForThisOperation", exArgs);
+        }
 
-         return this._signatureAlgorithm.verify(jcebytes);
-      } catch (SignatureException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (IOException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+        try {
+            this._signatureAlgorithm.initSign((PrivateKey) privateKey,
+                                           secureRandom);
+        } catch (InvalidKeyException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /**
-    * @inheritDoc
-    */
-   protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
+    /**
+     * @inheritDoc
+     */
+    protected void engineInitSign(Key privateKey) throws XMLSignatureException {
 
-      if (!(publicKey instanceof PublicKey)) {
-         String supplied = publicKey.getClass().getName();
-         String needed = PublicKey.class.getName();
-         Object exArgs[] = { supplied, needed };
+        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.initVerify((PublicKey) publicKey);
-      } catch (InvalidKeyException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+        try {
+            this._signatureAlgorithm.initSign((PrivateKey) privateKey);
+        } catch (InvalidKeyException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /**
-    * @inheritDoc
-    */
-   protected byte[] engineSign() throws XMLSignatureException {
+    /**
+     * @inheritDoc
+     */
+    protected void engineUpdate(byte[] input) throws XMLSignatureException {
+        try {
+            this._signatureAlgorithm.update(input);
+        } catch (SignatureException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-      try {
-         byte jcebytes[] = this._signatureAlgorithm.sign();
+    /**
+     * @inheritDoc
+     */
+    protected void engineUpdate(byte input) throws XMLSignatureException {
+        try {
+            this._signatureAlgorithm.update(input);
+        } catch (SignatureException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-         return SignatureDSA.convertASN1toXMLDSIG(jcebytes);
-      } catch (IOException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (SignatureException 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 engineInitSign(Key privateKey, SecureRandom secureRandom)
-           throws XMLSignatureException {
+    /**
+     * Method engineGetJCEAlgorithmString
+     *
+     * @inheritDoc
+     */
+    protected String engineGetJCEAlgorithmString() {
+        return this._signatureAlgorithm.getAlgorithm();
+    }
 
-      if (!(privateKey instanceof PrivateKey)) {
-         String supplied = privateKey.getClass().getName();
-         String needed = PrivateKey.class.getName();
-         Object exArgs[] = { supplied, needed };
+    /**
+     * Method engineGetJCEProviderName
+     *
+     * @inheritDoc
+     */
+    protected String engineGetJCEProviderName() {
+        return this._signatureAlgorithm.getProvider().getName();
+    }
 
-         throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
-                                         exArgs);
-      }
-
-      try {
-         this._signatureAlgorithm.initSign((PrivateKey) privateKey,
-                                           secureRandom);
-      } catch (InvalidKeyException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
-
-   /**
-    * @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);
-      }
-
-      try {
-         this._signatureAlgorithm.initSign((PrivateKey) privateKey);
-      } catch (InvalidKeyException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
-
-   /**
-    * @inheritDoc
-    */
-   protected void engineUpdate(byte[] input) throws XMLSignatureException {
-
-      try {
-         this._signatureAlgorithm.update(input);
-      } catch (SignatureException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
-
-   /**
-    * @inheritDoc
-    */
-   protected void engineUpdate(byte input) throws XMLSignatureException {
-
-      try {
-         this._signatureAlgorithm.update(input);
-      } catch (SignatureException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
-
-   /**
-    * @inheritDoc
-    */
-   protected void engineUpdate(byte buf[], int offset, int len)
-           throws XMLSignatureException {
-
-      try {
-         this._signatureAlgorithm.update(buf, offset, len);
-      } catch (SignatureException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
-
-   /**
-    * Method engineGetJCEAlgorithmString
-    *
-    * @inheritDoc
-    */
-   protected String engineGetJCEAlgorithmString() {
-      return this._signatureAlgorithm.getAlgorithm();
-   }
-
-   /**
-    * Method engineGetJCEProviderName
-    *
-    * @inheritDoc
-    */
-   protected String engineGetJCEProviderName() {
-      return this._signatureAlgorithm.getProvider().getName();
-   }
-
-
-   /**
-    * Converts an ASN.1 DSA value to a XML Signature DSA Value.
-    *
-    * The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
-    * pairs; the XML Signature requires the core BigInteger values.
-    *
-    * @param asn1Bytes
-    * @return the decode bytes
-    *
-    * @throws IOException
-    * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
-    */
-   private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[])
+    /**
+     * Converts an ASN.1 DSA value to a XML Signature DSA Value.
+     *
+     * The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
+     * pairs; the XML Signature requires the core BigInteger values.
+     *
+     * @param asn1Bytes
+     * @return the decode bytes
+     *
+     * @throws IOException
+     * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
+     */
+    private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[])
            throws IOException {
 
-      byte rLength = asn1Bytes[3];
-      int i;
+        byte rLength = asn1Bytes[3];
+        int i;
 
-      for (i = rLength; (i > 0) && (asn1Bytes[(4 + rLength) - i] == 0); i--);
+        for (i = rLength; (i > 0) && (asn1Bytes[(4 + rLength) - i] == 0); i--);
 
-      byte sLength = asn1Bytes[5 + rLength];
-      int j;
+        byte sLength = asn1Bytes[5 + rLength];
+        int j;
 
-      for (j = sLength;
+        for (j = sLength;
               (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--);
 
-      if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2)
+        if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2)
               || (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];
+            throw new IOException("Invalid ASN.1 format of DSA signature");
+        }
+        byte xmldsigBytes[] = new byte[40];
 
-      System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 20 - i,
+        System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 20 - i,
                           i);
-      System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes,
+        System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes,
                           40 - j, j);
 
-       return xmldsigBytes;
-   }
+        return xmldsigBytes;
+    }
 
-   /**
-    * Converts a XML Signature DSA Value to an ASN.1 DSA value.
-    *
-    * The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
-    * pairs; the XML Signature requires the core BigInteger values.
-    *
-    * @param xmldsigBytes
-    * @return the encoded ASN.1 bytes
-    *
-    * @throws IOException
-    * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
-    */
-   private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[])
+    /**
+     * Converts a XML Signature DSA Value to an ASN.1 DSA value.
+     *
+     * The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
+     * pairs; the XML Signature requires the core BigInteger values.
+     *
+     * @param xmldsigBytes
+     * @return the encoded ASN.1 bytes
+     *
+     * @throws IOException
+     * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
+     */
+    private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[])
            throws IOException {
 
-      if (xmldsigBytes.length != 40) {
-         throw new IOException("Invalid XMLDSIG format of DSA signature");
-      }
+        if (xmldsigBytes.length != 40) {
+            throw new IOException("Invalid XMLDSIG format of DSA signature");
+        }
 
-      int i;
+        int i;
 
-      for (i = 20; (i > 0) && (xmldsigBytes[20 - i] == 0); i--);
+        for (i = 20; (i > 0) && (xmldsigBytes[20 - i] == 0); i--);
 
-      int j = i;
+        int j = i;
 
-      if (xmldsigBytes[20 - i] < 0) {
+        if (xmldsigBytes[20 - i] < 0) {
          j += 1;
-      }
+        }
 
-      int k;
+        int k;
 
-      for (k = 20; (k > 0) && (xmldsigBytes[40 - k] == 0); k--);
+        for (k = 20; (k > 0) && (xmldsigBytes[40 - k] == 0); k--);
 
-      int l = k;
+        int l = k;
 
-      if (xmldsigBytes[40 - k] < 0) {
-         l += 1;
-      }
+        if (xmldsigBytes[40 - k] < 0) {
+            l += 1;
+        }
 
-      byte asn1Bytes[] = new byte[6 + j + l];
+        byte asn1Bytes[] = new byte[6 + j + l];
 
-      asn1Bytes[0] = 48;
-      asn1Bytes[1] = (byte) (4 + j + l);
-      asn1Bytes[2] = 2;
-      asn1Bytes[3] = (byte) j;
+        asn1Bytes[0] = 48;
+        asn1Bytes[1] = (byte) (4 + j + l);
+        asn1Bytes[2] = 2;
+        asn1Bytes[3] = (byte) j;
 
-      System.arraycopy(xmldsigBytes, 20 - i, asn1Bytes, (4 + j) - i, i);
+        System.arraycopy(xmldsigBytes, 20 - i, asn1Bytes, (4 + j) - i, i);
 
-      asn1Bytes[4 + j] = 2;
-      asn1Bytes[5 + j] = (byte) l;
+        asn1Bytes[4 + j] = 2;
+        asn1Bytes[5 + j] = (byte) l;
 
-      System.arraycopy(xmldsigBytes, 40 - k, asn1Bytes, (6 + j + l) - k, k);
+        System.arraycopy(xmldsigBytes, 40 - k, asn1Bytes, (6 + j + l) - k, k);
 
-      return asn1Bytes;
-   }
+        return asn1Bytes;
+    }
 
-   /**
-    * Method engineSetHMACOutputLength
-    *
-    * @param HMACOutputLength
-    * @throws XMLSignatureException
-    */
-   protected void engineSetHMACOutputLength(int HMACOutputLength)
-           throws XMLSignatureException {
-      throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
-   }
+    /**
+     * Method engineSetHMACOutputLength
+     *
+     * @param HMACOutputLength
+     * @throws XMLSignatureException
+     */
+    protected void engineSetHMACOutputLength(int HMACOutputLength)
+            throws XMLSignatureException {
+        throw new XMLSignatureException(
+            "algorithms.HMACOutputLengthOnlyForHMAC");
+    }
 
-   /**
-    * Method engineInitSign
-    *
-    * @param signingKey
-    * @param algorithmParameterSpec
-    * @throws XMLSignatureException
-    */
-   protected void engineInitSign(
-           Key signingKey, AlgorithmParameterSpec algorithmParameterSpec)
-              throws XMLSignatureException {
-      throw new XMLSignatureException(
-         "algorithms.CannotUseAlgorithmParameterSpecOnDSA");
-   }
+    /**
+     * Method engineInitSign
+     *
+     * @param signingKey
+     * @param algorithmParameterSpec
+     * @throws XMLSignatureException
+     */
+    protected void engineInitSign(
+        Key signingKey, AlgorithmParameterSpec algorithmParameterSpec)
+            throws XMLSignatureException {
+        throw new XMLSignatureException(
+            "algorithms.CannotUseAlgorithmParameterSpecOnDSA");
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java	Tue Oct 07 14:11:10 2008 +0100
@@ -0,0 +1,384 @@
+/*
+ * 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.algorithms.implementations;
+
+
+
+import java.io.IOException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchProviderException;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.SecureRandom;
+import java.security.Signature;
+import java.security.SignatureException;
+import java.security.spec.AlgorithmParameterSpec;
+
+import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
+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;
+import com.sun.org.apache.xml.internal.security.utils.Base64;
+
+
+/**
+ *
+ * @author $Author: mullan $
+ */
+public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
+
+   /** {@link java.util.logging} logging facility */
+    static java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(SignatureECDSA.class.getName());
+
+    /** @inheritDoc */
+   public abstract String engineGetURI();
+
+   /** Field algorithm */
+   private java.security.Signature _signatureAlgorithm = null;
+
+   /**
+    * Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value.
+    *
+    * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value
+    * pairs; the XML Signature requires the core BigInteger values.
+    *
+    * @param asn1Bytes
+    * @return the decode bytes
+    *
+    * @throws IOException
+    * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
+    * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
+    */
+   private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[])
+           throws IOException {
+
+      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 <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
+    * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
+    */
+   private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[])
+           throws IOException {
+
+      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);
+        }
+   }
+
+   /** @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;
+            try {
+                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;
+            }
+            throw new XMLSignatureException("empty", ex);
+      }
+   }
+
+   /** @inheritDoc */
+   protected byte[] engineSign() throws XMLSignatureException {
+
+      try {
+         byte jcebytes[] = this._signatureAlgorithm.sign();
+
+         return SignatureECDSA.convertASN1toXMLDSIG(jcebytes);
+      } catch (SignatureException ex) {
+         throw new XMLSignatureException("empty", ex);
+      } catch (IOException ex) {
+          throw new XMLSignatureException("empty", ex);
+      }
+   }
+
+   /** @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);
+      }
+
+      try {
+         this._signatureAlgorithm.initSign((PrivateKey) privateKey,
+                                           secureRandom);
+      } catch (InvalidKeyException ex) {
+         throw new XMLSignatureException("empty", ex);
+      }
+   }
+
+   /** @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);
+      }
+
+      try {
+         this._signatureAlgorithm.initSign((PrivateKey) privateKey);
+      } catch (InvalidKeyException ex) {
+         throw new XMLSignatureException("empty", ex);
+      }
+   }
+
+   /** @inheritDoc */
+   protected void engineUpdate(byte[] input) throws XMLSignatureException {
+
+      try {
+         this._signatureAlgorithm.update(input);
+      } catch (SignatureException ex) {
+         throw new XMLSignatureException("empty", ex);
+      }
+   }
+
+   /** @inheritDoc */
+   protected void engineUpdate(byte input) throws XMLSignatureException {
+
+      try {
+         this._signatureAlgorithm.update(input);
+      } catch (SignatureException ex) {
+         throw new XMLSignatureException("empty", ex);
+      }
+   }
+
+   /** @inheritDoc */
+   protected void engineUpdate(byte buf[], int offset, int len)
+           throws XMLSignatureException {
+
+      try {
+         this._signatureAlgorithm.update(buf, offset, len);
+      } catch (SignatureException ex) {
+         throw new XMLSignatureException("empty", ex);
+      }
+   }
+
+   /** @inheritDoc */
+   protected String engineGetJCEAlgorithmString() {
+      return this._signatureAlgorithm.getAlgorithm();
+   }
+
+   /** @inheritDoc */
+   protected String engineGetJCEProviderName() {
+      return this._signatureAlgorithm.getProvider().getName();
+   }
+
+   /** @inheritDoc */
+   protected void engineSetHMACOutputLength(int HMACOutputLength)
+           throws XMLSignatureException {
+      throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
+   }
+
+   /** @inheritDoc */
+   protected void engineInitSign(
+           Key signingKey, AlgorithmParameterSpec algorithmParameterSpec)
+              throws XMLSignatureException {
+      throw new XMLSignatureException(
+         "algorithms.CannotUseAlgorithmParameterSpecOnRSA");
+   }
+
+   /**
+    * Class SignatureRSASHA1
+    *
+    * @author $Author: mullan $
+    * @version $Revision: 1.2 $
+    */
+   public static class SignatureECDSASHA1 extends SignatureECDSA {
+
+      /**
+       * Constructor SignatureRSASHA1
+       *
+       * @throws XMLSignatureException
+       */
+      public SignatureECDSASHA1() throws XMLSignatureException {
+         super();
+      }
+
+      /** @inheritDoc */
+      public String engineGetURI() {
+         return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1;
+      }
+   }
+
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java	Tue Oct 07 14:11:10 2008 +0100
@@ -2,7 +2,6 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-
 /*
  * Copyright  1999-2004 The Apache Software Foundation.
  *
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java	Tue Oct 07 14:11:10 2008 +0100
@@ -3,7 +3,7 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright  1999-2004 The Apache Software Foundation.
+ * Copyright  1999-2008 The Apache Software Foundation.
  *
  *  Licensed under the Apache License, Version 2.0 (the "License");
  *  you may not use this file except in compliance with the License.
@@ -20,8 +20,6 @@
  */
 package com.sun.org.apache.xml.internal.security.c14n;
 
-
-
 import java.io.ByteArrayInputStream;
 import java.io.OutputStream;
 import java.util.HashMap;
@@ -37,318 +35,326 @@
 import org.w3c.dom.NodeList;
 import org.xml.sax.InputSource;
 
-
 /**
  *
- *
  * @author Christian Geuer-Pollmann
  */
 public class Canonicalizer {
 
-   //J-
-   /** The output encoding of canonicalized data */
-   public static final String ENCODING = "UTF8";
+    /** The output encoding of canonicalized data */
+    public static final String ENCODING = "UTF8";
 
+    /**
+     * XPath Expresion for selecting every node and continuous comments joined
+     * in only one node
+     */
+    public static final String XPATH_C14N_WITH_COMMENTS_SINGLE_NODE =
+        "(.//. | .//@* | .//namespace::*)";
 
-   /**
-     * XPath Expresion for selecting every node and continuos comments joined in only one node
-     */
-    public static final String XPATH_C14N_WITH_COMMENTS_SINGLE_NODE = "(.//. | .//@* | .//namespace::*)";
-
-
-   /**
+    /**
      * The URL defined in XML-SEC Rec for inclusive c14n <b>without</b> comments.
      */
-   public static final String ALGO_ID_C14N_OMIT_COMMENTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
-   /**
-    * The URL defined in XML-SEC Rec for inclusive c14n <b>with</b> comments.
-    */
-   public static final String ALGO_ID_C14N_WITH_COMMENTS = ALGO_ID_C14N_OMIT_COMMENTS + "#WithComments";
-   /**
-    * The URL defined in XML-SEC Rec for exclusive c14n <b>without</b> comments.
-    */
-   public static final String ALGO_ID_C14N_EXCL_OMIT_COMMENTS = "http://www.w3.org/2001/10/xml-exc-c14n#";
-   /**
-    * The URL defined in XML-SEC Rec for exclusive c14n <b>with</b> comments.
-    */
-   public static final String ALGO_ID_C14N_EXCL_WITH_COMMENTS = ALGO_ID_C14N_EXCL_OMIT_COMMENTS + "WithComments";
+    public static final String ALGO_ID_C14N_OMIT_COMMENTS =
+        "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
+    /**
+     * The URL defined in XML-SEC Rec for inclusive c14n <b>with</b> comments.
+     */
+    public static final String ALGO_ID_C14N_WITH_COMMENTS =
+        ALGO_ID_C14N_OMIT_COMMENTS + "#WithComments";
+    /**
+     * The URL defined in XML-SEC Rec for exclusive c14n <b>without</b> comments.
+     */
+    public static final String ALGO_ID_C14N_EXCL_OMIT_COMMENTS =
+        "http://www.w3.org/2001/10/xml-exc-c14n#";
+    /**
+     * The URL defined in XML-SEC Rec for exclusive c14n <b>with</b> comments.
+     */
+    public static final String ALGO_ID_C14N_EXCL_WITH_COMMENTS =
+        ALGO_ID_C14N_EXCL_OMIT_COMMENTS + "WithComments";
+    /**
+     * The URI for inclusive c14n 1.1 <b>without</b> comments.
+     */
+    public static final String ALGO_ID_C14N11_OMIT_COMMENTS =
+        "http://www.w3.org/2006/12/xml-c14n11";
+    /**
+     * The URI for inclusive c14n 1.1 <b>with</b> comments.
+     */
+    public static final String ALGO_ID_C14N11_WITH_COMMENTS =
+        ALGO_ID_C14N11_OMIT_COMMENTS + "#WithComments";
 
-   static boolean _alreadyInitialized = false;
-   static Map _canonicalizerHash = null;
+    static boolean _alreadyInitialized = false;
+    static Map _canonicalizerHash = null;
 
-   protected CanonicalizerSpi canonicalizerSpi = null;
-   //J+
+    protected CanonicalizerSpi canonicalizerSpi = null;
 
-   /**
-    * Method init
-    *
-    */
-   public static void init() {
+    /**
+     * Method init
+     *
+     */
+    public static void init() {
 
-      if (!Canonicalizer._alreadyInitialized) {
-         Canonicalizer._canonicalizerHash = new HashMap(10);
-         Canonicalizer._alreadyInitialized = true;
-      }
-   }
+        if (!Canonicalizer._alreadyInitialized) {
+            Canonicalizer._canonicalizerHash = new HashMap(10);
+            Canonicalizer._alreadyInitialized = true;
+        }
+    }
 
-   /**
-    * Constructor Canonicalizer
-    *
-    * @param algorithmURI
-    * @throws InvalidCanonicalizerException
-    */
-   private Canonicalizer(String algorithmURI)
+    /**
+     * Constructor Canonicalizer
+     *
+     * @param algorithmURI
+     * @throws InvalidCanonicalizerException
+     */
+    private Canonicalizer(String algorithmURI)
            throws InvalidCanonicalizerException {
 
-      try {
-         Class implementingClass = getImplementingClass(algorithmURI);
+        try {
+            Class implementingClass = getImplementingClass(algorithmURI);
 
-         this.canonicalizerSpi =
-            (CanonicalizerSpi) implementingClass.newInstance();
-         this.canonicalizerSpi.reset=true;
-      } catch (Exception e) {
-         Object exArgs[] = { algorithmURI };
+            this.canonicalizerSpi =
+                (CanonicalizerSpi) implementingClass.newInstance();
+            this.canonicalizerSpi.reset=true;
+        } catch (Exception e) {
+            Object exArgs[] = { algorithmURI };
 
-         throw new InvalidCanonicalizerException(
-            "signature.Canonicalizer.UnknownCanonicalizer", exArgs);
-      }
-   }
+            throw new InvalidCanonicalizerException(
+               "signature.Canonicalizer.UnknownCanonicalizer", exArgs);
+        }
+    }
 
-   /**
-    * Method getInstance
-    *
-    * @param algorithmURI
-    * @return a Conicicalizer instance ready for the job
-    * @throws InvalidCanonicalizerException
-    */
-   public static final Canonicalizer getInstance(String algorithmURI)
+    /**
+     * Method getInstance
+     *
+     * @param algorithmURI
+     * @return a Conicicalizer instance ready for the job
+     * @throws InvalidCanonicalizerException
+     */
+    public static final Canonicalizer getInstance(String algorithmURI)
            throws InvalidCanonicalizerException {
 
-      Canonicalizer c14nizer = new Canonicalizer(algorithmURI);
+        Canonicalizer c14nizer = new Canonicalizer(algorithmURI);
 
-      return c14nizer;
-   }
+        return c14nizer;
+    }
 
-   /**
-    * Method register
-    *
-    * @param algorithmURI
-    * @param implementingClass
-    * @throws AlgorithmAlreadyRegisteredException
-    */
-   public static void register(String algorithmURI, String implementingClass)
+    /**
+     * Method register
+     *
+     * @param algorithmURI
+     * @param implementingClass
+     * @throws AlgorithmAlreadyRegisteredException
+     */
+    public static void register(String algorithmURI, String implementingClass)
            throws AlgorithmAlreadyRegisteredException {
 
-      // check whether URI is already registered
-      Class registeredClass = getImplementingClass(algorithmURI);
+        // check whether URI is already registered
+        Class registeredClass = getImplementingClass(algorithmURI);
 
-      if (registeredClass != null)  {
-         Object exArgs[] = { algorithmURI, registeredClass };
+        if (registeredClass != null)  {
+            Object exArgs[] = { algorithmURI, registeredClass };
 
-         throw new AlgorithmAlreadyRegisteredException(
-            "algorithm.alreadyRegistered", exArgs);
-      }
+            throw new AlgorithmAlreadyRegisteredException(
+                "algorithm.alreadyRegistered", exArgs);
+        }
 
-      try {
-                _canonicalizerHash.put(algorithmURI, Class.forName(implementingClass));
+        try {
+            _canonicalizerHash.put(algorithmURI, Class.forName(implementingClass));
         } catch (ClassNotFoundException e) {
-                throw new RuntimeException("c14n class not found");
+            throw new RuntimeException("c14n class not found");
         }
-   }
+    }
 
-   /**
-    * Method getURI
-    *
-    * @return the URI defined for this c14n instance.
-    */
-   public final String getURI() {
-      return this.canonicalizerSpi.engineGetURI();
-   }
+    /**
+     * Method getURI
+     *
+     * @return the URI defined for this c14n instance.
+     */
+    public final String getURI() {
+        return this.canonicalizerSpi.engineGetURI();
+    }
 
-   /**
-    * Method getIncludeComments
-    *
-    * @return true if the c14n respect the comments.
-    */
-   public boolean getIncludeComments() {
-      return this.canonicalizerSpi.engineGetIncludeComments();
-   }
+    /**
+     * Method getIncludeComments
+     *
+     * @return true if the c14n respect the comments.
+     */
+    public boolean getIncludeComments() {
+        return this.canonicalizerSpi.engineGetIncludeComments();
+    }
 
-   /**
-    * This method tries to canonicalize the given bytes. It's possible to even
-    * canonicalize non-wellformed sequences if they are well-formed after being
-    * wrapped with a <CODE>&gt;a&lt;...&gt;/a&lt;</CODE>.
-    *
-    * @param inputBytes
-    * @return the result of the conicalization.
-    * @throws CanonicalizationException
-    * @throws java.io.IOException
-    * @throws javax.xml.parsers.ParserConfigurationException
-    * @throws org.xml.sax.SAXException
-    */
-   public byte[] canonicalize(byte[] inputBytes)
+    /**
+     * This method tries to canonicalize the given bytes. It's possible to even
+     * canonicalize non-wellformed sequences if they are well-formed after being
+     * wrapped with a <CODE>&gt;a&lt;...&gt;/a&lt;</CODE>.
+     *
+     * @param inputBytes
+     * @return the result of the conicalization.
+     * @throws CanonicalizationException
+     * @throws java.io.IOException
+     * @throws javax.xml.parsers.ParserConfigurationException
+     * @throws org.xml.sax.SAXException
+     */
+    public byte[] canonicalize(byte[] inputBytes)
            throws javax.xml.parsers.ParserConfigurationException,
                   java.io.IOException, org.xml.sax.SAXException,
                   CanonicalizationException {
 
-      ByteArrayInputStream bais = new ByteArrayInputStream(inputBytes);
-      InputSource in = new InputSource(bais);
-      DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
+        ByteArrayInputStream bais = new ByteArrayInputStream(inputBytes);
+        InputSource in = new InputSource(bais);
+        DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
 
-      dfactory.setNamespaceAware(true);
+        dfactory.setNamespaceAware(true);
 
-      // needs to validate for ID attribute nomalization
-      dfactory.setValidating(true);
+        // needs to validate for ID attribute nomalization
+        dfactory.setValidating(true);
 
-      DocumentBuilder db = dfactory.newDocumentBuilder();
+        DocumentBuilder db = dfactory.newDocumentBuilder();
 
-      /*
-       * for some of the test vectors from the specification,
-       * there has to be a validatin parser for ID attributes, default
-       * attribute values, NMTOKENS, etc.
-       * Unfortunaltely, the test vectors do use different DTDs or
-       * even no DTD. So Xerces 1.3.1 fires many warnings about using
-       * ErrorHandlers.
-       *
-       * Text from the spec:
-       *
-       * The input octet stream MUST contain a well-formed XML document,
-       * but the input need not be validated. However, the attribute
-       * value normalization and entity reference resolution MUST be
-       * performed in accordance with the behaviors of a validating
-       * XML processor. As well, nodes for default attributes (declared
-       * in the ATTLIST with an AttValue but not specified) are created
-       * in each element. Thus, the declarations in the document type
-       * declaration are used to help create the canonical form, even
-       * though the document type declaration is not retained in the
-       * canonical form.
-       *
-       */
-      db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils
-         .IgnoreAllErrorHandler());
+        /*
+         * 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.
+         *
+         */
+        db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils
+            .IgnoreAllErrorHandler());
 
-      Document document = db.parse(in);
-      byte result[] = this.canonicalizeSubtree(document);
+        Document document = db.parse(in);
+        byte result[] = this.canonicalizeSubtree(document);
 
-      return result;
-   }
+        return result;
+    }
 
-   /**
-    * Canonicalizes the subtree rooted by <CODE>node</CODE>.
-    *
-    * @param node The node to canicalize
-    * @return the result of the c14n.
-    *
-    * @throws CanonicalizationException
-    */
-   public byte[] canonicalizeSubtree(Node node)
+    /**
+     * Canonicalizes the subtree rooted by <CODE>node</CODE>.
+     *
+     * @param node The node to canicalize
+     * @return the result of the c14n.
+     *
+     * @throws CanonicalizationException
+     */
+    public byte[] canonicalizeSubtree(Node node)
            throws CanonicalizationException {
-      return this.canonicalizerSpi.engineCanonicalizeSubTree(node);
-   }
+        return this.canonicalizerSpi.engineCanonicalizeSubTree(node);
+    }
 
-   /**
-    * Canonicalizes the subtree rooted by <CODE>node</CODE>.
-    *
-    * @param node
-    * @param inclusiveNamespaces
-    * @return the result of the c14n.
-    * @throws CanonicalizationException
-    */
-   public byte[] canonicalizeSubtree(Node node, String inclusiveNamespaces)
+    /**
+     * Canonicalizes the subtree rooted by <CODE>node</CODE>.
+     *
+     * @param node
+     * @param inclusiveNamespaces
+     * @return the result of the c14n.
+     * @throws CanonicalizationException
+     */
+    public byte[] canonicalizeSubtree(Node node, String inclusiveNamespaces)
            throws CanonicalizationException {
-      return this.canonicalizerSpi.engineCanonicalizeSubTree(node,
+        return this.canonicalizerSpi.engineCanonicalizeSubTree(node,
               inclusiveNamespaces);
-   }
+    }
 
-   /**
-    * Canonicalizes an XPath node set. The <CODE>xpathNodeSet</CODE> is treated
-    * as a list of XPath nodes, not as a list of subtrees.
-    *
-    * @param xpathNodeSet
-    * @return the result of the c14n.
-    * @throws CanonicalizationException
-    */
-   public byte[] canonicalizeXPathNodeSet(NodeList xpathNodeSet)
+    /**
+     * Canonicalizes an XPath node set. The <CODE>xpathNodeSet</CODE> is treated
+     * as a list of XPath nodes, not as a list of subtrees.
+     *
+     * @param xpathNodeSet
+     * @return the result of the c14n.
+     * @throws CanonicalizationException
+     */
+    public byte[] canonicalizeXPathNodeSet(NodeList xpathNodeSet)
            throws CanonicalizationException {
-      return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet);
-   }
+        return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet);
+    }
 
-   /**
-    * Canonicalizes an XPath node set. The <CODE>xpathNodeSet</CODE> is treated
-    * as a list of XPath nodes, not as a list of subtrees.
-    *
-    * @param xpathNodeSet
-    * @param inclusiveNamespaces
-    * @return the result of the c14n.
-    * @throws CanonicalizationException
-    */
-   public byte[] canonicalizeXPathNodeSet(
+    /**
+     * Canonicalizes an XPath node set. The <CODE>xpathNodeSet</CODE> is treated
+     * as a list of XPath nodes, not as a list of subtrees.
+     *
+     * @param xpathNodeSet
+     * @param inclusiveNamespaces
+     * @return the result of the c14n.
+     * @throws CanonicalizationException
+     */
+    public byte[] canonicalizeXPathNodeSet(
            NodeList xpathNodeSet, String inclusiveNamespaces)
               throws CanonicalizationException {
-      return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet,
+        return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet,
               inclusiveNamespaces);
-   }
+    }
 
-   /**
-    * Canonicalizes an XPath node set.
-    *
-    * @param xpathNodeSet
-    * @return the result of the c14n.
-    * @throws CanonicalizationException
-    */
-   public byte[] canonicalizeXPathNodeSet(Set xpathNodeSet)
+    /**
+     * Canonicalizes an XPath node set.
+     *
+     * @param xpathNodeSet
+     * @return the result of the c14n.
+     * @throws CanonicalizationException
+     */
+    public byte[] canonicalizeXPathNodeSet(Set xpathNodeSet)
            throws CanonicalizationException {
-       return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet);
-   }
+        return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet);
+    }
 
-   /**
-    * Canonicalizes an XPath node set.
-    *
-    * @param xpathNodeSet
-    * @param inclusiveNamespaces
-    * @return the result of the c14n.
-    * @throws CanonicalizationException
-    */
-   public byte[] canonicalizeXPathNodeSet(
-           Set xpathNodeSet, String inclusiveNamespaces)
-              throws CanonicalizationException {
-       return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet,
-              inclusiveNamespaces);
-   }
+    /**
+     * Canonicalizes an XPath node set.
+     *
+     * @param xpathNodeSet
+     * @param inclusiveNamespaces
+     * @return the result of the c14n.
+     * @throws CanonicalizationException
+     */
+    public byte[] canonicalizeXPathNodeSet(Set xpathNodeSet,
+        String inclusiveNamespaces) throws CanonicalizationException {
+        return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet,
+            inclusiveNamespaces);
+    }
 
-   /**
-    * Sets the writter where the cannocalization ends. ByteArrayOutputStream if
-    * none is setted.
-    * @param os
-    */
-   public void setWriter(OutputStream os) {
-            this.canonicalizerSpi.setWriter(os);
-   }
+    /**
+     * Sets the writer where the canonicalization ends.  ByteArrayOutputStream
+     * if none is set.
+     * @param os
+     */
+    public void setWriter(OutputStream os) {
+        this.canonicalizerSpi.setWriter(os);
+    }
 
-   /**
-    * Returns the name of the implementing {@link CanonicalizerSpi} class
-    *
-    * @return the name of the implementing {@link CanonicalizerSpi} class
-    */
-   public String getImplementingCanonicalizerClass() {
-      return this.canonicalizerSpi.getClass().getName();
-   }
+    /**
+     * Returns the name of the implementing {@link CanonicalizerSpi} class
+     *
+     * @return the name of the implementing {@link CanonicalizerSpi} class
+     */
+    public String getImplementingCanonicalizerClass() {
+        return this.canonicalizerSpi.getClass().getName();
+    }
 
-   /**
-    * Method getImplementingClass
-    *
-    * @param URI
-    * @return the name of the class that implements the give URI
-    */
-   private static Class getImplementingClass(String URI) {
-      return (Class) _canonicalizerHash.get(URI);
-   }
+    /**
+     * Method getImplementingClass
+     *
+     * @param URI
+     * @return the name of the class that implements the given URI
+     */
+    private static Class getImplementingClass(String URI) {
+        return (Class) _canonicalizerHash.get(URI);
+    }
 
-   /**
-    * Set the canonicalizator behaviour to not reset.
-    *
-    */
-   public void notReset() {
-            this.canonicalizerSpi.reset=false;
-   }
+    /**
+     * Set the canonicalizer behaviour to not reset.
+     */
+    public void notReset() {
+        this.canonicalizerSpi.reset = false;
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java	Tue Oct 07 14:11:10 2008 +0100
@@ -2,7 +2,6 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-
 /*
  * Copyright  1999-2004 The Apache Software Foundation.
  *
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java	Tue Oct 07 14:11:10 2008 +0100
@@ -2,7 +2,6 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-
 /*
  * Copyright  1999-2004 The Apache Software Foundation.
  *
@@ -21,17 +20,17 @@
  */
 package com.sun.org.apache.xml.internal.security.c14n.helper;
 
-
-
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import org.w3c.dom.Attr;
-
+import java.io.Serializable;
+import java.util.Comparator;
 
 /**
  * Compares two attributes based on the C14n specification.
  *
  * <UL>
- * <LI>Namespace nodes have a lesser document order position than attribute nodes.
+ * <LI>Namespace nodes have a lesser document order position than attribute
+ *   nodes.
  * <LI> An element's namespace nodes are sorted lexicographically by
  *   local name (the default namespace node, if one exists, has no
  *   local name and is therefore lexicographically least).
@@ -40,104 +39,89 @@
  *   key (an empty namespace URI is lexicographically least).
  * </UL>
  *
- * $todo$ Should we implement java.util.Comparator and import java.util.Arrays to use Arrays.sort(intarray);
  * @author Christian Geuer-Pollmann
  */
-public class AttrCompare implements java.util.Comparator {
+public class AttrCompare implements Comparator, Serializable {
 
-   private final int ATTR0_BEFORE_ATTR1 = -1;
-   private final int ATTR1_BEFORE_ATTR0 = 1;
+    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 final static String XMLNS=Constants.NamespaceSpecNS;
-   /**
-    * Compares two attributes based on the C14n specification.
-    *
-    * <UL>
-    * <LI>Namespace nodes have a lesser document order position than attribute nodes.
-    * <LI> An element's namespace nodes are sorted lexicographically by
-    *   local name (the default namespace node, if one exists, has no
-    *   local name and is therefore lexicographically least).
-    * <LI> An element's attribute nodes are sorted lexicographically with
-    *   namespace URI as the primary key and local name as the secondary
-    *   key (an empty namespace URI is lexicographically least).
-    * </UL>
-    *
-    * @param obj0 casted Attr
-    * @param obj1 casted Attr
-    * @return returns a negative integer, zero, or a positive integer as obj0 is less than, equal to, or greater than obj1
-    *
-    */
-   public int compare(Object obj0, Object obj1) {
+    /**
+     * Compares two attributes based on the C14n specification.
+     *
+     * <UL>
+     * <LI>Namespace nodes have a lesser document order position than
+     *   attribute nodes.
+     * <LI> An element's namespace nodes are sorted lexicographically by
+     *   local name (the default namespace node, if one exists, has no
+     *   local name and is therefore lexicographically least).
+     * <LI> An element's attribute nodes are sorted lexicographically with
+     *   namespace URI as the primary key and local name as the secondary
+     *   key (an empty namespace URI is lexicographically least).
+     * </UL>
+     *
+     * @param obj0 casted Attr
+     * @param obj1 casted Attr
+     * @return returns a negative integer, zero, or a positive integer as
+     *   obj0 is less than, equal to, or greater than obj1
+     *
+     */
+    public int compare(Object obj0, Object obj1) {
 
-      Attr attr0 = (Attr) obj0;
-      Attr attr1 = (Attr) obj1;
-      String namespaceURI0 = attr0.getNamespaceURI();
-      String namespaceURI1 = attr1.getNamespaceURI();
+        Attr attr0 = (Attr) obj0;
+        Attr attr1 = (Attr) obj1;
+        String namespaceURI0 = attr0.getNamespaceURI();
+        String namespaceURI1 = attr1.getNamespaceURI();
 
-      boolean isNamespaceAttr0 =
-        XMLNS.equals(namespaceURI0);
-      boolean isNamespaceAttr1 =
-        XMLNS.equals(namespaceURI1);
+        boolean isNamespaceAttr0 = XMLNS==namespaceURI0;
+        boolean isNamespaceAttr1 = XMLNS==namespaceURI1;
 
-      if (isNamespaceAttr0) {
-         if (isNamespaceAttr1) {
+        if (isNamespaceAttr0) {
+            if (isNamespaceAttr1) {
+                // both are namespaces
+                String localname0 = attr0.getLocalName();
+                String localname1 = attr1.getLocalName();
 
-            // both are namespaces
-            String localname0 = attr0.getLocalName();
-            String localname1 = attr1.getLocalName();
+                if (localname0.equals("xmlns")) {
+                    localname0 = "";
+                }
 
-            if (localname0.equals("xmlns")) {
-               localname0 = "";
+                if (localname1.equals("xmlns")) {
+                    localname1 = "";
+                }
+
+                return localname0.compareTo(localname1);
             }
+            // attr0 is a namespace, attr1 is not
+            return ATTR0_BEFORE_ATTR1;
+        }
 
-            if (localname1.equals("xmlns")) {
-               localname1 = "";
-            }
-
-            return localname0.compareTo(localname1);
-         }
-         // attr0 is a namespace, attr1 is not
-         return ATTR0_BEFORE_ATTR1;
-
-      }
-      if (isNamespaceAttr1) {
-
+        if (isNamespaceAttr1) {
             // attr1 is a namespace, attr0 is not
             return ATTR1_BEFORE_ATTR0;
-      }
+        }
 
-      // none is a namespae
-
-      if (namespaceURI0 == null) {
-        if (namespaceURI1 == null) {
-                /*
-                 String localName0 = attr0.getLocalName();
-                 String localName1 = attr1.getLocalName();
-                 return localName0.compareTo(localName1);
-                 */
-
+        // none is a namespace
+        if (namespaceURI0 == null) {
+            if (namespaceURI1 == null) {
                 String name0 = attr0.getName();
                 String name1 = attr1.getName();
                 return name0.compareTo(name1);
+            }
+            return ATTR0_BEFORE_ATTR1;
         }
-        return ATTR0_BEFORE_ATTR1;
 
-      }
-      if (namespaceURI1 == null) {
-                return ATTR1_BEFORE_ATTR0;
-      }
-      int a = namespaceURI0.compareTo(namespaceURI1);
+        if (namespaceURI1 == null) {
+            return ATTR1_BEFORE_ATTR0;
+        }
 
-      if (a != 0) {
-        return a;
-      }
-      /*
-      String localName0 = ;
-      String localName1 =;*/
+        int a = namespaceURI0.compareTo(namespaceURI1);
+        if (a != 0) {
+            return a;
+        }
 
-      return (attr0.getLocalName())
-                                .compareTo( attr1.getLocalName());
-
-   }
-
+        return (attr0.getLocalName()).compareTo(attr1.getLocalName());
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java	Tue Oct 07 14:11:10 2008 +0100
@@ -0,0 +1,684 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/*
+ * Copyright 2008 The Apache Software Foundation.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 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.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import javax.xml.parsers.ParserConfigurationException;
+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;
+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;
+import com.sun.org.apache.xml.internal.security.utils.Constants;
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
+
+/**
+ * Implements <A HREF="http://www.w3.org/TR/2008/PR-xml-c14n11-20080129/">
+ * Canonical XML Version 1.1</A>, a W3C Proposed Recommendation from 29
+ * January 2008.
+ *
+ * @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());
+
+    static class XmlAttrStack {
+        int currentLevel = 0;
+        int lastlevel = 0;
+        XmlsStackElement cur;
+        static class XmlsStackElement {
+            int level;
+            boolean rendered = false;
+            List nodes = new ArrayList();
+        };
+        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=((XmlsStackElement)levels.get(levels.size()-1)).level;
+            }
+        }
+        void addXmlnsAttr(Attr n) {
+            if (cur == null) {
+                cur = new XmlsStackElement();
+                cur.level = currentLevel;
+                levels.add(cur);
+                lastlevel = currentLevel;
+            }
+            cur.nodes.add(n);
+        }
+        void getXmlnsAttr(Collection col) {
+            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 = (XmlsStackElement) 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();
+            List baseAttrs = new ArrayList();
+            boolean successiveOmitted = true;
+            for (;size>=0;size--) {
+                e = (XmlsStackElement) levels.get(size);
+                if (e.rendered) {
+                    successiveOmitted = false;
+                }
+                Iterator it = e.nodes.iterator();
+                while (it.hasNext() && successiveOmitted) {
+                    Attr n = (Attr) it.next();
+                    if (n.getLocalName().equals("base")) {
+                        if (!e.rendered) {
+                            baseAttrs.add(n);
+                        }
+                    } else if (!loa.containsKey(n.getName()))
+                        loa.put(n.getName(), n);
+                }
+            }
+            if (!baseAttrs.isEmpty()) {
+                Iterator it = cur.nodes.iterator();
+                String base = null;
+                Attr baseAttr = null;
+                while (it.hasNext()) {
+                    Attr n = (Attr) it.next();
+                    if (n.getLocalName().equals("base")) {
+                        base = n.getValue();
+                        baseAttr = n;
+                        break;
+                    }
+                }
+                it = baseAttrs.iterator();
+                while (it.hasNext()) {
+                    Attr n = (Attr) it.next();
+                    if (base == null) {
+                        base = n.getValue();
+                        baseAttr = n;
+                    } else {
+                        try {
+                            base = joinURI(n.getValue(), base);
+                        } catch (URISyntaxException ue) {
+                            ue.printStackTrace();
+                        }
+                    }
+                }
+                if (base != null && base.length() != 0) {
+                    baseAttr.setValue(base);
+                    col.add(baseAttr);
+                }
+            }
+
+            cur.rendered = true;
+            col.addAll(loa.values());
+        }
+    };
+    XmlAttrStack xmlattrStack = new XmlAttrStack();
+
+    /**
+     * Constructor Canonicalizer11
+     *
+     * @param includeComments
+     */
+    public Canonicalizer11(boolean includeComments) {
+        super(includeComments);
+    }
+
+    /**
+     * Returns the Attr[]s to be outputted for the given element.
+     * <br>
+     * The code of this method is a copy of {@link #handleAttributes(Element,
+     * NameSpaceSymbTable)},
+     * whereas it takes into account that subtree-c14n is -- well --
+     * subtree-based.
+     * So if the element in question isRoot of c14n, it's parent is not in the
+     * node set, as well as all other ancestors.
+     *
+     * @param E
+     * @param ns
+     * @return the Attr[]s to be outputted
+     * @throws CanonicalizationException
+     */
+    Iterator 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(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(result);
+            firstCall = false;
+        }
+
+        return result.iterator();
+    }
+
+    /**
+     * Returns the Attr[]s to be outputted for the given element.
+     * <br>
+     * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a
+     * DOM which has been prepared using
+     * {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650(
+     * org.w3c.dom.Document)}.
+     *
+     * @param E
+     * @param ns
+     * @return the Attr[]s to be outputted
+     * @throws CanonicalizationException
+     */
+    Iterator 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(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(n);
+            }
+            // Float all xml:* attributes of the unselected parent elements to
+            // this one. addXmlAttributes(E,result);
+            xmlattrStack.getXmlnsAttr(result);
+            ns.getUnrenderedNodes(result);
+        }
+
+        return result.iterator();
+    }
+
+    /**
+     * Always throws a CanonicalizationException because this is inclusive c14n.
+     *
+     * @param xpathNodeSet
+     * @param inclusiveNamespaces
+     * @return none it always fails
+     * @throws CanonicalizationException always
+     */
+    public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet,
+        String inclusiveNamespaces) throws CanonicalizationException {
+        throw new CanonicalizationException(
+         "c14n.Canonicalizer.UnsupportedOperation");
+    }
+
+    /**
+     * Always throws a CanonicalizationException because this is inclusive c14n.
+     *
+     * @param rootNode
+     * @param inclusiveNamespaces
+     * @return none it always fails
+     * @throws CanonicalizationException
+     */
+    public byte[] engineCanonicalizeSubTree(Node rootNode,
+        String inclusiveNamespaces) throws CanonicalizationException {
+        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);
+        }
+    }
+
+    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) {
+            if (baseURI.endsWith("..")) {
+                baseURI = baseURI + "/";
+            }
+            URI base = new URI(baseURI);
+            bscheme = base.getScheme();
+            bauthority = base.getAuthority();
+            bpath = base.getPath();
+            bquery = base.getQuery();
+            bfragment = base.getFragment();
+        }
+
+        URI r = new URI(relativeURI);
+        String rscheme = r.getScheme();
+        String rauthority = r.getAuthority();
+        String rpath = r.getPath();
+        String rquery = r.getQuery();
+        String rfragment = null;
+
+        String tscheme, tauthority, tpath, tquery, tfragment;
+        if (rscheme != null && rscheme.equals(bscheme)) {
+            rscheme = null;
+        }
+        if (rscheme != null) {
+            tscheme = rscheme;
+            tauthority = rauthority;
+            tpath = removeDotSegments(rpath);
+            tquery = rquery;
+        } else {
+            if (rauthority != null) {
+                tauthority = rauthority;
+                tpath = removeDotSegments(rpath);
+                tquery = rquery;
+            } else {
+                if (rpath.length() == 0) {
+                    tpath = bpath;
+                    if (rquery != null) {
+                        tquery = rquery;
+                    } else {
+                        tquery = bquery;
+                    }
+                } else {
+                    if (rpath.startsWith("/")) {
+                        tpath = removeDotSegments(rpath);
+                    } else {
+                        if (bauthority != null && bpath.length() == 0) {
+                            tpath = "/" + rpath;
+                        } else {
+                            int last = bpath.lastIndexOf('/');
+                            if (last == -1) {
+                                tpath = rpath;
+                            } else {
+                                tpath = bpath.substring(0, last+1) + rpath;
+                            }
+                        }
+                        tpath = removeDotSegments(tpath);
+                    }
+                    tquery = rquery;
+                }
+                tauthority = bauthority;
+            }
+            tscheme = bscheme;
+        }
+        tfragment = rfragment;
+        return new URI(tscheme, tauthority, tpath, tquery, tfragment).toString();
+    }
+
+    private static String removeDotSegments(String path) {
+
+        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
+        // with "/" until no more occurrences of "//" are in the input buffer.
+        String input = path;
+        while (input.indexOf("//") > -1) {
+            input = input.replaceAll("//", "/");
+        }
+
+        // Initialize the output buffer with the empty string.
+        StringBuffer output = new StringBuffer();
+
+        // If the input buffer starts with a root slash "/" then move this
+        // character to the output buffer.
+        if (input.charAt(0) == '/') {
+            output.append("/");
+            input = input.substring(1);
+        }
+
+        printStep("1 ", output.toString(), input);
+
+        // While the input buffer is not empty, loop as follows
+        while (input.length() != 0) {
+            // 2A. If the input buffer begins with a prefix of "./",
+            // then remove that prefix from the input buffer
+            // else if the input buffer begins with a prefix of "../", then
+            // if also the output does not contain the root slash "/" only,
+            // then move this prefix to the end of the output buffer else
+            // remove that prefix
+            if (input.startsWith("./")) {
+                input = input.substring(2);
+                printStep("2A", output.toString(), input);
+            } else if (input.startsWith("../")) {
+                input = input.substring(3);
+                if (!output.toString().equals("/")) {
+                    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,
+            } else if (input.startsWith("/./")) {
+                input = input.substring(2);
+                printStep("2B", output.toString(), input);
+            } else if (input.equals("/.")) {
+                // 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,
+            } else if (input.startsWith("/../")) {
+                input = input.substring(3);
+                if (output.length() == 0) {
+                    output.append("/");
+                } else if (output.toString().endsWith("../")) {
+                    output.append("..");
+                } else if (output.toString().endsWith("..")) {
+                    output.append("/..");
+                } else {
+                    int index = output.lastIndexOf("/");
+                    if (index == -1) {
+                        output = new StringBuffer();
+                        if (input.charAt(0) == '/') {
+                            input = input.substring(1);
+                        }
+                    } else {
+                        output = output.delete(index, output.length());
+                    }
+                }
+                printStep("2C", output.toString(), input);
+            } else if (input.equals("/..")) {
+                // FIXME: what is complete path segment?
+                input = input.replaceFirst("/..", "/");
+                if (output.length() == 0) {
+                    output.append("/");
+                } else if (output.toString().endsWith("../")) {
+                    output.append("..");
+                } else if (output.toString().endsWith("..")) {
+                    output.append("/..");
+                } else {
+                    int index = output.lastIndexOf("/");
+                    if (index == -1) {
+                        output = new StringBuffer();
+                        if (input.charAt(0) == '/') {
+                            input = input.substring(1);
+                        }
+                    } else {
+                        output = output.delete(index, output.length());
+                    }
+                }
+                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,
+            } else if (input.equals(".")) {
+                input = "";
+                printStep("2D", output.toString(), input);
+            } else if (input.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.
+            } else {
+                int end = -1;
+                int begin = input.indexOf('/');
+                if (begin == 0) {
+                    end = input.indexOf('/', 1);
+                } else {
+                    end = begin;
+                    begin = 0;
+                }
+                String segment;
+                if (end == -1) {
+                    segment = input.substring(begin);
+                    input = "";
+                } else {
+                    segment = input.substring(begin, end);
+                    input = input.substring(end);
+                }
+                output.append(segment);
+                printStep("2E", output.toString(), input);
+            }
+        }
+
+        // 3. Finally, if the only or last segment of the output buffer is
+        // "..", where ".." is a complete path segment not followed by a slash
+        // then append a slash "/". The output buffer is returned as the result
+        // of remove_dot_segments
+        if (output.toString().endsWith("..")) {
+            output.append("/");
+            printStep("3 ", output.toString(), input);
+        }
+
+        return output.toString();
+    }
+
+    private static void printStep(String step, String output, String input) {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, " " + step + ":   " + output);
+            if (output.length() == 0) {
+                log.log(java.util.logging.Level.FINE, "\t\t\t\t" + input);
+            } else {
+                log.log(java.util.logging.Level.FINE, "\t\t\t" + input);
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java	Tue Oct 07 14:11:10 2008 +0100
@@ -0,0 +1,41 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/*
+ * Copyright 2008 The Apache Software Foundation.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 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 Sean Mullan
+ */
+public class Canonicalizer11_OmitComments extends Canonicalizer11 {
+
+    public Canonicalizer11_OmitComments() {
+        super(false);
+    }
+
+    public final String engineGetURI() {
+        return Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS;
+    }
+
+    public final boolean engineGetIncludeComments() {
+        return false;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java	Tue Oct 07 14:11:10 2008 +0100
@@ -0,0 +1,41 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/*
+ * Copyright 2008 The Apache Software Foundation.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 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 Sean Mullan
+ */
+public class Canonicalizer11_WithComments extends Canonicalizer11 {
+
+    public Canonicalizer11_WithComments() {
+        super(true);
+    }
+
+    public final String engineGetURI() {
+        return Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS;
+    }
+
+    public final boolean engineGetIncludeComments() {
+        return true;
+    }
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java	Tue Oct 07 14:11:10 2008 +0100
@@ -2,7 +2,6 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-
 /*
  * Copyright  1999-2004 The Apache Software Foundation.
  *
@@ -23,20 +22,30 @@
 
 
 
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
 import java.util.HashMap;
 import java.util.Iterator;
+import java.util.List;
 import java.util.Map;
 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.helper.C14nHelper;
+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 org.w3c.dom.Attr;
+import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.NamedNodeMap;
 import org.w3c.dom.Node;
+import org.xml.sax.SAXException;
 
 
 /**
@@ -44,13 +53,92 @@
  * XML Version 1.0</A>, a W3C Recommendation from 15 March 2001.
  *
  * @author Christian Geuer-Pollmann <geuerp@apache.org>
+ * @version $Revision: 1.5 $
  */
 public abstract class Canonicalizer20010315 extends CanonicalizerBase {
         boolean firstCall=true;
         final SortedSet 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;
+        static class XmlsStackElement {
+                int level;
+                boolean rendered=false;
+                List nodes=new ArrayList();
+        };
+        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=((XmlsStackElement)levels.get(levels.size()-1)).level;
+                }
+        }
+        void addXmlnsAttr(Attr 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);
+                }
+                boolean parentRendered=false;
+                XmlsStackElement e=null;
+                if (size==-1) {
+                        parentRendered=true;
+                } else {
+                        e=(XmlsStackElement)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=(XmlsStackElement)levels.get(size);
+                        Iterator it=e.nodes.iterator();
+                        while (it.hasNext()) {
+                                Attr n=(Attr)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());
+        }
+
+    }
+    XmlAttrStack xmlattrStack=new XmlAttrStack();
+    /**
     * Constructor Canonicalizer20010315
     *
     * @param includeComments
@@ -86,16 +174,16 @@
 
       for (int i = 0; i < attrsLength; i++) {
          Attr N = (Attr) attrs.item(i);
-         String NName=N.getLocalName();
-         String NValue=N.getValue();
          String NUri =N.getNamespaceURI();
 
-         if (!XMLNS_URI.equals(NUri)) {
+         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.
@@ -120,65 +208,14 @@
         //Obtain all the namespaces defined in the parents, and added to the output.
         ns.getUnrenderedNodes(result);
         //output the attributes in the xml namespace.
-                addXmlAttributesSubtree(E, result);
-        firstCall=false;
+        xmlattrStack.getXmlnsAttr(result);
+                firstCall=false;
       }
 
       return result.iterator();
    }
 
    /**
-    * Float the xml:* attributes of the parent nodes to the root node of c14n
-    * @param E the root node.
-    * @param result the xml:* attributes  to output.
-    */
-   private void addXmlAttributesSubtree(Element E, SortedSet result) {
-         // E is in the node-set
-         Node parent = E.getParentNode();
-         Map loa = new HashMap();
-
-         if ((parent != null) && (parent.getNodeType() == Node.ELEMENT_NODE)) {
-
-            // parent element is not in node set
-            for (Node ancestor = parent;
-                    (ancestor != null)
-                    && (ancestor.getNodeType() == Node.ELEMENT_NODE);
-                    ancestor = ancestor.getParentNode()) {
-               Element el=((Element) ancestor);
-               if (!el.hasAttributes()) {
-                    continue;
-               }
-               // for all ancestor elements
-               NamedNodeMap ancestorAttrs = el.getAttributes();
-
-               for (int i = 0; i < ancestorAttrs.getLength(); i++) {
-                  // for all attributes in the ancestor element
-                  Attr currentAncestorAttr = (Attr) ancestorAttrs.item(i);
-
-                  if (XML_LANG_URI.equals(
-                          currentAncestorAttr.getNamespaceURI())) {
-
-                     // do we have an xml:* ?
-                     if (!E.hasAttributeNS(
-                             XML_LANG_URI,
-                             currentAncestorAttr.getLocalName())) {
-
-                        // the xml:* attr is not in E
-                        if (!loa.containsKey(currentAncestorAttr.getName())) {
-                           loa.put(currentAncestorAttr.getName(),
-                                   currentAncestorAttr);
-                        }
-                     }
-                  }
-               }
-            }
-         }
-
-         result.addAll( loa.values());
-
-      }
-
-   /**
     * Returns the Attr[]s to be outputted for the given element.
     * <br>
     * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has
@@ -192,7 +229,8 @@
     */
    Iterator handleAttributes(Element E,  NameSpaceSymbTable ns ) throws CanonicalizationException {
     // result will contain the attrs which have to be outputted
-    boolean isRealVisible=isVisible(E);
+        xmlattrStack.push(ns.getLevel());
+    boolean isRealVisible=isVisibleDO(E,ns.getLevel())==1;
     NamedNodeMap attrs = null;
     int attrsLength = 0;
     if (E.hasAttributes()) {
@@ -204,16 +242,15 @@
     SortedSet result = this.result;
     result.clear();
 
-
     for (int i = 0; i < attrsLength; i++) {
        Attr N = (Attr) attrs.item(i);
-       String NName=N.getLocalName();
-       String NValue=N.getValue();
        String NUri =N.getNamespaceURI();
 
-       if (!XMLNS_URI.equals(NUri)) {
+       if (XMLNS_URI!=NUri) {
           //A non namespace definition node.
-          if (isRealVisible){
+           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);
           }
@@ -221,7 +258,8 @@
           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
@@ -232,16 +270,26 @@
        //add the prefix binding to the ns symb table.
        //ns.addInclusiveMapping(NName,NValue,N,isRealVisible);
             if  (isVisible(N))  {
-                            //The xpath select this node output it if needed.
-                        Node n=ns.addMappingAndRenderXNodeSet(NName,NValue,N,isRealVisible);
-                                if (n!=null) {
+                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(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) {
@@ -254,85 +302,22 @@
         } else if ( !isVisible(xmlns)) {
                 //There is a definition but the xmlns is not selected by the xpath.
                 //then xmlns=""
-                n=ns.addMappingAndRenderXNodeSet(XMLNS,"",nullNode,true);
+                n=ns.addMappingAndRender(XMLNS,"",nullNode);
         }
         //output the xmlns def if needed.
         if (n!=null) {
                         result.add(n);
         }
         //Float all xml:* attributes of the unselected parent elements to this one.
-        addXmlAttributes(E,result);
+        //addXmlAttributes(E,result);
+        xmlattrStack.getXmlnsAttr(result);
+        ns.getUnrenderedNodes(result);
+
     }
 
     return result.iterator();
    }
    /**
-    *  Float the xml:* attributes of the unselected parent nodes to the ciurrent node.
-    * @param E
-    * @param result
-    */
-   private void addXmlAttributes(Element E, SortedSet result) {
-        /* The processing of an element node E MUST be modified slightly when an
-       * XPath node-set is given as input and the element's parent is omitted
-       * from the node-set. The method for processing the attribute axis of an
-       * element E in the node-set is enhanced. All element nodes along E's
-       * ancestor axis are examined for nearest occurrences of attributes in
-       * the xml namespace, such as xml:lang and xml:space (whether or not they
-       * are in the node-set). From this list of attributes, remove any that are
-       * in E's attribute axis (whether or not they are in the node-set). Then,
-       * lexicographically merge this attribute list with the nodes of E's
-       * attribute axis that are in the node-set. The result of visiting the
-       * attribute axis is computed by processing the attribute nodes in this
-       * merged attribute list.
-       */
-
-         // E is in the node-set
-         Node parent = E.getParentNode();
-         Map loa = new HashMap();
-
-         if ((parent != null) && (parent.getNodeType() == Node.ELEMENT_NODE)
-                 &&!isVisible(parent)) {
-
-            // parent element is not in node set
-            for (Node ancestor = parent;
-                    (ancestor != null)
-                    && (ancestor.getNodeType() == Node.ELEMENT_NODE);
-                    ancestor = ancestor.getParentNode()) {
-                Element el=((Element) ancestor);
-                if (!el.hasAttributes()) {
-                        continue;
-                }
-               // for all ancestor elements
-               NamedNodeMap ancestorAttrs =el.getAttributes();
-
-               for (int i = 0; i < ancestorAttrs.getLength(); i++) {
-
-                  // for all attributes in the ancestor element
-                  Attr currentAncestorAttr = (Attr) ancestorAttrs.item(i);
-
-                  if (XML_LANG_URI.equals(
-                          currentAncestorAttr.getNamespaceURI())) {
-
-                     // do we have an xml:* ?
-                     if (!E.hasAttributeNS(
-                             XML_LANG_URI,
-                             currentAncestorAttr.getLocalName())) {
-
-                        // the xml:* attr is not in E
-                        if (!loa.containsKey(currentAncestorAttr.getName())) {
-                           loa.put(currentAncestorAttr.getName(),
-                                   currentAncestorAttr);
-                        }
-                     }
-                  }
-               }
-            }
-         }
-         result.addAll(loa.values());
-
-}
-
-   /**
     * Always throws a CanonicalizationException because this is inclusive c14n.
     *
     * @param xpathNodeSet
@@ -363,4 +348,43 @@
       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);
+           }
+   }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java	Tue Oct 07 14:11:10 2008 +0100
@@ -2,7 +2,6 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-
 /*
  * Copyright 1999-2004 The Apache Software Foundation.
  *
@@ -21,20 +20,26 @@
  */
 package com.sun.org.apache.xml.internal.security.c14n.implementations;
 
+import java.io.IOException;
 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.helper.C14nHelper;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import com.sun.org.apache.xml.internal.security.transforms.params.InclusiveNamespaces;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
+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;
 import org.w3c.dom.NamedNodeMap;
 import org.w3c.dom.Node;
+import org.xml.sax.SAXException;
 /**
  * Implements &quot; <A
  * HREF="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/">Exclusive XML
@@ -47,6 +52,7 @@
  * <i>THIS </i> implementation is a complete rewrite of the algorithm.
  *
  * @author Christian Geuer-Pollmann <geuerp@apache.org>
+ * @version $Revision: 1.5 $
  * @see <a href="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/ Exclusive#">
  *          XML Canonicalization, Version 1.0</a>
  */
@@ -55,7 +61,7 @@
       * This Set contains the names (Strings like "xmlns" or "xmlns:foo") of
       * the inclusive namespaces.
       */
-    TreeSet _inclusiveNSSet = null;
+    TreeSet _inclusiveNSSet = new TreeSet();
     static final String XMLNS_URI=Constants.NamespaceSpecNS;
     final SortedSet result = new TreeSet(COMPARE);
         /**
@@ -143,10 +149,8 @@
 
                 for (int i = 0; i < attrsLength; i++) {
                         Attr N = (Attr) attrs.item(i);
-                        String NName=N.getLocalName();
-                        String NNodeValue=N.getNodeValue();
 
-                        if (!XMLNS_URI.equals(N.getNamespaceURI())) {
+                        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();
@@ -157,6 +161,8 @@
                                  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.
@@ -168,17 +174,17 @@
                 }
             }
                 }
+                String prefix;
+                if (E.getNamespaceURI() != null) {
+                        prefix = E.getPrefix();
+                        if ((prefix == null) || (prefix.length() == 0)) {
+                                prefix=XMLNS;
+                        }
 
-                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);
+                        prefix=XMLNS;
                 }
+                visiblyUtilized.add(prefix);
 
                 //This can be optimezed by I don't have time
                 Iterator it=visiblyUtilized.iterator();
@@ -211,12 +217,6 @@
 
         }
 
-    /** @inheritDoc */
-    public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet
-            ) throws CanonicalizationException {
-        return engineCanonicalizeXPathNodeSet(xpathNodeSet,"");
-    }
-
         /**
      * @inheritDoc
          * @param E
@@ -236,21 +236,20 @@
                 //The prefix visibly utilized(in the attribute or in the name) in the element
                 Set visiblyUtilized =null;
                 //It's the output selected.
-                boolean isOutputElement = isVisible(E);
+                boolean isOutputElement=isVisibleDO(E,ns.getLevel())==1;
                 if (isOutputElement) {
                         visiblyUtilized =  (Set) this._inclusiveNSSet.clone();
                 }
 
                 for (int i = 0; i < attrsLength; i++) {
                         Attr N = (Attr) attrs.item(i);
-                        String NName=N.getLocalName();
-                        String NNodeValue=N.getNodeValue();
-                        if ( !isVisible(N) )  {
-                                //The node is not in the nodeset(if there is a nodeset)
-                                continue;
-                        }
 
-                        if (!XMLNS_URI.equals(N.getNamespaceURI())) {
+
+                        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
@@ -263,6 +262,25 @@
                                 }
                                 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(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)) {
@@ -306,18 +324,20 @@
                                 }
                                 result.add(key);
                         }
-                } else /*if (_circunvented)*/ {
-                        Iterator it=this._inclusiveNSSet.iterator();
-                        while (it.hasNext()) {
-                                String s=(String)it.next();
-                                Attr key=ns.getMappingWithoutRendered(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());
+               }
+
+                XMLUtils.circumventBug2650(doc);
+           }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java	Tue Oct 07 14:11:10 2008 +0100
@@ -28,6 +28,7 @@
 /**
  * Class Canonicalizer20010315ExclWithComments
  *
+ * @version $Revision: 1.5 $
  */
 public class Canonicalizer20010315ExclWithComments
         extends Canonicalizer20010315Excl {
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java	Tue Oct 07 14:11:10 2008 +0100
@@ -2,7 +2,6 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-
 /*
  * Copyright  1999-2004 The Apache Software Foundation.
  *
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java	Tue Oct 07 14:11:10 2008 +0100
@@ -27,9 +27,11 @@
 import java.io.OutputStream;
 import java.io.UnsupportedEncodingException;
 import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.ListIterator;
+import java.util.Map;
 import java.util.Set;
 
 import javax.xml.parsers.DocumentBuilderFactory;
@@ -45,7 +47,6 @@
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Comment;
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.NamedNodeMap;
 import org.w3c.dom.Node;
@@ -57,6 +58,7 @@
  * Abstract base class for canonicalization algorithms.
  *
  * @author Christian Geuer-Pollmann <geuerp@apache.org>
+ * @version $Revision: 1.5 $
  */
 public abstract class CanonicalizerBase extends CanonicalizerSpi {
    //Constants to be outputed, In char array form, so
@@ -123,6 +125,18 @@
                 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.
@@ -143,15 +157,8 @@
                                 return bytes;
                         } else if (input.isNodeSet()) {
                                 nodeFilter=input.getNodeFilters();
-                                Document doc = null;
-                                if (input.getSubNode() != null) {
-                                    doc=XMLUtils.getOwnerDocument(input.getSubNode());
-                                } else {
-                                    doc=XMLUtils.getOwnerDocument(input.getNodeSet());
-                                }
-                                if (input.isNeedsToBeExpanded()) {
-                                        XMLUtils.circumventBug2650(doc);
-                                }
+
+                circumventBugIfNeeded(input);
 
                                 if (input.getSubNode() != null) {
                                     bytes = engineCanonicalizeXPathNodeSetInternal(input.getSubNode());
@@ -173,6 +180,13 @@
                 }
    }
    /**
+    * @param _writer The _writer to set.
+    */
+    public void setWriter(OutputStream _writer) {
+        this._writer = _writer;
+    }
+
+    /**
          * Canonicalizes a Subtree node.
          *
          * @param rootNode
@@ -187,11 +201,13 @@
         this._excludeNode = excludeNode;
         try {
          NameSpaceSymbTable ns=new NameSpaceSymbTable();
+         int nodeLevel=NODE_BEFORE_DOCUMENT_ELEMENT;
          if (rootNode instanceof Element) {
                 //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);
+         this.canonicalizeSubTree(rootNode,ns,rootNode,nodeLevel);
          this._writer.close();
          if (this._writer instanceof ByteArrayOutputStream) {
             byte []result=((ByteArrayOutputStream)this._writer).toByteArray();
@@ -199,6 +215,12 @@
                 ((ByteArrayOutputStream)this._writer).reset();
             }
                 return result;
+         }  else if (this._writer instanceof UnsyncByteArrayOutputStream) {
+                 byte []result=((UnsyncByteArrayOutputStream)this._writer).toByteArray();
+             if (reset) {
+                 ((UnsyncByteArrayOutputStream)this._writer).reset();
+             }
+                 return result;
          }
          return null;
 
@@ -219,13 +241,17 @@
     * @throws CanonicalizationException
     * @throws IOException
     */
-    final void canonicalizeSubTree(Node currentNode, NameSpaceSymbTable ns,Node endnode)
+    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()) {
 
@@ -242,18 +268,17 @@
             case Node.DOCUMENT_FRAGMENT_NODE :
                 case Node.DOCUMENT_NODE :
                         ns.outputNodePush();
-                        //currentNode = currentNode.getFirstChild();
                         sibling= currentNode.getFirstChild();
                         break;
 
                 case Node.COMMENT_NODE :
                         if (includeComments) {
-                                outputCommentToWriter((Comment) currentNode, writer);
+                                outputCommentToWriter((Comment) currentNode, writer, documentLevel);
                         }
                         break;
 
                 case Node.PROCESSING_INSTRUCTION_NODE :
-                        outputPItoWriter((ProcessingInstruction) currentNode, writer);
+                        outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel);
                         break;
 
                 case Node.TEXT_NODE :
@@ -262,6 +287,7 @@
                         break;
 
                 case Node.ELEMENT_NODE :
+                        documentLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
                         if (currentNode==excludeNode) {
                                 break;
                         }
@@ -270,27 +296,27 @@
                         ns.outputNodePush();
                         writer.write('<');
                         String name=currentElement.getTagName();
-                        writeStringToUtf8(name,writer);
+                        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 = (Attr) attrs.next();
-                                        outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer);
+                                        outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer,cache);
                                 }
                         }
                         writer.write('>');
                         sibling= currentNode.getFirstChild();
                         if (sibling==null) {
                                 writer.write(_END_TAG);
-                                writeStringToUtf8(name,writer);
+                                UtfHelpper.writeStringToUtf8(name,writer);
                                 writer.write('>');
                                 //We fineshed with this level, pop to the previous definitions.
                                 ns.outputNodePop();
-                                if (parentNode != null) {
+                                    if (parentNode != null) {
                                         sibling= currentNode.getNextSibling();
-                                }
+                                    }
                         } else {
                                 parentNode=currentElement;
                         }
@@ -298,7 +324,7 @@
                 }
                 while (sibling==null  && parentNode!=null) {
                         writer.write(_END_TAG);
-                        writeStringToUtf8(((Element)parentNode).getTagName(),writer);
+                        UtfHelpper.writeByte(((Element)parentNode).getTagName(),writer,cache);
                         writer.write('>');
                         //We fineshed with this level, pop to the previous definitions.
                         ns.outputNodePop();
@@ -307,6 +333,7 @@
                         sibling=parentNode.getNextSibling();
                         parentNode=parentNode.getParentNode();
                         if (!(parentNode instanceof Element)) {
+                                documentLevel=NODE_AFTER_DOCUMENT_ELEMENT;
                                 parentNode=null;
                         }
                 }
@@ -317,47 +344,8 @@
         } while(true);
     }
 
-   /**
-    * 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
-    */
-   final static int getPositionRelativeToDocumentElement(Node currentNode) {
 
-      if ((currentNode == null) ||
-            (currentNode.getParentNode().getNodeType() != Node.DOCUMENT_NODE) ) {
-         return CanonicalizerBase.NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
-      }
-      Element documentElement = currentNode.getOwnerDocument().getDocumentElement();
-      if ( (documentElement == null)  || (documentElement == currentNode) ){
-         return CanonicalizerBase.NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
-      }
 
-      for (Node x = currentNode; x != null; x = x.getNextSibling()) {
-         if (x == documentElement) {
-            return CanonicalizerBase.NODE_BEFORE_DOCUMENT_ELEMENT;
-         }
-      }
-
-      return CanonicalizerBase.NODE_AFTER_DOCUMENT_ELEMENT;
-   }
-
-   /**
-    * Method engineCanonicalizeXPathNodeSet
-    * @inheritDoc
-    * @param xpathNodeSet
-    * @throws CanonicalizationException
-    */
-   public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet)
-           throws CanonicalizationException {
-           this._xpathNodeSet = xpathNodeSet;
-           return engineCanonicalizeXPathNodeSetInternal(XMLUtils.getOwnerDocument(this._xpathNodeSet));
-   }
    private  byte[] engineCanonicalizeXPathNodeSetInternal(Node doc)
            throws CanonicalizationException {
 
@@ -370,6 +358,12 @@
                 ((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) {
@@ -390,11 +384,17 @@
     */
    final void canonicalizeXPathNodeSet(Node currentNode,Node endnode )
            throws CanonicalizationException, IOException {
-           boolean currentNodeIsVisible = false;
-           NameSpaceSymbTable ns=new  NameSpaceSymbTable();
+        if (isVisibleInt(currentNode)==-1)
+                return;
+        boolean currentNodeIsVisible = false;
+        NameSpaceSymbTable ns=new  NameSpaceSymbTable();
+        if (currentNode instanceof Element)
+                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()) {
 
@@ -416,14 +416,14 @@
                         break;
 
                 case Node.COMMENT_NODE :
-                        if (this._includeComments && isVisible(currentNode)) {
-                                outputCommentToWriter((Comment) currentNode, writer);
+                        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);
+                                outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel);
                         break;
 
                 case Node.TEXT_NODE :
@@ -436,12 +436,6 @@
                         || (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
-                */
                outputTextToWriter(nextSibling.getNodeValue(), writer);
                currentNode=nextSibling;
                sibling=currentNode.getNextSibling();
@@ -451,15 +445,21 @@
                         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;
-                        currentNodeIsVisible=isVisible(currentNode);
+                        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();
-                                writeStringToUtf8(name,writer);
+                                UtfHelpper.writeByte(name,writer,cache);
                         } else {
                                 ns.push();
                         }
@@ -469,7 +469,7 @@
                                 //we output all Attrs which are available
                                 while (attrs.hasNext()) {
                                         Attr attr = (Attr) attrs.next();
-                                        outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer);
+                                        outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer,cache);
                                 }
                         }
                         if (currentNodeIsVisible) {
@@ -480,7 +480,7 @@
                         if (sibling==null) {
                                 if (currentNodeIsVisible) {
                                         writer.write(_END_TAG);
-                                        writeStringToUtf8(name,writer);
+                                        UtfHelpper.writeByte(name,writer,cache);
                                         writer.write('>');
                                         //We fineshed with this level, pop to the previous definitions.
                                         ns.outputNodePop();
@@ -498,7 +498,7 @@
                 while (sibling==null  && parentNode!=null) {
                         if (isVisible(parentNode)) {
                                 writer.write(_END_TAG);
-                                writeStringToUtf8(((Element)parentNode).getTagName(),writer);
+                                UtfHelpper.writeByte(((Element)parentNode).getTagName(),writer,cache);
                                 writer.write('>');
                                 //We fineshed with this level, pop to the previous definitions.
                                 ns.outputNodePop();
@@ -511,6 +511,7 @@
                         parentNode=parentNode.getParentNode();
                         if (!(parentNode instanceof Element)) {
                                 parentNode=null;
+                                documentLevel=NODE_AFTER_DOCUMENT_ELEMENT;
                         }
                 }
                 if (sibling==null)
@@ -519,12 +520,38 @@
                 sibling=currentNode.getNextSibling();
         } while(true);
    }
+   int isVisibleDO(Node currentNode,int level) {
+           if (nodeFilter!=null) {
+                        Iterator it=nodeFilter.iterator();
+                        while (it.hasNext()) {
+                                int i=((NodeFilter)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=((NodeFilter)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 (!((NodeFilter)it.next()).isNodeInclude(currentNode))
+                        if (((NodeFilter)it.next()).isNodeInclude(currentNode)!=1)
                                 return false;
                 }
            }
@@ -533,19 +560,42 @@
                 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 static void getParentNameSpaces(Element el,NameSpaceSymbTable ns)  {
-                List parents=new ArrayList();
+        final void getParentNameSpaces(Element el,NameSpaceSymbTable ns)  {
+                List parents=new ArrayList(10);
                 Node n1=el.getParentNode();
                 if (!(n1 instanceof Element)) {
                         return;
                 }
                 //Obtain all the parents of the elemnt
-                Element parent=(Element) el.getParentNode();
+                Element parent=(Element) n1;
                 while (parent!=null) {
                         parents.add(parent);
                         Node n=parent.getParentNode();
@@ -557,28 +607,9 @@
                 //Visit them in reverse order.
                 ListIterator it=parents.listIterator(parents.size());
                 while (it.hasPrevious()) {
-                Element ele=(Element)it.previous();
-        if (!ele.hasAttributes()) {
-                continue;
+                        Element ele=(Element)it.previous();
+                        handleParent(ele, ns);
         }
-                NamedNodeMap attrs = ele.getAttributes();
-                int attrsLength = attrs.getLength();
-                 for (int i = 0; i < attrsLength; i++) {
-            Attr N = (Attr) attrs.item(i);
-            if (!Constants.NamespaceSpecNS.equals(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);
-                 }
-                }
         Attr nsprefix;
         if (((nsprefix=ns.getMappingWithoutRendered("xmlns"))!=null)
                 && "".equals(nsprefix.getValue())) {
@@ -586,269 +617,6 @@
         }
         }
    /**
-    * Outputs an Attribute to the internal Writer.
-    *
-    * The string value of the node is modified by replacing
-    * <UL>
-    * <LI>all ampersands (&) with <CODE>&amp;amp;</CODE></LI>
-    * <LI>all open angle brackets (<) with <CODE>&amp;lt;</CODE></LI>
-    * <LI>all quotation mark characters with <CODE>&amp;quot;</CODE></LI>
-    * <LI>and the whitespace characters <CODE>#x9</CODE>, #xA, and #xD, with character
-    * references. The character references are written in uppercase
-    * hexadecimal with no leading zeroes (for example, <CODE>#xD</CODE> is represented
-    * by the character reference <CODE>&amp;#xD;</CODE>)</LI>
-    * </UL>
-    *
-    * @param name
-    * @param value
-    * @param writer
-    * @throws IOException
-    */
-   static final void outputAttrToWriter(final String name, final String value, final OutputStream writer) throws IOException {
-      writer.write(' ');
-      writeStringToUtf8(name,writer);
-      writer.write(equalsStr);
-      byte  []toWrite;
-      final int length = value.length();
-      for (int i=0;i < length; i++) {
-         char c = value.charAt(i);
-
-         switch (c) {
-
-         case '&' :
-                toWrite=_AMP_;
-            //writer.write(_AMP_);
-            break;
-
-         case '<' :
-                toWrite=_LT_;
-            //writer.write(_LT_);
-            break;
-
-         case '"' :
-                toWrite=_QUOT_;
-            //writer.write(_QUOT_);
-            break;
-
-         case 0x09 :    // '\t'
-                toWrite=__X9_;
-            //writer.write(__X9_);
-            break;
-
-         case 0x0A :    // '\n'
-                toWrite=__XA_;
-            //writer.write(__XA_);
-            break;
-
-         case 0x0D :    // '\r'
-                toWrite=__XD_;
-            //writer.write(__XD_);
-            break;
-
-         default :
-            writeCharToUtf8(c,writer);
-            //this._writer.write(c);
-            continue;
-         }
-         writer.write(toWrite);
-      }
-
-      writer.write('\"');
-   }
-
-   final static void writeCharToUtf8(final char c,final OutputStream out) throws IOException{
-        char ch;
-        if (/*(c >= 0x0001) &&*/ (c <= 0x007F)) {
-        out.write(c);
-        return;
-    }
-    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));
-
-   }
-
-   final static void writeStringToUtf8(final String str,final OutputStream out) throws IOException{
-        final int length=str.length();
-        int i=0;
-    char c;
-        while (i<length) {
-                c=str.charAt(i++);
-        if (/*(c >= 0x0001) &&*/ (c <= 0x007F)) {
-            out.write(c);
-            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));
-        continue;
-
-        }
-
-   }
-   /**
-    * 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) throws IOException {
-          final int position = getPositionRelativeToDocumentElement(currentPI);
-
-      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 {
-            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 {
-               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
-    */
-   static final void outputCommentToWriter(Comment currentComment, OutputStream writer) throws IOException {
-          final int position = getPositionRelativeToDocumentElement(currentComment);
-          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 {
-            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_;
-            //writer.write(_AMP_);
-            break;
-
-         case '<' :
-                toWrite=_LT_;
-            //writer.write(_LT_);
-            break;
-
-         case '>' :
-                toWrite=_GT_;
-            //writer.write(_GT_);
-            break;
-
-         case 0xD :
-                toWrite=__XD_;
-            //writer.write(__XD_);
-            break;
-
-         default :
-            writeCharToUtf8(c,writer);
-            continue;
-         }
-         writer.write(toWrite);
-      }
-   }
-
-   /**
     * Obtain the attributes to output for this node in XPathNodeSet c14n.
     *
     * @param E
@@ -870,13 +638,207 @@
    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
+            * <UL>
+            * <LI>all ampersands (&) with <CODE>&amp;amp;</CODE></LI>
+            * <LI>all open angle brackets (<) with <CODE>&amp;lt;</CODE></LI>
+            * <LI>all quotation mark characters with <CODE>&amp;quot;</CODE></LI>
+            * <LI>and the whitespace characters <CODE>#x9</CODE>, #xA, and #xD, with character
+            * references. The character references are written in uppercase
+            * hexadecimal with no leading zeroes (for example, <CODE>#xD</CODE> is represented
+            * by the character reference <CODE>&amp;#xD;</CODE>)</LI>
+            * </UL>
+            *
+            * @param name
+            * @param value
+            * @param writer
+            * @throws IOException
+            */
+           static final void outputAttrToWriter(final String name, final String value, final OutputStream writer,
+                                final Map 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++);
 
-    /**
-     * @param _writer The _writer to set.
-     */
-    public void setWriter(OutputStream _writer) {
-        this._writer = _writer;
-    }
+                 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
+            */
+           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);
+                    }
+                 }
+              }
+
+              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);
+              }
+           }
 
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java	Tue Oct 07 14:11:10 2008 +0100
@@ -20,16 +20,10 @@
  */
 package com.sun.org.apache.xml.internal.security.c14n.implementations;
 
-import java.lang.reflect.Array;
-import java.util.AbstractList;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Collection;
-import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
-import java.util.Map;
-
 
 
 import org.w3c.dom.Attr;
@@ -46,21 +40,26 @@
 public class NameSpaceSymbTable {
 
         /**The map betwen prefix-> entry table. */
-        SymbMap symb = new SymbMap();
+        SymbMap symb;
         /**The level of nameSpaces (for Inclusive visibility).*/
         int nameSpaces=0;
         /**The stacks for removing the definitions when doing pop.*/
-        List level = new ArrayList();
+        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);
+        }
     /**
      * Default constractor
      **/
     public NameSpaceSymbTable() {
+        level = new ArrayList(10);
         //Insert the default binding for xmlns.
-        NameSpaceSymbEntry ne=new NameSpaceSymbEntry("",null,true);
-                ne.lastrendered="";
-        symb.put(XMLNS,ne);
+        symb=(SymbMap) initialMap.clone();
     }
 
     /**
@@ -75,8 +74,14 @@
                         NameSpaceSymbEntry n=(NameSpaceSymbEntry)(it.next());
                         //put them rendered?
                         if ((!n.rendered) && (n.n!=null)) {
+                                n=(NameSpaceSymbEntry) n.clone();
+                needsClone();
+                symb.put(n.prefix,n);
+                n.lastrendered=n.uri;
+                n.rendered=true;
+
                                 result.add(n.n);
-                                n.rendered=true;
+
                         }
            }
         }
@@ -104,10 +109,6 @@
      **/
         public void push() {
                 //Put the number of namespace definitions in the stack.
-        /**if (cloned) {
-                Object ob[]= {symb,cloned ? symb : null};
-                level.add(ob);
-        } **/
         level.add(null);
         cloned=false;
         }
@@ -124,7 +125,7 @@
             if (size==0) {
                cloned=false;
             } else
-            cloned=(level.get(size-1)!=symb);
+                cloned=(level.get(size-1)!=symb);
         } else {
                 cloned=false;
         }
@@ -134,8 +135,7 @@
 
         final void needsClone() {
                 if (!cloned) {
-            level.remove(level.size()-1);
-            level.add(symb);
+            level.set(level.size()-1,symb);
                         symb=(SymbMap) symb.clone();
             cloned=true;
         }
@@ -200,7 +200,7 @@
                         return false;
                 }
                 //Creates and entry in the table for this new definition.
-                NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,false);
+                NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,false,prefix);
         needsClone();
                 symb.put(prefix, ne);
                 if (ob != null) {
@@ -238,7 +238,7 @@
             return null;
         }
 
-        NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,true);
+        NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,true,prefix);
         ne.lastrendered=uri;
         needsClone();
         symb.put(prefix, ne);
@@ -251,53 +251,38 @@
         }
         return ne.n;
     }
-        /**
-     * Adds & gets(if needed) the attribute node that defines the binding for the prefix.
-     * Take on account if the rules of rendering in the inclusive c14n.
-     * For inclusive c14n.
-     * @param prefix the prefix to obtain the attribute.
-     * @param outputNode the container element is an output element.
-     * @param uri the Uri of the definition
-     * @param n the attribute that have the definition
-     * @return null if there is no need to render the prefix. Otherwise the node of
-     * definition.
-     **/
-        public Node addMappingAndRenderXNodeSet(String prefix, String uri,Attr n,boolean outputNode) {
+
+        public int getLevel() {
+                // TODO Auto-generated method stub
+                return level.size();
+        }
+
+        public void removeMapping(String prefix) {
                 NameSpaceSymbEntry ob = symb.get(prefix);
-                int visibleNameSpaces=nameSpaces;
-                if ((ob!=null) && uri.equals(ob.uri)) {
-                        if (!ob.rendered) {
-                                ob=(NameSpaceSymbEntry)ob.clone();
-                needsClone();
-                symb.put(prefix,ob);
-                                ob.rendered=true;
-                                ob.level=visibleNameSpaces;
-                                return ob.n;
-                        }
-            ob=(NameSpaceSymbEntry)ob.clone();
+
+        if (ob!=null) {
             needsClone();
-            symb.put(prefix,ob);
-                        if (outputNode && (((visibleNameSpaces-ob.level)<2) || XMLNS.equals(prefix)) ) {
-                                ob.level=visibleNameSpaces;
-                                return null; //Already rendered, just return nulll
-                        }
-                        ob.level=visibleNameSpaces;
-                        return ob.n;
-                }
+            symb.put(prefix,null);
+        }
+        }
 
-                NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,true);
-                ne.level=nameSpaces;
-                ne.rendered=true;
-        needsClone();
-                symb.put(prefix, ne);
-                if (ob != null) {
-                        ne.lastrendered=ob.lastrendered;
+        public void removeMappingIfNotRender(String prefix) {
+                NameSpaceSymbEntry ob = symb.get(prefix);
 
-                        if ((ob.lastrendered!=null)&& (ob.lastrendered.equals(uri))) {
-                                ne.rendered=true;
-                        }
-                }
-                return ne.n;
+        if (ob!=null && !ob.rendered) {
+            needsClone();
+            symb.put(prefix,null);
+        }
+        }
+
+        public boolean removeMappingIfRender(String prefix) {
+                NameSpaceSymbEntry ob = symb.get(prefix);
+
+        if (ob!=null && ob.rendered) {
+            needsClone();
+            symb.put(prefix,null);
+        }
+        return false;
         }
 }
 
@@ -305,10 +290,11 @@
  * The internal structure of NameSpaceSymbTable.
  **/
 class NameSpaceSymbEntry implements Cloneable {
-    NameSpaceSymbEntry(String name,Attr n,boolean rendered) {
+    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() {
@@ -320,6 +306,7 @@
     }
     /** 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).*/
@@ -330,53 +317,57 @@
     Attr n;
 };
 
-class SymbMap implements Cloneable{
-        int free=23;
-        NameSpaceSymbEntry[] entries=new NameSpaceSymbEntry[free];
-        String[] keys=new String[free];
-
-        void put(String key, NameSpaceSymbEntry value) {
+class SymbMap implements Cloneable {
+    int free=23;
+    NameSpaceSymbEntry[] entries;
+    String[] keys;
+        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;
+        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 (--free == 0) {
+                free=entries.length;
+                int newCapacity = free<<2;
+                rehash(newCapacity);
+            }
         }
     }
 
     List entrySet() {
-                List a=new ArrayList();
-                for (int i=0;i<entries.length;i++) {
-                        if ((entries[i]!=null) && !("".equals(entries[i]))) {
-                                a.add(entries[i]);
-                        }
-                }
-                return a;
+        List 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;
+    }
 
-
-        protected int index(Object obj) {
+    protected int index(Object obj) {
         Object[] set = keys;
-                int length = set.length;
-                //abs of index
+        int length = set.length;
+        //abs of index
         int index = (obj.hashCode() & 0x7fffffff) %  length;
         Object cur = set[index];
 
         if (cur == null || (cur.equals( obj))) {
-                        return index;
+                return index;
         }
+        length=length-1;
         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;
     }
-         /**
+
+    /**
      * rehashes the map to the new capacity.
      *
      * @param newCapacity an <code>int</code> value
@@ -384,37 +375,38 @@
     protected void rehash(int newCapacity) {
         int oldCapacity = keys.length;
         String oldKeys[] = keys;
-                NameSpaceSymbEntry oldVals[] = entries;
+        NameSpaceSymbEntry oldVals[] = entries;
 
-                keys = new String[newCapacity];
-                entries = new NameSpaceSymbEntry[newCapacity];
+        keys = new String[newCapacity];
+        entries = new NameSpaceSymbEntry[newCapacity];
 
         for (int i = oldCapacity; i-- > 0;) {
             if(oldKeys[i] != null) {
                 String o = oldKeys[i];
                 int index = index(o);
-                                keys[index] = o;
-                                entries[index] = oldVals[i];
+                keys[index] = o;
+                entries[index] = oldVals[i];
             }
         }
     }
-         NameSpaceSymbEntry get(String key) {
-                return  entries[index(key)];
-            }
-         protected Object clone()  {
-                // TODO Auto-generated method stub
-                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);
 
-                        return copy;
-                } catch (CloneNotSupportedException e) {
-                        // TODO Auto-generated catch block
-                        e.printStackTrace();
-                }
-                return null;
+    NameSpaceSymbEntry get(String 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);
+
+                return copy;
+        } catch (CloneNotSupportedException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
         }
+        return null;
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java	Tue Oct 07 14:11:10 2008 +0100
@@ -0,0 +1,155 @@
+package com.sun.org.apache.xml.internal.security.c14n.implementations;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Map;
+
+public class UtfHelpper {
+
+        final static void writeByte(final String str,final OutputStream out,Map cache) throws IOException {
+                   byte []result=(byte[]) cache.get(str);
+                   if (result==null) {
+                           result=getStringInUtf8(str);
+                           cache.put(str,result);
+                   }
+
+                   out.write(result);
+
+           }
+
+        final static void writeCharToUtf8(final char c,final OutputStream out) throws IOException{
+                if (c < 0x80) {
+                out.write(c);
+                return;
+            }
+                if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){
+                //No Surrogates in sun java
+                out.write(0x3f);
+                return;
+        }
+            int bias;
+            int write;
+            char ch;
+            if (c > 0x07FF) {
+                ch=(char)(c>>>12);
+                write=0xE0;
+                if (ch>0) {
+                    write |= ( ch & 0x0F);
+                }
+                out.write(write);
+                write=0x80;
+                bias=0x3F;
+            } else {
+                write=0xC0;
+                bias=0x1F;
+            }
+            ch=(char)(c>>>6);
+            if (ch>0) {
+                 write|= (ch & bias);
+            }
+            out.write(write);
+            out.write(0x80 | ((c) & 0x3F));
+
+           }
+
+        final static void writeStringToUtf8(final String str,final OutputStream out) throws IOException{
+                final int length=str.length();
+                int i=0;
+            char c;
+                while (i<length) {
+                        c=str.charAt(i++);
+                if (c < 0x80)  {
+                    out.write(c);
+                    continue;
+                }
+                if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){
+                        //No Surrogates in sun java
+                        out.write(0x3f);
+                        continue;
+                }
+                char ch;
+                int bias;
+                int write;
+                if (c > 0x07FF) {
+                    ch=(char)(c>>>12);
+                    write=0xE0;
+                    if (ch>0) {
+                        write |= ( ch & 0x0F);
+                    }
+                    out.write(write);
+                    write=0x80;
+                    bias=0x3F;
+                } else {
+                        write=0xC0;
+                        bias=0x1F;
+                }
+                ch=(char)(c>>>6);
+                if (ch>0) {
+                     write|= (ch & bias);
+                }
+                out.write(write);
+                out.write(0x80 | ((c) & 0x3F));
+
+                }
+
+           }
+        public final static byte[] getStringInUtf8(final String str) {
+                   final int length=str.length();
+                   boolean expanded=false;
+                   byte []result=new byte[length];
+                        int i=0;
+                        int out=0;
+                    char c;
+                        while (i<length) {
+                                c=str.charAt(i++);
+                        if ( c < 0x80 ) {
+                            result[out++]=(byte)c;
+                            continue;
+                        }
+                        if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){
+                                   //No Surrogates in sun java
+                                   result[out++]=0x3f;
+
+                                continue;
+                        }
+                        if (!expanded) {
+                                byte newResult[]=new byte[3*length];
+                                        System.arraycopy(result, 0, newResult, 0, out);
+                                        result=newResult;
+                                        expanded=true;
+                        }
+                        char ch;
+                        int bias;
+                        byte write;
+                        if (c > 0x07FF) {
+                            ch=(char)(c>>>12);
+                            write=(byte)0xE0;
+                            if (ch>0) {
+                                write |= ( ch & 0x0F);
+                            }
+                            result[out++]=write;
+                            write=(byte)0x80;
+                            bias=0x3F;
+                        } else {
+                                write=(byte)0xC0;
+                                bias=0x1F;
+                        }
+                        ch=(char)(c>>>6);
+                        if (ch>0) {
+                             write|= (ch & bias);
+                        }
+                        result[out++]=write;
+                        result[out++]=(byte)(0x80 | ((c) & 0x3F));/**/
+
+                        }
+                        if (expanded) {
+                                byte newResult[]=new byte[out];
+                                System.arraycopy(result, 0, newResult, 0, out);
+                                result=newResult;
+                        }
+                        return result;
+           }
+
+
+
+}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java	Tue Oct 07 14:11:10 2008 +0100
@@ -22,6 +22,7 @@
 
 
 import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
 import java.io.IOException;
 import java.io.StringReader;
 import java.io.UnsupportedEncodingException;
@@ -30,6 +31,7 @@
 import java.security.Key;
 import java.security.NoSuchAlgorithmException;
 import java.security.NoSuchProviderException;
+import java.util.HashMap;
 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.List;
@@ -204,7 +206,7 @@
      * @since 1.0.
      */
     private XMLCipher() {
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Constructing XMLCipher...");
+        logger.log(java.util.logging.Level.FINE, "Constructing XMLCipher...");
 
         _factory = new Factory();
         _serializer = new Serializer();
@@ -266,7 +268,7 @@
     public static XMLCipher getInstance(String transformation) throws
             XMLEncryptionException {
         // sanity checks
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Getting XMLCipher...");
+        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))
@@ -294,7 +296,7 @@
 
                 try {
             instance._contextCipher = Cipher.getInstance(jceAlgorithm);
-            if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "cihper.algoritm = " +
+            logger.log(java.util.logging.Level.FINE, "cihper.algoritm = " +
                 instance._contextCipher.getAlgorithm());
         } catch (NoSuchAlgorithmException nsae) {
             throw new XMLEncryptionException("empty", nsae);
@@ -305,49 +307,6 @@
         return (instance);
     }
 
-    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);
-        }
-
-        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);
-    }
-
-
-
         /**
          * Returns an <code>XMLCipher</code> that implements the specified
          * transformation, operates on the specified context document and serializes
@@ -380,6 +339,45 @@
                 return instance;
         }
 
+    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);
+        }
+
+        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);
+    }
 
     /**
      * Returns an <code>XMLCipher</code> that implements the specified
@@ -396,7 +394,7 @@
     public static XMLCipher getProviderInstance(String transformation, String provider)
             throws XMLEncryptionException {
         // sanity checks
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Getting XMLCipher...");
+        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)
@@ -429,9 +427,9 @@
 
             instance._contextCipher = Cipher.getInstance(jceAlgorithm, provider);
 
-            if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "cipher._algorithm = " +
+            logger.log(java.util.logging.Level.FINE, "cipher._algorithm = " +
                 instance._contextCipher.getAlgorithm());
-            if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "provider.name = " + provider);
+            logger.log(java.util.logging.Level.FINE, "provider.name = " + provider);
         } catch (NoSuchAlgorithmException nsae) {
             throw new XMLEncryptionException("empty", nsae);
         } catch (NoSuchProviderException nspre) {
@@ -490,7 +488,7 @@
     public static XMLCipher getInstance()
             throws XMLEncryptionException {
         // sanity checks
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Getting XMLCipher for no transformation...");
+        logger.log(java.util.logging.Level.FINE, "Getting XMLCipher for no transformation...");
 
                 XMLCipher instance = new XMLCipher();
 
@@ -532,7 +530,7 @@
             throws XMLEncryptionException {
         // sanity checks
 
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Getting XMLCipher, provider but no transformation");
+        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)
@@ -578,7 +576,7 @@
      */
     public void init(int opmode, Key key) throws XMLEncryptionException {
         // sanity checks
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Initializing XMLCipher...");
+        logger.log(java.util.logging.Level.FINE, "Initializing XMLCipher...");
 
                 _ek = null;
                 _ed = null;
@@ -586,18 +584,18 @@
                 switch (opmode) {
 
                 case ENCRYPT_MODE :
-                        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "opmode = ENCRYPT_MODE");
+                        logger.log(java.util.logging.Level.FINE, "opmode = ENCRYPT_MODE");
                         _ed = createEncryptedData(CipherData.VALUE_TYPE, "NO VALUE YET");
                         break;
                 case DECRYPT_MODE :
-                        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "opmode = DECRYPT_MODE");
+                        logger.log(java.util.logging.Level.FINE, "opmode = DECRYPT_MODE");
                         break;
                 case WRAP_MODE :
-                        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "opmode = WRAP_MODE");
+                        logger.log(java.util.logging.Level.FINE, "opmode = WRAP_MODE");
                         _ek = createEncryptedKey(CipherData.VALUE_TYPE, "NO VALUE YET");
                         break;
                 case UNWRAP_MODE :
-                        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "opmode = UNWRAP_MODE");
+                        logger.log(java.util.logging.Level.FINE, "opmode = UNWRAP_MODE");
                         break;
                 default :
                         logger.log(java.util.logging.Level.SEVERE, "Mode unexpectedly invalid");
@@ -622,7 +620,7 @@
         public EncryptedData getEncryptedData() {
 
                 // Sanity checks
-                if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Returning EncryptedData");
+                logger.log(java.util.logging.Level.FINE, "Returning EncryptedData");
                 return _ed;
 
         }
@@ -640,7 +638,7 @@
         public EncryptedKey getEncryptedKey() {
 
                 // Sanity checks
-                if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Returning EncryptedKey");
+                logger.log(java.util.logging.Level.FINE, "Returning EncryptedKey");
                 return _ek;
         }
 
@@ -750,11 +748,11 @@
      */
 
     private Document encryptElement(Element element) throws Exception{
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Encrypting element...");
+        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)
-            if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
+            logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
 
                 if (_algorithm == null) {
                 throw new XMLEncryptionException("XMLCipher instance without transformation specified");
@@ -785,11 +783,11 @@
      */
     private Document encryptElementContent(Element element) throws
             /* XMLEncryption */Exception {
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Encrypting element content...");
+        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)
-            if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
+            logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
 
                 if (_algorithm == null) {
                 throw new XMLEncryptionException("XMLCipher instance without transformation specified");
@@ -815,7 +813,7 @@
      */
     public Document doFinal(Document context, Document source) throws
             /* XMLEncryption */Exception {
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Processing source document...");
+        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)
@@ -855,7 +853,7 @@
      */
     public Document doFinal(Document context, Element element) throws
             /* XMLEncryption */Exception {
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Processing source element...");
+        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)
@@ -898,7 +896,7 @@
      */
     public Document doFinal(Document context, Element element, boolean content)
             throws /* XMLEncryption*/ Exception {
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Processing source element...");
+        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)
@@ -954,6 +952,34 @@
 
     /**
      * Returns an <code>EncryptedData</code> interface. Use this operation if
+     * you want to have full control over the serialization of the element
+     * or element content.
+     *
+     * This does not change the source document in any way.
+     *
+     * @param context the context <code>Document</code>.
+     * @param type a URI identifying type information about the plaintext form
+     *    of the encrypted content (may be <code>null</code>)
+     * @param serializedData the serialized data
+     * @return the <code>EncryptedData</code>
+     * @throws Exception
+     */
+    public EncryptedData encryptData(Document context, String type,
+        InputStream serializedData) throws Exception {
+
+        logger.log(java.util.logging.Level.FINE, "Encrypting element...");
+        if (null == context)
+            logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
+        if (null == serializedData)
+            logger.log(java.util.logging.Level.SEVERE, "Serialized data unexpectedly null...");
+        if (_cipherMode != ENCRYPT_MODE)
+            logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
+
+        return encryptData(context, null, type, serializedData);
+    }
+
+    /**
+     * Returns an <code>EncryptedData</code> interface. Use this operation if
      * you want to have full control over the contents of the
      * <code>EncryptedData</code> structure.
      *
@@ -966,160 +992,60 @@
      * @return the <code>EncryptedData</code>
      * @throws Exception
      */
-    public EncryptedData encryptData(Document context, Element element, boolean contentMode) throws
-            /* XMLEncryption */ Exception {
-                if (logger.isLoggable(java.util.logging.Level.FINE))                                     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)
-                        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
-
-                _contextDocument = context;
-
-                if (_algorithm == null) {
-                        throw new XMLEncryptionException("XMLCipher instance without transformation specified");
-                }
-
-                String serializedOctets = null;
-                if (contentMode) {
-                        NodeList children = element.getChildNodes();
-                        if ((null != children)) {
-                                serializedOctets = _serializer.serialize(children);
-                        } else {
-                                Object exArgs[] = { "Element has no content." };
-                                throw new XMLEncryptionException("empty", exArgs);
-                        }
-                } else {
-                        serializedOctets = _serializer.serialize(element);
-                }
-                if (logger.isLoggable(java.util.logging.Level.FINE))                                     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);
-
-                        if (logger.isLoggable(java.util.logging.Level.FINE))                                     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(_cipherMode, _key);
-                } catch (InvalidKeyException ike) {
-                        throw new XMLEncryptionException("empty", ike);
-                }
-
-        try {
-            encryptedBytes =
-                c.doFinal(serializedOctets.getBytes("UTF-8"));
-
-            if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Expected cipher.outputSize = " +
-                Integer.toString(c.getOutputSize(
-                    serializedOctets.getBytes().length)));
-            if (logger.isLoggable(java.util.logging.Level.FINE))                                     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) {
-            throw new XMLEncryptionException("empty", ibse);
-        } catch (BadPaddingException bpe) {
-            throw new XMLEncryptionException("empty", bpe);
-        } catch (UnsupportedEncodingException uee) {
-                        throw new XMLEncryptionException("empty", uee);
-                }
-
-                // 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];
-                System.arraycopy(iv, 0, finalEncryptedBytes, 0,
-                                                 iv.length);
-                System.arraycopy(encryptedBytes, 0, finalEncryptedBytes,
-                                                 iv.length,
-                                                 encryptedBytes.length);
-
-        String base64EncodedEncryptedOctets = Base64.encode(finalEncryptedBytes);
-
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     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 length = " +
-            base64EncodedEncryptedOctets.length());
-
-                try {
-                        CipherData cd = _ed.getCipherData();
-                        CipherValue cv = cd.getCipherValue();
-                        // cv.setValue(base64EncodedEncryptedOctets.getBytes());
-                        cv.setValue(base64EncodedEncryptedOctets);
-
-                        if (contentMode) {
-                                _ed.setType(
-                                        new URI(EncryptionConstants.TYPE_CONTENT).toString());
-                        } else {
-                                _ed.setType(
-                                        new URI(EncryptionConstants.TYPE_ELEMENT).toString());
-                        }
-                        EncryptionMethod method =
-                                _factory.newEncryptionMethod(new URI(_algorithm).toString());
-                        _ed.setEncryptionMethod(method);
-                } catch (URI.MalformedURIException mfue) {
-                        throw new XMLEncryptionException("empty", mfue);
-                }
-        return (_ed);
-    }
-
-
-
-    public EncryptedData encryptData(Document context, byte [] serializedOctets, boolean contentMode) throws
-            /* XMLEncryption */ 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 == serializedOctets)
-            logger.log(java.util.logging.Level.SEVERE, "Canonicalized Data is 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...");
 
+        if (contentMode) {
+            return encryptData
+                (context, element, EncryptionConstants.TYPE_CONTENT, null);
+        } else {
+            return encryptData
+                (context, element, EncryptionConstants.TYPE_ELEMENT, null);
+        }
+    }
+
+    private EncryptedData encryptData(
+        Document context, Element element, String type,
+        InputStream serializedData) throws /* XMLEncryption */ Exception {
+
         _contextDocument = context;
 
         if (_algorithm == null) {
-            throw new XMLEncryptionException("XMLCipher instance without transformation specified");
+            throw new XMLEncryptionException
+                ("XMLCipher instance without transformation specified");
         }
 
-
-        logger.log(java.util.logging.Level.FINE, "Serialized octets:\n" + serializedOctets);
+        String serializedOctets = null;
+        if (serializedData == null) {
+            if (type == EncryptionConstants.TYPE_CONTENT) {
+                NodeList children = element.getChildNodes();
+                if (null != children) {
+                    serializedOctets = _serializer.serialize(children);
+                } else {
+                    Object exArgs[] = { "Element has no content." };
+                    throw new XMLEncryptionException("empty", exArgs);
+                }
+            } else {
+                serializedOctets = _serializer.serialize(element);
+            }
+            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);
-
+            String jceAlgorithm = JCEMapper.translateURItoJCEID(_algorithm);
             logger.log(java.util.logging.Level.FINE, "alg = " + jceAlgorithm);
 
             try {
@@ -1148,41 +1074,47 @@
         }
 
         try {
-            encryptedBytes =
-                    c.doFinal(serializedOctets);
-
-            logger.log(java.util.logging.Level.FINE, "Expected cipher.outputSize = " +
+            if (serializedData != null) {
+                int numBytes;
+                byte[] buf = new byte[8192];
+                ByteArrayOutputStream baos = new ByteArrayOutputStream();
+                while ((numBytes = serializedData.read(buf)) != -1) {
+                    byte[] data = c.update(buf, 0, numBytes);
+                    baos.write(data);
+                }
+                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.length)));
+                        serializedOctets.getBytes().length)));
+            }
             logger.log(java.util.logging.Level.FINE, "Actual cipher.outputSize = " +
-                    Integer.toString(encryptedBytes.length));
+                Integer.toString(encryptedBytes.length));
         } catch (IllegalStateException ise) {
             throw new XMLEncryptionException("empty", ise);
         } catch (IllegalBlockSizeException ibse) {
             throw new XMLEncryptionException("empty", ibse);
         } catch (BadPaddingException bpe) {
             throw new XMLEncryptionException("empty", bpe);
-        } catch (Exception uee) {
+        } catch (UnsupportedEncodingException uee) {
             throw new XMLEncryptionException("empty", uee);
         }
 
         // 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];
-        System.arraycopy(iv, 0, finalEncryptedBytes, 0,
-                iv.length);
-        System.arraycopy(encryptedBytes, 0, finalEncryptedBytes,
-                iv.length,
-                encryptedBytes.length);
-
+        System.arraycopy(iv, 0, finalEncryptedBytes, 0, iv.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());
+            base64EncodedEncryptedOctets.length());
 
         try {
             CipherData cd = _ed.getCipherData();
@@ -1190,15 +1122,11 @@
             // cv.setValue(base64EncodedEncryptedOctets.getBytes());
             cv.setValue(base64EncodedEncryptedOctets);
 
-            if (contentMode) {
-                _ed.setType(
-                        new URI(EncryptionConstants.TYPE_CONTENT).toString());
-            } else {
-                _ed.setType(
-                        new URI(EncryptionConstants.TYPE_ELEMENT).toString());
+            if (type != null) {
+                _ed.setType(new URI(type).toString());
             }
             EncryptionMethod method =
-                    _factory.newEncryptionMethod(new URI(_algorithm).toString());
+                _factory.newEncryptionMethod(new URI(_algorithm).toString());
             _ed.setEncryptionMethod(method);
         } catch (URI.MalformedURIException mfue) {
             throw new XMLEncryptionException("empty", mfue);
@@ -1206,7 +1134,6 @@
         return (_ed);
     }
 
-
     /**
      * Returns an <code>EncryptedData</code> interface. Use this operation if
      * you want to load an <code>EncryptedData</code> structure from a DOM
@@ -1219,7 +1146,7 @@
      */
     public EncryptedData loadEncryptedData(Document context, Element element)
                 throws XMLEncryptionException {
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Loading encrypted element...");
+        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)
@@ -1246,13 +1173,13 @@
 
     public EncryptedKey loadEncryptedKey(Document context, Element element)
                 throws XMLEncryptionException {
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Loading encrypted key...");
+        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)
-            if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE or DECRYPT_MODE...");
+            logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE or DECRYPT_MODE...");
 
         _contextDocument = context;
         _ek = _factory.newEncryptedKey(element);
@@ -1290,12 +1217,12 @@
     public EncryptedKey encryptKey(Document doc, Key key) throws
             XMLEncryptionException {
 
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Encrypting key ...");
+        logger.log(java.util.logging.Level.FINE, "Encrypting key ...");
 
         if(null == key)
             logger.log(java.util.logging.Level.SEVERE, "Key unexpectedly null...");
         if(_cipherMode != WRAP_MODE)
-            if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in WRAP_MODE...");
+            logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in WRAP_MODE...");
 
                 if (_algorithm == null) {
 
@@ -1313,7 +1240,7 @@
                         String jceAlgorithm =
                                 JCEMapper.translateURItoJCEID(_algorithm);
 
-                        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "alg = " + jceAlgorithm);
+                        logger.log(java.util.logging.Level.FINE, "alg = " + jceAlgorithm);
 
                         try {
                             if (_requestedJCEProvider == null)
@@ -1345,8 +1272,8 @@
 
         String base64EncodedEncryptedOctets = Base64.encode(encryptedBytes);
 
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Encrypted key octets:\n" + base64EncodedEncryptedOctets);
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Encrypted key octets length = " +
+        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();
@@ -1376,10 +1303,10 @@
         public Key decryptKey(EncryptedKey encryptedKey, String algorithm) throws
                     XMLEncryptionException {
 
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Decrypting key from previously loaded EncryptedKey...");
+        logger.log(java.util.logging.Level.FINE, "Decrypting key from previously loaded EncryptedKey...");
 
         if(_cipherMode != UNWRAP_MODE)
-            if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in 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");
@@ -1387,7 +1314,7 @@
 
                 if (_key == null) {
 
-                        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Trying to find a KEK via key resolvers");
+                        logger.log(java.util.logging.Level.FINE, "Trying to find a KEK via key resolvers");
 
                         KeyInfo ki = encryptedKey.getKeyInfo();
                         if (ki != null) {
@@ -1418,7 +1345,7 @@
                                 JCEMapper.translateURItoJCEID(
                                         encryptedKey.getEncryptionMethod().getAlgorithm());
 
-                        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm);
+                        logger.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm);
 
                         try {
                             if (_requestedJCEProvider == null)
@@ -1448,7 +1375,7 @@
                         throw new XMLEncryptionException("empty", nsae);
                 }
 
-                if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Decryption of key type " + algorithm + " OK");
+                logger.log(java.util.logging.Level.FINE, "Decryption of key type " + algorithm + " OK");
 
                 return ret;
 
@@ -1478,14 +1405,9 @@
      *
      * @param node the <code>Node</code> to clear.
      */
-    private void removeContent(Node node) {
-        NodeList list = node.getChildNodes();
-        if (list.getLength() > 0) {
-            Node n = list.item(0);
-            if (null != n) {
-                n.getParentNode().removeChild(n);
-            }
-            removeContent(node);
+    private static void removeContent(Node node) {
+       while (node.hasChildNodes()) {
+            node.removeChild(node.getFirstChild());
         }
     }
 
@@ -1499,7 +1421,7 @@
     private Document decryptElement(Element element) throws
             XMLEncryptionException {
 
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Decrypting element...");
+        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...");
@@ -1512,7 +1434,7 @@
                 }
 
 
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + octets);
+        logger.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + octets);
 
         Node sourceParent =  element.getParentNode();
 
@@ -1573,7 +1495,7 @@
         public byte[] decryptToByteArray(Element element)
                 throws XMLEncryptionException {
 
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Decrypting to ByteArray...");
+        logger.log(java.util.logging.Level.FINE, "Decrypting to ByteArray...");
 
         if(_cipherMode != DECRYPT_MODE)
             logger.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
@@ -2226,7 +2148,7 @@
         AgreementMethod newAgreementMethod(Element element) throws
                 XMLEncryptionException {
             if (null == element) {
-                //complain
+                throw new NullPointerException("element is null");
             }
 
             String algorithm = element.getAttributeNS(null,
@@ -2292,7 +2214,7 @@
         CipherData newCipherData(Element element) throws
                 XMLEncryptionException {
             if (null == element) {
-                // complain
+                throw new NullPointerException("element is null");
             }
 
             int type = 0;
@@ -2352,7 +2274,7 @@
                                 (Element) transformsElements.item(0);
 
                         if (transformsElement != null) {
-                                if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Creating a DSIG based Transforms element");
+                                logger.log(java.util.logging.Level.FINE, "Creating a DSIG based Transforms element");
                                 try {
                                         result.setTransforms(new TransformsImpl(transformsElement));
                                 }
@@ -2411,34 +2333,28 @@
                         XMLEncryptionException {
             EncryptedData result = null;
 
-                        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
+            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
 
             Element dataElement =
-                                (Element) dataElements.item(dataElements.getLength() - 1);
+                (Element) dataElements.item(dataElements.getLength() - 1);
 
             CipherData data = newCipherData(dataElement);
 
             result = newEncryptedData(data);
 
-            try {
-                result.setId(element.getAttributeNS(
-                    null, EncryptionConstants._ATT_ID));
-                result.setType(new URI(
-                    element.getAttributeNS(
-                        null, EncryptionConstants._ATT_TYPE)).toString());
-                result.setMimeType(element.getAttributeNS(
-                    null, EncryptionConstants._ATT_MIMETYPE));
-                result.setEncoding(new URI(
-                    element.getAttributeNS(
-                        null, Constants._ATT_ENCODING)).toString());
-            } catch (URI.MalformedURIException mfue) {
-                // do nothing
-            }
+            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(
@@ -2450,18 +2366,18 @@
             }
 
             // BFL 16/7/03 - simple implementation
-                        // TODO: Work out how to handle relative URI
+            // TODO: Work out how to handle relative URI
 
             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);
-                                }
+                try {
+                    result.setKeyInfo(new KeyInfo(keyInfoElement, null));
+                } catch (XMLSecurityException xse) {
+                    throw new XMLEncryptionException("Error loading Key Info",
+                                                     xse);
+                }
             }
 
             // TODO: Implement
@@ -2511,31 +2427,25 @@
         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);
+                (Element) dataElements.item(dataElements.getLength() - 1);
 
             CipherData data = newCipherData(dataElement);
             result = newEncryptedKey(data);
 
-            try {
-                result.setId(element.getAttributeNS(
-                    null, EncryptionConstants._ATT_ID));
-                result.setType(new URI(
-                    element.getAttributeNS(
-                        null, EncryptionConstants._ATT_TYPE)).toString());
-                result.setMimeType(element.getAttributeNS(
-                    null, EncryptionConstants._ATT_MIMETYPE));
-                result.setEncoding(new URI(
-                    element.getAttributeNS(
-                        null, Constants._ATT_ENCODING)).toString());
-                result.setRecipient(element.getAttributeNS(
-                    null, EncryptionConstants._ATT_RECIPIENT));
-            } catch (URI.MalformedURIException mfue) {
-                // do nothing
-            }
+            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(
@@ -2550,12 +2460,12 @@
                 (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);
-                                }
+                try {
+                    result.setKeyInfo(new KeyInfo(keyInfoElement, null));
+                } catch (XMLSecurityException xse) {
+                    throw new XMLEncryptionException
+                        ("Error loading Key Info", xse);
+                }
             }
 
             // TODO: Implement
@@ -2581,7 +2491,8 @@
                     EncryptionConstants.EncryptionSpecNS,
                     EncryptionConstants._TAG_CARRIEDKEYNAME).item(0);
             if (null != carriedNameElement) {
-                result.setCarriedName(carriedNameElement.getNodeValue());
+                result.setCarriedName
+                    (carriedNameElement.getFirstChild().getNodeValue());
             }
 
             return (result);
@@ -2680,13 +2591,8 @@
         EncryptionProperty newEncryptionProperty(Element element) {
             EncryptionProperty result = newEncryptionProperty();
 
-            try {
-                result.setTarget(new URI(
-                    element.getAttributeNS(
-                        null, EncryptionConstants._ATT_TARGET)).toString());
-            } catch (URI.MalformedURIException mfue) {
-                // do nothing
-            }
+            result.setTarget(
+                element.getAttributeNS(null, EncryptionConstants._ATT_TARGET));
             result.setId(element.getAttributeNS(
                 null, EncryptionConstants._ATT_ID));
             // TODO: Make this lot work...
@@ -2943,7 +2849,7 @@
                 } catch (URI.MalformedURIException mfue) {
                     //complain
                 }
-                algorithm = tmpAlgorithm.toString();
+                algorithmURI = tmpAlgorithm.toString();
             }
 
             // <element name="AgreementMethod" type="xenc:AgreementMethodType"/>
@@ -3183,7 +3089,7 @@
                     _contextDocument, EncryptionConstants.EncryptionSpecNS,
                     EncryptionConstants._TAG_CIPHERVALUE);
                 result.appendChild(_contextDocument.createTextNode(
-                    new String(cipherValue)));
+                    cipherValue));
 
                 return (result);
             }
@@ -3247,8 +3153,7 @@
                 }
                 if (null != super.getType()) {
                     result.setAttributeNS(
-                        null, EncryptionConstants._ATT_TYPE,
-                        super.getType().toString());
+                        null, EncryptionConstants._ATT_TYPE, super.getType());
                 }
                 if (null != super.getMimeType()) {
                     result.setAttributeNS(
@@ -3258,7 +3163,7 @@
                 if (null != super.getEncoding()) {
                     result.setAttributeNS(
                         null, EncryptionConstants._ATT_ENCODING,
-                        super.getEncoding().toString());
+                        super.getEncoding());
                 }
                 if (null != super.getEncryptionMethod()) {
                     result.appendChild(((EncryptionMethodImpl)
@@ -3383,8 +3288,7 @@
                 }
                 if (null != super.getType()) {
                     result.setAttributeNS(
-                        null, EncryptionConstants._ATT_TYPE,
-                        super.getType().toString());
+                        null, EncryptionConstants._ATT_TYPE, super.getType());
                 }
                 if (null != super.getMimeType()) {
                     result.setAttributeNS(null,
@@ -3392,7 +3296,7 @@
                 }
                 if (null != super.getEncoding()) {
                     result.setAttributeNS(null, Constants._ATT_ENCODING,
-                        super.getEncoding().toString());
+                        super.getEncoding());
                 }
                 if (null != getRecipient()) {
                     result.setAttributeNS(null,
@@ -3468,13 +3372,17 @@
              * @param type
              */
             public void setType(String type) {
-                URI tmpType = null;
-                try {
-                    tmpType = new URI(type);
-                } catch (URI.MalformedURIException mfue) {
-                    // complain
+                if (type == null || type.length() == 0) {
+                    this.type = null;
+                } else {
+                    URI tmpType = null;
+                    try {
+                        tmpType = new URI(type);
+                    } catch (URI.MalformedURIException mfue) {
+                        // complain
+                    }
+                    this.type = tmpType.toString();
                 }
-                this.type = tmpType.toString();
             }
             /**
              *
@@ -3502,13 +3410,17 @@
              * @param encoding
              */
             public void setEncoding(String encoding) {
-                URI tmpEncoding = null;
-                try {
-                    tmpEncoding = new URI(encoding);
-                } catch (URI.MalformedURIException mfue) {
-                    // complain
+                if (encoding == null || encoding.length() == 0) {
+                    this.encoding = null;
+                } else {
+                    URI tmpEncoding = null;
+                    try {
+                        tmpEncoding = new URI(encoding);
+                    } catch (URI.MalformedURIException mfue) {
+                        // complain
+                    }
+                    this.encoding = tmpEncoding.toString();
                 }
-                this.encoding = tmpEncoding.toString();
             }
             /**
              *
@@ -3635,7 +3547,7 @@
                     _contextDocument, EncryptionConstants.EncryptionSpecNS,
                     EncryptionConstants._TAG_ENCRYPTIONMETHOD);
                 result.setAttributeNS(null, EncryptionConstants._ATT_ALGORITHM,
-                    algorithm.toString());
+                    algorithm);
                 if (keySize > 0) {
                     result.appendChild(
                         ElementProxy.createElementForFamily(_contextDocument,
@@ -3735,8 +3647,7 @@
         private class EncryptionPropertyImpl implements EncryptionProperty {
             private String target = null;
             private String id = null;
-            private String attributeName = null;
-            private String attributeValue = null;
+            private HashMap attributeMap = new HashMap();
             private List encryptionInformation = null;
 
             /**
@@ -3752,13 +3663,24 @@
             }
             /** @inheritDoc */
             public void setTarget(String target) {
-                URI tmpTarget = null;
-                try {
-                    tmpTarget = new URI(target);
-                } catch (URI.MalformedURIException mfue) {
-                    // complain
+                if (target == null || target.length() == 0) {
+                    this.target = null;
+                } 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.
+                     */
+                    this.target = target;
+                } else {
+                    URI tmpTarget = null;
+                    try {
+                        tmpTarget = new URI(target);
+                    } catch (URI.MalformedURIException mfue) {
+                        // complain
+                    }
+                    this.target = tmpTarget.toString();
                 }
-                this.target = tmpTarget.toString();
             }
             /** @inheritDoc */
             public String getId() {
@@ -3770,12 +3692,11 @@
             }
             /** @inheritDoc */
             public String getAttribute(String attribute) {
-                return (attributeValue);
+                return (String) attributeMap.get(attribute);
             }
             /** @inheritDoc */
             public void setAttribute(String attribute, String value) {
-                attributeName = attribute;
-                attributeValue = value;
+                attributeMap.put(attribute, value);
             }
             /** @inheritDoc */
             public Iterator getEncryptionInformation() {
@@ -3805,7 +3726,7 @@
                     EncryptionConstants._TAG_ENCRYPTIONPROPERTY);
                 if (null != target) {
                     result.setAttributeNS(null, EncryptionConstants._ATT_TARGET,
-                        target.toString());
+                        target);
                 }
                 if (null != id) {
                     result.setAttributeNS(null, EncryptionConstants._ATT_ID,
@@ -3839,7 +3760,13 @@
                          * @param doc
                          */
                         public TransformsImpl(Document doc) {
-                                super(doc);
+                                if (doc == null) {
+                                 throw new RuntimeException("Document is null");
+                              }
+
+                              this._doc = doc;
+                              this._constructionElement =  createElementForFamilyLocal(this._doc,
+                                          this.getBaseNamespace(), this.getBaseLocalName());
                         }
                         /**
              *
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java	Tue Oct 07 14:11:10 2008 +0100
@@ -108,84 +108,78 @@
                 return null;
         }
 
-        /**
-         * Internal method to get bytes in decryption mode
+    /**
+     * Internal method to get bytes in decryption mode
      * @return the decripted bytes
      * @throws XMLEncryptionException
-         */
+     */
+    private byte[] getDecryptBytes() throws XMLEncryptionException {
 
-        private byte[] getDecryptBytes() throws XMLEncryptionException {
-
-                String base64EncodedEncryptedOctets = null;
+        String base64EncodedEncryptedOctets = null;
 
         if (_cipherData.getDataType() == CipherData.REFERENCE_TYPE) {
-                        // Fun time!
-                        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Found a reference type CipherData");
-                        CipherReference cr = _cipherData.getCipherReference();
+            // Fun time!
+            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
+            // Need to wrap the uri in an Attribute node so that we can
+            // Pass to the resource resolvers
 
-                        Attr uriAttr = cr.getURIAsAttr();
-                        XMLSignatureInput input = null;
+            Attr uriAttr = cr.getURIAsAttr();
+            XMLSignatureInput input = null;
 
-                        try {
-                                ResourceResolver resolver =
-                                        ResourceResolver.getInstance(uriAttr, null);
-                                input = resolver.resolve(uriAttr, null);
-                        } catch (ResourceResolverException ex) {
-                                throw new XMLEncryptionException("empty", ex);
-                        }
+            try {
+                ResourceResolver resolver =
+                    ResourceResolver.getInstance(uriAttr, null);
+                input = resolver.resolve(uriAttr, null);
+            } catch (ResourceResolverException ex) {
+                throw new XMLEncryptionException("empty", ex);
+            }
 
-                        if (input != null) {
-                                if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Managed to resolve URI \"" + cr.getURI() + "\"");
-                        }
-                        else {
-                                if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Failed to resolve URI \"" + cr.getURI() + "\"");
-                        }
+            if (input != null) {
+                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() + "\"");
+            }
 
-                        // Lets see if there are any transforms
-                        Transforms transforms = cr.getTransforms();
-                        if (transforms != null) {
-                                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();
-                                    input =     dsTransforms.performTransforms(input);
-                                } catch (TransformationException ex) {
-                                        throw new XMLEncryptionException("empty", ex);
-                                }
-                        }
+            // 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");
+                try {
+                    com.sun.org.apache.xml.internal.security.transforms.Transforms dsTransforms =
+                        transforms.getDSTransforms();
+                    input = dsTransforms.performTransforms(input);
+                } catch (TransformationException ex) {
+                    throw new XMLEncryptionException("empty", ex);
+                }
+            }
 
-                        try {
-                                return input.getBytes();
-                        }
-                        catch (IOException ex) {
-                                throw new XMLEncryptionException("empty", ex);
-                        } catch (CanonicalizationException ex) {
-                                throw new XMLEncryptionException("empty", ex);
-                        }
+            try {
+                return input.getBytes();
+            } catch (IOException ex) {
+                throw new XMLEncryptionException("empty", ex);
+            } catch (CanonicalizationException ex) {
+                throw new XMLEncryptionException("empty", ex);
+            }
 
-            // retrieve the cipher text
+        // retrieve the cipher text
         } else if (_cipherData.getDataType() == CipherData.VALUE_TYPE) {
-            CipherValue cv = _cipherData.getCipherValue();
-            base64EncodedEncryptedOctets = new String(cv.getValue());
+            base64EncodedEncryptedOctets =
+                _cipherData.getCipherValue().getValue();
         } else {
-                        throw new XMLEncryptionException("CipherData.getDataType() returned unexpected value");
-                }
+            throw new XMLEncryptionException("CipherData.getDataType() returned unexpected value");
+        }
 
-        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets);
+        logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets);
 
         byte[] encryptedBytes = null;
-
         try {
-                        encryptedBytes = Base64.decode(base64EncodedEncryptedOctets);
+            encryptedBytes = Base64.decode(base64EncodedEncryptedOctets);
         } catch (Base64DecodingException bde) {
             throw new XMLEncryptionException("empty", bde);
         }
 
-                return (encryptedBytes);
-
-        }
-
+        return (encryptedBytes);
+    }
 }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java	Tue Oct 07 14:11:10 2008 +0100
@@ -2,7 +2,6 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-
 /*
  * Copyright  1999-2004 The Apache Software Foundation.
  *
@@ -28,7 +27,7 @@
 
 /**
  *
- * @author $Author: raul $
+ * @author $Author: mullan $
  */
 public class ContentHandlerAlreadyRegisteredException
         extends XMLSecurityException {
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java	Fri Oct 03 19:14:15 2008 +0100
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java	Tue Oct 07 14:11:10 2008 +0100
@@ -25,6 +25,8 @@
 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;
 
 import javax.crypto.SecretKey;
@@ -88,15 +90,22 @@
  * The <CODE>containsXXX()</CODE> methods return <I>whether</I> the KeyInfo
  * contains the corresponding type.
  *
- * @author $Author: raul $
+ * @author $Author: mullan $
  */
 public class KeyInfo extends SignatureElementProxy {
 
    /** {@link java.util.logging} logging facility */
     static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(KeyInfo.class.getName());
+    List x509Datas=null;
+    List encryptedKeys=null;
 
-
+    static final List nullList;
+    static {
+        List list = new ArrayList();
+        list.add(null);
+        nullList = Collections.unmodifiableList(list);
+    }
 
    /**
     * Constructor KeyInfo
@@ -108,7 +117,6 @@
 
       XMLUtils.addReturnToElement(this._constructionElement);
 
-
    }
 
    /**
@@ -119,8 +127,8 @@
     * @throws XMLSecurityException
     */
    public KeyInfo(Element element, String BaseURI) throws XMLSecurityException {
-
       super(element, BaseURI);
+     // _storageResolvers.add(null);
 
    }
 
@@ -131,7 +139,7 @@
     */
    public void setId(String Id) {
 
-      if ((this._state == MODE_SIGN) && (Id != null)) {
+      if ((Id != null)) {
          this._constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
          IdResolver.registerElementById(this._constructionElement, Id);