java/sql-dk/src/info/globalcode/sql/dk/formatting/AbstractXmlFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Sat, 04 Jan 2014 23:39:38 +0100
branchv_0
changeset 136 c0f9521900bf
parent 132 f785ee7a70a2
child 152 7a3382823fc3
permissions -rw-r--r--
XML/XHTML formatter – DOCTYPE
     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 static final TerminalColor XML_DOCTYPE_COLOR = TerminalColor.Cyan;
    54 	private Stack<QName> treePosition = new Stack<>();
    55 	private final ColorfulPrintWriter out;
    56 	private final String indent;
    57 	private final boolean indentText;
    58 
    59 	public AbstractXmlFormatter(FormatterContext formatterContext) {
    60 		super(formatterContext);
    61 		boolean colorful = formatterContext.getProperties().getBoolean(PROPERTY_COLORFUL, false);
    62 		out = new ColorfulPrintWriter(formatterContext.getOutputStream(), false, colorful);
    63 		indent = formatterContext.getProperties().getString(PROPERTY_INDENT, "\t");
    64 		indentText = formatterContext.getProperties().getBoolean(PROPERTY_INDENT_TEXT, true);
    65 
    66 		if (!indent.matches("\\s*")) {
    67 			log.log(Level.WARNING, "Setting indent to „{0}“ is weird & freaky; in hex: {1}", new Object[]{indent, toHex(indent.getBytes())});
    68 		}
    69 
    70 	}
    71 
    72 	protected void printStartDocument() {
    73 		out.print(XML_DECLARATION_COLOR, "<?xml version=\"1.0\" encoding=\"" + Charset.defaultCharset().name() + "\"?>");
    74 	}
    75 
    76 	protected void printDoctype(String doctype) {
    77 		out.print(XML_DOCTYPE_COLOR, "\n<!DOCTYPE " + doctype + ">");
    78 	}
    79 
    80 	protected void printEndDocument() {
    81 		out.println();
    82 		out.flush();
    83 		if (!treePosition.empty()) {
    84 			throw new IllegalStateException("Some elements are not closed: " + treePosition);
    85 		}
    86 	}
    87 
    88 	protected void printStartElement(QName element) {
    89 		printStartElement(element, null);
    90 	}
    91 
    92 	protected Map<QName, String> singleAttribute(QName name, String value) {
    93 		Map<QName, String> attributes = new HashMap<>(1);
    94 		attributes.put(name, value);
    95 		return attributes;
    96 	}
    97 
    98 	protected void printStartElement(QName element, Map<QName, String> attributes) {
    99 		printStartElement(element, attributes, false);
   100 	}
   101 
   102 	/**
   103 	 * @param empty whether element should be closed <codfe>… /&gt;</code> (has no content, do not
   104 	 * call {@linkplain #printEndElement()})
   105 	 */
   106 	private void printStartElement(QName element, Map<QName, String> attributes, boolean empty) {
   107 		printIndent();
   108 
   109 		out.print(ELEMENT_COLOR, "<" + toString(element));
   110 
   111 		if (attributes != null) {
   112 			for (Entry<QName, String> attribute : attributes.entrySet()) {
   113 				out.print(" ");
   114 				out.print(ATTRIBUTE_NAME_COLOR, toString(attribute.getKey()));
   115 				out.print("=");
   116 				out.print(ATTRIBUTE_VALUE_COLOR, '"' + escapeXmlAttribute(attribute.getValue()) + '"');
   117 			}
   118 		}
   119 
   120 		if (empty) {
   121 			out.print(ELEMENT_COLOR, "/>");
   122 		} else {
   123 			out.print(ELEMENT_COLOR, ">");
   124 			treePosition.add(element);
   125 		}
   126 
   127 		out.flush();
   128 	}
   129 
   130 	/**
   131 	 * Prints text node wrapped in given element without indenting the text and adding line breaks
   132 	 * (useful for short texts).
   133 	 *
   134 	 * @param attributes use {@linkplain  LinkedHashMap} to preserve attributes order
   135 	 */
   136 	protected void printTextElement(QName element, Map<QName, String> attributes, String text) {
   137 		printStartElement(element, attributes);
   138 
   139 		String[] lines = text.split("\\n");
   140 
   141 		if (indentText && lines.length > 1) {
   142 			for (String line : lines) {
   143 				printText(line, true);
   144 			}
   145 			printEndElement(true);
   146 		} else {
   147 			/*
   148 			 * line breaks at the end of the text will be eaten – if you need them, use indentText = false
   149 			 */
   150 			if (lines.length == 1 && text.endsWith("\n")) {
   151 				text = text.substring(0, text.length() - 1);
   152 			}
   153 
   154 			printText(text, false);
   155 			printEndElement(false);
   156 		}
   157 	}
   158 
   159 	protected void printEmptyElement(QName element, Map<QName, String> attributes) {
   160 		printStartElement(element, attributes, true);
   161 	}
   162 
   163 	protected void printEndElement() {
   164 		printEndElement(true);
   165 	}
   166 
   167 	private void printEndElement(boolean indent) {
   168 		try {
   169 			QName name = treePosition.pop();
   170 
   171 			if (indent) {
   172 				printIndent();
   173 			}
   174 
   175 			out.print(ELEMENT_COLOR, "</" + toString(name) + ">");
   176 			out.flush();
   177 
   178 		} catch (EmptyStackException e) {
   179 			throw new IllegalStateException("No more elements to end.", e);
   180 		}
   181 	}
   182 
   183 	protected void printText(String s, boolean indent) {
   184 		if (indent) {
   185 			printIndent();
   186 		}
   187 		out.print(escapeXmlText(s));
   188 		out.flush();
   189 	}
   190 
   191 	protected void printIndent() {
   192 		out.println();
   193 		for (int i = 0; i < treePosition.size(); i++) {
   194 			out.print(indent);
   195 		}
   196 	}
   197 
   198 	protected static QName qname(String name) {
   199 		return new QName(name);
   200 	}
   201 
   202 	protected static QName qname(String prefix, String name) {
   203 		return new QName(null, name, prefix);
   204 	}
   205 
   206 	private String toString(QName name) {
   207 		if (isEmpty(name.getPrefix(), true)) {
   208 			return escapeName(name.getLocalPart());
   209 		} else {
   210 			return escapeName(name.getPrefix()) + ":" + escapeName(name.getLocalPart());
   211 		}
   212 	}
   213 
   214 	private String escapeName(String s) {
   215 		// TODO: avoid ugly values in <name name="…"/>		
   216 		return s;
   217 	}
   218 
   219 	private static String escapeXmlText(String s) {
   220 		return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
   221 		// Not needed:
   222 		// return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
   223 	}
   224 
   225 	/**
   226 	 * Expects attribute values enclosed in "quotes" not 'apostrophes'.
   227 	 */
   228 	private static String escapeXmlAttribute(String s) {
   229 		return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
   230 	}
   231 }