Attachment 'NamespaceStripperTransformer.java'

Download

   1 /*
   2 
   3  ============================================================================
   4                    The Apache Software License, Version 1.1
   5  ============================================================================
   6 
   7  Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
   8 
   9  Redistribution and use in source and binary forms, with or without modifica-
  10  tion, are permitted provided that the following conditions are met:
  11 
  12  1. Redistributions of  source code must  retain the above copyright  notice,
  13     this list of conditions and the following disclaimer.
  14 
  15  2. Redistributions in binary form must reproduce the above copyright notice,
  16     this list of conditions and the following disclaimer in the documentation
  17     and/or other materials provided with the distribution.
  18 
  19  3. The end-user documentation included with the redistribution, if any, must
  20     include  the following  acknowledgment:  "This product includes  software
  21     developed  by the  Apache Software Foundation  (http://www.apache.org/)."
  22     Alternately, this  acknowledgment may  appear in the software itself,  if
  23     and wherever such third-party acknowledgments normally appear.
  24 
  25  4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
  26     used to  endorse or promote  products derived from  this software without
  27     prior written permission. For written permission, please contact
  28     apache@apache.org.
  29 
  30  5. Products  derived from this software may not  be called "Apache", nor may
  31     "Apache" appear  in their name,  without prior written permission  of the
  32     Apache Software Foundation.
  33 
  34  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  35  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  36  FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
  37  APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
  38  INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
  39  DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
  40  OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
  41  ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
  42  (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
  43  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44 
  45  This software  consists of voluntary contributions made  by many individuals
  46  on  behalf of the Apache Software  Foundation and was  originally created by
  47  Stefano Mazzocchi  <stefano@apache.org>. For more  information on the Apache
  48  Software Foundation, please see <http://www.apache.org/>.
  49 
  50 */
  51 package org.apache.cocoon.transformation;
  52 
  53 import java.util.HashMap;
  54 import java.util.HashSet;
  55 import java.util.Iterator;
  56 import java.util.Set;
  57 
  58 import org.w3c.dom.Attr;
  59 import org.w3c.dom.DOMException;
  60 import org.w3c.dom.Document;
  61 import org.w3c.dom.Element;
  62 import org.w3c.dom.NamedNodeMap;
  63 import org.w3c.dom.Node;
  64 
  65 /**
  66  * This transformer, strips all unused namespaces from documents.
  67  * NOTE: Yes, this uses DOM, but when using SAX, we would have to simulate
  68  * something like DOM. When using SAX, we haven't access to the previous elements.
  69  * The result is, that we could only move the namespace declarations up to a point
  70  * where they are used and "loose" them, when there aren't more child nodes. But
  71  * this would make documents not valid against their DTD. Mostly the position for the
  72  * namespace declarations can't be changed. This is why we need DOM.
  73  * NOTE: Like most others, I consider this a hack class. The better way would be an
  74  * option in the HTML and XML serializers, to remove unused and according to the
  75  * DTD or XML Scheme not allowed namespaces. There is a 
  76  * <a href="http://nagoya.apache.org/bugzilla/showvotes.cgi?bug_id=19933">
  77  * discussion in the xalan BTS</a> about the problem.
  78  *
  79  * @author <a href="mailto:tk-cocoon@datas-world.de">Torsten Knodt</a>
  80  * @version CVS $Id: 
  81  */
  82 public class NamespaceStripperTransformer extends AbstractDOMTransformer {
  83 
  84     /**
  85      * DFS traversation for one node returning a list of used namespaces
  86      * and deletion of own unused namespaces.
  87      * @param node is the Node to traverse
  88      * @return a list of used namespaces
  89      */
  90     private HashMap traverse(final Node node) {
  91         final HashMap list = new HashMap();
  92 
  93         // Put own namespace into hash
  94         list.put(node.getPrefix(), node.getNamespaceURI());
  95 
  96         // Include namespaces of child nodes
  97         for (Node mynode = node.getFirstChild();
  98             mynode != null;
  99             mynode = mynode.getNextSibling())
 100             list.putAll(traverse(mynode));
 101 
 102         // Delete unused namespaces and remove local (beginning with us) ones
 103         final NamedNodeMap map = node.getAttributes();
 104         if (map != null) {
 105             final Set dellist = new HashSet();
 106             for (int i = 0; i < map.getLength(); i++) {
 107                 final Attr att = (Attr) map.item(i);
 108                 final String attPrefix = att.getPrefix();
 109                 if (attPrefix == null)
 110                     continue;
 111                 if (!attPrefix.equals("xmlns"))
 112                     continue;
 113                 final String URI = (String) list.get(att.getLocalName());
 114                 if (URI != null)
 115                     if (URI.equals(att.getValue()))
 116                         list.remove(att.getLocalName());
 117                     else
 118                         dellist.add(att);
 119                 else
 120                     dellist.add(att);
 121             }
 122 
 123             // Iterating through list of attributes to delete and deleting them
 124             final Iterator i = dellist.iterator();
 125             while (i.hasNext()) {
 126                 final Attr att = (Attr) i.next();
 127                 i.remove();
 128                 boolean mode = false;
 129                 String l =
 130                     "Removing namespace prefix "
 131                         + att.getLocalName()
 132                         + " assigned to URI "
 133                         + att.getValue();
 134                 try {
 135                     ((Element) node).removeAttributeNode(att);
 136                 } catch (DOMException e) {
 137                     mode = true;
 138                 } finally {
 139                     if (mode)
 140                         if (getLogger().isErrorEnabled())
 141                             getLogger().error(l + " failed");
 142                         else if (getLogger().isInfoEnabled())
 143                             getLogger().info(l);
 144                 }
 145             }
 146         }
 147 
 148         // Return list of non-local used namespaces
 149         return list;
 150     }
 151 
 152     /**
 153      * Transform the specified DOM, returning a new DOM without unused
 154      * namespaces to stream down the pipeline.
 155      * @param doc The DOM Document representing the SAX stream
 156      * @return A DOM Document without unsed namespaces to stream down the
 157      * pipeline
 158      */
 159     protected Document transform(final Document doc) {
 160         final HashMap NSList = traverse(doc.getDocumentElement());
 161         return doc;
 162     }
 163 
 164 }

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.
  • [get | view] (2005-03-22 06:03:41, 6.9 KB) [[attachment:NamespaceStripperTransformer.java]]
  • [get | view] (2005-03-22 06:03:41, 11.0 KB) [[attachment:OmitNsTransformer.java]]
 All files | Selected Files: delete move to page

You are not allowed to attach a file to this page.