DocBuffer.asnode: Convert null properly.
[jsvc.git] / src / dolda / jsvc / next / DocBuffer.java
index 432d817..b936c0a 100644 (file)
@@ -19,7 +19,8 @@ public class DocBuffer {
     private Node findcursor(Node c, String name) {
        if(c instanceof Element) {
            Element el = (Element)c;
-           if(el.getNamespaceURI().equals(ns) && el.getTagName().equals("cursor") && el.getAttributeNS(ns, "name").equals(name))
+           String ns = el.getNamespaceURI();
+           if((ns != null) && ns.equals(DocBuffer.ns) && el.getTagName().equals("cursor") && el.getAttributeNS(null, "name").equals(name))
                return(c);
        }
        for(Node n = c.getFirstChild(); n != null; n = n.getNextSibling()) {
@@ -45,12 +46,14 @@ public class DocBuffer {
        Node c = cursor(cursor);
        if(c == null)
            throw(new RuntimeException("No such cursor: `" + cursor + "'"));
-       c.getParentNode().insertBefore(c, doc.importNode(n, true));
+       if(n.getOwnerDocument() != doc)
+           n = doc.importNode(n, true);
+       c.getParentNode().insertBefore(n, c);
     }
     
     public Element makecursor(String name) {
        Element el = doc.createElementNS(ns, "cursor");
-       Attr a = doc.createAttributeNS(ns, "name");
+       Attr a = doc.createAttributeNS(null, "name");
        a.setValue(name);
        el.setAttributeNodeNS(a);
        return(el);
@@ -68,6 +71,48 @@ public class DocBuffer {
     }
     
     public Text text(String text) {
+       if(text == null)
+           return(null);
        return(doc.createTextNode(text));
     }
+    
+    public Node asnode(Object o) {
+       if(o == null)
+           return(text(""));
+       if(o instanceof Node) {
+           Node n = (Node)o;
+           if(n.getOwnerDocument() != doc)
+               return(doc.importNode(n, true));
+           return(n);
+       }
+       if(o instanceof String)
+           return(text((String)o));
+       throw(new RuntimeException("Cannot convert a " + o.getClass().getName() + " to a DOM node"));
+    }
+    
+    public void finalise() {
+       Node n = doc;
+       while(true) {
+           Node nx;
+           if(n.getFirstChild() != null) {
+               nx = n.getFirstChild();
+           } else if(n.getNextSibling() != null) {
+               nx = n.getNextSibling();
+           } else {
+               for(nx = n.getParentNode(); nx != null; nx = nx.getParentNode()) {
+                   if(nx.getNextSibling() != null) {
+                       nx = nx.getNextSibling();
+                       break;
+                   }
+               }
+           }
+           String ns = n.getNamespaceURI();
+           if((ns != null) && ns.equals(DocBuffer.ns))
+               n.getParentNode().removeChild(n);
+           if(nx == null)
+               break;
+           else
+               n = nx;
+       }
+    }
 }