001package org.hl7.fhir.utilities.xhtml;
002
003/*
004  Copyright (c) 2011+, HL7, Inc.
005  All rights reserved.
006  
007  Redistribution and use in source and binary forms, with or without modification, 
008  are permitted provided that the following conditions are met:
009    
010   * Redistributions of source code must retain the above copyright notice, this 
011     list of conditions and the following disclaimer.
012   * Redistributions in binary form must reproduce the above copyright notice, 
013     this list of conditions and the following disclaimer in the documentation 
014     and/or other materials provided with the distribution.
015   * Neither the name of HL7 nor the names of its contributors may be used to 
016     endorse or promote products derived from this software without specific 
017     prior written permission.
018  
019  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
020  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
021  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
022  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
023  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
024  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
025  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
026  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
027  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
028  POSSIBILITY OF SUCH DAMAGE.
029  
030 */
031
032
033
034import java.io.IOException;
035import java.io.Serializable;
036import java.util.ArrayList;
037import java.util.HashMap;
038import java.util.List;
039import java.util.Map;
040
041import org.hl7.fhir.instance.model.api.IBaseXhtml;
042import org.hl7.fhir.utilities.Utilities;
043
044import ca.uhn.fhir.model.primitive.XhtmlDt;
045
046import static org.apache.commons.lang3.StringUtils.isNotBlank;
047
048@ca.uhn.fhir.model.api.annotation.DatatypeDef(name="xhtml")
049public class XhtmlNode implements IBaseXhtml {
050  private static final long serialVersionUID = -4362547161441436492L;
051
052
053  public static class Location implements Serializable {
054    private static final long serialVersionUID = -4079302502900219721L;
055    private int line;
056    private int column;
057    public Location(int line, int column) {
058      super();
059      this.line = line;
060      this.column = column;
061    }
062    public int getLine() {
063      return line;
064    }
065    public int getColumn() {
066      return column;
067    }
068    @Override
069    public String toString() {
070      return "Line "+Integer.toString(line)+", column "+Integer.toString(column);
071    }
072  }
073
074  public static final String NBSP = Character.toString((char)0xa0);
075  public static final String XMLNS = "http://www.w3.org/1999/xhtml";
076  private static final String DECL_XMLNS = " xmlns=\""+XMLNS+"\"";
077
078  private Location location;
079  private NodeType nodeType;
080  private String name;
081  private Map<String, String> attributes = new HashMap<String, String>();
082  private List<XhtmlNode> childNodes = new ArrayList<XhtmlNode>();
083  private String content;
084  private boolean notPretty;
085
086  public XhtmlNode() {
087    super();
088  }
089
090
091  public XhtmlNode(NodeType nodeType, String name) {
092    super();
093    this.nodeType = nodeType;
094    this.name = name;
095  }
096
097  public XhtmlNode(NodeType nodeType) {
098    super();
099    this.nodeType = nodeType;
100  }
101
102  public NodeType getNodeType() {
103    return nodeType;
104  }
105
106  public void setNodeType(NodeType nodeType) {
107    this.nodeType = nodeType;
108  }
109
110  public String getName() {
111    return name;
112  }
113
114  public XhtmlNode setName(String name) {
115    assert name.contains(":") == false : "Name should not contain any : but was " + name;
116    this.name = name;
117    return this;
118  }
119
120  public Map<String, String> getAttributes() {
121    return attributes;
122  }
123
124  public List<XhtmlNode> getChildNodes() {
125    return childNodes;
126  }
127
128  public String getContent() {
129    return content;
130  }
131
132  public XhtmlNode setContent(String content) {
133    if (!(nodeType != NodeType.Text || nodeType != NodeType.Comment)) 
134      throw new Error("Wrong node type");
135    this.content = content;
136    return this;
137  }
138
139  public XhtmlNode addTag(String name)
140  {
141
142    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) 
143      throw new Error("Wrong node type - node is "+nodeType.toString()+" ('"+getName()+"/"+getContent()+"')");
144    XhtmlNode node = new XhtmlNode(NodeType.Element);
145    node.setName(name);
146    childNodes.add(node);
147    return node;
148  }
149
150  public XhtmlNode addTag(int index, String name)
151  {
152
153    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) 
154      throw new Error("Wrong node type. is "+nodeType.toString());
155    XhtmlNode node = new XhtmlNode(NodeType.Element);
156    node.setName(name);
157    childNodes.add(index, node);
158    return node;
159  }
160
161  public XhtmlNode addComment(String content)
162  {
163    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) 
164      throw new Error("Wrong node type");
165    XhtmlNode node = new XhtmlNode(NodeType.Comment);
166    node.setContent(content);
167    childNodes.add(node);
168    return node;
169  }
170
171  public XhtmlNode addDocType(String content)
172  {
173    if (!(nodeType == NodeType.Document)) 
174      throw new Error("Wrong node type");
175    XhtmlNode node = new XhtmlNode(NodeType.DocType);
176    node.setContent(content);
177    childNodes.add(node);
178    return node;
179  }
180
181  public XhtmlNode addInstruction(String content)
182  {
183    if (!(nodeType == NodeType.Document)) 
184      throw new Error("Wrong node type");
185    XhtmlNode node = new XhtmlNode(NodeType.Instruction);
186    node.setContent(content);
187    childNodes.add(node);
188    return node;
189  }
190
191  public XhtmlNode addText(String content)
192  {
193    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) 
194      throw new Error("Wrong node type");
195    if (content != null) {
196      XhtmlNode node = new XhtmlNode(NodeType.Text);
197      node.setContent(content);
198      childNodes.add(node);
199      return node;
200    } else 
201      return null;
202  }
203
204  public XhtmlNode addText(int index, String content)
205  {
206    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) 
207      throw new Error("Wrong node type");
208    if (content == null)
209      throw new Error("Content cannot be null");
210
211    XhtmlNode node = new XhtmlNode(NodeType.Text);
212    node.setContent(content);
213    childNodes.add(index, node);
214    return node;
215  }
216
217  public boolean allChildrenAreText()
218  {
219    boolean res = true;
220    for (XhtmlNode n : childNodes)
221      res = res && n.getNodeType() == NodeType.Text;
222    return res;
223  }
224
225  public XhtmlNode getElement(String name) {
226    for (XhtmlNode n : childNodes)
227      if (n.getNodeType() == NodeType.Element && name.equals(n.getName())) 
228        return n;
229    return null;
230  }
231
232  public XhtmlNode getFirstElement() {
233    for (XhtmlNode n : childNodes)
234      if (n.getNodeType() == NodeType.Element) 
235        return n;
236    return null;
237  }
238
239  public String allText() {
240    if (childNodes == null || childNodes.isEmpty())
241      return getContent();
242    
243    StringBuilder b = new StringBuilder();
244    for (XhtmlNode n : childNodes)
245      if (n.getNodeType() == NodeType.Text)
246        b.append(n.getContent());
247      else if (n.getNodeType() == NodeType.Element)
248        b.append(n.allText());
249    return b.toString();
250  }
251
252  public XhtmlNode attribute(String name, String value) {
253    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) 
254      throw new Error("Wrong node type");
255    if (name == null)
256      throw new Error("name is null");
257    if (value == null)
258      throw new Error("value is null");
259    attributes.put(name, value);
260    return this;
261  }
262
263  public boolean hasAttribute(String name) {
264    return getAttributes().containsKey(name);
265  }
266
267  public String getAttribute(String name) {
268    return getAttributes().get(name);
269  }
270
271  public XhtmlNode setAttribute(String name, String value) {
272    if (nodeType != NodeType.Element) {
273      throw new Error("Attempt to set an attribute on something that is not an element");
274    }
275    getAttributes().put(name, value);
276    return this;    
277  }
278
279  public XhtmlNode copy() {
280    XhtmlNode dst = new XhtmlNode(nodeType);
281    dst.name = name;
282    for (String n : attributes.keySet()) {
283      dst.attributes.put(n, attributes.get(n));
284    }
285    for (XhtmlNode n : childNodes)
286      dst.childNodes.add(n.copy());
287    dst.content = content;
288    return dst;
289  }
290
291  @Override
292  public boolean isEmpty() {
293    return (childNodes == null || childNodes.isEmpty()) && content == null;
294  }
295
296  public boolean equalsDeep(XhtmlNode other) {
297    if (other == null) {
298      return false;
299    }
300
301    if (!(nodeType == other.nodeType) || !compare(name, other.name) || !compare(content, other.content))
302      return false;
303    if (attributes.size() != other.attributes.size())
304      return false;
305    for (String an : attributes.keySet())
306      if (!attributes.get(an).equals(other.attributes.get(an)))
307        return false;
308    if (childNodes.size() != other.childNodes.size())
309      return false;
310    for (int i = 0; i < childNodes.size(); i++) {
311      if (!compareDeep(childNodes.get(i), other.childNodes.get(i)))
312        return false;
313    }
314    return true;
315  }
316
317  private boolean compare(String s1, String s2) {
318    if (s1 == null && s2 == null)
319      return true;
320    if (s1 == null || s2 == null)
321      return false;
322    return s1.equals(s2);
323  }
324
325  private static boolean compareDeep(XhtmlNode e1, XhtmlNode e2) {
326    if (e1 == null && e2 == null)
327      return true;
328    if (e1 == null || e2 == null)
329      return false;
330    return e1.equalsDeep(e2);
331  }
332
333  public String getNsDecl() {
334    for (String an : attributes.keySet()) {
335      if (an.equals("xmlns")) {
336        return attributes.get(an);
337      }
338    }
339    return null;
340  }
341
342
343  @Override
344  public String getValueAsString() {
345    if (isEmpty()) {
346      return null;
347    }
348    try {
349      String retVal = new XhtmlComposer(XhtmlComposer.XML).compose(this);
350      retVal = XhtmlDt.preprocessXhtmlNamespaceDeclaration(retVal);
351      return retVal;
352    } catch (Exception e) {
353      // TODO: composer shouldn't throw exception like this
354      throw new RuntimeException(e);
355    }
356  }
357
358  @Override
359  public void setValueAsString(String theValue) throws IllegalArgumentException {
360    this.attributes = null;
361    this.childNodes = null;
362    this.content = null;
363    this.name = null;
364    this.nodeType= null;
365    if (theValue == null || theValue.length() == 0) {
366      return;
367    }
368
369    String val = theValue.trim();
370
371    if (!val.startsWith("<")) {
372      val = "<div" + DECL_XMLNS +">" + val + "</div>";
373    }
374    if (val.startsWith("<?") && val.endsWith("?>")) {
375      return;
376    }
377
378    val = XhtmlDt.preprocessXhtmlNamespaceDeclaration(val);
379
380    try {
381      XhtmlDocument fragment = new XhtmlParser().parse(val, "div");
382      this.attributes = fragment.getAttributes();
383      this.childNodes = fragment.getChildNodes();
384      // Strip the <? .. ?> declaration if one was present
385      if (childNodes.size() > 0 && childNodes.get(0) != null && childNodes.get(0).getNodeType() == NodeType.Instruction) {
386        childNodes.remove(0);
387      }
388      this.content = fragment.getContent();
389      this.name = fragment.getName();
390      this.nodeType= fragment.getNodeType();
391    } catch (Exception e) {
392      // TODO: composer shouldn't throw exception like this
393      throw new RuntimeException(e);
394    }
395
396  }
397
398  public XhtmlNode getElementByIndex(int i) {
399    int c = 0;
400    for (XhtmlNode n : childNodes)
401      if (n.getNodeType() == NodeType.Element) {
402        if (c == i)
403          return n;
404        else
405          c++;
406      }
407    return null;
408  }
409
410  @Override
411  public String getValue() {
412    return getValueAsString();
413  }
414
415  public boolean hasValue() {
416    return isNotBlank(getValueAsString());
417  }
418
419  @Override
420  public XhtmlNode setValue(String theValue) throws IllegalArgumentException {
421    setValueAsString(theValue);
422    return this;
423  }
424
425  /**
426   * Returns false
427   */
428  public boolean hasFormatComment() {
429    return false;
430  }
431
432  /**
433   * NOT SUPPORTED - Throws {@link UnsupportedOperationException}
434   */
435  public List<String> getFormatCommentsPre() {
436    throw new UnsupportedOperationException();
437  }
438
439  /**
440   * NOT SUPPORTED - Throws {@link UnsupportedOperationException}
441   */
442  public List<String> getFormatCommentsPost() {
443    throw new UnsupportedOperationException();
444  }
445
446  /**
447   * NOT SUPPORTED - Throws {@link UnsupportedOperationException}
448   */
449  public Object getUserData(String theName) {
450    throw new UnsupportedOperationException();
451  }
452
453  /**
454   * NOT SUPPORTED - Throws {@link UnsupportedOperationException}
455   */
456  public void setUserData(String theName, Object theValue) {
457    throw new UnsupportedOperationException();
458  }
459
460
461  public Location getLocation() {
462    return location;
463  }
464
465
466  public void setLocation(Location location) {
467    this.location = location;
468  }
469
470  // xhtml easy adders -----------------------------------------------
471  public XhtmlNode h1() {
472    return addTag("h1");
473  }
474  
475  public XhtmlNode h2() {
476    return addTag("h2");
477  }
478  
479  public XhtmlNode h3() {
480    return addTag("h3");
481  }
482  
483  public XhtmlNode h4() {
484    return addTag("h4");
485  }
486  
487  public XhtmlNode table(String clss) {
488    XhtmlNode res = addTag("table");
489    if (!Utilities.noString(clss))
490      res.setAttribute("class", clss);
491    return res;
492  }
493  
494  public XhtmlNode tr() {
495    return addTag("tr");
496  }
497  
498  public XhtmlNode th() {
499    return addTag("th");
500  }
501  
502  public XhtmlNode td() {
503    return addTag("td");
504  }
505  
506  public XhtmlNode td(String clss) {
507    return addTag("td").attribute("class", clss);
508  }
509  
510  public XhtmlNode colspan(String n) {
511    return setAttribute("colspan", n);
512  }
513  
514  public XhtmlNode div() {
515    return addTag("div");
516  }
517
518  public XhtmlNode para() {
519    return addTag("p");
520  }
521
522  public XhtmlNode pre() {
523    return addTag("pre");
524  }
525
526  public void br() {
527    addTag("br");
528  }
529
530  public void hr() {
531    addTag("hr");
532  }
533
534  public XhtmlNode ul() {
535    return addTag("ul");
536  }
537
538  public XhtmlNode li() {
539    return addTag("li");
540  }
541
542  public XhtmlNode b() {
543    return addTag("b");
544  }
545
546  public XhtmlNode i() {
547    return addTag("i");
548  }
549  
550  public XhtmlNode tx(String cnt) {
551    return addText(cnt);
552  }
553
554  public XhtmlNode tx(int cnt) {
555    return addText(Integer.toString(cnt));
556  }
557
558  public XhtmlNode ah(String href) {
559    return addTag("a").attribute("href", href);
560  }
561
562  public XhtmlNode ah(String href, String title) {
563    return addTag("a").attribute("href", href).attribute("title", title);
564  }
565
566  public XhtmlNode img(String src) {
567    return addTag("img").attribute("src", src);    
568  }
569
570  public XhtmlNode img(String src, String title) {
571    return addTag("img").attribute("src", src).attribute("title", title);    
572  }
573
574  public XhtmlNode an(String href) {
575    return an(href, " ");
576  }
577  
578  public XhtmlNode an(String href, String tx) {
579    XhtmlNode a = addTag("a").attribute("name", href);
580    a.tx(tx);
581    return a;
582  }
583
584  public XhtmlNode span(String style, String title) {
585    XhtmlNode res = addTag("span");
586    if (!Utilities.noString(style))
587      res.attribute("style", style);
588    if (!Utilities.noString(title))
589      res.attribute("title", title);
590    return res;
591  }
592
593
594  public XhtmlNode code(String text) {
595    return addTag("code").tx(text);
596  }
597
598  public XhtmlNode code() {
599    return addTag("code");
600  }
601
602
603  public XhtmlNode blockquote() {
604    return addTag("blockquote");
605  }
606
607
608  @Override
609  public String toString() {
610    switch (nodeType) {
611    case Document: 
612    case Element:
613      try {
614        return new XhtmlComposer(XhtmlComposer.HTML).compose(this);
615      } catch (IOException e) {
616        return super.toString();
617      }
618    case Text:
619      return this.content;
620    case Comment:
621      return "<!-- "+this.content+" -->";
622    case DocType: 
623      return "<? "+this.content+" />";
624    case Instruction:
625      return "<? "+this.content+" />";
626    }
627    return super.toString();
628  }
629
630
631  public XhtmlNode getNextElement(XhtmlNode c) {
632    boolean f = false;
633    for (XhtmlNode n : childNodes) {
634      if (n == c)
635        f = true;
636      else if (f && n.getNodeType() == NodeType.Element) 
637        return n;
638    }
639    return null;
640  }
641
642
643  public XhtmlNode notPretty() {
644    notPretty = true;
645    return this;
646  }
647
648
649  public boolean isNoPretty() {
650    return notPretty;
651  }
652
653
654  public XhtmlNode style(String style) {
655    if (hasAttribute("style")) {
656      setAttribute("style", getAttribute("style")+"; "+style);
657    } else {
658      setAttribute("style", style);
659    }
660    return this;
661  }
662
663
664  public XhtmlNode nbsp() {
665    return addText(NBSP);    
666  }
667
668
669  public XhtmlNode para(String text) {
670    XhtmlNode p = para();
671    p.addText(text);
672    return p;
673    
674  }
675
676  public XhtmlNode add(XhtmlNode n) {
677    getChildNodes().add(n);
678    return this;
679  }
680
681
682  public XhtmlNode addChildren(List<XhtmlNode> children) {
683    getChildNodes().addAll(children);
684    return this;
685  }
686
687  public XhtmlNode addChildren(XhtmlNode x) {
688    if (x != null) {
689      getChildNodes().addAll(x.getChildNodes());
690    }
691    return this;
692  }
693
694
695  public XhtmlNode input(String name, String type, String placeholder, int size) {
696    XhtmlNode p = new XhtmlNode(NodeType.Element, "input");
697    p.attribute("name", name);
698    p.attribute("type", type);
699    p.attribute("placeholder", placeholder);
700    p.attribute("size", Integer.toString(size));
701    getChildNodes().add(p);
702    return p;
703  }
704
705  public XhtmlNode select(String name) {
706    XhtmlNode p = new XhtmlNode(NodeType.Element, "select");
707    p.attribute("name", name);
708    p.attribute("size", "1");
709    getChildNodes().add(p);
710    return p;
711  }
712  
713  public XhtmlNode option(String value, String text, boolean selected) {
714    XhtmlNode p = new XhtmlNode(NodeType.Element, "option");
715    p.attribute("value", value);
716    p.attribute("selected", Boolean.toString(selected));
717    p.tx(text);
718    getChildNodes().add(p);
719    return p;
720  }
721
722
723  public XhtmlNode remove(XhtmlNode x) {
724    getChildNodes().remove(x);
725    return this;
726    
727  }
728
729
730  public void clear() {
731    getChildNodes().clear();
732    
733  }
734
735
736  
737
738  
739  
740}