| 1 | package dolda.jsvc.next; |
| 2 | |
| 3 | import java.util.*; |
| 4 | import org.w3c.dom.*; |
| 5 | |
| 6 | public class DocBuffer { |
| 7 | public final Document doc; |
| 8 | private final Map<String, Node> cursors = new HashMap<String, Node>(); |
| 9 | public static final String ns = "jsvc:next:buffer"; |
| 10 | |
| 11 | public DocBuffer(String ns, String root, String doctype, String pubid, String sysid) { |
| 12 | doc = DomUtil.document(ns, root, doctype, pubid, sysid); |
| 13 | } |
| 14 | |
| 15 | public DocBuffer(String ns, String root) { |
| 16 | this(ns, root, null, null, null); |
| 17 | } |
| 18 | |
| 19 | private Node findcursor(Node c, String name) { |
| 20 | if(c instanceof Element) { |
| 21 | Element el = (Element)c; |
| 22 | if(el.getNamespaceURI().equals(ns) && el.getTagName().equals("cursor") && el.getAttributeNS(ns, "name").equals(name)) |
| 23 | return(c); |
| 24 | } |
| 25 | for(Node n = c.getFirstChild(); n != null; n = n.getNextSibling()) { |
| 26 | Node r = findcursor(n, name); |
| 27 | if(r != null) |
| 28 | return(r); |
| 29 | } |
| 30 | return(null); |
| 31 | } |
| 32 | |
| 33 | private Node cursor(String name) { |
| 34 | Node n; |
| 35 | if((n = cursors.get(name)) != null) { |
| 36 | return(n); |
| 37 | } |
| 38 | if((n = findcursor(doc, name)) == null) |
| 39 | return(null); |
| 40 | cursors.put(name, n); |
| 41 | return(n); |
| 42 | } |
| 43 | |
| 44 | public void insert(String cursor, Node n) { |
| 45 | Node c = cursor(cursor); |
| 46 | if(c == null) |
| 47 | throw(new RuntimeException("No such cursor: `" + cursor + "'")); |
| 48 | c.getParentNode().insertBefore(c, doc.importNode(n, true)); |
| 49 | } |
| 50 | |
| 51 | public Element makecursor(String name) { |
| 52 | Element el = doc.createElementNS(ns, "cursor"); |
| 53 | Attr a = doc.createAttributeNS(ns, "name"); |
| 54 | a.setValue(name); |
| 55 | el.setAttributeNodeNS(a); |
| 56 | return(el); |
| 57 | } |
| 58 | |
| 59 | public Element el(String ns, String nm, Node contents, String... attrs) { |
| 60 | Element el = doc.createElementNS(ns, nm); |
| 61 | if(contents != null) |
| 62 | el.appendChild(contents); |
| 63 | for(String attr : attrs) { |
| 64 | int p = attr.indexOf('='); |
| 65 | el.setAttribute(attr.substring(0, p), attr.substring(p + 1)); |
| 66 | } |
| 67 | return(el); |
| 68 | } |
| 69 | |
| 70 | public Text text(String text) { |
| 71 | return(doc.createTextNode(text)); |
| 72 | } |
| 73 | } |