java/sql-dk/src/info/globalcode/sql/dk/formatting/AbstractXmlFormatter.java
branchv_0
changeset 128 67f5ff139da0
child 130 8548e21177f9
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/java/sql-dk/src/info/globalcode/sql/dk/formatting/AbstractXmlFormatter.java	Sat Jan 04 19:39:35 2014 +0100
@@ -0,0 +1,206 @@
+/**
+ * SQL-DK
+ * Copyright © 2014 František Kučera (frantovo.cz)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package info.globalcode.sql.dk.formatting;
+
+import info.globalcode.sql.dk.ColorfulPrintWriter;
+import info.globalcode.sql.dk.ColorfulPrintWriter.TerminalColor;
+import java.util.Stack;
+import javax.xml.namespace.QName;
+import static info.globalcode.sql.dk.Functions.isEmpty;
+import static info.globalcode.sql.dk.Functions.toHex;
+import java.nio.charset.Charset;
+import java.util.EmptyStackException;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ *
+ * @author Ing. František Kučera (frantovo.cz)
+ */
+public abstract class AbstractXmlFormatter extends AbstractFormatter {
+
+	private static final Logger log = Logger.getLogger(AbstractXmlFormatter.class.getName());
+	public static final String PROPERTY_COLORFUL = "color";
+	public static final String PROPERTY_INDENT = "indent";
+	private static final TerminalColor ELEMENT_COLOR = TerminalColor.Magenta;
+	private static final TerminalColor ATTRIBUTE_NAME_COLOR = TerminalColor.Green;
+	private static final TerminalColor ATTRIBUTE_VALUE_COLOR = TerminalColor.Yellow;
+	private static final TerminalColor XML_DECLARATION_COLOR = TerminalColor.Red;
+	private Stack<QName> treePosition = new Stack<>();
+	private final ColorfulPrintWriter out;
+	private final String indent;
+
+	public AbstractXmlFormatter(FormatterContext formatterContext) {
+		super(formatterContext);
+		boolean colorful = formatterContext.getProperties().getBoolean(PROPERTY_COLORFUL, false);
+		out = new ColorfulPrintWriter(formatterContext.getOutputStream(), false, colorful);
+		indent = formatterContext.getProperties().getString(PROPERTY_INDENT, "\t");
+
+		if (!indent.matches("\\s*")) {
+			log.log(Level.WARNING, "Setting indent to „{0}“ is weird & freaky; in hex: {1}", new Object[]{indent, toHex(indent.getBytes())});
+		}
+
+	}
+
+	protected void printStartDocument() {
+		out.print(XML_DECLARATION_COLOR, "<?xml version=\"1.0\" encoding=\"" + Charset.defaultCharset().name() + "\"?>");
+	}
+
+	protected void printEndDocument() {
+		out.println();
+		out.flush();
+		if (!treePosition.empty()) {
+			throw new IllegalStateException("Some elements are not closed: " + treePosition);
+		}
+	}
+
+	protected void printStartElement(QName element) {
+		printStartElement(element, null);
+	}
+
+	protected Map<QName, String> singleAttribute(QName name, String value) {
+		Map<QName, String> attributes = new HashMap<>(1);
+		attributes.put(name, value);
+		return attributes;
+	}
+
+	protected void printStartElement(QName element, Map<QName, String> attributes) {
+		printStartElement(element, attributes, false);
+	}
+
+	/**
+	 * @param empty whether element should be closed <codfe>… /&gt;</code> (has no content, do not
+	 * call {@linkplain #printEndElement()})
+	 */
+	private void printStartElement(QName element, Map<QName, String> attributes, boolean empty) {
+		printIndent();
+
+		out.print(ELEMENT_COLOR, "<" + toString(element));
+
+		if (attributes != null) {
+			for (Entry<QName, String> attribute : attributes.entrySet()) {
+				out.print(" ");
+				out.print(ATTRIBUTE_NAME_COLOR, toString(attribute.getKey()));
+				out.print("=");
+				out.print(ATTRIBUTE_VALUE_COLOR, '"' + escapeXmlAttribute(attribute.getValue()) + '"');
+			}
+		}
+
+		if (empty) {
+			out.print(ELEMENT_COLOR, "/>");
+		} else {
+			out.print(ELEMENT_COLOR, ">");
+			treePosition.add(element);
+		}
+
+		out.flush();
+	}
+
+	/**
+	 * Prints text node wrapped in given element without indenting the text and adding line breaks
+	 * (useful for short texts).
+	 *
+	 * @param attributes use {@linkplain  LinkedHashMap} to preserve attributes order
+	 */
+	protected void printTextElement(QName element, Map<QName, String> attributes, String text) {
+		printStartElement(element, attributes);
+		printText(text, false);
+		printEndElement(false);
+	}
+
+	protected void printEmptyElement(QName element, Map<QName, String> attributes) {
+		printStartElement(element, attributes, true);
+	}
+
+	protected void printEndElement() {
+		printEndElement(true);
+	}
+
+	private void printEndElement(boolean indent) {
+		try {
+			QName name = treePosition.pop();
+
+			if (indent) {
+				printIndent();
+			}
+
+			out.print(ELEMENT_COLOR, "</" + toString(name) + ">");
+			out.flush();
+
+		} catch (EmptyStackException e) {
+			throw new IllegalStateException("No more elements to end.", e);
+		}
+	}
+
+	protected void printText(String s) {
+		printText(s, true);
+	}
+
+	private void printText(String s, boolean indent) {
+		if (indent) {
+			printIndent();
+		}
+		out.print(escapeXmlText(s));
+		out.flush();
+	}
+
+	protected void printIndent() {
+		out.println();
+		for (int i = 0; i < treePosition.size(); i++) {
+			out.print(indent);
+		}
+	}
+
+	protected static QName qname(String name) {
+		return new QName(name);
+	}
+
+	protected static QName qname(String prefix, String name) {
+		return new QName(null, name, prefix);
+	}
+
+	private String toString(QName name) {
+		if (isEmpty(name.getPrefix(), true)) {
+			return escapeName(name.getLocalPart());
+		} else {
+			return escapeName(name.getPrefix()) + ":" + escapeName(name.getLocalPart());
+		}
+	}
+
+	private String escapeName(String s) {
+		// TODO: avoid ugly values in <name name="…"/>		
+		return s;
+	}
+
+	private static String escapeXmlText(String s) {
+		return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
+		// Not needed:
+		// return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
+	}
+
+	/**
+	 * Expects attribute values enclosed in "quotes" not 'apostrophes'.
+	 */
+	private static String escapeXmlAttribute(String s) {
+		return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
+	}
+}