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 * @author Ing. František Kučera (frantovo.cz)
39 public abstract class AbstractXmlFormatter extends AbstractFormatter {
41 private static final Logger log = Logger.getLogger(AbstractXmlFormatter.class.getName());
42 public static final String PROPERTY_COLORFUL = "color";
43 public static final String PROPERTY_INDENT = "indent";
45 * Whether text with line breaks should be indented (default). Otherwise original whitespace
48 public static final String PROPERTY_INDENT_TEXT = "indentText";
49 private static final TerminalColor ELEMENT_COLOR = TerminalColor.Magenta;
50 private static final TerminalColor ATTRIBUTE_NAME_COLOR = TerminalColor.Green;
51 private static final TerminalColor ATTRIBUTE_VALUE_COLOR = TerminalColor.Yellow;
52 private static final TerminalColor XML_DECLARATION_COLOR = TerminalColor.Red;
53 private Stack<QName> treePosition = new Stack<>();
54 private final ColorfulPrintWriter out;
55 private final String indent;
56 private final boolean indentText;
58 public AbstractXmlFormatter(FormatterContext formatterContext) {
59 super(formatterContext);
60 boolean colorful = formatterContext.getProperties().getBoolean(PROPERTY_COLORFUL, false);
61 out = new ColorfulPrintWriter(formatterContext.getOutputStream(), false, colorful);
62 indent = formatterContext.getProperties().getString(PROPERTY_INDENT, "\t");
63 indentText = formatterContext.getProperties().getBoolean(PROPERTY_INDENT_TEXT, true);
65 if (!indent.matches("\\s*")) {
66 log.log(Level.WARNING, "Setting indent to „{0}“ is weird & freaky; in hex: {1}", new Object[]{indent, toHex(indent.getBytes())});
71 protected void printStartDocument() {
72 out.print(XML_DECLARATION_COLOR, "<?xml version=\"1.0\" encoding=\"" + Charset.defaultCharset().name() + "\"?>");
75 protected void printEndDocument() {
78 if (!treePosition.empty()) {
79 throw new IllegalStateException("Some elements are not closed: " + treePosition);
83 protected void printStartElement(QName element) {
84 printStartElement(element, null);
87 protected Map<QName, String> singleAttribute(QName name, String value) {
88 Map<QName, String> attributes = new HashMap<>(1);
89 attributes.put(name, value);
93 protected void printStartElement(QName element, Map<QName, String> attributes) {
94 printStartElement(element, attributes, false);
98 * @param empty whether element should be closed <codfe>… /></code> (has no content, do not
99 * call {@linkplain #printEndElement()})
101 private void printStartElement(QName element, Map<QName, String> attributes, boolean empty) {
104 out.print(ELEMENT_COLOR, "<" + toString(element));
106 if (attributes != null) {
107 for (Entry<QName, String> attribute : attributes.entrySet()) {
109 out.print(ATTRIBUTE_NAME_COLOR, toString(attribute.getKey()));
111 out.print(ATTRIBUTE_VALUE_COLOR, '"' + escapeXmlAttribute(attribute.getValue()) + '"');
116 out.print(ELEMENT_COLOR, "/>");
118 out.print(ELEMENT_COLOR, ">");
119 treePosition.add(element);
126 * Prints text node wrapped in given element without indenting the text and adding line breaks
127 * (useful for short texts).
129 * @param attributes use {@linkplain LinkedHashMap} to preserve attributes order
131 protected void printTextElement(QName element, Map<QName, String> attributes, String text) {
132 printStartElement(element, attributes);
134 String[] lines = text.split("\\n");
136 if (indentText && lines.length > 1) {
137 for (String line : lines) {
138 printText(line, true);
140 printEndElement(true);
143 * line breaks at the end of the text will be eaten – if you need them, use indentText = false
145 if (lines.length == 1 && text.endsWith("\n")) {
146 text = text.substring(0, text.length() - 1);
149 printText(text, false);
150 printEndElement(false);
154 protected void printEmptyElement(QName element, Map<QName, String> attributes) {
155 printStartElement(element, attributes, true);
158 protected void printEndElement() {
159 printEndElement(true);
162 private void printEndElement(boolean indent) {
164 QName name = treePosition.pop();
170 out.print(ELEMENT_COLOR, "</" + toString(name) + ">");
173 } catch (EmptyStackException e) {
174 throw new IllegalStateException("No more elements to end.", e);
178 protected void printText(String s, boolean indent) {
182 out.print(escapeXmlText(s));
186 protected void printIndent() {
188 for (int i = 0; i < treePosition.size(); i++) {
193 protected static QName qname(String name) {
194 return new QName(name);
197 protected static QName qname(String prefix, String name) {
198 return new QName(null, name, prefix);
201 private String toString(QName name) {
202 if (isEmpty(name.getPrefix(), true)) {
203 return escapeName(name.getLocalPart());
205 return escapeName(name.getPrefix()) + ":" + escapeName(name.getLocalPart());
209 private String escapeName(String s) {
210 // TODO: avoid ugly values in <name name="…"/>
214 private static String escapeXmlText(String s) {
215 return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
217 // return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """).replaceAll("'", "'");
221 * Expects attribute values enclosed in "quotes" not 'apostrophes'.
223 private static String escapeXmlAttribute(String s) {
224 return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """);