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