java/sql-dk/src/info/globalcode/sql/dk/formatting/TabularFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Sat, 15 Aug 2015 10:34:18 +0200
branchv_0
changeset 207 2bba68ef47c1
parent 206 e2f24eea8543
child 218 8e38caf43ca8
permissions -rw-r--r--
property annotations: default values
franta-hg@32
     1
/**
franta-hg@32
     2
 * SQL-DK
franta-hg@32
     3
 * Copyright © 2013 František Kučera (frantovo.cz)
franta-hg@32
     4
 *
franta-hg@32
     5
 * This program is free software: you can redistribute it and/or modify
franta-hg@32
     6
 * it under the terms of the GNU General Public License as published by
franta-hg@32
     7
 * the Free Software Foundation, either version 3 of the License, or
franta-hg@32
     8
 * (at your option) any later version.
franta-hg@32
     9
 *
franta-hg@32
    10
 * This program is distributed in the hope that it will be useful,
franta-hg@32
    11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
franta-hg@32
    12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
franta-hg@32
    13
 * GNU General Public License for more details.
franta-hg@32
    14
 *
franta-hg@32
    15
 * You should have received a copy of the GNU General Public License
franta-hg@32
    16
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
franta-hg@32
    17
 */
franta-hg@32
    18
package info.globalcode.sql.dk.formatting;
franta-hg@32
    19
franta-hg@34
    20
import info.globalcode.sql.dk.ColorfulPrintWriter;
franta-hg@37
    21
import static info.globalcode.sql.dk.ColorfulPrintWriter.*;
franta-hg@39
    22
import static info.globalcode.sql.dk.Functions.lpad;
franta-hg@39
    23
import static info.globalcode.sql.dk.Functions.rpad;
franta-hg@40
    24
import static info.globalcode.sql.dk.Functions.repeat;
franta-hg@206
    25
import info.globalcode.sql.dk.configuration.PropertyDeclaration;
franta-hg@206
    26
import static info.globalcode.sql.dk.formatting.CommonProperties.COLORFUL;
franta-hg@206
    27
import static info.globalcode.sql.dk.formatting.CommonProperties.COLORFUL_DESCRIPTION;
franta-hg@88
    28
import java.util.List;
franta-hg@169
    29
import java.util.regex.Matcher;
franta-hg@169
    30
import java.util.regex.Pattern;
franta-hg@34
    31
franta-hg@32
    32
/**
franta-hg@185
    33
 * <p>
franta-hg@185
    34
 * Prints human-readable output – tables of result sets and text messages with update counts.
franta-hg@185
    35
 * </p>
franta-hg@155
    36
 *
franta-hg@185
    37
 * <p>
franta-hg@185
    38
 * Longer values might break the table – overflow the cells – see alternative tabular formatters
franta-hg@185
    39
 * and the {@linkplain #PROPERTY_TRIM} property.
franta-hg@185
    40
 * </p>
franta-hg@32
    41
 *
franta-hg@32
    42
 * @author Ing. František Kučera (frantovo.cz)
franta-hg@155
    43
 * @see TabularPrefetchingFormatter
franta-hg@155
    44
 * @see TabularWrappingFormatter
franta-hg@32
    45
 */
franta-hg@207
    46
@PropertyDeclaration(name = COLORFUL, defaultValue = "true", type = Boolean.class, description = COLORFUL_DESCRIPTION)
franta-hg@207
    47
@PropertyDeclaration(name = TabularFormatter.PROPERTY_ASCII, defaultValue = "false", type = Boolean.class, description = "whether to use ASCII table borders instead of unicode ones")
franta-hg@207
    48
@PropertyDeclaration(name = TabularFormatter.PROPERTY_TRIM, defaultValue = "false", type = Boolean.class, description = "whether to trim the values to fit the column width")
franta-hg@32
    49
public class TabularFormatter extends AbstractFormatter {
franta-hg@32
    50
franta-hg@79
    51
	public static final String NAME = "tabular"; // bash-completion:formatter
franta-hg@39
    52
	private static final String HEADER_TYPE_PREFIX = " (";
franta-hg@39
    53
	private static final String HEADER_TYPE_SUFFIX = ")";
franta-hg@104
    54
	public static final String PROPERTY_ASCII = "ascii";
franta-hg@104
    55
	public static final String PROPERTY_TRIM = "trim";
franta-hg@170
    56
	private static final String NBSP = " ";
franta-hg@185
    57
	private static final Pattern whitespaceToReplace = Pattern.compile("\\n|\\r|\\t|" + NBSP);
franta-hg@123
    58
	protected ColorfulPrintWriter out;
franta-hg@37
    59
	private boolean firstResult = true;
franta-hg@39
    60
	private int[] columnWidth;
franta-hg@87
    61
	/**
franta-hg@87
    62
	 * use ASCII borders instead of unicode ones
franta-hg@87
    63
	 */
franta-hg@104
    64
	private final boolean asciiNostalgia;
franta-hg@87
    65
	/**
franta-hg@87
    66
	 * Trim values if they are longer than cell size
franta-hg@87
    67
	 */
franta-hg@104
    68
	private final boolean trimValues;
franta-hg@32
    69
franta-hg@32
    70
	public TabularFormatter(FormatterContext formatterContext) {
franta-hg@32
    71
		super(formatterContext);
franta-hg@34
    72
		out = new ColorfulPrintWriter(formatterContext.getOutputStream());
franta-hg@104
    73
		asciiNostalgia = formatterContext.getProperties().getBoolean(PROPERTY_ASCII, false);
franta-hg@104
    74
		trimValues = formatterContext.getProperties().getBoolean(PROPERTY_TRIM, false);
franta-hg@206
    75
		out.setColorful(formatterContext.getProperties().getBoolean(COLORFUL, true));
franta-hg@34
    76
	}
franta-hg@34
    77
franta-hg@34
    78
	@Override
franta-hg@142
    79
	public void writeStartResultSet(ColumnsHeader header) {
franta-hg@142
    80
		super.writeStartResultSet(header);
franta-hg@37
    81
		printResultSeparator();
franta-hg@37
    82
franta-hg@88
    83
		initColumnWidths(header.getColumnCount());
franta-hg@39
    84
franta-hg@40
    85
		printTableIndent();
franta-hg@40
    86
		printTableBorder("╭");
franta-hg@88
    87
franta-hg@88
    88
		List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
franta-hg@88
    89
franta-hg@88
    90
		for (ColumnDescriptor cd : columnDescriptors) {
franta-hg@88
    91
			// padding: make header cell at least same width as data cells in this column
franta-hg@88
    92
			int typeWidth = cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length();
franta-hg@88
    93
			cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
franta-hg@88
    94
			updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
franta-hg@88
    95
franta-hg@40
    96
			if (!cd.isFirstColumn()) {
franta-hg@40
    97
				printTableBorder("┬");
franta-hg@40
    98
			}
franta-hg@40
    99
			printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
franta-hg@40
   100
		}
franta-hg@40
   101
		printTableBorder("╮");
franta-hg@40
   102
		out.println();
franta-hg@40
   103
franta-hg@88
   104
		for (ColumnDescriptor cd : columnDescriptors) {
franta-hg@40
   105
			if (cd.isFirstColumn()) {
franta-hg@40
   106
				printTableIndent();
franta-hg@40
   107
				printTableBorder("│ ");
franta-hg@40
   108
			} else {
franta-hg@40
   109
				printTableBorder(" │ ");
franta-hg@40
   110
			}
franta-hg@37
   111
			out.print(TerminalStyle.Bright, cd.getLabel());
franta-hg@39
   112
			out.print(HEADER_TYPE_PREFIX);
franta-hg@37
   113
			out.print(cd.getTypeName());
franta-hg@39
   114
			out.print(HEADER_TYPE_SUFFIX);
franta-hg@40
   115
			if (cd.isLastColumn()) {
franta-hg@40
   116
				printTableBorder(" │");
franta-hg@37
   117
			}
franta-hg@37
   118
		}
franta-hg@37
   119
		out.println();
franta-hg@40
   120
franta-hg@40
   121
		printTableIndent();
franta-hg@40
   122
		printTableBorder("├");
franta-hg@40
   123
		for (int i = 1; i <= header.getColumnCount(); i++) {
franta-hg@40
   124
			if (i > 1) {
franta-hg@40
   125
				printTableBorder("┼");
franta-hg@40
   126
			}
franta-hg@40
   127
			printTableBorder(repeat('─', getColumnWidth(i) + 2));
franta-hg@40
   128
		}
franta-hg@40
   129
		printTableBorder("┤");
franta-hg@40
   130
		out.println();
franta-hg@40
   131
franta-hg@37
   132
		out.flush();
franta-hg@37
   133
	}
franta-hg@37
   134
franta-hg@88
   135
	/**
franta-hg@88
   136
	 * Must be called before
franta-hg@88
   137
	 * {@linkplain #updateColumnWidth(int, int)}
franta-hg@88
   138
	 * and {@linkplain #getColumnWidth(int)}
franta-hg@88
   139
	 * for each result set.
franta-hg@88
   140
	 *
franta-hg@88
   141
	 * @param columnCount number of columns in current result set
franta-hg@88
   142
	 */
franta-hg@88
   143
	protected void initColumnWidths(int columnCount) {
franta-hg@88
   144
		if (columnWidth == null) {
franta-hg@88
   145
			columnWidth = new int[columnCount];
franta-hg@88
   146
		}
franta-hg@88
   147
	}
franta-hg@88
   148
franta-hg@88
   149
	protected void cleanColumnWidths() {
franta-hg@88
   150
		columnWidth = null;
franta-hg@88
   151
	}
franta-hg@88
   152
franta-hg@37
   153
	@Override
franta-hg@34
   154
	public void writeColumnValue(Object value) {
franta-hg@34
   155
		super.writeColumnValue(value);
franta-hg@123
   156
		writeColumnValueInternal(value);
franta-hg@123
   157
	}
franta-hg@123
   158
franta-hg@123
   159
	protected void writeColumnValueInternal(Object value) {
franta-hg@34
   160
franta-hg@40
   161
		if (isCurrentColumnFirst()) {
franta-hg@40
   162
			printTableIndent();
franta-hg@40
   163
			printTableBorder("│ ");
franta-hg@40
   164
		} else {
franta-hg@90
   165
			printTableBorder(" │ ");
franta-hg@34
   166
		}
franta-hg@37
   167
franta-hg@123
   168
		String valueString = toString(value);
franta-hg@169
   169
		printValueWithWhitespaceReplaced(valueString);
franta-hg@40
   170
franta-hg@40
   171
		if (isCurrentColumnLast()) {
franta-hg@90
   172
			printTableBorder(" │");
franta-hg@40
   173
		}
franta-hg@40
   174
franta-hg@39
   175
	}
franta-hg@39
   176
franta-hg@123
   177
	protected int getColumnWidth(int columnNumber) {
franta-hg@39
   178
		return columnWidth[columnNumber - 1];
franta-hg@39
   179
	}
franta-hg@39
   180
franta-hg@39
   181
	private void setColumnWidth(int columnNumber, int width) {
franta-hg@39
   182
		columnWidth[columnNumber - 1] = width;
franta-hg@39
   183
	}
franta-hg@39
   184
franta-hg@88
   185
	protected void updateColumnWidth(int columnNumber, int width) {
franta-hg@39
   186
		int oldWidth = getColumnWidth(columnNumber);
franta-hg@39
   187
		setColumnWidth(columnNumber, Math.max(width, oldWidth));
franta-hg@39
   188
franta-hg@39
   189
	}
franta-hg@39
   190
franta-hg@39
   191
	protected String toString(Object value) {
franta-hg@39
   192
		final int width = getColumnWidth(getCurrentColumnsCount());
franta-hg@87
   193
		String result;
franta-hg@43
   194
		if (value instanceof Number || value instanceof Boolean) {
franta-hg@98
   195
			result = lpad(String.valueOf(value), width);
franta-hg@39
   196
		} else {
franta-hg@98
   197
			result = rpad(String.valueOf(value), width);
franta-hg@39
   198
		}
franta-hg@40
   199
		// ?	value = (boolean) value ? "✔" : "✗";
franta-hg@87
   200
franta-hg@87
   201
		if (trimValues && result.length() > width) {
franta-hg@87
   202
			result = result.substring(0, width - 1) + "…";
franta-hg@87
   203
		}
franta-hg@87
   204
franta-hg@87
   205
		return result;
franta-hg@34
   206
	}
franta-hg@34
   207
franta-hg@34
   208
	@Override
franta-hg@34
   209
	public void writeEndRow() {
franta-hg@34
   210
		super.writeEndRow();
franta-hg@123
   211
		writeEndRowInternal();
franta-hg@123
   212
	}
franta-hg@123
   213
franta-hg@123
   214
	public void writeEndRowInternal() {
franta-hg@34
   215
		out.println();
franta-hg@34
   216
		out.flush();
franta-hg@32
   217
	}
franta-hg@37
   218
franta-hg@37
   219
	@Override
franta-hg@37
   220
	public void writeEndResultSet() {
franta-hg@40
   221
		int columnCount = getCurrentColumnsHeader().getColumnCount();
franta-hg@37
   222
		super.writeEndResultSet();
franta-hg@40
   223
franta-hg@40
   224
		printTableIndent();
franta-hg@40
   225
		printTableBorder("╰");
franta-hg@40
   226
		for (int i = 1; i <= columnCount; i++) {
franta-hg@40
   227
			if (i > 1) {
franta-hg@40
   228
				printTableBorder("┴");
franta-hg@40
   229
			}
franta-hg@40
   230
			printTableBorder(repeat('─', getColumnWidth(i) + 2));
franta-hg@40
   231
		}
franta-hg@40
   232
		printTableBorder("╯");
franta-hg@40
   233
		out.println();
franta-hg@40
   234
franta-hg@88
   235
		cleanColumnWidths();
franta-hg@40
   236
franta-hg@37
   237
		out.print(TerminalColor.Yellow, "Record count: ");
franta-hg@37
   238
		out.println(getCurrentRowCount());
franta-hg@40
   239
		out.bell();
franta-hg@37
   240
		out.flush();
franta-hg@37
   241
	}
franta-hg@37
   242
franta-hg@37
   243
	@Override
franta-hg@142
   244
	public void writeUpdatesResult(int updatedRowsCount) {
franta-hg@142
   245
		super.writeUpdatesResult(updatedRowsCount);
franta-hg@37
   246
		printResultSeparator();
franta-hg@37
   247
		out.print(TerminalColor.Red, "Updated records: ");
franta-hg@37
   248
		out.println(updatedRowsCount);
franta-hg@40
   249
		out.bell();
franta-hg@37
   250
		out.flush();
franta-hg@37
   251
	}
franta-hg@37
   252
franta-hg@37
   253
	@Override
franta-hg@37
   254
	public void writeEndDatabase() {
franta-hg@37
   255
		super.writeEndDatabase();
franta-hg@37
   256
		out.flush();
franta-hg@37
   257
	}
franta-hg@37
   258
franta-hg@37
   259
	private void printResultSeparator() {
franta-hg@37
   260
		if (firstResult) {
franta-hg@37
   261
			firstResult = false;
franta-hg@37
   262
		} else {
franta-hg@37
   263
			out.println();
franta-hg@37
   264
		}
franta-hg@37
   265
	}
franta-hg@40
   266
franta-hg@123
   267
	protected void printTableBorder(String border) {
franta-hg@76
   268
		if (asciiNostalgia) {
franta-hg@76
   269
			border = border.replaceAll("─", "-");
franta-hg@76
   270
			border = border.replaceAll("│", "|");
franta-hg@76
   271
			border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
franta-hg@76
   272
		}
franta-hg@87
   273
franta-hg@40
   274
		out.print(TerminalColor.Green, border);
franta-hg@40
   275
	}
franta-hg@40
   276
franta-hg@123
   277
	protected void printTableIndent() {
franta-hg@40
   278
		out.print(" ");
franta-hg@40
   279
	}
franta-hg@123
   280
franta-hg@169
   281
	protected void printValueWithWhitespaceReplaced(String valueString) {
franta-hg@169
   282
franta-hg@169
   283
		Matcher m = whitespaceToReplace.matcher(valueString);
franta-hg@169
   284
franta-hg@169
   285
		int start = 0;
franta-hg@169
   286
		while (m.find(start)) {
franta-hg@169
   287
franta-hg@169
   288
			out.print(TerminalColor.Cyan, valueString.substring(start, m.start()));
franta-hg@169
   289
franta-hg@169
   290
			switch (m.group()) {
franta-hg@169
   291
				case "\n":
franta-hg@169
   292
					out.print(TerminalColor.Red, "↲");
franta-hg@169
   293
					break;
franta-hg@185
   294
				case "\r":
franta-hg@185
   295
					out.print(TerminalColor.Red, "⏎");
franta-hg@185
   296
					break;
franta-hg@169
   297
				case "\t":
franta-hg@169
   298
					out.print(TerminalColor.Red, "↹");
franta-hg@169
   299
					break;
franta-hg@170
   300
				case NBSP:
franta-hg@170
   301
					out.print(TerminalColor.Red, "⎵");
franta-hg@170
   302
					break;
franta-hg@169
   303
				default:
franta-hg@169
   304
					throw new IllegalStateException("Unexpected whitespace token: „" + m.group() + "“");
franta-hg@123
   305
			}
franta-hg@169
   306
franta-hg@169
   307
			start = m.end();
franta-hg@123
   308
		}
franta-hg@167
   309
franta-hg@169
   310
		out.print(TerminalColor.Cyan, valueString.substring(start, valueString.length()));
franta-hg@123
   311
	}
franta-hg@32
   312
}