1 23 24 package org.enhydra.xml.lazydom; 25 26 import java.util.ArrayList ; 27 import java.util.HashMap ; 28 29 import org.enhydra.xml.dom.SimpleDOMTraversal; 30 import org.w3c.dom.Document ; 31 import org.w3c.dom.DocumentType ; 32 import org.w3c.dom.Node ; 33 34 38 public class NodeIdMap { 39 42 private HashMap fNodeIdMap = new HashMap (); 43 44 47 private ArrayList fIdNodeMap = new ArrayList (); 48 49 52 public NodeIdMap(Document document) { 53 buildNodeIdMap(document); 54 } 55 56 59 private void buildNodeIdMap(Document document) { 60 SimpleDOMTraversal traverser 61 = new SimpleDOMTraversal(new SimpleDOMTraversal.Handler() { 62 public void handleNode(Node node) { 63 put(node); 64 } 65 }); 66 traverser.traverse(document); 67 if (fIdNodeMap.get(LazyNode.DOCUMENT_NODE_ID) != document) { 68 throw new LazyDOMError("document assigned wrong id"); 69 } 70 } 71 72 75 private void put(Node node) { 76 int nodeId = fIdNodeMap.size(); 77 fNodeIdMap.put(node, new Integer (nodeId)); 78 fIdNodeMap.add(node); 79 } 80 81 84 public Node getNode(int id) { 85 return (Node )fIdNodeMap.get(id); 86 } 87 88 92 public int getId(Node node) { 93 if (node == null) { 94 return LazyNode.NULL_NODE_ID; 95 } 96 Integer id = (Integer )fNodeIdMap.get(node); 97 if (id == null) { 98 throw new LazyDOMError("Id not found for node: " + node 99 + ": " + node.getClass()); 100 } 101 return id.intValue(); 102 } 103 104 107 public String getIdStr(Node node) { 108 return Integer.toString(getId(node)); 109 } 110 111 114 public int getMaxNodeId() { 115 return fIdNodeMap.size()-1; 116 } 117 118 121 public int size() { 122 return fIdNodeMap.size(); 123 } 124 125 128 public int getDocumentTypeNodeId(Node node) { 129 Document document = node.getOwnerDocument(); 130 if (document == null) { 131 document = (Document )node; 132 } 133 DocumentType documentType = document.getDoctype(); 134 if (documentType == null) { 135 return LazyNode.NULL_NODE_ID; 136 } else { 137 return getId(documentType); 138 } 139 } 140 } 141 | Popular Tags |