java/sql-dk/src/info/globalcode/sql/dk/formatting/TabularFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Fri, 10 Jan 2014 23:21:28 +0100
branchv_0
changeset 155 eb3676c6929b
parent 142 da1e38386d84
child 167 84aaa91642bf
permissions -rw-r--r--
more JavaDoc
     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.ColorfulPrintWriter;
    21 import static info.globalcode.sql.dk.ColorfulPrintWriter.*;
    22 import static info.globalcode.sql.dk.Functions.lpad;
    23 import static info.globalcode.sql.dk.Functions.rpad;
    24 import static info.globalcode.sql.dk.Functions.repeat;
    25 import java.util.List;
    26 
    27 /**
    28  * <p>Prints human-readable output – tables of result sets and text messages with update counts.</p>
    29  *
    30  * <p>Longer values might break the table – overflow the cells – see alternative tabular formatters
    31  * and the {@linkplain #PROPERTY_TRIM} property.</p>
    32  *
    33  * @author Ing. František Kučera (frantovo.cz)
    34  * @see TabularPrefetchingFormatter
    35  * @see TabularWrappingFormatter
    36  */
    37 public class TabularFormatter extends AbstractFormatter {
    38 
    39 	public static final String NAME = "tabular"; // bash-completion:formatter
    40 	private static final String HEADER_TYPE_PREFIX = " (";
    41 	private static final String HEADER_TYPE_SUFFIX = ")";
    42 	public static final String PROPERTY_ASCII = "ascii";
    43 	public static final String PROPERTY_COLORFUL = "color";
    44 	public static final String PROPERTY_TRIM = "trim";
    45 	protected ColorfulPrintWriter out;
    46 	private boolean firstResult = true;
    47 	private int[] columnWidth;
    48 	/**
    49 	 * use ASCII borders instead of unicode ones
    50 	 */
    51 	private final boolean asciiNostalgia;
    52 	/**
    53 	 * Trim values if they are longer than cell size
    54 	 */
    55 	private final boolean trimValues;
    56 
    57 	public TabularFormatter(FormatterContext formatterContext) {
    58 		super(formatterContext);
    59 		out = new ColorfulPrintWriter(formatterContext.getOutputStream());
    60 		asciiNostalgia = formatterContext.getProperties().getBoolean(PROPERTY_ASCII, false);
    61 		trimValues = formatterContext.getProperties().getBoolean(PROPERTY_TRIM, false);
    62 		out.setColorful(formatterContext.getProperties().getBoolean(PROPERTY_COLORFUL, true));
    63 	}
    64 
    65 	@Override
    66 	public void writeStartResultSet(ColumnsHeader header) {
    67 		super.writeStartResultSet(header);
    68 		printResultSeparator();
    69 
    70 		initColumnWidths(header.getColumnCount());
    71 
    72 		printTableIndent();
    73 		printTableBorder("╭");
    74 
    75 		List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
    76 
    77 		for (ColumnDescriptor cd : columnDescriptors) {
    78 			// padding: make header cell at least same width as data cells in this column
    79 			int typeWidth = cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length();
    80 			cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
    81 			updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
    82 
    83 			if (!cd.isFirstColumn()) {
    84 				printTableBorder("┬");
    85 			}
    86 			printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
    87 		}
    88 		printTableBorder("╮");
    89 		out.println();
    90 
    91 		for (ColumnDescriptor cd : columnDescriptors) {
    92 			if (cd.isFirstColumn()) {
    93 				printTableIndent();
    94 				printTableBorder("│ ");
    95 			} else {
    96 				printTableBorder(" │ ");
    97 			}
    98 			out.print(TerminalStyle.Bright, cd.getLabel());
    99 			out.print(HEADER_TYPE_PREFIX);
   100 			out.print(cd.getTypeName());
   101 			out.print(HEADER_TYPE_SUFFIX);
   102 			if (cd.isLastColumn()) {
   103 				printTableBorder(" │");
   104 			}
   105 		}
   106 		out.println();
   107 
   108 		printTableIndent();
   109 		printTableBorder("├");
   110 		for (int i = 1; i <= header.getColumnCount(); i++) {
   111 			if (i > 1) {
   112 				printTableBorder("┼");
   113 			}
   114 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   115 		}
   116 		printTableBorder("┤");
   117 		out.println();
   118 
   119 		out.flush();
   120 	}
   121 
   122 	/**
   123 	 * Must be called before
   124 	 * {@linkplain #updateColumnWidth(int, int)}
   125 	 * and {@linkplain #getColumnWidth(int)}
   126 	 * for each result set.
   127 	 *
   128 	 * @param columnCount number of columns in current result set
   129 	 */
   130 	protected void initColumnWidths(int columnCount) {
   131 		if (columnWidth == null) {
   132 			columnWidth = new int[columnCount];
   133 		}
   134 	}
   135 
   136 	protected void cleanColumnWidths() {
   137 		columnWidth = null;
   138 	}
   139 
   140 	@Override
   141 	public void writeColumnValue(Object value) {
   142 		super.writeColumnValue(value);
   143 		writeColumnValueInternal(value);
   144 	}
   145 
   146 	protected void writeColumnValueInternal(Object value) {
   147 
   148 		if (isCurrentColumnFirst()) {
   149 			printTableIndent();
   150 			printTableBorder("│ ");
   151 		} else {
   152 			printTableBorder(" │ ");
   153 		}
   154 
   155 		String valueString = toString(value);
   156 		printValueWithNewLinesReplaced(valueString);
   157 
   158 		if (isCurrentColumnLast()) {
   159 			printTableBorder(" │");
   160 		}
   161 
   162 	}
   163 
   164 	protected int getColumnWidth(int columnNumber) {
   165 		return columnWidth[columnNumber - 1];
   166 	}
   167 
   168 	private void setColumnWidth(int columnNumber, int width) {
   169 		columnWidth[columnNumber - 1] = width;
   170 	}
   171 
   172 	protected void updateColumnWidth(int columnNumber, int width) {
   173 		int oldWidth = getColumnWidth(columnNumber);
   174 		setColumnWidth(columnNumber, Math.max(width, oldWidth));
   175 
   176 	}
   177 
   178 	protected String toString(Object value) {
   179 		final int width = getColumnWidth(getCurrentColumnsCount());
   180 		String result;
   181 		if (value instanceof Number || value instanceof Boolean) {
   182 			result = lpad(String.valueOf(value), width);
   183 		} else {
   184 			result = rpad(String.valueOf(value), width);
   185 		}
   186 		// ?	value = (boolean) value ? "✔" : "✗";
   187 
   188 		if (trimValues && result.length() > width) {
   189 			result = result.substring(0, width - 1) + "…";
   190 		}
   191 
   192 		return result;
   193 	}
   194 
   195 	@Override
   196 	public void writeEndRow() {
   197 		super.writeEndRow();
   198 		writeEndRowInternal();
   199 	}
   200 
   201 	public void writeEndRowInternal() {
   202 		out.println();
   203 		out.flush();
   204 	}
   205 
   206 	@Override
   207 	public void writeEndResultSet() {
   208 		int columnCount = getCurrentColumnsHeader().getColumnCount();
   209 		super.writeEndResultSet();
   210 
   211 		printTableIndent();
   212 		printTableBorder("╰");
   213 		for (int i = 1; i <= columnCount; i++) {
   214 			if (i > 1) {
   215 				printTableBorder("┴");
   216 			}
   217 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   218 		}
   219 		printTableBorder("╯");
   220 		out.println();
   221 
   222 		cleanColumnWidths();
   223 
   224 		out.print(TerminalColor.Yellow, "Record count: ");
   225 		out.println(getCurrentRowCount());
   226 		out.bell();
   227 		out.flush();
   228 	}
   229 
   230 	@Override
   231 	public void writeUpdatesResult(int updatedRowsCount) {
   232 		super.writeUpdatesResult(updatedRowsCount);
   233 		printResultSeparator();
   234 		out.print(TerminalColor.Red, "Updated records: ");
   235 		out.println(updatedRowsCount);
   236 		out.bell();
   237 		out.flush();
   238 	}
   239 
   240 	@Override
   241 	public void writeEndDatabase() {
   242 		super.writeEndDatabase();
   243 		out.flush();
   244 	}
   245 
   246 	private void printResultSeparator() {
   247 		if (firstResult) {
   248 			firstResult = false;
   249 		} else {
   250 			out.println();
   251 		}
   252 	}
   253 
   254 	protected void printTableBorder(String border) {
   255 		if (asciiNostalgia) {
   256 			border = border.replaceAll("─", "-");
   257 			border = border.replaceAll("│", "|");
   258 			border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
   259 		}
   260 
   261 		out.print(TerminalColor.Green, border);
   262 	}
   263 
   264 	protected void printTableIndent() {
   265 		out.print(" ");
   266 	}
   267 
   268 	protected void printValueWithNewLinesReplaced(String valueString) {
   269 		String[] valueParts = valueString.split("\n");
   270 		for (int i = 0; i < valueParts.length; i++) {
   271 			String valuePart = valueParts[i];
   272 			// TODO: replace also TABs
   273 			out.print(TerminalColor.Cyan, valuePart);
   274 			if (i < valueParts.length - 1) {
   275 				out.print(TerminalColor.Red, "↲");
   276 			}
   277 		}
   278 	}
   279 }