java/sql-dk/src/info/globalcode/sql/dk/formatting/AbstractXmlFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Sat, 04 Jan 2014 21:20:48 +0100
branchv_0
changeset 132 f785ee7a70a2
parent 130 8548e21177f9
child 136 c0f9521900bf
permissions -rw-r--r--
XML formatter fix: line breaks at the end of the text will be eaten – if you need them, use indentText = false
     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, either version 3 of the License, or
     8  * (at your option) any later version.
     9  *
    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.
    14  *
    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/>.
    17  */
    18 package info.globalcode.sql.dk.formatting;
    19 
    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;
    30 import java.util.Map;
    31 import java.util.Map.Entry;
    32 import java.util.logging.Level;
    33 import java.util.logging.Logger;
    34 
    35 /**
    36  *
    37  * @author Ing. František Kučera (frantovo.cz)
    38  */
    39 public abstract class AbstractXmlFormatter extends AbstractFormatter {
    40 
    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";
    44 	/**
    45 	 * Whether text with line breaks should be indented (default). Otherwise original whitespace
    46 	 * will be preserved.
    47 	 */
    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;
    57 
    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);
    64 
    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())});
    67 		}
    68 
    69 	}
    70 
    71 	protected void printStartDocument() {
    72 		out.print(XML_DECLARATION_COLOR, "<?xml version=\"1.0\" encoding=\"" + Charset.defaultCharset().name() + "\"?>");
    73 	}
    74 
    75 	protected void printEndDocument() {
    76 		out.println();
    77 		out.flush();
    78 		if (!treePosition.empty()) {
    79 			throw new IllegalStateException("Some elements are not closed: " + treePosition);
    80 		}
    81 	}
    82 
    83 	protected void printStartElement(QName element) {
    84 		printStartElement(element, null);
    85 	}
    86 
    87 	protected Map<QName, String> singleAttribute(QName name, String value) {
    88 		Map<QName, String> attributes = new HashMap<>(1);
    89 		attributes.put(name, value);
    90 		return attributes;
    91 	}
    92 
    93 	protected void printStartElement(QName element, Map<QName, String> attributes) {
    94 		printStartElement(element, attributes, false);
    95 	}
    96 
    97 	/**
    98 	 * @param empty whether element should be closed <codfe>… /&gt;</code> (has no content, do not
    99 	 * call {@linkplain #printEndElement()})
   100 	 */
   101 	private void printStartElement(QName element, Map<QName, String> attributes, boolean empty) {
   102 		printIndent();
   103 
   104 		out.print(ELEMENT_COLOR, "<" + toString(element));
   105 
   106 		if (attributes != null) {
   107 			for (Entry<QName, String> attribute : attributes.entrySet()) {
   108 				out.print(" ");
   109 				out.print(ATTRIBUTE_NAME_COLOR, toString(attribute.getKey()));
   110 				out.print("=");
   111 				out.print(ATTRIBUTE_VALUE_COLOR, '"' + escapeXmlAttribute(attribute.getValue()) + '"');
   112 			}
   113 		}
   114 
   115 		if (empty) {
   116 			out.print(ELEMENT_COLOR, "/>");
   117 		} else {
   118 			out.print(ELEMENT_COLOR, ">");
   119 			treePosition.add(element);
   120 		}
   121 
   122 		out.flush();
   123 	}
   124 
   125 	/**
   126 	 * Prints text node wrapped in given element without indenting the text and adding line breaks
   127 	 * (useful for short texts).
   128 	 *
   129 	 * @param attributes use {@linkplain  LinkedHashMap} to preserve attributes order
   130 	 */
   131 	protected void printTextElement(QName element, Map<QName, String> attributes, String text) {
   132 		printStartElement(element, attributes);
   133 
   134 		String[] lines = text.split("\\n");
   135 
   136 		if (indentText && lines.length > 1) {
   137 			for (String line : lines) {
   138 				printText(line, true);
   139 			}
   140 			printEndElement(true);
   141 		} else {
   142 			/*
   143 			 * line breaks at the end of the text will be eaten – if you need them, use indentText = false
   144 			 */
   145 			if (lines.length == 1 && text.endsWith("\n")) {
   146 				text = text.substring(0, text.length() - 1);
   147 			}
   148 
   149 			printText(text, false);
   150 			printEndElement(false);
   151 		}
   152 	}
   153 
   154 	protected void printEmptyElement(QName element, Map<QName, String> attributes) {
   155 		printStartElement(element, attributes, true);
   156 	}
   157 
   158 	protected void printEndElement() {
   159 		printEndElement(true);
   160 	}
   161 
   162 	private void printEndElement(boolean indent) {
   163 		try {
   164 			QName name = treePosition.pop();
   165 
   166 			if (indent) {
   167 				printIndent();
   168 			}
   169 
   170 			out.print(ELEMENT_COLOR, "</" + toString(name) + ">");
   171 			out.flush();
   172 
   173 		} catch (EmptyStackException e) {
   174 			throw new IllegalStateException("No more elements to end.", e);
   175 		}
   176 	}
   177 
   178 	protected void printText(String s, boolean indent) {
   179 		if (indent) {
   180 			printIndent();
   181 		}
   182 		out.print(escapeXmlText(s));
   183 		out.flush();
   184 	}
   185 
   186 	protected void printIndent() {
   187 		out.println();
   188 		for (int i = 0; i < treePosition.size(); i++) {
   189 			out.print(indent);
   190 		}
   191 	}
   192 
   193 	protected static QName qname(String name) {
   194 		return new QName(name);
   195 	}
   196 
   197 	protected static QName qname(String prefix, String name) {
   198 		return new QName(null, name, prefix);
   199 	}
   200 
   201 	private String toString(QName name) {
   202 		if (isEmpty(name.getPrefix(), true)) {
   203 			return escapeName(name.getLocalPart());
   204 		} else {
   205 			return escapeName(name.getPrefix()) + ":" + escapeName(name.getLocalPart());
   206 		}
   207 	}
   208 
   209 	private String escapeName(String s) {
   210 		// TODO: avoid ugly values in <name name="…"/>		
   211 		return s;
   212 	}
   213 
   214 	private static String escapeXmlText(String s) {
   215 		return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
   216 		// Not needed:
   217 		// return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
   218 	}
   219 
   220 	/**
   221 	 * Expects attribute values enclosed in "quotes" not 'apostrophes'.
   222 	 */
   223 	private static String escapeXmlAttribute(String s) {
   224 		return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
   225 	}
   226 }