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, either version 3 of the License, or
8 * (at your option) any later version.
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.
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/>.
18 package info.globalcode.sql.dk.formatting;
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;
31 import java.util.Map.Entry;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
37 * Provides helper methods for printing pretty intended and optionally colorful (syntax highlighted)
42 * Must be used with care – bad usage can lead to invalid XML (e.g. using undeclared namespaces).
45 * @author Ing. František Kučera (frantovo.cz)
47 public abstract class AbstractXmlFormatter extends AbstractFormatter {
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";
53 * Whether text with line breaks should be indented (default). Otherwise original whitespace
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;
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);
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())});
80 protected void printStartDocument() {
81 out.print(XML_DECLARATION_COLOR, "<?xml version=\"1.0\" encoding=\"" + Charset.defaultCharset().name() + "\"?>");
84 protected void printDoctype(String doctype) {
85 out.print(XML_DOCTYPE_COLOR, "\n<!DOCTYPE " + doctype + ">");
88 protected void printEndDocument() {
91 if (!treePosition.empty()) {
92 throw new IllegalStateException("Some elements are not closed: " + treePosition);
96 protected void printStartElement(QName element) {
97 printStartElement(element, null);
100 protected Map<QName, String> singleAttribute(QName name, String value) {
101 Map<QName, String> attributes = new HashMap<>(2);
102 attributes.put(name, value);
106 protected void printStartElement(QName element, Map<QName, String> attributes) {
107 printStartElement(element, attributes, false);
111 * @param empty whether element should be closed <codfe>… /></code> (has no content, do not
112 * call {@linkplain #printEndElement()})
114 private void printStartElement(QName element, Map<QName, String> attributes, boolean empty) {
117 out.print(ELEMENT_COLOR, "<" + toString(element));
119 if (attributes != null) {
120 for (Entry<QName, String> attribute : attributes.entrySet()) {
122 out.print(ATTRIBUTE_NAME_COLOR, toString(attribute.getKey()));
124 out.print(ATTRIBUTE_VALUE_COLOR, '"' + escapeXmlAttribute(attribute.getValue()) + '"');
129 out.print(ELEMENT_COLOR, "/>");
131 out.print(ELEMENT_COLOR, ">");
132 treePosition.add(element);
139 * Prints text node wrapped in given element without indenting the text and adding line breaks
140 * (useful for short texts).
142 * @param attributes use {@linkplain LinkedHashMap} to preserve attributes order
144 protected void printTextElement(QName element, Map<QName, String> attributes, String text) {
145 printStartElement(element, attributes);
147 String[] lines = text.split("\\n");
149 if (indentText && lines.length > 1) {
150 for (String line : lines) {
151 printText(line, true);
153 printEndElement(true);
156 * line breaks at the end of the text will be eaten – if you need them, use indentText = false
158 if (lines.length == 1 && text.endsWith("\n")) {
159 text = text.substring(0, text.length() - 1);
162 printText(text, false);
163 printEndElement(false);
167 protected void printEmptyElement(QName element, Map<QName, String> attributes) {
168 printStartElement(element, attributes, true);
171 protected void printEndElement() {
172 printEndElement(true);
175 private void printEndElement(boolean indent) {
177 QName name = treePosition.pop();
183 out.print(ELEMENT_COLOR, "</" + toString(name) + ">");
186 } catch (EmptyStackException e) {
187 throw new IllegalStateException("No more elements to end.", e);
191 protected void printText(String s, boolean indent) {
195 out.print(escapeXmlText(s));
199 protected void printIndent() {
201 for (int i = 0; i < treePosition.size(); i++) {
206 protected static QName qname(String name) {
207 return new QName(name);
210 protected static QName qname(String prefix, String name) {
211 return new QName(null, name, prefix);
214 private String toString(QName name) {
215 if (isEmpty(name.getPrefix(), true)) {
216 return escapeName(name.getLocalPart());
218 return escapeName(name.getPrefix()) + ":" + escapeName(name.getLocalPart());
222 private String escapeName(String s) {
223 // TODO: avoid ugly values in <name name="…"/>
227 private static String escapeXmlText(String s) {
228 return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
230 // return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """).replaceAll("'", "'");
234 * Expects attribute values enclosed in "quotes" not 'apostrophes'.
236 private static String escapeXmlAttribute(String s) {
237 return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """);