]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/gcr/xml/DomContent.java
19bae2d87797045a4c6a88200a3a2a34f3ae32d0
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / gcr / xml / DomContent.java
1 package org.argeo.cms.gcr.xml;
2
3 import java.util.HashSet;
4 import java.util.Iterator;
5 import java.util.Set;
6
7 import org.argeo.api.gcr.AbstractContent;
8 import org.argeo.api.gcr.Content;
9 import org.argeo.api.gcr.ContentSession;
10 import org.w3c.dom.Attr;
11 import org.w3c.dom.Element;
12 import org.w3c.dom.NamedNodeMap;
13 import org.w3c.dom.Node;
14 import org.w3c.dom.NodeList;
15 import org.w3c.dom.Text;
16
17 public class DomContent extends AbstractContent implements Content {
18
19 private final DomContentSession contentSession;
20 private final Element element;
21
22 // private String text = null;
23 private Boolean hasText = null;
24
25 public DomContent(DomContentSession contentSession, Element element) {
26 this.contentSession = contentSession;
27 this.element = element;
28 }
29
30 @Override
31 public Iterator<Content> iterator() {
32 NodeList nodeList = element.getChildNodes();
33 return new ElementIterator(contentSession, nodeList);
34 }
35
36 @Override
37 public String getName() {
38 return element.getNodeName();
39 }
40
41 @Override
42 public Iterable<String> keys() {
43 // TODO implement an iterator?
44 Set<String> result = new HashSet<>();
45 NamedNodeMap attributes = element.getAttributes();
46 for (int i = 0; i < attributes.getLength(); i++) {
47 Attr attr = (Attr) attributes.item(i);
48 String attrName = attr.getNodeName();
49 result.add(attrName);
50 }
51 return result;
52 }
53
54 @Override
55 public <A> A get(String key, Class<A> clss) {
56 if (element.hasAttribute(key)) {
57 String value = element.getAttribute(key);
58 if (clss.isAssignableFrom(String.class))
59 return (A) value;
60 else
61 throw new IllegalArgumentException();
62 } else
63 return null;
64 }
65
66 @Override
67 public ContentSession getSession() {
68 return contentSession;
69 }
70
71 @Override
72 public boolean hasText() {
73 // return element instanceof Text;
74 if (hasText != null)
75 return hasText;
76 NodeList nodeList = element.getChildNodes();
77 if (nodeList.getLength() > 1) {
78 hasText = false;
79 return hasText;
80 }
81 nodes: for (int i = 0; i < nodeList.getLength(); i++) {
82 Node node = nodeList.item(i);
83 if (node instanceof Text) {
84 Text text =(Text) node;
85 if (!text.isElementContentWhitespace()) {
86 hasText = true;
87 break nodes;
88 }
89 }
90 }
91 if (hasText == null)
92 hasText = false;
93 return hasText;
94 // if (text != null)
95 // return true;
96 // text = element.getTextContent();
97 // return text != null;
98 }
99
100 @Override
101 public String getText() {
102 if (hasText())
103 return element.getTextContent();
104 else
105 return null;
106 }
107
108 }