001: package org.uispec4j.xml;
002:
003: import org.uispec4j.utils.Utils;
004:
005: import java.io.IOException;
006: import java.io.Writer;
007:
008: public class XmlWriter {
009:
010: public static Tag startTag(Writer writer, String rootTag) {
011: try {
012: writer.write('<');
013: writer.write(rootTag);
014: return new Tag(writer, NULL, rootTag);
015: } catch (IOException e) {
016: throw new RuntimeException(e);
017: }
018: }
019:
020: public static class Tag {
021: private String tagValue;
022: private Writer writer;
023: private Tag parent;
024: private boolean closed = false;
025:
026: private Tag(Writer writer, Tag parent, String tag) {
027: this .writer = writer;
028: this .parent = parent;
029: this .tagValue = normalize(tag);
030: }
031:
032: public Tag start(String tagName) {
033: try {
034: closeSup();
035: writer.write(Utils.LINE_SEPARATOR);
036: writer.write("<");
037: writer.write(tagName);
038: return new Tag(writer, this , tagName);
039: } catch (IOException e) {
040: throw new RuntimeException(e);
041: }
042: }
043:
044: public Tag addAttribute(String attrName, String attrValue) {
045: try {
046: if (attrValue == null) {
047: return this ;
048: }
049: if (closed) {
050: throw new RuntimeException(
051: "Bad use of 'addAttribute' method after tag closure");
052: }
053: writer.write(' ');
054: writer.write(normalize(attrName));
055: writer.write("=\"");
056: writer.write(normalize(attrValue));
057: writer.write('"');
058: return this ;
059: } catch (IOException e) {
060: throw new RuntimeException(e);
061: }
062: }
063:
064: public Tag end() {
065: try {
066: if (closed) {
067: writer.write("</");
068: writer.write(tagValue);
069: writer.write(">");
070: } else {
071: writer.write("/>");
072: }
073: return parent;
074: } catch (IOException e) {
075: throw new RuntimeException(e);
076: }
077: }
078:
079: public Tag addValue(String value) {
080: try {
081: closeSup();
082: writer.write(normalize(value));
083: return this ;
084: } catch (IOException e) {
085: throw new RuntimeException(e);
086: }
087: }
088:
089: private void closeSup() {
090: try {
091: if (!closed) {
092: closed = true;
093: writer.write(">");
094: }
095: } catch (IOException e) {
096: throw new RuntimeException(e);
097: }
098: }
099:
100: private static String normalize(String value) {
101: return XmlEscape.convertToXmlWithEntities(value);
102: }
103: }
104:
105: private static Tag NULL = new Tag(null, null, "") {
106: public Tag addAttribute(String attrName, String attrValue) {
107: return this ;
108: }
109:
110: public Tag end() {
111: return this ;
112: }
113:
114: public Tag start(String tag) {
115: return this ;
116: }
117: };
118:
119: private XmlWriter() {
120: }
121: }
|