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
55 changes: 54 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ Here's an example of the standard **text** output:
+------------+----------+------------+
```

The `PrettyTable` class handles a table as shown above. The `TableBuilder` class can be used to turn a `Map` or `List` object into a `PrettyTable`.
The `PrettyTable` class handles a table as shown above. The `TableBuilder` class can be used to turn a `Map` or `List` object into a `PrettyTable`. `PrettyObject` also renders similar data types directly to a string with special handling for **json** and **yaml**.

## PrettyTable Usage
Here are the basics for how to create a `PrettyTable` as shown above:
Expand Down Expand Up @@ -411,6 +411,59 @@ import rickwporter.prettytable.BuilderConfig;
| `setUrlPrefixes` | `http://`, `https://`, `ftp://` |
| `setColumns` | `null` |

## PrettyObject Usage
`PrettyObject` renders a `Map` or a `List` to a string. The constructor takes an optional `BuilderConfig`. The output format and the data are passed to `render`.

The `PrettyObject` adds some special handling for other data types, and **json** and **yaml** output formats. The **json** and **yaml** output formats render the object directly, while the other types build/render the data into a `PrettyTable` using the `TableBuilder` with provided configuration.

```Java
import rickwporter.prettytable.PrettyObject;
import rickwporter.prettytable.OutputFormat;

Map<String, Object> item = new LinkedHashMap<String, Object>();
item.put("abc", "def");
item.put("ghi", false);
item.put("jkl", Arrays.asList("mno", "pqr", "stu"));
item.put("yxa", null);

PrettyObject pretty = new PrettyObject();
System.out.println(pretty.render(OutputFormat.TEXT, item));
```

```
+----------+---------------+
| Property | Value |
+----------+---------------+
| abc | def |
| ghi | False |
| jkl | mno, pqr, stu |
| yxa | None |
+----------+---------------+
```

The same map in **json**:
```
{
"abc" : "def",
"ghi" : false,
"jkl" : [
"mno",
"pqr",
"stu"
],
"yxa" : null
}
```

A `BuilderConfig` changes the table formats. **json** and **yaml** keep the object as given.

```Java
import rickwporter.prettytable.BuilderConfig;

BuilderConfig config = new BuilderConfig().setPropertyLabel("Field");
System.out.println(new PrettyObject(config).render(OutputFormat.RICH, item));
```

## Example

[`examples/pets-cli`](examples/pets-cli) is a [picocli](https://picocli.info/) client for the modified [OpenAPI Petstore](examples/pets.yaml). It prints JSON responses with `TableBuilder`. See the example README for how to build and run it.
Expand Down
17 changes: 13 additions & 4 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,13 @@
<version>${version.apache.lang3}</version>
</dependency>

<!-- General things -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${version.jackson}</version>
</dependency>

<!-- CSV writing -->
<dependency>
<groupId>org.apache.commons</groupId>
Expand All @@ -75,13 +82,15 @@

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

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

Expand Down
77 changes: 77 additions & 0 deletions src/main/java/rickwporter/prettytable/PrettyObject.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package rickwporter.prettytable;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.util.DefaultIndenter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;

public final class PrettyObject {
private static final String INDENT = " ";
private BuilderConfig config;

public PrettyObject() {
this(null);
}

public PrettyObject(BuilderConfig options) {
this.config = options == null ? new BuilderConfig() : options;
}

private static ObjectMapper jsonMapper() {
ObjectMapper mapper = new ObjectMapper();
DefaultIndenter indenter = new DefaultIndenter(INDENT, "\n");
DefaultPrettyPrinter printer = new DefaultPrettyPrinter()
.withArrayIndenter(indenter)
.withObjectIndenter(indenter);
mapper.setDefaultPrettyPrinter(printer);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
return mapper;
}

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;
}

String renderJson(Object object, ObjectMapper mapper) {
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException ex) {
throw new IllegalStateException("Unable to render object as JSON", ex);
}
}

String renderYaml(Object object, YAMLMapper mapper) {
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException ex) {
throw new IllegalStateException("Unable to render object as YAML", ex);
}
}

public String render(OutputFormat format, Object object) {
if (object == null) {
return "";
}
if (object instanceof String || object instanceof Number || object instanceof Boolean) {
return String.valueOf(object);
}
if (format == OutputFormat.JSON) {
return this.renderJson(object, jsonMapper());
}

if (format == OutputFormat.YAML) {
return this.renderYaml(object, yamlMapper());
}

PrettyTable table = new TableBuilder(this.config).build(format, object);
return table.toString();
}

}
143 changes: 143 additions & 0 deletions src/test/java/rickwporter/prettytable/PrettyObjectTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
package rickwporter.prettytable;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;

public class PrettyObjectTest {
private String loadFileContent(String filename) {
URL resource = getClass().getClassLoader().getResource(filename);
if (resource == null) {
throw new IllegalStateException("Missing resource " + filename);
}
try {
return Files.readString(Paths.get(resource.toURI()));
} catch (Exception ex) {
throw new IllegalStateException("Unable to read " + filename, ex);
}
}

private static Map<Object, Object> mapOf(Object... pairs) {
if (pairs.length % 2 != 0) {
throw new IllegalArgumentException("Expected key/value pairs");
}
Map<Object, Object> result = new LinkedHashMap<Object, Object>();
for (int i = 0; i < pairs.length; i += 2) {
result.put(pairs[i], pairs[i + 1]);
}
return result;
}

private Map<Object, Object> simpleDict() {
return mapOf(
"abc", "def",
"ghi", false,
"jkl", Arrays.asList("mno", "pqr", "stu"),
"vwx", Arrays.asList(1, 2, 4),
2, 3,
"yxa", null);
}

@Test
public void testSimpleDict() {
Map<OutputFormat, String> extensions = new LinkedHashMap<OutputFormat, String>();
extensions.put(OutputFormat.TEXT, "text");
extensions.put(OutputFormat.RICH, "txt");
extensions.put(OutputFormat.CSV, "csv");
extensions.put(OutputFormat.HTML, "html");
extensions.put(OutputFormat.JSON, "json");
extensions.put(OutputFormat.YAML, "yaml");

PrettyObject pretty = new PrettyObject();
Map<Object, Object> data = this.simpleDict();
for (Map.Entry<OutputFormat, String> entry : extensions.entrySet()) {
String filename = "PrettyObject_simple_dict." + entry.getValue();
Assertions.assertEquals(
this.loadFileContent(filename),
pretty.render(entry.getKey(), data),
filename);
}
}

@Test
public void testNullValue() {
PrettyObject uut = new PrettyObject();

for (OutputFormat format : OutputFormat.values()) {
Assertions.assertEquals("", uut.render(format, null));
}
}

@Test
public void testSimpleValues() {
PrettyObject uut = new PrettyObject();

for (OutputFormat format : OutputFormat.values()) {
Assertions.assertEquals("1", uut.render(format, 1));
Assertions.assertEquals("foo", uut.render(format, "foo"));
Assertions.assertEquals("true", uut.render(format, true));
}
}

@Test
public void testConfig() {
Map<Object, Object> data = this.simpleDict();

String label = "My label";
PrettyObject config = new PrettyObject(new BuilderConfig().setPropertyLabel(label));
PrettyObject unconfig = new PrettyObject();

String labeled = config.render(OutputFormat.RICH, data);
String unlabeled = unconfig.render(OutputFormat.RICH, data);

Assertions.assertNotEquals(labeled, unlabeled);
Assertions.assertTrue(labeled.contains(label));
Assertions.assertFalse(unlabeled.contains(label));
}

@Test
public void testJsonProcessingException() throws JsonProcessingException {
JsonProcessingException failure = new JsonGenerationException("this is it", (JsonGenerator) null);
ObjectMapper mapper = mock(ObjectMapper.class);
when(mapper.writeValueAsString(any())).thenThrow(failure);

PrettyObject uut = new PrettyObject();
IllegalStateException ex = Assertions.assertThrows(
IllegalStateException.class,
() -> uut.renderJson(this.simpleDict(), mapper)
);
Assertions.assertEquals("Unable to render object as JSON", ex.getMessage());
Assertions.assertSame(failure, ex.getCause());
}

@Test
public void testYamlProcessingException() throws JsonProcessingException {
JsonProcessingException failure = new JsonGenerationException("this is it", (JsonGenerator) null);
YAMLMapper mapper = mock(YAMLMapper.class);
when(mapper.writeValueAsString(any())).thenThrow(failure);

PrettyObject uut = new PrettyObject();
IllegalStateException ex = Assertions.assertThrows(
IllegalStateException.class,
() -> uut.renderYaml(this.simpleDict(), mapper)
);
Assertions.assertEquals("Unable to render object as YAML", ex.getMessage());
Assertions.assertSame(failure, ex.getCause());
}
}
7 changes: 7 additions & 0 deletions src/test/resources/PrettyObject_simple_dict.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Property,Value
abc,def
ghi,False
jkl,"mno, pqr, stu"
vwx,"1, 2, 4"
2,3
yxa,None
34 changes: 34 additions & 0 deletions src/test/resources/PrettyObject_simple_dict.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<table>
<thead>
<tr>
<th style="text-align:left">Property</th>
<th style="text-align:left">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">abc</td>
<td style="text-align:left">def</td>
</tr>
<tr>
<td style="text-align:left">ghi</td>
<td style="text-align:left">False</td>
</tr>
<tr>
<td style="text-align:left">jkl</td>
<td style="text-align:left">mno, pqr, stu</td>
</tr>
<tr>
<td style="text-align:left">vwx</td>
<td style="text-align:left">1, 2, 4</td>
</tr>
<tr>
<td style="text-align:left">2</td>
<td style="text-align:left">3</td>
</tr>
<tr>
<td style="text-align:left">yxa</td>
<td style="text-align:left">None</td>
</tr>
</tbody>
</table>
16 changes: 16 additions & 0 deletions src/test/resources/PrettyObject_simple_dict.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"abc" : "def",
"ghi" : false,
"jkl" : [
"mno",
"pqr",
"stu"
],
"vwx" : [
1,
2,
4
],
"2" : 3,
"yxa" : null
}
10 changes: 10 additions & 0 deletions src/test/resources/PrettyObject_simple_dict.text
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
+----------+---------------+
| Property | Value |
+----------+---------------+
| abc | def |
| ghi | False |
| jkl | mno, pqr, stu |
| vwx | 1, 2, 4 |
| 2 | 3 |
| yxa | None |
+----------+---------------+
Loading
Loading