java/sql-dk/src/info/globalcode/sql/dk/formatting/XmlFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Sun, 06 Sep 2015 21:46:03 +0200
branchv_0
changeset 225 906f767ef9b3
parent 207 2bba68ef47c1
child 233 0fb3b92e01c5
permissions -rw-r--r--
XmlFormatter: support for printing SQLXML types
     1 /**
     2  * SQL-DK
     3  * Copyright © 2013 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.Parameter;
    21 import info.globalcode.sql.dk.Xmlns;
    22 import info.globalcode.sql.dk.configuration.DatabaseDefinition;
    23 import static info.globalcode.sql.dk.Functions.notNull;
    24 import info.globalcode.sql.dk.NamedParameter;
    25 import info.globalcode.sql.dk.configuration.PropertyDeclaration;
    26 import static info.globalcode.sql.dk.formatting.AbstractXmlFormatter.qname;
    27 import java.sql.Array;
    28 import java.sql.SQLException;
    29 import java.sql.SQLXML;
    30 import java.util.LinkedHashMap;
    31 import java.util.List;
    32 import java.util.Map;
    33 import java.util.logging.Level;
    34 import java.util.logging.Logger;
    35 import javax.xml.namespace.QName;
    36 
    37 /**
    38  * <p>
    39  * Prints machine-readable output – XML document containing resultsets and updates count. Good
    40  * choice for further processing – e.g. XSL transformation.</p>
    41  *
    42  * <p>
    43  * TODO: XSD</p>
    44  *
    45  * @author Ing. František Kučera (frantovo.cz)
    46  */
    47 @PropertyDeclaration(name = XmlFormatter.PROPERTY_LABELED_COLUMNS, defaultValue = "false", type = Boolean.class, description = "whether to add 'label' attribute to each 'column' element")
    48 public class XmlFormatter extends AbstractXmlFormatter {
    49 
    50 	public static final String NAME = "xml"; // bash-completion:formatter
    51 	public static final String PROPERTY_LABELED_COLUMNS = "labeledColumns";
    52 	private static final Logger log = Logger.getLogger(XmlFormatter.class.getName());
    53 	private final boolean labeledColumns;
    54 
    55 	public XmlFormatter(FormatterContext formatterContext) {
    56 		super(formatterContext);
    57 		labeledColumns = formatterContext.getProperties().getBoolean(PROPERTY_LABELED_COLUMNS, false);
    58 	}
    59 
    60 	@Override
    61 	public void writeStartBatch() {
    62 		super.writeStartBatch();
    63 		printStartDocument();
    64 		printStartElement(qname("batchResult"), singleAttribute(qname("xmlns"), Xmlns.BATCH_RESULT));
    65 	}
    66 
    67 	@Override
    68 	public void writeEndBatch() {
    69 		super.writeEndBatch();
    70 		printEndElement();
    71 		printEndDocument();
    72 	}
    73 
    74 	@Override
    75 	public void writeStartDatabase(DatabaseDefinition databaseDefinition) {
    76 		super.writeStartDatabase(databaseDefinition);
    77 		Map<QName, String> attributes = databaseDefinition.getName() == null ? null : singleAttribute(qname("name"), databaseDefinition.getName());
    78 		printStartElement(qname("database"), attributes);
    79 	}
    80 
    81 	@Override
    82 	public void writeEndDatabase() {
    83 		super.writeEndDatabase();
    84 		printEndElement();
    85 	}
    86 
    87 	@Override
    88 	public void writeStartStatement() {
    89 		super.writeStartStatement();
    90 		printStartElement(qname("statement"));
    91 	}
    92 
    93 	@Override
    94 	public void writeEndStatement() {
    95 		super.writeEndStatement();
    96 		printEndElement();
    97 	}
    98 
    99 	@Override
   100 	public void writeQuery(String sql) {
   101 		super.writeQuery(sql);
   102 		printTextElement(qname("sql"), null, sql);
   103 	}
   104 
   105 	@Override
   106 	public void writeParameters(List<? extends Parameter> parameters) {
   107 		super.writeParameters(parameters);
   108 
   109 		for (Parameter p : notNull(parameters)) {
   110 
   111 			Map<QName, String> attributes = new LinkedHashMap<>(2);
   112 			if (p instanceof NamedParameter) {
   113 				attributes.put(qname("name"), ((NamedParameter) p).getName());
   114 			}
   115 			attributes.put(qname("type"), p.getType().name());
   116 
   117 			printTextElement(qname("parameter"), attributes, String.valueOf(p.getValue()));
   118 		}
   119 
   120 	}
   121 
   122 	@Override
   123 	public void writeStartResultSet(ColumnsHeader header) {
   124 		super.writeStartResultSet(header);
   125 		printStartElement(qname("resultSet"));
   126 
   127 		for (ColumnDescriptor cd : header.getColumnDescriptors()) {
   128 			Map<QName, String> attributes = new LinkedHashMap<>(4);
   129 			attributes.put(qname("label"), cd.getLabel());
   130 			attributes.put(qname("name"), cd.getName());
   131 			attributes.put(qname("typeName"), cd.getTypeName());
   132 			attributes.put(qname("type"), String.valueOf(cd.getType()));
   133 			printEmptyElement(qname("columnHeader"), attributes);
   134 		}
   135 	}
   136 
   137 	@Override
   138 	public void writeEndResultSet() {
   139 		super.writeEndResultSet();
   140 		printEndElement();
   141 	}
   142 
   143 	@Override
   144 	public void writeStartRow() {
   145 		super.writeStartRow();
   146 		printStartElement(qname("row"));
   147 	}
   148 
   149 	@Override
   150 	public void writeColumnValue(Object value) {
   151 		super.writeColumnValue(value);
   152 
   153 		Map<QName, String> attributes = null;
   154 		if (labeledColumns) {
   155 			attributes = new LinkedHashMap<>(2);
   156 			attributes.put(qname("label"), getCurrentColumnsHeader().getColumnDescriptors().get(getCurrentColumnsCount() - 1).getLabel());
   157 		}
   158 
   159 		if (value == null) {
   160 			if (attributes == null) {
   161 				attributes = new LinkedHashMap<>(2);
   162 			}
   163 			attributes.put(qname("null"), "true");
   164 			printEmptyElement(qname("column"), attributes);
   165 		} else if (value instanceof Array) {
   166 
   167 			Array sqlArray = (Array) value;
   168 			try {
   169 				Object[] array = (Object[]) sqlArray.getArray();
   170 				printStartElement(qname("column"), attributes);
   171 				printArray(array);
   172 				printEndElement();
   173 			} catch (SQLException e) {
   174 				log.log(Level.SEVERE, "Unable to format array", e);
   175 				writeColumnValue(String.valueOf(value));
   176 			}
   177 
   178 		} else if (value instanceof SQLXML) {
   179 			SQLXML xml = (SQLXML) value;
   180 			// TODO: parse DOM/SAX and transplant XML, don't escape (optional)
   181 			try {
   182 				printTextElement(qname("column"), attributes, xml.getString());
   183 			} catch (SQLException e) {
   184 				log.log(Level.SEVERE, "Unable to format XML", e);
   185 				writeColumnValue(String.valueOf(value));
   186 			}
   187 		} else {
   188 			printTextElement(qname("column"), attributes, toString(value));
   189 		}
   190 	}
   191 
   192 	private void printArray(Object[] array) {
   193 		printStartElement(qname("array"));
   194 		for (Object o : array) {
   195 			if (o instanceof Object[]) {
   196 				printStartElement(qname("item"));
   197 				printArray((Object[]) o);
   198 				printEndElement();
   199 			} else {
   200 				printTextElement(qname("item"), null, String.valueOf(o));
   201 			}
   202 		}
   203 		printEndElement();
   204 	}
   205 
   206 	@Override
   207 	public void writeEndRow() {
   208 		super.writeEndRow();
   209 		printEndElement();
   210 	}
   211 
   212 	@Override
   213 	public void writeUpdatesResult(int updatedRowsCount) {
   214 		super.writeUpdatesResult(updatedRowsCount);
   215 		printTextElement(qname("updatedRows"), null, String.valueOf(updatedRowsCount));
   216 	}
   217 
   218 	protected String toString(Object value) {
   219 		return String.valueOf(value);
   220 	}
   221 }