001package org.hl7.fhir.utilities.xhtml;
002
003import static org.apache.commons.lang3.StringUtils.isNotBlank;
004
005/*
006  Copyright (c) 2011+, HL7, Inc.
007  All rights reserved.
008  
009  Redistribution and use in source and binary forms, with or without modification, 
010  are permitted provided that the following conditions are met:
011    
012   * Redistributions of source code must retain the above copyright notice, this 
013     list of conditions and the following disclaimer.
014   * Redistributions in binary form must reproduce the above copyright notice, 
015     this list of conditions and the following disclaimer in the documentation 
016     and/or other materials provided with the distribution.
017   * Neither the name of HL7 nor the names of its contributors may be used to 
018     endorse or promote products derived from this software without specific 
019     prior written permission.
020  
021  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
022  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
023  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
024  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
025  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
026  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
027  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
028  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
029  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
030  POSSIBILITY OF SUCH DAMAGE.
031  
032 */
033
034
035
036import java.io.IOException;
037import java.io.Serializable;
038import java.util.ArrayList;
039import java.util.HashMap;
040import java.util.List;
041import java.util.Map;
042import java.util.Set;
043
044import org.hl7.fhir.exceptions.FHIRException;
045import org.hl7.fhir.instance.model.api.IBaseXhtml;
046import org.hl7.fhir.utilities.Utilities;
047
048import ca.uhn.fhir.model.primitive.XhtmlDt;
049
050@ca.uhn.fhir.model.api.annotation.DatatypeDef(name="xhtml")
051public class XhtmlNode extends XhtmlFluent implements IBaseXhtml {
052  private static final long serialVersionUID = -4362547161441436492L;
053
054  public static class Location implements Serializable {
055    private static final long serialVersionUID = -4079302502900219721L;
056    private int line;
057    private int column;
058    public Location(int line, int column) {
059      super();
060      this.line = line;
061      this.column = column;
062    }
063    public int getLine() {
064      return line;
065    }
066    public int getColumn() {
067      return column;
068    }
069    @Override
070    public String toString() {
071      return "Line "+Integer.toString(line)+", column "+Integer.toString(column);
072    }
073  }
074
075  private static boolean checkParaGeneral = false;
076  private boolean checkParaTree = false;
077  
078  public static final String NBSP = Character.toString((char)0xa0);
079  public static final String XMLNS = "http://www.w3.org/1999/xhtml";
080  private static final String DECL_XMLNS = " xmlns=\""+XMLNS+"\"";
081
082  private Location location;
083  private NodeType nodeType;
084  private String name;
085  protected Map<String, String> attributes;
086  protected XhtmlNodeList childNodes;
087  private String content;
088  private boolean notPretty;
089  private boolean seperated;  
090  private Boolean emptyExpanded;
091  private Map<String, XhtmlNode> namedParams;
092  private Map<String, String> namedParamValues;
093
094  public XhtmlNode() {
095    super();
096    checkParaTree = checkParaGeneral;
097  }
098
099
100  public XhtmlNode(NodeType nodeType, String name) {
101    super();
102    this.nodeType = nodeType;
103    this.name = name;
104  }
105
106  public XhtmlNode(NodeType nodeType) {
107    super();
108    this.nodeType = nodeType;
109  }
110
111  public NodeType getNodeType() {
112    return nodeType;
113  }
114
115  public void setNodeType(NodeType nodeType) {
116    this.nodeType = nodeType;
117  }
118
119  public String getName() {
120    return name;
121  }
122
123  public XhtmlNode setName(String name) {
124    assert name.contains(":") == false : "Name should not contain any : but was " + name;
125    if (checkParaTree && "p".equals(name)) {
126      isInPara = true;
127    }
128    this.name = name;
129    return this;
130  }
131
132  public boolean hasAttributes() {
133    return attributes != null && !attributes.isEmpty();
134  }
135  
136  public Map<String, String> getAttributes() {
137    if (attributes == null) {
138      attributes = new HashMap<String, String>();
139    }
140    return attributes;
141  }
142
143  public boolean hasChildren() {
144    return childNodes != null && !childNodes.isEmpty();
145  }
146
147
148  public XhtmlNodeList getChildNodes() {
149    if (childNodes == null) {
150      childNodes = new XhtmlNodeList();
151    }
152    return childNodes;
153  }
154
155  public String getContent() {
156    return content;
157  }
158
159  public XhtmlNode setContent(String content) {
160    if (!(nodeType != NodeType.Text || nodeType != NodeType.Comment)) 
161      throw new Error("Wrong node type");
162    this.content = content;
163    return this;
164  }
165
166  public void validate(List<String> errors, String path, boolean inResource, boolean inPara, boolean inLink) {
167    if (nodeType == NodeType.Element || nodeType == NodeType.Document) {
168      path = Utilities.noString(path) ? name : path+"/"+name;
169      if (inResource) {
170        if (!Utilities.existsInList(name, "p", "br", "div", "h1", "h2", "h3", "h4", "h5", "h6", "a", "span", "b", "em", "i", "strong",
171            "small", "big", "tt", "small", "dfn", "q", "var", "abbr", "acronym", "cite", "blockquote", "hr", "address", "bdo", "kbd", "q", "sub", "sup",
172            "ul", "ol", "li", "dl", "dt", "dd", "pre", "table", "caption", "colgroup", "col", "thead", "tr", "tfoot", "tbody", "th", "td",
173            "code", "samp", "img", "map", "area")) {
174          errors.add("Error at "+path+": Found "+name+" in a resource");          
175        }      
176        if (hasAttributes()) {
177          for (String an : attributes.keySet()) {
178            boolean ok = an.startsWith("xmlns") || Utilities.existsInList(an,
179                "title", "style", "class", "ID", "lang", "xml:lang", "dir", "accesskey", "tabindex",
180                // tables
181                "span", "width", "align", "valign", "char", "charoff", "abbr", "axis", "headers", "scope", "rowspan", "colspan") ||
182                Utilities.existsInList(name + "." + an, "a.href", "a.name", "img.src", "img.border", "div.xmlns", "blockquote.cite", "q.cite",
183                    "a.charset", "a.type", "a.name", "a.href", "a.hreflang", "a.rel", "a.rev", "a.shape", "a.coords", "img.src",
184                    "img.alt", "img.longdesc", "img.height", "img.width", "img.usemap", "img.ismap", "map.name", "area.shape",
185                    "area.coords", "area.href", "area.nohref", "area.alt", "table.summary", "table.width", "table.border",
186                    "table.frame", "table.rules", "table.cellspacing", "table.cellpadding", "pre.space", "td.nowrap"
187                    );
188            if (!ok)
189              errors.add("Error at "+path+": Found attribute "+name+"."+an+" in a resource");          
190          }
191        }
192      }
193      if (inPara && Utilities.existsInList(name, "div",  "blockquote", "table", "ol", "ul", "p")) {
194        errors.add("Error at "+path+": Found "+name+" inside an html paragraph");
195      }
196      if (inLink && Utilities.existsInList(name, "a")) {
197        errors.add("Error at "+path+": Found an <a> inside an <a> paragraph");
198      }
199
200      if (hasChildren()) {
201        if ("p".equals(name)) {
202          inPara = true;
203        }
204        if ("a".equals(name)) {
205          inLink = true;
206        }
207        for (XhtmlNode child : childNodes) {
208          child.validate(errors, path, inResource, inPara, inLink);
209        }
210      }
211    }
212  }
213  
214  private XhtmlNode makeTag(String name) {
215    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document))  {
216      throw new Error("Wrong node type - node is "+nodeType.toString()+" ('"+getName()+"/"+getContent()+"')");
217    }
218//  if (inPara && name.equals("p")) {
219//  throw new FHIRException("nested Para");
220//}
221//if (inLink && name.equals("a")) {
222//  throw new FHIRException("Nested Link");
223//}
224    XhtmlNode node = new XhtmlNode(NodeType.Element);
225    node.setName(name);
226    if (getChildNodes().isInPara() || name.equals("p")) {
227      node.getChildNodes().setInPara(true);
228    }
229    if (getChildNodes().isInLink() || name.equals("a")) {
230      node.getChildNodes().setInLink(true);
231    }
232    if (Utilities.existsInList(name, "b", "big", "i", "small", "tt", "abbr", "acronym", "cite", "code", "dfn", "em", "kbd", "strong", "samp", "var", "a", "bdo", "br", "img", "map", "object", "q", "script", "span", "sub", "sup", " button", "input", "label", "select", "textarea")) {
233      node.notPretty();
234    }        
235    return node;
236  }
237  
238  public XhtmlNode addTag(String name) {
239    XhtmlNode node = makeTag(name);
240    addChildNode(node);
241    return node;
242  }
243  
244  
245
246  public XhtmlNode addTag(int index, String name) {
247    XhtmlNode node = makeTag(name);
248    addChildNode(index, node);
249    return node;
250  }
251
252
253  public XhtmlNode addComment(String content) {
254    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) 
255      throw new Error("Wrong node type");
256    XhtmlNode node = new XhtmlNode(NodeType.Comment);
257    node.setContent(content);
258    addChildNode(node);
259    return node;
260  }
261
262  public XhtmlNode addDocType(String content) {
263    if (!(nodeType == NodeType.Document)) 
264      throw new Error("Wrong node type");
265    XhtmlNode node = new XhtmlNode(NodeType.DocType);
266    node.setContent(content);
267    addChildNode(node);
268    return node;
269  }
270
271  public XhtmlNode addInstruction(String content) {
272    if (!(nodeType == NodeType.Document)) 
273      throw new Error("Wrong node type");
274    XhtmlNode node = new XhtmlNode(NodeType.Instruction);
275    node.setContent(content);
276    addChildNode(node);
277    return node;
278  }
279  
280  public XhtmlNode addText(String content) {
281    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) 
282      throw new Error("Wrong node type");
283    if (content != null) {
284      XhtmlNode node = new XhtmlNode(NodeType.Text);
285      node.setContent(content);
286      addChildNode(node);
287      return node;
288    } else 
289      return null;
290  }
291
292  public XhtmlNode addText(int index, String content) {
293    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) 
294      throw new Error("Wrong node type");
295    if (content == null)
296      throw new Error("Content cannot be null");
297
298    XhtmlNode node = new XhtmlNode(NodeType.Text);
299    node.setContent(content);
300    addChildNode(index, node);
301    return node;
302  }
303
304  public boolean allChildrenAreText() {
305    boolean res = true;
306    if (hasChildren()) {
307      for (XhtmlNode n : childNodes)
308        res = res && n.getNodeType() == NodeType.Text;
309    }
310    return res;
311  }
312
313  public XhtmlNode getElement(String name) {
314    if (hasChildren()) {
315      for (XhtmlNode n : childNodes)
316        if (n.getNodeType() == NodeType.Element && name.equals(n.getName())) 
317          return n;
318    }
319    return null;
320  }
321
322  public XhtmlNode getFirstElement() {
323    if (hasChildren()) {
324      for (XhtmlNode n : childNodes)
325        if (n.getNodeType() == NodeType.Element) 
326          return n;
327    }
328    return null;
329  }
330
331  public String allText() {
332    if (!hasChildren()) {
333      if (getContent() == null) {
334        return "";
335      } else {
336        return getContent();
337      }
338    }
339    
340    StringBuilder b = new StringBuilder();
341    for (XhtmlNode n : childNodes) {
342      if (n.getNodeType() == NodeType.Element && Utilities.existsInList(n.getName(), "li")) {
343        b.append("* ");
344      }
345      if (n.getNodeType() == NodeType.Text) {
346        if (n.getContent() != null) {
347          b.append(n.getContent());
348        }
349      } 
350      if (n.getNodeType() == NodeType.Element) {
351        if (!Utilities.existsInList(n.getName(), "img")) {
352          b.append(n.allText());          
353        } else if (n.hasAttribute("alt")) {
354          b.append(n.getAttribute("alt"));
355        } else {
356          b.append("[image]");
357        }
358        if (Utilities.existsInList(n.getName(), "p", "div", "tr", "th", "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6")) {
359          b.append("\r\n");
360        } else if (Utilities.existsInList(n.getName(), "th", "td", "span")) {
361          b.append(" ");
362        }
363      }
364    }
365    return b.toString();
366  }
367
368  public XhtmlNode attribute(String name, String value) {
369    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) 
370      throw new Error("Wrong node type");
371    if (name == null)
372      throw new Error("name is null");
373    if (value == null)
374      throw new Error("value is null");
375    getAttributes().put(name, value);
376    return this;
377  }
378
379  public XhtmlNode attributeNN(String name, String value) {
380    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) 
381      throw new Error("Wrong node type");
382    if (name == null)
383      throw new Error("name is null");
384    if (value != null) {
385      getAttributes().put(name, value);
386    }
387    return this;
388  }
389
390  public boolean hasAttribute(String name) {
391    return hasAttributes() && getAttributes().containsKey(name);
392  }
393
394  public boolean hasAttribute(String name, String value) {
395    return hasAttributes() && getAttributes().containsKey(name) && value.equals(getAttributes().get(name));
396  }
397
398  public String getAttribute(String name) {
399    return hasAttributes() ? getAttributes().get(name) : null;
400  }
401
402  public XhtmlNode setAttribute(String name, String value) {
403    if (nodeType != NodeType.Element) {
404      throw new Error("Attempt to set an attribute on something that is not an element");
405    }
406    getAttributes().put(name, value);
407    return this;    
408  }
409
410  public XhtmlNode copy() {
411    XhtmlNode dst = new XhtmlNode(nodeType);
412    dst.name = name;
413    if (hasAttributes()) {
414      for (String n : attributes.keySet()) {
415        dst.getAttributes().put(n, attributes.get(n));
416      }
417    }
418    if (hasChildren()) {
419      for (XhtmlNode n : childNodes)
420        dst.addChildNode(n.copy());
421    }
422    dst.content = content;
423    return dst;
424  }
425
426  @Override
427  public boolean isEmpty() {
428    return !hasChildren() && content == null;
429  }
430
431  public boolean equalsDeep(XhtmlNode other) {
432    if (other == null) {
433      return false;
434    }
435
436    if (!(nodeType == other.nodeType) || !compare(name, other.name) || !compare(content, other.content))
437      return false;
438    if (hasAttributes() != other.hasAttributes()) {
439      return false;
440    }
441    if (hasAttributes()) {
442      if (attributes.size() != other.attributes.size())
443        return false;
444      for (String an : attributes.keySet())
445        if (!attributes.get(an).equals(other.attributes.get(an)))
446          return false;
447    }
448    if (hasChildren() != other.hasChildren()) {
449      return false;
450    }
451    if (hasChildren()) {
452      if (childNodes.size() != other.childNodes.size())
453        return false;
454      for (int i = 0; i < childNodes.size(); i++) {
455        if (!compareDeep(childNodes.get(i), other.childNodes.get(i)))
456          return false;
457      }
458    }
459    return true;
460  }
461
462  private boolean compare(String s1, String s2) {
463    if (s1 == null && s2 == null)
464      return true;
465    if (s1 == null || s2 == null)
466      return false;
467    return s1.equals(s2);
468  }
469
470  private static boolean compareDeep(XhtmlNode e1, XhtmlNode e2) {
471    if (e1 == null && e2 == null)
472      return true;
473    if (e1 == null || e2 == null)
474      return false;
475    return e1.equalsDeep(e2);
476  }
477
478  public String getNsDecl() {
479    if (hasAttributes()) {
480      for (String an : attributes.keySet()) {
481        if (an.equals("xmlns")) {
482          return attributes.get(an);
483        }
484      }
485    }
486    return null;
487  }
488
489
490  public Boolean getEmptyExpanded() {
491    return emptyExpanded;
492  }
493
494  public boolean hasEmptyExpanded() {
495    return emptyExpanded != null;
496  }
497
498  public void setEmptyExpanded(Boolean emptyExpanded) {
499    this.emptyExpanded = emptyExpanded;
500  }
501
502
503  @Override
504  public String getValueAsString() {
505    if (isEmpty()) {
506      return null;
507    }
508    try {
509      String retVal = new XhtmlComposer(XhtmlComposer.XML).compose(this);
510      retVal = XhtmlDt.preprocessXhtmlNamespaceDeclaration(retVal);
511      return retVal;
512    } catch (Exception e) {
513      // TODO: composer shouldn't throw exception like this
514      throw new RuntimeException(e);
515    }
516  }
517
518  @Override
519  public void setValueAsString(String theValue) throws IllegalArgumentException {
520    this.attributes = null;
521    this.childNodes = null;
522    this.content = null;
523    this.name = null;
524    this.nodeType= null;
525    if (theValue == null || theValue.length() == 0) {
526      return;
527    }
528
529    String val = theValue.trim();
530
531    if (!val.startsWith("<")) {
532      val = "<div" + DECL_XMLNS +">" + val + "</div>";
533    }
534    if (val.startsWith("<?") && val.endsWith("?>")) {
535      return;
536    }
537
538    val = XhtmlDt.preprocessXhtmlNamespaceDeclaration(val);
539
540    try {
541      XhtmlDocument fragment = new XhtmlParser().parse(val, "div");
542      // Skip the <? .. ?> declaration if one was present
543      XhtmlNodeList nodes = fragment.getChildNodes();
544      XhtmlNode root = nodes.get((nodes.size() > 0 && nodes.get(0) != null && nodes.get(0).getNodeType() == NodeType.Instruction)  ? 1 : 0);
545      this.attributes = root.attributes;
546      this.childNodes = root.childNodes;
547      this.content = root.getContent();
548      this.name = root.getName();
549      this.nodeType= root.getNodeType();
550    } catch (Exception e) {
551      // TODO: composer shouldn't throw exception like this
552      throw new RuntimeException(e);
553    }
554  }
555
556  public XhtmlNode getElementByIndex(int i) {
557    int c = 0;
558    for (XhtmlNode n : childNodes)
559      if (n.getNodeType() == NodeType.Element) {
560        if (c == i)
561          return n;
562        else
563          c++;
564      }
565    return null;
566  }
567
568  @Override
569  public String getValue() {
570    return getValueAsString();
571  }
572
573  public boolean hasValue() {
574    return isNotBlank(getValueAsString());
575  }
576
577  @Override
578  public XhtmlNode setValue(String theValue) throws IllegalArgumentException {
579    setValueAsString(theValue);
580    return this;
581  }
582
583  /**
584   * Returns false
585   */
586  public boolean hasFormatComment() {
587    return false;
588  }
589
590  /**
591   * NOT SUPPORTED - Throws {@link UnsupportedOperationException}
592   */
593  public List<String> getFormatCommentsPre() {
594    throw new UnsupportedOperationException();
595  }
596
597  /**
598   * NOT SUPPORTED - Throws {@link UnsupportedOperationException}
599   */
600  public List<String> getFormatCommentsPost() {
601    throw new UnsupportedOperationException();
602  }
603
604  private Map<String, Object> userData;
605  private boolean isInPara;
606  
607  public Object getUserData(String theName) {
608    if (hasUserData(theName)) {
609      return userData.get(theName);
610    } else {
611      return null;
612    }
613  }
614
615  public boolean hasUserData(String theName) {
616    return userData != null && userData.containsKey(theName);
617  }
618
619  public void setUserData(String theName, Object theValue) {
620    if (userData == null) {
621      userData = new HashMap<>();
622    }
623    userData.put(theName, theValue);
624  }
625
626
627  public Location getLocation() {
628    return location;
629  }
630
631
632  public void setLocation(Location location) {
633    this.location = location;
634  }
635
636  // xhtml easy adders -----------------------------------------------
637  
638
639  @Override
640  public String toString() {
641    if (nodeType == null) {
642      return super.toString();
643    }
644    switch (nodeType) {
645    case Document: 
646    case Element:
647      try {
648        return new XhtmlComposer(XhtmlComposer.HTML).compose(this);
649      } catch (IOException e) {
650        return super.toString();
651      }
652    case Text:
653      return this.content;
654    case Comment:
655      return "<!-- "+this.content+" -->";
656    case DocType: 
657      return "<? "+this.content+" />";
658    case Instruction:
659      return "<? "+this.content+" />";
660    }
661    return super.toString();
662  }
663
664
665  public XhtmlNode getNextElement(XhtmlNode c) {
666    boolean f = false;
667    for (XhtmlNode n : childNodes) {
668      if (n == c)
669        f = true;
670      else if (f && n.getNodeType() == NodeType.Element) 
671        return n;
672    }
673    return null;
674  }
675
676
677  public XhtmlNode notPretty() {
678    notPretty = true;
679    return this;
680  }
681
682
683  public boolean isNoPretty() {
684    return notPretty;
685  }
686
687
688  public XhtmlNode style(String style) {
689    if (hasAttribute("style")) {
690      setAttribute("style", getAttribute("style")+"; "+style);
691    } else {
692      setAttribute("style", style);
693    }
694    return this;
695  }
696
697
698  public XhtmlNode nbsp() {
699    addText(NBSP);
700    return this;
701  }
702
703
704  public XhtmlNode para(String text) {
705    XhtmlNode p = para();
706    p.addText(text);
707    return p;
708    
709  }
710
711  public XhtmlNode add(XhtmlNode n) {
712    addChildNode(n);
713    return this;
714  }
715
716
717  public XhtmlNode addChildren(List<XhtmlNode> children) {
718    addChildNodes(children);
719    return this;
720  }
721
722  public XhtmlNode addChildren(XhtmlNode x) {
723    if (x != null) {
724      addChildNodes(x.getChildNodes());
725    }
726    return this;
727  }
728
729
730  public XhtmlNode input(String name, String type, String placeholder, int size) {
731    XhtmlNode p = new XhtmlNode(NodeType.Element, "input");
732    p.attribute("name", name);
733    p.attribute("type", type);
734    p.attribute("placeholder", placeholder);
735    p.attribute("size", Integer.toString(size));
736    addChildNode(p);
737    return p;
738  }
739
740  public XhtmlNode select(String name) {
741    XhtmlNode p = new XhtmlNode(NodeType.Element, "select");
742    p.attribute("name", name);
743    p.attribute("size", "1");
744    addChildNode(p);
745    return p;
746  }
747  
748  public XhtmlNode option(String value, String text, boolean selected) {
749    XhtmlNode p = new XhtmlNode(NodeType.Element, "option");
750    p.attribute("value", value);
751    p.attribute("selected", Boolean.toString(selected));
752    p.tx(text);
753    addChildNode(p);
754    return p;
755  }
756
757
758  public XhtmlNode remove(XhtmlNode x) {
759    getChildNodes().remove(x);
760    return this;
761    
762  }
763
764
765  public void clear() {
766    getChildNodes().clear();
767    
768  }
769
770
771  public XhtmlNode backgroundColor(String color) {
772    style("background-color: "+color);
773    return this;
774  }
775
776
777  public boolean isPara() {
778    return "p".equals(name);
779  }
780
781  public XhtmlNode sep(String separator) {
782    // if there's already text, add the separator. otherwise, we'll add it next time
783    if (!seperated) {
784      seperated = true;
785      return this;
786    }
787    return tx(separator);
788  }
789
790
791  // more fluent
792  
793  public XhtmlNode colspan(String n) {
794    return setAttribute("colspan", n);
795  }
796
797  public XhtmlNode colspan(int n) {
798    return setAttribute("colspan", Integer.toString(n));
799  }
800
801  public XhtmlNode rowspan(int n) {
802    if (n > 1) {
803      return setAttribute("rowspan", Integer.toString(n));      
804    } else {
805      return this;
806    }
807  }
808
809  @Override
810  protected void addChildren(XhtmlNodeList childNodes) {
811    this.addChildNodes(childNodes);    
812  }
813
814
815  public XhtmlNode color(String color) {
816    return span("color: "+color, null);
817  }
818  
819  public void startScript(String name) {
820    if (namedParams != null) {
821      throw new Error("Sequence Error - script is already open @ "+name);
822    }
823    namedParams = new HashMap<>();    
824    namedParamValues = new HashMap<>();
825  }
826  
827  public XhtmlNode param(String name) {
828    if (namedParams == null) {
829      throw new Error("Sequence Error - script is not already open");
830    }
831    XhtmlNode node = new XhtmlNode(NodeType.Element, "p"); // this node is dead will never appear anywhere, but we are in paragraph mode
832    namedParams.put(name, node);
833    return node;
834  }
835
836
837  public void paramValue(String name, String value) {
838    if (namedParamValues == null) {
839      throw new Error("Sequence Error - script is not already open");
840    }
841    namedParamValues.put(name, value); 
842  }
843
844  public void paramValue(String name, int value) {
845    if (namedParamValues == null) {
846      throw new Error("Sequence Error - script is not already open");
847    }
848    namedParamValues.put(name, Integer.toString(value)); 
849  }
850
851  /**
852   * To set up a script, you do the following:
853   * 
854   * * call startScript - setting up the parameter infrastructure 
855   * * define a set of parameters. Parameter values can be provided as string or integer, or:
856   * * you can use param(name) to render an arbitrarily complicated html fragment that will be inserted by the script
857   * * you can redefine parameters with the same name 
858   * * call execScript() to execute the script. You can call this any number of times
859   * * call closeScript
860   * 
861   * The script format is an xhtml fragment that can have any html in it, and also the following tags:
862   *   param: <param name="{name}"/> - replace this tag with the named parameter (or delete it if no value)
863   *   if: <if test="{condition}"/> - condition is param op value, where value is a string, and op is =, != <, >
864   *   
865   * @param structure
866   * @throws FHIRException
867   * @throws IOException
868   */
869  public void execScript(String structure) throws FHIRException, IOException {
870    XhtmlNode script = new XhtmlParser().parseFragment("<div>"+structure+"</div>");
871    parseNodes(script.getChildNodes(), this.getChildNodes());
872  }
873
874  private void parseNodes(XhtmlNodeList source, XhtmlNodeList dest) {
875    for (XhtmlNode n : source) {
876      if ("param".equals(n.getName())) {
877        XhtmlNode node = namedParams.get(n.getAttribute("name"));
878        if (node != null) {
879          parseNodes(node.getChildNodes(), dest);
880        }
881      } else if ("if".equals(n.getName())) {
882        String test = n.getAttribute("test");
883        if (passesTest(test)) {
884          parseNodes(n.getChildNodes(), dest);
885        }
886      } else {
887        dest.add(n);
888      }
889    }
890
891  }
892
893
894  public void closeScript() {
895    if (namedParams == null) {
896      throw new Error("Sequence Error - script is not already open");
897    }
898    namedParams = null;    
899    namedParamValues = null;
900  }
901
902  private boolean passesTest(String test) {
903    String[] p = test.split("\\s+");
904    if (p.length != 3) {
905      return false;
906    }
907    if (!namedParamValues.containsKey(p[0])) {
908      return false;
909    }
910    String pv = namedParamValues.get(p[0]);
911    switch (p[1]) {
912    case "=": return p[2].equalsIgnoreCase(pv);
913    case "!=": return !p[2].equalsIgnoreCase(pv);
914    case "<": return Utilities.isInteger(p[2]) && Utilities.isInteger(pv) && Integer.parseInt(pv) < Integer.parseInt(p[2]);
915    case "<=": return Utilities.isInteger(p[2]) && Utilities.isInteger(pv) && Integer.parseInt(pv) <= Integer.parseInt(p[2]);
916    case ">": return Utilities.isInteger(p[2]) && Utilities.isInteger(pv) && Integer.parseInt(pv) > Integer.parseInt(p[2]);
917    case ">=": return Utilities.isInteger(p[2]) && Utilities.isInteger(pv) && Integer.parseInt(pv) >= Integer.parseInt(p[2]);
918    }
919    return false;
920  }
921
922
923  public XhtmlNode getElementById(String id) {
924    if (id.equals(getAttribute("id"))) {
925      return this;
926    }
927    if (childNodes != null) {
928      for (XhtmlNode x : childNodes) {
929        XhtmlNode r = x.getElementById(id);
930        if (r != null) {
931          return r;
932        }   
933      }
934    }
935    return null;
936  }
937
938
939  public List<XhtmlNode> getChildren(String name) {
940    List<XhtmlNode> res = new ArrayList<>();
941    XhtmlNode x = getFirstElement();
942    while (x != null) {
943      if (name.equals(x.getName())) {
944        res.add(x);
945      }
946      x = getNextElement(x);
947    }
948    return res;
949  }
950
951
952  public XhtmlNode strikethrough() {
953    return addTag("s");
954  }
955
956
957  public XhtmlNode svg() {
958    return addTag("svg");
959  }
960
961
962  public XhtmlNode path(String value) {
963    return addTag("path").attribute("d", value);
964    
965  }
966
967
968  public void copyAllContent(XhtmlNode other) {
969    addChildNodes(other.getChildNodes());
970    getAttributes().putAll(other.getAttributes());
971    if (!Utilities.noString(other.getContent())) {
972      tx(other.getContent());
973    }    
974  }
975
976  public boolean isClass(String name) {
977    return hasAttribute("class", name);
978  }
979
980
981  public void styleCells(XhtmlNode x) {
982    setUserData("cells", x);    
983  }
984
985
986  public XhtmlNode td(int index) {
987    XhtmlNode x = addTag(index, "td");
988    XhtmlNode t = (XhtmlNode) getUserData("cells");
989    if (t != null) {
990      x.copyAllContent(t);
991    }
992    return x;    
993  }
994  
995  public XhtmlNode td() {
996    XhtmlNode x = addTag("td");
997    XhtmlNode t = (XhtmlNode) getUserData("cells");
998    if (t != null) {
999      x.copyAllContent(t);
1000    }
1001    return x;
1002  }
1003
1004  public XhtmlNode td(int index, String width) {
1005    XhtmlNode x = addTag(index, "td");
1006    x.attribute("width", width);
1007    XhtmlNode t = (XhtmlNode) getUserData("cells");
1008    if (t != null) {
1009      x.copyAllContent(t);
1010    }
1011    return x;    
1012  }
1013  
1014  public XhtmlNode tdW(int width) {
1015    XhtmlNode x = addTag("td");
1016    x.attribute("width", Integer.toString(width));
1017    XhtmlNode t = (XhtmlNode) getUserData("cells");
1018    if (t != null) {
1019      x.copyAllContent(t);
1020    }
1021    return x;
1022  }
1023
1024
1025
1026  // differs from tx because it returns the owner node, not the created text
1027  public XhtmlNode txN(String cnt) {
1028    addText(cnt);
1029    return this;
1030  }
1031  
1032  public XhtmlNode txOrCode(boolean code, String cnt) {
1033    if (code) {
1034      XhtmlNode c = code();
1035      boolean first = true;
1036      for (String line : cnt.split("\\r?\\n")) {
1037        if (first) first = false; else c.br();
1038        c.tx(line.replace(" ", Character.toString(0xA0)));
1039      }
1040    } else {
1041      addText(cnt);
1042    }
1043    return this;
1044  }
1045
1046
1047  public XhtmlNode iff(boolean test) {
1048    if (test) {
1049      return this;
1050    } else {
1051      return new XhtmlNode(NodeType.Element, "span"); // which will never be connected
1052    }
1053  }
1054
1055
1056  public XhtmlNode button(String class_, String title) {
1057    XhtmlNode btn = addTag("button");
1058    btn.attribute("class", class_);
1059    if (title != null) {
1060      btn.attribute("title", title);
1061    }
1062    return btn;
1063  }
1064
1065
1066  public XhtmlNode head() {
1067    return addTag("head");
1068  }
1069  
1070  public XhtmlNode body() {
1071    return addTag("body");
1072  }
1073  public XhtmlNode title(String title) {
1074    return addTag("title").tx(title);
1075  }
1076  
1077  public XhtmlNode link(String rel, String href) {
1078    return addTag("link").attribute("rel", rel).attribute("href", href);
1079  }
1080
1081  public XhtmlNode ahOrNot(String href) {
1082    if (href == null) {
1083      return this;
1084    }
1085    XhtmlNode x = addTag("a").attribute("href", href);
1086    return x;
1087  }
1088
1089
1090  public void wbr() {
1091    addTag("wbr");
1092    
1093  }
1094  
1095  protected int indexOfNode(XhtmlNode node) {
1096    return getChildNodes().indexOf(node);
1097  }
1098  
1099
1100  
1101  public int compareTo(XhtmlNode other) {
1102    return compare(this, other);
1103  }
1104
1105  private static int compare(XhtmlNode base, XhtmlNode other) {
1106    if (base == null || other == null) {
1107      return 0;
1108    } else if (base.getNodeType() != other.getNodeType()) {
1109      return base.getNodeType().ordinal() - other.getNodeType().ordinal();
1110    } else switch (base.getNodeType()) {
1111    case Comment: return base.getContent().compareTo(other.getContent());
1112    case DocType: return 0;
1113    case Element:
1114      int r = base.getName().compareTo(other.getName());
1115      if (r != 0) {
1116        return r;
1117      }
1118    case Document:
1119      if (base.getAttributes().size() != other.getAttributes().size()) {
1120        return base.getAttributes().size() - other.getAttributes().size();
1121      } else {
1122        for (String n : base.getAttributes().keySet()) {
1123          String vb = base.getAttributes().get(n);
1124          String vo = other.getAttributes().get(n);
1125          r = vo == null ? -1 : vb.compareTo(vo);
1126          if (r != 0) {
1127            return r;
1128          }
1129        }
1130      }
1131      if (base.getChildNodes().size() != other.getChildNodes().size()) {
1132        return base.getChildNodes().size() - other.getChildNodes().size();
1133      } else {
1134        for (int i = 0; i < base.getChildNodes().size(); i++) {
1135          r = compare(base, other);
1136          if (r != 0) {
1137            return r;
1138          }
1139        }
1140       }
1141      return 0;
1142    case Instruction: return 0;
1143    case Text: return base.getContent().compareTo(other.getContent());
1144    default: return 0;
1145    } 
1146  }
1147
1148
1149  public void stripAnchorsByName(Set<String> anchors) {
1150    if (hasChildren()) {
1151      childNodes.removeIf(n -> "a".equals(n.getName()) && anchors.contains(n.getAttribute("name")));
1152      for (XhtmlNode c : childNodes) {
1153        c.stripAnchorsByName(anchors);
1154      }
1155    }
1156  }
1157
1158  public void addChildNodes(List<XhtmlNode> nodes) {
1159    for (XhtmlNode node : nodes) {
1160      addChildNode(node);
1161    }
1162  }
1163
1164  
1165  public void addChildNode(XhtmlNode node) {
1166    checkWhenAddingNode(node);
1167    getChildNodes().add(node);    
1168  }
1169
1170
1171  private void checkWhenAddingNode(XhtmlNode node) {
1172    node.checkParaTree = checkParaTree;
1173    if (checkParaTree) {
1174      if (isInPara) {
1175        if (Utilities.existsInList(node.name, "div",  "blockquote", "table", "ol", "ul", "p")) {
1176          throw new Error("Error: attempt to add "+node.name+" inside an html paragraph");
1177        }
1178        node.isInPara = true;
1179      } 
1180    }
1181  }
1182
1183  public void addChildNode(int index, XhtmlNode node) {
1184    checkWhenAddingNode(node);
1185    getChildNodes().add(index, node);
1186  }
1187
1188
1189  public static boolean isCheckParaGeneral() {
1190    return checkParaGeneral;
1191  }
1192
1193
1194  public static void setCheckParaGeneral(boolean checkParaGeneral) {
1195    XhtmlNode.checkParaGeneral = checkParaGeneral;
1196  }
1197
1198
1199  public boolean isCheckParaTree() {
1200    return checkParaTree;
1201  }
1202
1203
1204  public void setCheckParaTree(boolean checkParaTree) {
1205    this.checkParaTree = checkParaTree;
1206  }
1207
1208}