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 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;
34 import java.util.Map.Entry;
35 import java.util.logging.Level;
36 import java.util.logging.Logger;
40 * Provides helper methods for printing pretty intended and optionally colorful (syntax highlighted)
45 * Must be used with care – bad usage can lead to invalid XML (e.g. using undeclared namespaces).
48 * @author Ing. František Kučera (frantovo.cz)
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 {
55 private static final Logger log = Logger.getLogger(AbstractXmlFormatter.class.getName());
56 public static final String PROPERTY_INDENT = "indent";
58 * Whether text with line breaks should be indented (default). Otherwise original whitespace
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;
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);
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())});
85 protected void printStartDocument() {
86 out.print(XML_DECLARATION_COLOR, "<?xml version=\"1.0\" encoding=\"" + Charset.defaultCharset().name() + "\"?>");
89 protected void printDoctype(String doctype) {
90 out.print(XML_DOCTYPE_COLOR, "\n<!DOCTYPE " + doctype + ">");
93 protected void printEndDocument() {
96 if (!treePosition.empty()) {
97 throw new IllegalStateException("Some elements are not closed: " + treePosition);
101 protected void printStartElement(QName element) {
102 printStartElement(element, null);
105 protected Map<QName, String> singleAttribute(QName name, String value) {
106 Map<QName, String> attributes = new HashMap<>(2);
107 attributes.put(name, value);
111 protected void printStartElement(QName element, Map<QName, String> attributes) {
112 printStartElement(element, attributes, false);
116 * @param empty whether element should be closed <codfe>… /></code> (has no content, do not
117 * call {@linkplain #printEndElement()})
119 private void printStartElement(QName element, Map<QName, String> attributes, boolean empty) {
122 out.print(ELEMENT_COLOR, "<" + toString(element));
124 if (attributes != null) {
125 for (Entry<QName, String> attribute : attributes.entrySet()) {
127 out.print(ATTRIBUTE_NAME_COLOR, toString(attribute.getKey()));
129 out.print(ATTRIBUTE_VALUE_COLOR, '"' + escapeXmlAttribute(attribute.getValue()) + '"');
134 out.print(ELEMENT_COLOR, "/>");
136 out.print(ELEMENT_COLOR, ">");
137 treePosition.add(element);
144 * Prints text node wrapped in given element without indenting the text and adding line breaks
145 * (useful for short texts).
147 * @param attributes use {@linkplain LinkedHashMap} to preserve attributes order
149 protected void printTextElement(QName element, Map<QName, String> attributes, String text) {
150 printStartElement(element, attributes);
152 String[] lines = text.split("\\n");
154 if (indentText && lines.length > 1) {
155 for (String line : lines) {
156 printText(line, true);
158 printEndElement(true);
161 * line breaks at the end of the text will be eaten – if you need them, use indentText = false
163 if (lines.length == 1 && text.endsWith("\n")) {
164 text = text.substring(0, text.length() - 1);
167 printText(text, false);
168 printEndElement(false);
172 protected void printEmptyElement(QName element, Map<QName, String> attributes) {
173 printStartElement(element, attributes, true);
176 protected void printEndElement() {
177 printEndElement(true);
180 private void printEndElement(boolean indent) {
182 QName name = treePosition.pop();
188 out.print(ELEMENT_COLOR, "</" + toString(name) + ">");
191 } catch (EmptyStackException e) {
192 throw new IllegalStateException("No more elements to end.", e);
196 protected void printText(String s, boolean indent) {
200 out.print(escapeXmlText(s));
204 protected void printIndent() {
206 for (int i = 0; i < treePosition.size(); i++) {
211 protected static QName qname(String name) {
212 return new QName(name);
215 protected static QName qname(String prefix, String name) {
216 return new QName(null, name, prefix);
219 private String toString(QName name) {
220 if (isEmpty(name.getPrefix(), true)) {
221 return escapeName(name.getLocalPart());
223 return escapeName(name.getPrefix()) + ":" + escapeName(name.getLocalPart());
227 private String escapeName(String s) {
228 // TODO: avoid ugly values in <name name="…"/>
232 private static String escapeXmlText(String s) {
233 return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
235 // return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """).replaceAll("'", "'");
239 * Expects attribute values enclosed in "quotes" not 'apostrophes'.
241 private static String escapeXmlAttribute(String s) {
242 return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """);