java/sql-dk/src/main/java/info/globalcode/sql/dk/formatting/AbstractXmlFormatter.java
3 * Copyright © 2014 František Kučera (frantovo.cz)
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, version 3 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package info.globalcode.sql.dk.formatting;
19 import info.globalcode.sql.dk.ColorfulPrintWriter;
20 import info.globalcode.sql.dk.ColorfulPrintWriter.TerminalColor;
21 import java.util.Stack;
22 import javax.xml.namespace.QName;
23 import static info.globalcode.sql.dk.Functions.isEmpty;
24 import static info.globalcode.sql.dk.Functions.toHex;
25 import info.globalcode.sql.dk.configuration.PropertyDeclaration;
26 import static info.globalcode.sql.dk.formatting.CommonProperties.COLORFUL;
27 import static info.globalcode.sql.dk.formatting.CommonProperties.COLORFUL_DESCRIPTION;
28 import java.nio.charset.Charset;
29 import java.util.EmptyStackException;
30 import java.util.HashMap;
31 import java.util.LinkedHashMap;
33 import java.util.Map.Entry;
34 import java.util.logging.Level;
35 import java.util.logging.Logger;
39 * Provides helper methods for printing pretty intended and optionally colorful (syntax highlighted)
44 * Must be used with care – bad usage can lead to invalid XML (e.g. using undeclared namespaces).
47 * @author Ing. František Kučera (frantovo.cz)
49 @PropertyDeclaration(name = COLORFUL, defaultValue = "false", type = Boolean.class, description = COLORFUL_DESCRIPTION)
50 @PropertyDeclaration(name = AbstractXmlFormatter.PROPERTY_INDENT, defaultValue = AbstractXmlFormatter.PROPERTY_INDENT_DEFAULT, type = String.class, description = "tab or sequence of spaces used for indentation of nested elements")
51 @PropertyDeclaration(name = AbstractXmlFormatter.PROPERTY_INDENT_TEXT, defaultValue = "true", type = Boolean.class, description = "whether text with line breaks should be indented; if not original whitespace will be preserved.")
52 public abstract class AbstractXmlFormatter extends AbstractFormatter {
54 private static final Logger log = Logger.getLogger(AbstractXmlFormatter.class.getName());
55 public static final String PROPERTY_INDENT = "indent";
56 protected static final String PROPERTY_INDENT_DEFAULT = "\t";
57 public static final String PROPERTY_INDENT_TEXT = "indentText";
58 private static final TerminalColor ELEMENT_COLOR = TerminalColor.Magenta;
59 private static final TerminalColor ATTRIBUTE_NAME_COLOR = TerminalColor.Green;
60 private static final TerminalColor ATTRIBUTE_VALUE_COLOR = TerminalColor.Yellow;
61 private static final TerminalColor XML_DECLARATION_COLOR = TerminalColor.Red;
62 private static final TerminalColor XML_DOCTYPE_COLOR = TerminalColor.Cyan;
63 private final Stack<QName> treePosition = new Stack<>();
64 private final ColorfulPrintWriter out;
65 private final String indent;
66 private final boolean indentText;
68 public AbstractXmlFormatter(FormatterContext formatterContext) {
69 super(formatterContext);
70 boolean colorful = formatterContext.getProperties().getBoolean(COLORFUL, false);
71 out = new ColorfulPrintWriter(formatterContext.getOutputStream(), false, colorful);
72 indent = formatterContext.getProperties().getString(PROPERTY_INDENT, PROPERTY_INDENT_DEFAULT);
73 indentText = formatterContext.getProperties().getBoolean(PROPERTY_INDENT_TEXT, true);
75 if (!indent.matches("\\s*")) {
76 log.log(Level.WARNING, "Setting indent to „{0}“ is weird & freaky; in hex: {1}", new Object[]{indent, toHex(indent.getBytes())});
81 protected void printStartDocument() {
82 out.print(XML_DECLARATION_COLOR, "<?xml version=\"1.0\" encoding=\"" + Charset.defaultCharset().name() + "\"?>");
85 protected void printDoctype(String doctype) {
86 out.print(XML_DOCTYPE_COLOR, "\n<!DOCTYPE " + doctype + ">");
89 protected void printEndDocument() {
92 if (!treePosition.empty()) {
93 throw new IllegalStateException("Some elements are not closed: " + treePosition);
97 protected void printStartElement(QName element) {
98 printStartElement(element, null);
101 protected Map<QName, String> singleAttribute(QName name, String value) {
102 Map<QName, String> attributes = new HashMap<>(2);
103 attributes.put(name, value);
107 protected void printStartElement(QName element, Map<QName, String> attributes) {
108 printStartElement(element, attributes, false);
112 * @param empty whether element should be closed <codfe>… /></code> (has no content, do not
113 * call {@linkplain #printEndElement()})
115 private void printStartElement(QName element, Map<QName, String> attributes, boolean empty) {
118 out.print(ELEMENT_COLOR, "<" + toString(element));
120 if (attributes != null) {
121 for (Entry<QName, String> attribute : attributes.entrySet()) {
123 out.print(ATTRIBUTE_NAME_COLOR, toString(attribute.getKey()));
125 out.print(ATTRIBUTE_VALUE_COLOR, '"' + escapeXmlAttribute(attribute.getValue()) + '"');
130 out.print(ELEMENT_COLOR, "/>");
132 out.print(ELEMENT_COLOR, ">");
133 treePosition.add(element);
140 * Prints text node wrapped in given element without indenting the text and adding line breaks
141 * (useful for short texts).
143 * @param attributes use {@linkplain LinkedHashMap} to preserve attributes order
145 protected void printTextElement(QName element, Map<QName, String> attributes, String text) {
146 printStartElement(element, attributes);
148 String[] lines = text.split("\\n");
150 if (indentText && lines.length > 1) {
151 for (String line : lines) {
152 printText(line, true);
154 printEndElement(true);
157 * line breaks at the end of the text will be eaten – if you need them, use indentText = false
159 if (lines.length == 1 && text.endsWith("\n")) {
160 text = text.substring(0, text.length() - 1);
163 printText(text, false);
164 printEndElement(false);
168 protected void printEmptyElement(QName element, Map<QName, String> attributes) {
169 printStartElement(element, attributes, true);
172 protected void printEndElement() {
173 printEndElement(true);
176 private void printEndElement(boolean indent) {
178 QName name = treePosition.pop();
184 out.print(ELEMENT_COLOR, "</" + toString(name) + ">");
187 } catch (EmptyStackException e) {
188 throw new IllegalStateException("No more elements to end.", e);
192 protected void printText(String s, boolean indent) {
196 out.print(escapeXmlText(s));
200 protected void printIndent() {
202 for (int i = 0; i < treePosition.size(); i++) {
207 private String toString(QName name) {
208 if (isEmpty(name.getPrefix(), true)) {
209 return escapeName(name.getLocalPart());
211 return escapeName(name.getPrefix()) + ":" + escapeName(name.getLocalPart());
215 private String escapeName(String s) {
216 // TODO: avoid ugly values in <name name="…"/>
220 private static String escapeXmlText(String s) {
221 return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
223 // return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """).replaceAll("'", "'");
227 * Expects attribute values enclosed in "quotes" not 'apostrophes'.
229 private static String escapeXmlAttribute(String s) {
230 return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """);