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
21 changes: 19 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ The data can be output in several different different forms:
* **csv** - comma separated values format
* **html** - HyperText Markup Language (HTML) format
* **json** - JavaScript Object Notation (JSON) format
* **yaml** - Yet Another Markup Language (YAML) format

Here's an example of the standard **text** output:
```
Expand Down Expand Up @@ -128,6 +129,22 @@ Using the **json** format (e.g. `OutputFormat.JSON`), you get the following outp
]
```

Using the **yaml** format (e.g. `OutputFormat.YAML`), you get the following output:
```
- - "Column A"
- "Column 2"
- "Column III"
- Column A: "A"
Column 2: "B"
Column III: "c"
- Column A: 1
Column 2: 1024
Column III: 65535
- Column A: "Washington"
Column 2: "Adams"
Column III: "Jefferson"
```

### Alignment
ASCII **text**, **rich**, and **html** support different alignments. Here's how you would update the above table:
```Java
Expand Down Expand Up @@ -157,7 +174,7 @@ The **html** output will have the appropriate `style="text-align:xxx"` attribute
```

### Text options
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.
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**, **json**, and **yaml** 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 @@ -288,7 +305,7 @@ ASCII **text**, **rich**, and **html** remove redundancy by default. This de-dup
| | | F | E |
+------+------+------+------+
```
By default, the code recognizes the redundant fields and removes them from the rendering of the data. `PrettyTable::setRemoveRedundant(false)` keeps every repeated value for `toString()` and for `formattedString(OutputFormat)`. One call can still override that setting with `formattedString(OutputFormat, boolean)`. **csv** and **json** keep every cell either way.
By default, the code recognizes the redundant fields and removes them from the rendering of the data. `PrettyTable::setRemoveRedundant(false)` keeps every repeated value for `toString()` and for `formattedString(OutputFormat)`. One call can still override that setting with `formattedString(OutputFormat, boolean)`. **csv**, **json**, and **yaml** keep every cell either way.

In this case, either of these calls:
```Java
Expand Down
10 changes: 9 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<packaging>jar</packaging>
<version>1.1.0</version>
<name>rickwporter-prettytable</name>
<description>Displays List and Map object data in a variety of forms (e.g. text [ascii], rich [utf-8], csv, html, json)</description>
<description>Displays List and Map object data in a variety of forms (e.g. text [ascii], rich [utf-8], csv, html, json, yaml)</description>
<url>https://github.com/rickwporter/prettytable-java</url>
<developers>
<developer>
Expand Down Expand Up @@ -37,6 +37,7 @@
<!-- Main versions -->
<version.apache.lang3>3.20.0</version.apache.lang3>
<version.apache.csv>1.14.1</version.apache.csv>
<version.jackson>2.18.2</version.jackson>

<!-- JUnit versions -->
<version.jupiter.junit>5.14.1</version.jupiter.junit>
Expand Down Expand Up @@ -71,6 +72,13 @@
<version>${version.apache.csv}</version>
</dependency>

<!-- YAML writing -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>${version.jackson}</version>
</dependency>

<!-- Unit test stuff -->
<dependency>
<groupId>org.junit.jupiter</groupId>
Expand Down
1 change: 1 addition & 0 deletions src/main/java/rickwporter/prettytable/OutputFormat.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ public enum OutputFormat {
CSV,
HTML,
JSON,
YAML,
}
6 changes: 6 additions & 0 deletions src/main/java/rickwporter/prettytable/PrettyTable.java
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,10 @@ String toJson() {
return formattedString(OutputFormat.JSON, false);
}

String toYaml() {
return formattedString(OutputFormat.YAML, false);
}

public String formattedString(OutputFormat format) {
return this.formattedString(format, this.omitRedundant);
}
Expand All @@ -220,6 +224,8 @@ public String formattedString(OutputFormat format, boolean removeRedundant) {
renderer = new CsvTableRender();
} else if (format == OutputFormat.JSON) {
renderer = new JsonTableRender();
} else if (format == OutputFormat.YAML) {
renderer = new YamlTableRender();
} else if (format == OutputFormat.HTML) {
renderer = new HtmlTableRender();
} else {
Expand Down
74 changes: 74 additions & 0 deletions src/main/java/rickwporter/prettytable/YamlTableRender.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package rickwporter.prettytable;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;

class YamlTableRender implements TableRenderInterface {
private static final YAMLMapper MAPPER = yamlMapper();

private static YAMLMapper yamlMapper() {
YAMLMapper mapper = new YAMLMapper();
mapper.disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);
mapper.disable(YAMLGenerator.Feature.SPLIT_LINES);
mapper.enable(YAMLGenerator.Feature.LITERAL_BLOCK_STYLE);
return mapper;
}

private List<Object> toData(PrettyTable table) {
List<Object> data = new ArrayList<Object>();
List<String> headers = table.getHeaders();
if (!headers.isEmpty()) {
data.add(new ArrayList<String>(headers));
}
for (List<Object> row : table.getRows()) {
if (headers.isEmpty()) {
List<Object> values = new ArrayList<Object>();
for (Object cell : row) {
values.add(this.cellValue(cell));
}
data.add(values);
} else {
Map<String, Object> values = new LinkedHashMap<String, Object>();
for (int column = 0; column < row.size(); column++) {
values.put(headers.get(column), this.cellValue(row.get(column)));
}
data.add(values);
}
}
return data;
}

private Object cellValue(Object cell) {
if (cell instanceof PrettyTable) {
PrettyTable nested = (PrettyTable) cell;
if (nested.getDefaultOutput() == OutputFormat.YAML) {
return this.toData(nested);
}
return nested.toString();
}
if (cell instanceof Integer) {
return cell;
}
String text = cell.toString();
try {
return Integer.valueOf(text);
} catch (NumberFormatException ex) {
return text;
}
}

@Override
public String render(PrettyTable table, boolean removeRedundant) {
try {
return MAPPER.writeValueAsString(this.toData(table));
} catch (IOException ex) {
throw new IllegalStateException("Unable to render table as YAML", ex);
}
}
}
44 changes: 42 additions & 2 deletions src/test/java/rickwporter/prettytable/PrettyTableTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public class PrettyTableTest {
put(OutputFormat.CSV, "csv");
put(OutputFormat.HTML, "html");
put(OutputFormat.JSON, "json");
put(OutputFormat.YAML, "yaml");
}};

final String loadFileContent(String filename) {
Expand Down Expand Up @@ -91,6 +92,19 @@ public void testBasicJson() {
Assertions.assertEquals(expected, result);
}

@Test
public void testBasicYaml() {
PrettyTable table = createBasicTable();
String result = table.toYaml();
String expected = loadFileContent("PrettyTable_basic.yaml");
Assertions.assertEquals(expected, result);
result = table.formattedString(OutputFormat.YAML);
Assertions.assertEquals(expected, result);
table.setOutputFormat(OutputFormat.YAML);
result = table.toString();
Assertions.assertEquals(expected, result);
}

@Test
public void testBasicText() {
PrettyTable table = createBasicTable();
Expand Down Expand Up @@ -158,6 +172,7 @@ public void testUnformatted() {
Map<OutputFormat, String> formats = new HashMap<OutputFormat, String>() {{
put(OutputFormat.CSV, "csv");
put(OutputFormat.JSON, "json");
put(OutputFormat.YAML, "yaml");
}};
PrettyTable table = createFormattedTable();
for (Map.Entry<OutputFormat, String> entry: formats.entrySet()) {
Expand Down Expand Up @@ -283,6 +298,10 @@ public void testNumberAsStringJson() {
String expected = loadFileContent("PrettyTable_stringnum.json");
String result = table.formattedString(OutputFormat.JSON);
Assertions.assertEquals(expected, result);

expected = loadFileContent("PrettyTable_stringnum.yaml");
result = table.formattedString(OutputFormat.YAML);
Assertions.assertEquals(expected, result);
}

@Test
Expand Down Expand Up @@ -330,6 +349,17 @@ public void testSort() {
Assertions.assertThrows(ArrayIndexOutOfBoundsException.class, () -> table.sortByHeader("Q"));
}

@Test
public void testYamlEncoding() {
PrettyTable table = new PrettyTable("note", "value");
table.addRow("a: b", "say \"hi\"");
table.addRow("line1\nline2", "plain");
table.addRow("crlf\r\nhere", "tab\there");

String expected = loadFileContent("PrettyTable_yaml_encoded.yaml");
Assertions.assertEquals(expected, table.formattedString(OutputFormat.YAML));
}

@Test
public void testCsvEncoding() {
// CSV encoding needs to update/encapsulate special characters
Expand Down Expand Up @@ -401,6 +431,12 @@ public void testNested() {
big.setOutputFormat(OutputFormat.JSON);
Assertions.assertEquals(expected, big.toString());

expected = loadFileContent("PrettyTable_nested_mixed.yaml");
letters.setOutputFormat(OutputFormat.HTML);
numbers.setOutputFormat(OutputFormat.CSV);
big.setOutputFormat(OutputFormat.YAML);
Assertions.assertEquals(expected, big.toString());

expected = loadFileContent("PrettyTable_nested_mixed.txt");
letters.setOutputFormat(OutputFormat.JSON);
numbers.setOutputFormat(OutputFormat.CSV);
Expand Down Expand Up @@ -508,10 +544,11 @@ public void testRowDividersOption() {
Assertions.assertEquals(lineless, table.formattedString(OutputFormat.TEXT, true));
table.setShowLines(true);

// csv, html, and json ignore the setting
// csv, html, json, and yaml ignore the setting
Assertions.assertEquals(loadFileContent("PrettyTable_basic.csv"), table.formattedString(OutputFormat.CSV));
Assertions.assertEquals(loadFileContent("PrettyTable_basic.html"), table.formattedString(OutputFormat.HTML));
Assertions.assertEquals(loadFileContent("PrettyTable_basic.json"), table.formattedString(OutputFormat.JSON));
Assertions.assertEquals(loadFileContent("PrettyTable_basic.yaml"), table.formattedString(OutputFormat.YAML));
table.setOutputFormat(OutputFormat.HTML);
Assertions.assertEquals(loadFileContent("PrettyTable_basic.html"), table.toString());

Expand Down Expand Up @@ -565,14 +602,17 @@ public void testRemoveRedundantOption() {
Assertions.assertEquals(fullRich, table.formattedString(OutputFormat.RICH, false));
Assertions.assertEquals(fullHtml, table.toHtml(false));

// CSV and JSON keep every value either way
// CSV, JSON, and YAML keep every value either way
String csv = loadFileContent("PrettyTable_duplicate.csv");
String json = loadFileContent("PrettyTable_duplicate.json");
String yaml = loadFileContent("PrettyTable_duplicate.yaml");
Assertions.assertEquals(csv, table.formattedString(OutputFormat.CSV));
Assertions.assertEquals(json, table.formattedString(OutputFormat.JSON));
Assertions.assertEquals(yaml, table.formattedString(OutputFormat.YAML));
table.setRemoveRedundant(false);
Assertions.assertEquals(csv, table.formattedString(OutputFormat.CSV));
Assertions.assertEquals(json, table.formattedString(OutputFormat.JSON));
Assertions.assertEquals(yaml, table.formattedString(OutputFormat.YAML));
}

@Test
Expand Down
4 changes: 4 additions & 0 deletions src/test/java/rickwporter/prettytable/TableBuilderTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,10 @@ public void testInnerListFormats() {
expected = this.loadFileContent("TableBuilder_inner.json");
Assertions.assertEquals(expected, actual);

actual = builder.build(OutputFormat.YAML, this.innerList()).toString();
expected = this.loadFileContent("TableBuilder_inner.yaml");
Assertions.assertEquals(expected, actual);

actual = builder.build(OutputFormat.HTML, this.innerList()).toString();
expected = this.loadFileContent("TableBuilder_inner.html");
Assertions.assertEquals(expected, actual);
Expand Down
12 changes: 12 additions & 0 deletions src/test/resources/PrettyTable_basic.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
- - "Column A"
- "Column 2"
- "Column III"
- Column A: "A"
Column 2: "B"
Column III: "c"
- Column A: 1
Column 2: 1024
Column III: 65535
- Column A: "Washington"
Column 2: "Adams"
Column III: "Jefferson"
20 changes: 20 additions & 0 deletions src/test/resources/PrettyTable_duplicate.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
- - "Col1"
- "Col2"
- "Col3"
- "Col4"
- Col1: "A"
Col2: "B"
Col3: "C"
Col4: "D"
- Col1: "A"
Col2: "B"
Col3: "C"
Col4: "Z"
- Col1: "A"
Col2: "B"
Col3: "F"
Col4: "E"
- Col1: "A"
Col2: "B"
Col3: "F"
Col4: "E"
4 changes: 4 additions & 0 deletions src/test/resources/PrettyTable_empty.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
- - "Col1"
- "Col2"
- "Col3"
- "Col4"
30 changes: 30 additions & 0 deletions src/test/resources/PrettyTable_nested.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
- - "Table name"
- "Data"
- Table name: "Letters"
Data:
- - "A"
- "B"
- "C"
- A: "abc"
B: "def"
C: "ghij"
- A: "klmn"
B: "o"
C: "pqr"
- A: "st"
B: "uvx"
C: "yz"
- Table name: "Numbers"
Data:
- - "First"
- "Second"
- "Third"
- First: 123
Second: 4567
Third: 89012
- First: 3456
Second: 78
Third: 901
- First: 23456
Second: 7890
Third: 12
Loading
Loading