java/sql-dk/src/info/globalcode/sql/dk/formatting/AbstractXmlFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Fri, 10 Jan 2014 23:21:28 +0100
branchv_0
changeset 155 eb3676c6929b
parent 152 7a3382823fc3
child 206 e2f24eea8543
permissions -rw-r--r--
more JavaDoc
     1 /**
     2  * SQL-DK
     3  * Copyright © 2014 František Kučera (frantovo.cz)
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, either version 3 of the License, or
     8  * (at your option) any later version.
     9  *
    10  * This program is distributed in the hope that it will be useful,
    11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  * GNU General Public License for more details.
    14  *
    15  * You should have received a copy of the GNU General Public License
    16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
    17  */
    18 package info.globalcode.sql.dk.formatting;
    19 
    20 import info.globalcode.sql.dk.ColorfulPrintWriter;
    21 import info.globalcode.sql.dk.ColorfulPrintWriter.TerminalColor;
    22 import java.util.Stack;
    23 import javax.xml.namespace.QName;
    24 import static info.globalcode.sql.dk.Functions.isEmpty;
    25 import static info.globalcode.sql.dk.Functions.toHex;
    26 import java.nio.charset.Charset;
    27 import java.util.EmptyStackException;
    28 import java.util.HashMap;
    29 import java.util.LinkedHashMap;
    30 import java.util.Map;
    31 import java.util.Map.Entry;
    32 import java.util.logging.Level;
    33 import java.util.logging.Logger;
    34 
    35 /**
    36  * <p>
    37  * Provides helper methods for printing pretty intended and optionally colorful (syntax highlighted)
    38  * XML output.
    39  * </p>
    40  *
    41  * <p>
    42  * Must be used with care – bad usage can lead to invalid XML (e.g. using undeclared namespaces).
    43  * </p>
    44  *
    45  * @author Ing. František Kučera (frantovo.cz)
    46  */
    47 public abstract class AbstractXmlFormatter extends AbstractFormatter {
    48 
    49 	private static final Logger log = Logger.getLogger(AbstractXmlFormatter.class.getName());
    50 	public static final String PROPERTY_COLORFUL = "color";
    51 	public static final String PROPERTY_INDENT = "indent";
    52 	/**
    53 	 * Whether text with line breaks should be indented (default). Otherwise original whitespace
    54 	 * will be preserved.
    55 	 */
    56 	public static final String PROPERTY_INDENT_TEXT = "indentText";
    57 	private static final TerminalColor ELEMENT_COLOR = TerminalColor.Magenta;
    58 	private static final TerminalColor ATTRIBUTE_NAME_COLOR = TerminalColor.Green;
    59 	private static final TerminalColor ATTRIBUTE_VALUE_COLOR = TerminalColor.Yellow;
    60 	private static final TerminalColor XML_DECLARATION_COLOR = TerminalColor.Red;
    61 	private static final TerminalColor XML_DOCTYPE_COLOR = TerminalColor.Cyan;
    62 	private Stack<QName> treePosition = new Stack<>();
    63 	private final ColorfulPrintWriter out;
    64 	private final String indent;
    65 	private final boolean indentText;
    66 
    67 	public AbstractXmlFormatter(FormatterContext formatterContext) {
    68 		super(formatterContext);
    69 		boolean colorful = formatterContext.getProperties().getBoolean(PROPERTY_COLORFUL, false);
    70 		out = new ColorfulPrintWriter(formatterContext.getOutputStream(), false, colorful);
    71 		indent = formatterContext.getProperties().getString(PROPERTY_INDENT, "\t");
    72 		indentText = formatterContext.getProperties().getBoolean(PROPERTY_INDENT_TEXT, true);
    73 
    74 		if (!indent.matches("\\s*")) {
    75 			log.log(Level.WARNING, "Setting indent to „{0}“ is weird & freaky; in hex: {1}", new Object[]{indent, toHex(indent.getBytes())});
    76 		}
    77 
    78 	}
    79 
    80 	protected void printStartDocument() {
    81 		out.print(XML_DECLARATION_COLOR, "<?xml version=\"1.0\" encoding=\"" + Charset.defaultCharset().name() + "\"?>");
    82 	}
    83 
    84 	protected void printDoctype(String doctype) {
    85 		out.print(XML_DOCTYPE_COLOR, "\n<!DOCTYPE " + doctype + ">");
    86 	}
    87 
    88 	protected void printEndDocument() {
    89 		out.println();
    90 		out.flush();
    91 		if (!treePosition.empty()) {
    92 			throw new IllegalStateException("Some elements are not closed: " + treePosition);
    93 		}
    94 	}
    95 
    96 	protected void printStartElement(QName element) {
    97 		printStartElement(element, null);
    98 	}
    99 
   100 	protected Map<QName, String> singleAttribute(QName name, String value) {
   101 		Map<QName, String> attributes = new HashMap<>(2);
   102 		attributes.put(name, value);
   103 		return attributes;
   104 	}
   105 
   106 	protected void printStartElement(QName element, Map<QName, String> attributes) {
   107 		printStartElement(element, attributes, false);
   108 	}
   109 
   110 	/**
   111 	 * @param empty whether element should be closed <codfe>… /&gt;</code> (has no content, do not
   112 	 * call {@linkplain #printEndElement()})
   113 	 */
   114 	private void printStartElement(QName element, Map<QName, String> attributes, boolean empty) {
   115 		printIndent();
   116 
   117 		out.print(ELEMENT_COLOR, "<" + toString(element));
   118 
   119 		if (attributes != null) {
   120 			for (Entry<QName, String> attribute : attributes.entrySet()) {
   121 				out.print(" ");
   122 				out.print(ATTRIBUTE_NAME_COLOR, toString(attribute.getKey()));
   123 				out.print("=");
   124 				out.print(ATTRIBUTE_VALUE_COLOR, '"' + escapeXmlAttribute(attribute.getValue()) + '"');
   125 			}
   126 		}
   127 
   128 		if (empty) {
   129 			out.print(ELEMENT_COLOR, "/>");
   130 		} else {
   131 			out.print(ELEMENT_COLOR, ">");
   132 			treePosition.add(element);
   133 		}
   134 
   135 		out.flush();
   136 	}
   137 
   138 	/**
   139 	 * Prints text node wrapped in given element without indenting the text and adding line breaks
   140 	 * (useful for short texts).
   141 	 *
   142 	 * @param attributes use {@linkplain  LinkedHashMap} to preserve attributes order
   143 	 */
   144 	protected void printTextElement(QName element, Map<QName, String> attributes, String text) {
   145 		printStartElement(element, attributes);
   146 
   147 		String[] lines = text.split("\\n");
   148 
   149 		if (indentText && lines.length > 1) {
   150 			for (String line : lines) {
   151 				printText(line, true);
   152 			}
   153 			printEndElement(true);
   154 		} else {
   155 			/*
   156 			 * line breaks at the end of the text will be eaten – if you need them, use indentText = false
   157 			 */
   158 			if (lines.length == 1 && text.endsWith("\n")) {
   159 				text = text.substring(0, text.length() - 1);
   160 			}
   161 
   162 			printText(text, false);
   163 			printEndElement(false);
   164 		}
   165 	}
   166 
   167 	protected void printEmptyElement(QName element, Map<QName, String> attributes) {
   168 		printStartElement(element, attributes, true);
   169 	}
   170 
   171 	protected void printEndElement() {
   172 		printEndElement(true);
   173 	}
   174 
   175 	private void printEndElement(boolean indent) {
   176 		try {
   177 			QName name = treePosition.pop();
   178 
   179 			if (indent) {
   180 				printIndent();
   181 			}
   182 
   183 			out.print(ELEMENT_COLOR, "</" + toString(name) + ">");
   184 			out.flush();
   185 
   186 		} catch (EmptyStackException e) {
   187 			throw new IllegalStateException("No more elements to end.", e);
   188 		}
   189 	}
   190 
   191 	protected void printText(String s, boolean indent) {
   192 		if (indent) {
   193 			printIndent();
   194 		}
   195 		out.print(escapeXmlText(s));
   196 		out.flush();
   197 	}
   198 
   199 	protected void printIndent() {
   200 		out.println();
   201 		for (int i = 0; i < treePosition.size(); i++) {
   202 			out.print(indent);
   203 		}
   204 	}
   205 
   206 	protected static QName qname(String name) {
   207 		return new QName(name);
   208 	}
   209 
   210 	protected static QName qname(String prefix, String name) {
   211 		return new QName(null, name, prefix);
   212 	}
   213 
   214 	private String toString(QName name) {
   215 		if (isEmpty(name.getPrefix(), true)) {
   216 			return escapeName(name.getLocalPart());
   217 		} else {
   218 			return escapeName(name.getPrefix()) + ":" + escapeName(name.getLocalPart());
   219 		}
   220 	}
   221 
   222 	private String escapeName(String s) {
   223 		// TODO: avoid ugly values in <name name="…"/>		
   224 		return s;
   225 	}
   226 
   227 	private static String escapeXmlText(String s) {
   228 		return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
   229 		// Not needed:
   230 		// return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
   231 	}
   232 
   233 	/**
   234 	 * Expects attribute values enclosed in "quotes" not 'apostrophes'.
   235 	 */
   236 	private static String escapeXmlAttribute(String s) {
   237 		return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
   238 	}
   239 }