Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Display data in a tabular form with Java

The data can be output in several different different forms:
* **text** - attractive ASCII format
* **rich** - Unicode box drawing
* **csv** - comma separated values format
* **html** - HyperText Markup Language (HTML) format
* **json** - JavaScript Object Notation (JSON) format
Expand Down Expand Up @@ -38,7 +39,7 @@ import rickwporter.prettytable.PrettyTable.OutputFormat;
System.out.println(table.formattedString(OutputFormat.TEXT));
```

You can use `PrettyTable::toString()` as an alternative to `PrettyTable::formattedString()`. If you want a format other than **text**, you can set it with `PrettyTable::setOutputFormat()`. Repeated leading cells in **text** and **html** follow `PrettyTable::setRemoveRedundant()`, which removes them by default. The code below would replace the `println()` call from above:
You can use `PrettyTable::toString()` as an alternative to `PrettyTable::formattedString()`. If you want a format other than **text**, you can set it with `PrettyTable::setOutputFormat()`. Repeated leading cells in **text**, **rich**, and **html** follow `PrettyTable::setRemoveRedundant()`, which removes them by default. The code below would replace the `println()` call from above:
```Java
table.setOutputFormat(OutputFormat.HTML);
System.out.println(table.toString());
Expand Down Expand Up @@ -85,6 +86,22 @@ Using the **html** format (e.g. `OutputFormat.HTML`), you get the following outp
</table>
```

Using the **rich** format (e.g. `OutputFormat.RICH`), you more aesthetically please lines for the table. The header (if shown) gets a heavier weight border. The header, border, row-divider, alignment, and deduplication settings are the same as **text**. Hiding the border (`setShowLines(false)`) leaves padded text, so a nested table stays borderless.

```Java
System.out.println(table.formattedString(OutputFormat.RICH));
```

```
┏━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━┓
┃ Column A ┃ Column 2 ┃ Column III ┃
┡━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━┩
│ A │ B │ c │
│ 1 │ 1024 │ 65535 │
│ Washington │ Adams │ Jefferson │
└────────────┴──────────┴────────────┘
```

Using the **json** format (e.g. `OutputFormat.JSON`), you get the following output:
```
[
Expand Down Expand Up @@ -112,7 +129,7 @@ Using the **json** format (e.g. `OutputFormat.JSON`), you get the following outp
```

### Alignment
Both ASCII **text** and **html** formats support different alignments. Here's how you would update the above table:
ASCII **text**, **rich**, and **html** support different alignments. Here's how you would update the above table:
```Java
import rickwporter.prettytable.PrettyTable.HorizontalAlign;

Expand Down Expand Up @@ -140,7 +157,7 @@ The **html** output will have the appropriate `style="text-align:xxx"` attribute
```

### Text options
ASCII **text** output can hide the header row, drop the border, draw a rule under data rows, and print a caption under the table. **csv**, **html**, and **json** ignore these settings.
ASCII **text** and **rich** output can hide the header row, drop the border, draw a rule under data rows, and print a caption under the table. **csv**, **html**, and **json** ignore these settings. A `null` or empty caption is skipped. Any other caption is printed unchanged.

`PrettyTable::setShowHeader(false)` omits the header. Column widths then come only from the data cells, so the columns can get narrower. A table built with no headers already skips that row.

Expand Down Expand Up @@ -250,7 +267,7 @@ US presidents
```

### Deduplication
Both ASCII **text** and **html** formats remove redundancy by default. This de-duplication generally makes the output more aesthetically pleasing, as demonstrated below.
ASCII **text**, **rich**, and **html** remove redundancy by default. This de-duplication generally makes the output more aesthetically pleasing, as demonstrated below.

A table created like this:
```Java
Expand Down Expand Up @@ -342,6 +359,8 @@ import rickwporter.prettytable.TableBuilder;
Found 1 items
```

`table.setOutputFormat(OutputFormat.RICH)` prints effectively the same table with prettier lines/borders.

### BuilderConfig
`BuilderConfig` holds the labels, caption, truncation limits, and column selection used by `build`. Each setter returns the config, so calls can be chained. A `null` config uses the defaults.

Expand Down
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<java.version>1.8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<!-- Main versions -->
<version.apache.lang3>3.20.0</version.apache.lang3>
Expand Down
7 changes: 7 additions & 0 deletions src/main/java/rickwporter/prettytable/PrettyTable.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public String getHtmlStyle() {

public enum OutputFormat {
TEXT,
RICH,
CSV,
HTML,
JSON,
Expand Down Expand Up @@ -211,6 +212,10 @@ String toText(boolean removeRedundant) {
return formattedString(OutputFormat.TEXT, removeRedundant);
}

String toRich(boolean removeRedundant) {
return formattedString(OutputFormat.RICH, removeRedundant);
}

String toCsv() {
return formattedString(OutputFormat.CSV, false);
}
Expand All @@ -231,6 +236,8 @@ public String formattedString(OutputFormat format, boolean removeRedundant) {
final TableRenderInterface renderer;
if (format == OutputFormat.TEXT) {
renderer = new TextTableRender();
} else if (format == OutputFormat.RICH) {
renderer = new RichTableRender();
} else if (format == OutputFormat.CSV) {
renderer = new CsvTableRender();
} else if (format == OutputFormat.JSON) {
Expand Down
56 changes: 56 additions & 0 deletions src/main/java/rickwporter/prettytable/RichTableRender.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package rickwporter.prettytable;

import java.util.ArrayList;
import java.util.List;

import rickwporter.prettytable.PrettyTable.HorizontalAlign;

class RichTableRender extends BaseTextTableRender {
// Four characters are left, fill, junction, right.
private static final TableGlyphs HEAVY_TOP = new TableGlyphs('┏', '━', '┳', '┓');
private static final TableGlyphs HEAVY_HEAD = new TableGlyphs('┡', '━', '╇', '┩');
private static final TableGlyphs HEAVY_VERT = new TableGlyphs('┃', ' ', '┃', '┃');
private static final TableGlyphs SQUARE_TOP = new TableGlyphs('┌', '─', '┬', '┐');
private static final TableGlyphs LIGHT_VERT = new TableGlyphs('│', ' ', '│', '│');
private static final TableGlyphs LIGHT_ROW = new TableGlyphs('├', '─', '┼', '┤');
private static final TableGlyphs LIGHT_BOTTOM = new TableGlyphs('└', '─', '┴', '┘');

@Override
public String render(PrettyTable table, boolean removeRedundant) {
List<Integer> maxWidths = table.getMaxWidths();
boolean showLines = table.isShowLines();
boolean rowDividers = table.isRowDividers() && showLines;
boolean header = table.isShowHeader() && !table.getHeaders().isEmpty();
List<HorizontalAlign> hAligns = this.alignments(table);
StringBuilder result = new StringBuilder();

if (showLines && header) {
result.append(this.rule(HEAVY_TOP, maxWidths, true));
result.append(this.textRow(table.getHeaders(), maxWidths, hAligns, HEAVY_VERT));
result.append(this.rule(HEAVY_HEAD, maxWidths, true));
} else if (header) {
result.append(this.textRow(table.getHeaders(), maxWidths, hAligns, null));
} else if (showLines) {
result.append(this.rule(SQUARE_TOP, maxWidths, true));
}

List<List<Object>> rows = table.getRows();
List<String> lastRow = new ArrayList<String>();
for (int rIdx = 0; rIdx < rows.size(); rIdx++) {
List<String> currentRow = this.cellText(rows.get(rIdx));
List<String> fullRow = new ArrayList<String>(currentRow);
boolean divider = true;
if (removeRedundant) {
divider = !this.sharesLeadingCells(lastRow, currentRow);
lastRow = fullRow;
}
TableGlyphs vertical = showLines ? LIGHT_VERT : null;
result.append(this.textRow(currentRow, maxWidths, hAligns, vertical));
boolean last = rIdx == rows.size() - 1;
result.append(this.rule(LIGHT_ROW, maxWidths, rowDividers && divider && !last));
}
result.append(this.rule(LIGHT_BOTTOM, maxWidths, showLines));
result.append(this.caption(table.getCaption()));
return result.toString();
}
}
45 changes: 45 additions & 0 deletions src/test/java/rickwporter/prettytable/PrettyTableTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
public class PrettyTableTest {
Map<OutputFormat, String> OUTPUT_FORMAT_EXTENSIONS = new HashMap<OutputFormat, String>() {{
put(OutputFormat.TEXT, "text");
// NOTE: this is a little hacky, but named rich text as `txt` to distinguish from plain/ascii text
put(OutputFormat.RICH, "txt");
put(OutputFormat.CSV, "csv");
put(OutputFormat.HTML, "html");
put(OutputFormat.JSON, "json");
Expand Down Expand Up @@ -112,12 +114,30 @@ public void testBasicText() {
Assertions.assertEquals(expected, result);
}

@Test
public void testBasicRich() {
PrettyTable table = createBasicTable();
String result = table.toRich(true);
String expected = loadFileContent("PrettyTable_basic.txt");
Assertions.assertEquals(expected, result);
// same answer when going through 'formattedString()'
result = table.formattedString(OutputFormat.RICH);
Assertions.assertEquals(expected, result);
// same answer in this case because there are no duplicates
result = table.toRich(false);
Assertions.assertEquals(expected, result);
table.setOutputFormat(OutputFormat.RICH);
result = table.toString();
Assertions.assertEquals(expected, result);
}

@Test
public void testFormatted() {
// this checks all the formatted outputs
Map<OutputFormat, String> formats = new HashMap<OutputFormat, String>() {{
put(OutputFormat.HTML, "html");
put(OutputFormat.TEXT, "text");
put(OutputFormat.RICH, "txt");
}};
PrettyTable table = createFormattedTable();
for (Map.Entry<OutputFormat, String> entry: formats.entrySet()) {
Expand Down Expand Up @@ -179,6 +199,12 @@ public void testDuplicated() {
Assertions.assertEquals(expected, result);
result = table.formattedString(OutputFormat.TEXT, false);
Assertions.assertEquals(expected, result);

expected = loadFileContent("PrettyTable_duplicate_undup.txt");
result = table.toRich(false);
Assertions.assertEquals(expected, result);
result = table.formattedString(OutputFormat.RICH, false);
Assertions.assertEquals(expected, result);

expected = loadFileContent("PrettyTable_duplicate_undup.html");
result = table.toHtml(false);
Expand All @@ -201,6 +227,9 @@ public void testDuplicatedMixed() {

expected = loadFileContent("PrettyTable_duplicate_mixed.html");
Assertions.assertEquals(expected, table.formattedString(OutputFormat.HTML));

expected = loadFileContent("PrettyTable_duplicate_mixed.txt");
Assertions.assertEquals(expected, table.formattedString(OutputFormat.RICH));
}

@Test
Expand Down Expand Up @@ -326,6 +355,8 @@ public void testTextNewlines() {

String expected = loadFileContent("PrettyTable_newlines.text");
Assertions.assertEquals(expected, table.formattedString(OutputFormat.TEXT));
expected = loadFileContent("PrettyTable_newlines.txt");
Assertions.assertEquals(expected, table.formattedString(OutputFormat.RICH));
}

@Test
Expand Down Expand Up @@ -372,6 +403,12 @@ public void testNested() {
numbers.setOutputFormat(OutputFormat.CSV);
big.setOutputFormat(OutputFormat.JSON);
Assertions.assertEquals(expected, big.toString());

expected = loadFileContent("PrettyTable_nested_mixed.txt");
letters.setOutputFormat(OutputFormat.JSON);
numbers.setOutputFormat(OutputFormat.CSV);
big.setOutputFormat(OutputFormat.RICH);
Assertions.assertEquals(expected, big.toString());
}

@Test
Expand Down Expand Up @@ -498,29 +535,37 @@ public void testRemoveRedundantOption() {
table.addRow("A", "B", "F", "E");

String dedupedText = loadFileContent("PrettyTable_duplicate.text");
String dedupedRich = loadFileContent("PrettyTable_duplicate.txt");
String dedupedHtml = loadFileContent("PrettyTable_duplicate.html");
String fullText = loadFileContent("PrettyTable_duplicate_undup.text");
String fullRich = loadFileContent("PrettyTable_duplicate_undup.txt");
String fullHtml = loadFileContent("PrettyTable_duplicate_undup.html");

Assertions.assertTrue(table.isRemoveRedundant());
Assertions.assertEquals(dedupedText, table.formattedString(OutputFormat.TEXT));
Assertions.assertEquals(dedupedRich, table.formattedString(OutputFormat.RICH));
Assertions.assertEquals(dedupedHtml, table.formattedString(OutputFormat.HTML));
Assertions.assertEquals(dedupedText, table.toString());

table.setRemoveRedundant(false);
Assertions.assertFalse(table.isRemoveRedundant());
Assertions.assertEquals(fullText, table.formattedString(OutputFormat.TEXT));
Assertions.assertEquals(fullRich, table.formattedString(OutputFormat.RICH));
Assertions.assertEquals(fullHtml, table.formattedString(OutputFormat.HTML));
Assertions.assertEquals(fullText, table.toString());

table.setOutputFormat(OutputFormat.HTML);
Assertions.assertEquals(fullHtml, table.toString());
table.setOutputFormat(OutputFormat.RICH);
Assertions.assertEquals(fullRich, table.toString());

// the explicit flag still overrides the option
Assertions.assertEquals(dedupedText, table.formattedString(OutputFormat.TEXT, true));
Assertions.assertEquals(dedupedRich, table.formattedString(OutputFormat.RICH, true));
Assertions.assertEquals(dedupedHtml, table.formattedString(OutputFormat.HTML, true));
table.setRemoveRedundant(true);
Assertions.assertEquals(fullText, table.formattedString(OutputFormat.TEXT, false));
Assertions.assertEquals(fullRich, table.formattedString(OutputFormat.RICH, false));
Assertions.assertEquals(fullHtml, table.toHtml(false));

// CSV and JSON keep every value either way
Expand Down
Loading
Loading