FileDocCategorySizeDatePackage
XMLUtils.javaAPI DocJava SE 6 API20178Tue Jun 10 00:23:04 BST 2008com.sun.org.apache.xml.internal.security.utils

XMLUtils

public class XMLUtils extends Object
DOM and XML accessibility and comfort functions.
author
Christian Geuer-Pollmann

Fields Summary
Constructors Summary
private XMLUtils()
Constructor XMLUtils


      // we don't allow instantiation
   
Methods Summary
public static voidaddReturnToElement(org.w3c.dom.Element e)
Method addReturnToElement

param
e


      Document doc = e.getOwnerDocument();

      e.appendChild(doc.createTextNode("\n"));
   
public static voidcircumventBug2650(org.w3c.dom.Document doc)
This method spreads all namespace attributes in a DOM document to their children. This is needed because the XML Signature XPath transform must evaluate the XPath against all nodes in the input, even against XPath namespace nodes. Through a bug in XalanJ2, the namespace nodes are not fully visible in the Xalan XPath model, so we have to do this by hand in DOM spaces so that the nodes become visible in XPath space.

param
doc
see
Namespace axis resolution is not XPath compliant


      Element documentElement = doc.getDocumentElement();

      // if the document element has no xmlns definition, we add xmlns=""
      Attr xmlnsAttr =
         documentElement.getAttributeNodeNS(Constants.NamespaceSpecNS, "xmlns");

      if (xmlnsAttr == null) {
         documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "");
      }

      XMLUtils.circumventBug2650internal(doc);
   
private static voidcircumventBug2650internal(org.w3c.dom.Node node)
This is the work horse for {@link #circumventBug2650}.

param
node
see
Namespace axis resolution is not XPath compliant

	   Node parent=null;
	   Node sibling=null;
	   final String namespaceNs=Constants.NamespaceSpecNS;
	   do {
         switch (node.getNodeType()) {
         case Node.ELEMENT_NODE :
        	 Element element = (Element) node;
             if (!element.hasChildNodes())
            	 break;
             if (element.hasAttributes()) {            	 
             NamedNodeMap attributes = element.getAttributes();         	
             int attributesLength = attributes.getLength();    
             
             for (Node child = element.getFirstChild(); child!=null; 
             	child=child.getNextSibling()) {            

             	if (child.getNodeType() != Node.ELEMENT_NODE) {
             		continue;
             	}
             	Element childElement = (Element) child;

             	for (int i = 0; i < attributesLength; i++) {
             		Attr currentAttr = (Attr) attributes.item(i); 
             		if (!namespaceNs.equals(currentAttr.getNamespaceURI()))
             			continue;
             		if (childElement.hasAttributeNS(namespaceNs,
    							currentAttr.getLocalName())) {
             				continue;
             		}
             		childElement.setAttributeNS(namespaceNs,
                                                currentAttr.getName(),
                                                currentAttr.getNodeValue());         					
             				
             			
             	}
             }            
             }
         case Node.ENTITY_REFERENCE_NODE :
         case Node.DOCUMENT_NODE :
        	 parent=node;
        	 sibling=node.getFirstChild();
             break;
         }
         while ((sibling==null) && (parent!=null)) {
        		 sibling=parent.getNextSibling();
        		 parent=parent.getParentNode();
        	 };
       if (sibling==null) {
        		 return;
        	 }
       	
         node=sibling;
         sibling=node.getNextSibling();
	   } while (true);
   
public static java.util.SetconvertNodelistToSet(org.w3c.dom.NodeList xpathNodeSet)
Method convertNodelistToSet

param
xpathNodeSet
return
the set with the nodelist


      if (xpathNodeSet == null) {
         return new HashSet();
      }

      int length = xpathNodeSet.getLength();
      Set set = new HashSet(length);

      for (int i = 0; i < length; i++) {
         set.add(xpathNodeSet.item(i));
      }

      return set;
   
public static org.w3c.dom.ElementcreateDSctx(org.w3c.dom.Document doc, java.lang.String prefix, java.lang.String namespace)
Method createDSctx

param
doc
param
prefix
param
namespace
return
the element.


      if ((prefix == null) || (prefix.trim().length() == 0)) {
         throw new IllegalArgumentException("You must supply a prefix");
      }

      Element ctx = doc.createElementNS(null, "namespaceContext");

      ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(),
                         namespace);

      return ctx;
   
public static org.w3c.dom.ElementcreateElementInSignatureSpace(org.w3c.dom.Document doc, java.lang.String elementName)
Creates an Element in the XML Signature specification namespace.

param
doc the factory Document
param
elementName the local name of the Element
return
the Element


      if (doc == null) {
         throw new RuntimeException("Document is null");
      }

      String ds = Constants.getSignatureSpecNSprefix();

      if ((ds == null) || (ds.length() == 0)) {
         Element element = doc.createElementNS(Constants.SignatureSpecNS,
                                               elementName);

         element.setAttributeNS(Constants.NamespaceSpecNS, "xmlns",
                                Constants.SignatureSpecNS);

         return element;
      } 
         Element element = doc.createElementNS(Constants.SignatureSpecNS,
                                               ds + ":" + elementName);

         element.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + ds,
                                Constants.SignatureSpecNS);

         return element;
      
   
public static booleanelementIsInEncryptionSpace(org.w3c.dom.Element element, java.lang.String localName)
Returns true if the element is in XML Encryption namespace and the local name equals the supplied one.

param
element
param
localName
return
true if the element is in XML Encryption namespace and the local name equals the supplied one


      if ((element == null) || 
            !EncryptionConstants.EncryptionSpecNS.equals(element.getNamespaceURI()) 
          ){
         return false;
      }

      if (!element.getLocalName().equals(localName)) {
         return false;
      }

      return true;
   
public static booleanelementIsInSignatureSpace(org.w3c.dom.Element element, java.lang.String localName)
Returns true if the element is in XML Signature namespace and the local name equals the supplied one.

param
element
param
localName
return
true if the element is in XML Signature namespace and the local name equals the supplied one


      if ((element == null) ||
          !Constants.SignatureSpecNS.equals(element.getNamespaceURI()) ){
         return false;
      }

      if (!element.getLocalName().equals(localName)) {
         return false;
      }

      return true;
   
public static java.util.SetexcludeNodeFromSet(org.w3c.dom.Node signatureElement, java.util.Set inputSet)

param
signatureElement
param
inputSet
return
nodes with the constrain

	  Set resultSet = new HashSet();
	  Iterator iterator = inputSet.iterator();

	  while (iterator.hasNext()) {
	    Node inputNode = (Node) iterator.next();

	    if (!XMLUtils
	            .isDescendantOrSelf(signatureElement, inputNode)) {
	       resultSet.add(inputNode);
	    }
	 }
	 return resultSet;
     
public static java.lang.StringgetFullTextChildrenFromElement(org.w3c.dom.Element element)
Method getFullTextChildrenFromElement

param
element
return
the string of chi;ds


      StringBuffer sb = new StringBuffer();
      NodeList children = element.getChildNodes();
      int iMax = children.getLength();

      for (int i = 0; i < iMax; i++) {
         Node curr = children.item(i);

         if (curr.getNodeType() == Node.TEXT_NODE) {
            sb.append(((Text) curr).getData());
         }
      }

      return sb.toString();
   
public static org.w3c.dom.DocumentgetOwnerDocument(org.w3c.dom.Node node)
This method returns the owner document of a particular node. This method is necessary because it always returns a {@link Document}. {@link Node#getOwnerDocument} returns null if the {@link Node} is a {@link Document}.

param
node
return
the owner document of the node


      if (node.getNodeType() == Node.DOCUMENT_NODE) {
         return (Document) node;
      } 
         try {
            return node.getOwnerDocument();
         } catch (NullPointerException npe) {
            throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0")
                                           + " Original message was \""
                                           + npe.getMessage() + "\"");
         }
      
   
public static org.w3c.dom.DocumentgetOwnerDocument(java.util.Set xpathNodeSet)
This method returns the first non-null owner document of the Node's in this Set. This method is necessary because it always returns a {@link Document}. {@link Node#getOwnerDocument} returns null if the {@link Node} is a {@link Document}.

param
xpathNodeSet
return
the owner document

       NullPointerException npe = null;
       Iterator iterator = xpathNodeSet.iterator();
       while(iterator.hasNext()) {
           Node node = (Node) iterator.next();
           int nodeType =node.getNodeType();
           if (nodeType == Node.DOCUMENT_NODE) {
              return (Document) node;
           } 
              try {
                 if (nodeType==Node.ATTRIBUTE_NODE) {
                    return ((Attr)node).getOwnerElement().getOwnerDocument();  
                 }
                 return node.getOwnerDocument();
              } catch (NullPointerException e) {
                  npe = e;
              }
           
       }
       throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0")
                                       + " Original message was \""
                                       + (npe == null ? "" : npe.getMessage()) + "\"");
    
public static voidgetSet(org.w3c.dom.Node rootNode, java.util.Set result, org.w3c.dom.Node exclude, boolean com)

param
rootNode
param
result
param
exclude
param
com wheather comments or not

   	  if ((exclude!=null) && isDescendantOrSelf(exclude,rootNode)){
   	  	return;
      }
      getSetRec(rootNode,result,exclude,com);
   
static final voidgetSetRec(org.w3c.dom.Node rootNode, java.util.Set result, org.w3c.dom.Node exclude, boolean com)

   	   //Set result = new HashSet();
       if (rootNode==exclude) {
          return;
       }
   	   switch (rootNode.getNodeType()) {   	   		   	   			
   	   	case Node.ELEMENT_NODE:
   	   			result.add(rootNode);
   	   	        Element el=(Element)rootNode;
                if (el.hasAttributes()) {
   	   		        NamedNodeMap nl = ((Element)rootNode).getAttributes();
   	   		        for (int i=0;i<nl.getLength();i++) {
   	   		        	result.add(nl.item(i));
   	   		        }
                }
                //no return keep working
   	   	case Node.DOCUMENT_NODE:   	   			
   	   			for (Node r=rootNode.getFirstChild();r!=null;r=r.getNextSibling()){                                    
   	   				if (r.getNodeType()==Node.TEXT_NODE) {
   	   					result.add(r); 
   	   					while ((r!=null) && (r.getNodeType()==Node.TEXT_NODE)) {
   	   						r=r.getNextSibling();
   	   					}
   	   					if (r==null)
   	   						return;
   	   				}  
   	   				getSetRec(r,result,exclude,com);                
   	   			}
   	   			return;
   	   		case Node.COMMENT_NODE:
   	   			if (com) {
   	   				result.add(rootNode);
   	   			}
   	   		    return;
   	   		case Node.DOCUMENT_TYPE_NODE:
   	   			return;
   	   		default:
   	   			result.add(rootNode);
   	   }
   	   return;
   
public static booleanisDescendantOrSelf(org.w3c.dom.Node ctx, org.w3c.dom.Node descendantOrSelf)
Returns true if the descendantOrSelf is on the descendant-or-self axis of the context node.

param
ctx
param
descendantOrSelf
return
true if the node is descendant


      if (ctx == descendantOrSelf) {
         return true;
      }

      Node parent = descendantOrSelf;

      while (true) {
         if (parent == null) {
            return false;
         }

         if (parent == ctx) {
            return true;
         }

         if (parent.getNodeType() == Node.ATTRIBUTE_NODE) {
            parent = ((Attr) parent).getOwnerElement();
         } else {
            parent = parent.getParentNode();
         }
      }
   
public static voidoutputDOM(org.w3c.dom.Node contextNode, java.io.OutputStream os)
Outputs a DOM tree to an {@link OutputStream}.

param
contextNode root node of the DOM tree
param
os the {@link OutputStream}

      XMLUtils.outputDOM(contextNode, os, false);
   
public static voidoutputDOM(org.w3c.dom.Node contextNode, java.io.OutputStream os, boolean addPreamble)
Outputs a DOM tree to an {@link OutputStream}. If an Exception is thrown during execution, it's StackTrace is output to System.out, but the Exception is not re-thrown.

param
contextNode root node of the DOM tree
param
os the {@link OutputStream}
param
addPreamble


      try {
         if (addPreamble) {
            os.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes());
         }

         os.write(
            Canonicalizer.getInstance(
               Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(
               contextNode));
      } catch (IOException ex) {}
      catch (InvalidCanonicalizerException ex) {
         ex.printStackTrace();
      } catch (CanonicalizationException ex) {
         ex.printStackTrace();
      }
   
public static voidoutputDOMc14nWithComments(org.w3c.dom.Node contextNode, java.io.OutputStream os)
Serializes the contextNode into the OutputStream, but supresses all Exceptions.
NOTE: This should only be used for debugging purposes, NOT in a production environment; this method ignores all exceptions, so you won't notice if something goes wrong. If you're asking what is to be used in a production environment, simply use the code inside the try{} statement, but handle the Exceptions appropriately.

param
contextNode
param
os


      try {
         os.write(
            Canonicalizer.getInstance(
               Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(
               contextNode));
      } catch (IOException ex) {

         // throw new RuntimeException(ex.getMessage());
      } catch (InvalidCanonicalizerException ex) {

         // throw new RuntimeException(ex.getMessage());
      } catch (CanonicalizationException ex) {

         // throw new RuntimeException(ex.getMessage());
      }
   
public static org.w3c.dom.ElementselectDsNode(org.w3c.dom.Node sibling, java.lang.String nodeName, int number)

param
sibling
param
nodeName
param
number
return
nodes with the constrain

	while (sibling!=null) {
		if (nodeName.equals(sibling.getLocalName())
				&& Constants.SignatureSpecNS.equals(sibling.getNamespaceURI())) {
			if (number==0){
				return (Element)sibling;
			}
			number--;
		}
		sibling=sibling.getNextSibling();
	}
	return null;
   
public static org.w3c.dom.TextselectDsNodeText(org.w3c.dom.Node sibling, java.lang.String nodeName, int number)

param
sibling
param
nodeName
param
number
return
nodes with the constrain

   	    Node n=selectDsNode(sibling,nodeName,number);
        if (n==null) {
        	return null;
        }
        n=n.getFirstChild();
        while (n!=null && n.getNodeType()!=Node.TEXT_NODE) {
        	n=n.getNextSibling();
        }
        return (Text)n;
   
public static org.w3c.dom.Element[]selectDsNodes(org.w3c.dom.Node sibling, java.lang.String nodeName)

param
sibling
param
nodeName
return
nodes with the constrain

     return selectNodes(sibling,Constants.SignatureSpecNS,nodeName);
   
public static org.w3c.dom.ElementselectNode(org.w3c.dom.Node sibling, java.lang.String uri, java.lang.String nodeName, int number)

param
sibling
param
uri
param
nodeName
param
number
return
nodes with the constrain

	while (sibling!=null) {
		if (nodeName.equals(sibling.getLocalName())
				&& uri.equals(sibling.getNamespaceURI())) {
			if (number==0){
				return (Element)sibling;
			}
			number--;
		}
		sibling=sibling.getNextSibling();
	}
	return null;
   
public static org.w3c.dom.TextselectNodeText(org.w3c.dom.Node sibling, java.lang.String uri, java.lang.String nodeName, int number)

param
sibling
param
uri
param
nodeName
param
number
return
nodes with the constrain

        Node n=selectNode(sibling,uri,nodeName,number);
    if (n==null) {
        return null;
    }
    n=n.getFirstChild();
    while (n!=null && n.getNodeType()!=Node.TEXT_NODE) {
        n=n.getNextSibling();
    }
    return (Text)n;
   
public static org.w3c.dom.Element[]selectNodes(org.w3c.dom.Node sibling, java.lang.String uri, java.lang.String nodeName)

param
sibling
param
uri
param
nodeName
return
nodes with the constrain

    	int size=20;
    	Element[] a= new Element[size];
    	int curr=0;
    	//List list=new ArrayList();
    	while (sibling!=null) {
    		if (nodeName.equals(sibling.getLocalName())
    				&& uri.equals(sibling.getNamespaceURI())) {
    			a[curr++]=(Element)sibling;
    			if (size<=curr) {
    				int cursize= size<<2;
    				Element []cp=new Element[cursize];
    				System.arraycopy(a,0,cp,0,size);
    				a=cp;
    				size=cursize;
    			}   
    		}
    		sibling=sibling.getNextSibling();
    	}
    	Element []af=new Element[curr];
    	System.arraycopy(a,0,af,0,curr);
    	return af;
   
public static org.w3c.dom.ElementselectXencNode(org.w3c.dom.Node sibling, java.lang.String nodeName, int number)

param
sibling
param
nodeName
param
number
return
nodes with the constrain

	while (sibling!=null) {
		if (nodeName.equals(sibling.getLocalName())
				&& EncryptionConstants.EncryptionSpecNS.equals(sibling.getNamespaceURI())) {
			if (number==0){
				return (Element)sibling;
			}
			number--;
		}
		sibling=sibling.getNextSibling();
	}
	return null;