java/sql-dk/src/main/java/info/globalcode/sql/dk/formatting/AbstractXmlFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Thu, 24 Oct 2019 21:43:08 +0200
branchv_0
changeset 250 aae5009bd0af
parent 245 b6ff5b7a8422
permissions -rw-r--r--
fix license version: GNU GPLv3
     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, version 3 of the License.
     8  *
     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.
    13  *
    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/>.
    16  */
    17 package info.globalcode.sql.dk.formatting;
    18 
    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;
    32 import java.util.Map;
    33 import java.util.Map.Entry;
    34 import java.util.logging.Level;
    35 import java.util.logging.Logger;
    36 
    37 /**
    38  * <p>
    39  * Provides helper methods for printing pretty intended and optionally colorful (syntax highlighted)
    40  * XML output.
    41  * </p>
    42  *
    43  * <p>
    44  * Must be used with care – bad usage can lead to invalid XML (e.g. using undeclared namespaces).
    45  * </p>
    46  *
    47  * @author Ing. František Kučera (frantovo.cz)
    48  */
    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 {
    53 
    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;
    67 
    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);
    74 
    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())});
    77 		}
    78 
    79 	}
    80 
    81 	protected void printStartDocument() {
    82 		out.print(XML_DECLARATION_COLOR, "<?xml version=\"1.0\" encoding=\"" + Charset.defaultCharset().name() + "\"?>");
    83 	}
    84 
    85 	protected void printDoctype(String doctype) {
    86 		out.print(XML_DOCTYPE_COLOR, "\n<!DOCTYPE " + doctype + ">");
    87 	}
    88 
    89 	protected void printEndDocument() {
    90 		out.println();
    91 		out.flush();
    92 		if (!treePosition.empty()) {
    93 			throw new IllegalStateException("Some elements are not closed: " + treePosition);
    94 		}
    95 	}
    96 
    97 	protected void printStartElement(QName element) {
    98 		printStartElement(element, null);
    99 	}
   100 
   101 	protected Map<QName, String> singleAttribute(QName name, String value) {
   102 		Map<QName, String> attributes = new HashMap<>(2);
   103 		attributes.put(name, value);
   104 		return attributes;
   105 	}
   106 
   107 	protected void printStartElement(QName element, Map<QName, String> attributes) {
   108 		printStartElement(element, attributes, false);
   109 	}
   110 
   111 	/**
   112 	 * @param empty whether element should be closed <codfe>… /&gt;</code> (has no content, do not
   113 	 * call {@linkplain #printEndElement()})
   114 	 */
   115 	private void printStartElement(QName element, Map<QName, String> attributes, boolean empty) {
   116 		printIndent();
   117 
   118 		out.print(ELEMENT_COLOR, "<" + toString(element));
   119 
   120 		if (attributes != null) {
   121 			for (Entry<QName, String> attribute : attributes.entrySet()) {
   122 				out.print(" ");
   123 				out.print(ATTRIBUTE_NAME_COLOR, toString(attribute.getKey()));
   124 				out.print("=");
   125 				out.print(ATTRIBUTE_VALUE_COLOR, '"' + escapeXmlAttribute(attribute.getValue()) + '"');
   126 			}
   127 		}
   128 
   129 		if (empty) {
   130 			out.print(ELEMENT_COLOR, "/>");
   131 		} else {
   132 			out.print(ELEMENT_COLOR, ">");
   133 			treePosition.add(element);
   134 		}
   135 
   136 		out.flush();
   137 	}
   138 
   139 	/**
   140 	 * Prints text node wrapped in given element without indenting the text and adding line breaks
   141 	 * (useful for short texts).
   142 	 *
   143 	 * @param attributes use {@linkplain  LinkedHashMap} to preserve attributes order
   144 	 */
   145 	protected void printTextElement(QName element, Map<QName, String> attributes, String text) {
   146 		printStartElement(element, attributes);
   147 
   148 		String[] lines = text.split("\\n");
   149 
   150 		if (indentText && lines.length > 1) {
   151 			for (String line : lines) {
   152 				printText(line, true);
   153 			}
   154 			printEndElement(true);
   155 		} else {
   156 			/*
   157 			 * line breaks at the end of the text will be eaten – if you need them, use indentText = false
   158 			 */
   159 			if (lines.length == 1 && text.endsWith("\n")) {
   160 				text = text.substring(0, text.length() - 1);
   161 			}
   162 
   163 			printText(text, false);
   164 			printEndElement(false);
   165 		}
   166 	}
   167 
   168 	protected void printEmptyElement(QName element, Map<QName, String> attributes) {
   169 		printStartElement(element, attributes, true);
   170 	}
   171 
   172 	protected void printEndElement() {
   173 		printEndElement(true);
   174 	}
   175 
   176 	private void printEndElement(boolean indent) {
   177 		try {
   178 			QName name = treePosition.pop();
   179 
   180 			if (indent) {
   181 				printIndent();
   182 			}
   183 
   184 			out.print(ELEMENT_COLOR, "</" + toString(name) + ">");
   185 			out.flush();
   186 
   187 		} catch (EmptyStackException e) {
   188 			throw new IllegalStateException("No more elements to end.", e);
   189 		}
   190 	}
   191 
   192 	protected void printText(String s, boolean indent) {
   193 		if (indent) {
   194 			printIndent();
   195 		}
   196 		out.print(escapeXmlText(s));
   197 		out.flush();
   198 	}
   199 
   200 	protected void printIndent() {
   201 		out.println();
   202 		for (int i = 0; i < treePosition.size(); i++) {
   203 			out.print(indent);
   204 		}
   205 	}
   206 
   207 	private String toString(QName name) {
   208 		if (isEmpty(name.getPrefix(), true)) {
   209 			return escapeName(name.getLocalPart());
   210 		} else {
   211 			return escapeName(name.getPrefix()) + ":" + escapeName(name.getLocalPart());
   212 		}
   213 	}
   214 
   215 	private String escapeName(String s) {
   216 		// TODO: avoid ugly values in <name name="…"/>		
   217 		return s;
   218 	}
   219 
   220 	private static String escapeXmlText(String s) {
   221 		return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
   222 		// Not needed:
   223 		// return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
   224 	}
   225 
   226 	/**
   227 	 * Expects attribute values enclosed in "quotes" not 'apostrophes'.
   228 	 */
   229 	private static String escapeXmlAttribute(String s) {
   230 		return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
   231 	}
   232 }