From 195b3c84aa204cf4118a1d5a14d55943f7cef0e8 Mon Sep 17 00:00:00 2001 From: Rick Porter Date: Mon, 9 Nov 2026 06:39:38 -0500 Subject: [PATCH] Add PrettyObject to directly render objects as json/yaml --- README.md | 55 ++++++- pom.xml | 17 ++- .../rickwporter/prettytable/PrettyObject.java | 77 ++++++++++ .../prettytable/PrettyObjectTest.java | 143 ++++++++++++++++++ .../resources/PrettyObject_simple_dict.csv | 7 + .../resources/PrettyObject_simple_dict.html | 34 +++++ .../resources/PrettyObject_simple_dict.json | 16 ++ .../resources/PrettyObject_simple_dict.text | 10 ++ .../resources/PrettyObject_simple_dict.txt | 10 ++ .../resources/PrettyObject_simple_dict.yaml | 12 ++ 10 files changed, 376 insertions(+), 5 deletions(-) create mode 100644 src/main/java/rickwporter/prettytable/PrettyObject.java create mode 100644 src/test/java/rickwporter/prettytable/PrettyObjectTest.java create mode 100644 src/test/resources/PrettyObject_simple_dict.csv create mode 100644 src/test/resources/PrettyObject_simple_dict.html create mode 100644 src/test/resources/PrettyObject_simple_dict.json create mode 100644 src/test/resources/PrettyObject_simple_dict.text create mode 100644 src/test/resources/PrettyObject_simple_dict.txt create mode 100644 src/test/resources/PrettyObject_simple_dict.yaml diff --git a/README.md b/README.md index 9d50fc7..59c8daa 100644 --- a/README.md +++ b/README.md @@ -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: @@ -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 item = new LinkedHashMap(); + 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. diff --git a/pom.xml b/pom.xml index c51b53e..d703254 100644 --- a/pom.xml +++ b/pom.xml @@ -66,6 +66,13 @@ ${version.apache.lang3} + + + com.fasterxml.jackson.core + jackson-core + ${version.jackson} + + org.apache.commons @@ -75,13 +82,15 @@ - com.fasterxml.jackson.core - jackson-core + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml ${version.jackson} + + - com.fasterxml.jackson.dataformat - jackson-dataformat-yaml + com.fasterxml.jackson.core + jackson-databind ${version.jackson} diff --git a/src/main/java/rickwporter/prettytable/PrettyObject.java b/src/main/java/rickwporter/prettytable/PrettyObject.java new file mode 100644 index 0000000..5d57ce3 --- /dev/null +++ b/src/main/java/rickwporter/prettytable/PrettyObject.java @@ -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(); + } + +} diff --git a/src/test/java/rickwporter/prettytable/PrettyObjectTest.java b/src/test/java/rickwporter/prettytable/PrettyObjectTest.java new file mode 100644 index 0000000..ef1fa24 --- /dev/null +++ b/src/test/java/rickwporter/prettytable/PrettyObjectTest.java @@ -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 mapOf(Object... pairs) { + if (pairs.length % 2 != 0) { + throw new IllegalArgumentException("Expected key/value pairs"); + } + Map result = new LinkedHashMap(); + for (int i = 0; i < pairs.length; i += 2) { + result.put(pairs[i], pairs[i + 1]); + } + return result; + } + + private Map 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 extensions = new LinkedHashMap(); + 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 data = this.simpleDict(); + for (Map.Entry 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 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()); + } +} diff --git a/src/test/resources/PrettyObject_simple_dict.csv b/src/test/resources/PrettyObject_simple_dict.csv new file mode 100644 index 0000000..63277f8 --- /dev/null +++ b/src/test/resources/PrettyObject_simple_dict.csv @@ -0,0 +1,7 @@ +Property,Value +abc,def +ghi,False +jkl,"mno, pqr, stu" +vwx,"1, 2, 4" +2,3 +yxa,None diff --git a/src/test/resources/PrettyObject_simple_dict.html b/src/test/resources/PrettyObject_simple_dict.html new file mode 100644 index 0000000..fd8d7eb --- /dev/null +++ b/src/test/resources/PrettyObject_simple_dict.html @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyValue
abcdef
ghiFalse
jklmno, pqr, stu
vwx1, 2, 4
23
yxaNone
diff --git a/src/test/resources/PrettyObject_simple_dict.json b/src/test/resources/PrettyObject_simple_dict.json new file mode 100644 index 0000000..567f571 --- /dev/null +++ b/src/test/resources/PrettyObject_simple_dict.json @@ -0,0 +1,16 @@ +{ + "abc" : "def", + "ghi" : false, + "jkl" : [ + "mno", + "pqr", + "stu" + ], + "vwx" : [ + 1, + 2, + 4 + ], + "2" : 3, + "yxa" : null +} \ No newline at end of file diff --git a/src/test/resources/PrettyObject_simple_dict.text b/src/test/resources/PrettyObject_simple_dict.text new file mode 100644 index 0000000..957671c --- /dev/null +++ b/src/test/resources/PrettyObject_simple_dict.text @@ -0,0 +1,10 @@ ++----------+---------------+ +| Property | Value | ++----------+---------------+ +| abc | def | +| ghi | False | +| jkl | mno, pqr, stu | +| vwx | 1, 2, 4 | +| 2 | 3 | +| yxa | None | ++----------+---------------+ diff --git a/src/test/resources/PrettyObject_simple_dict.txt b/src/test/resources/PrettyObject_simple_dict.txt new file mode 100644 index 0000000..af148e5 --- /dev/null +++ b/src/test/resources/PrettyObject_simple_dict.txt @@ -0,0 +1,10 @@ +┏━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ +┃ Property ┃ Value ┃ +┡━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ +│ abc │ def │ +│ ghi │ False │ +│ jkl │ mno, pqr, stu │ +│ vwx │ 1, 2, 4 │ +│ 2 │ 3 │ +│ yxa │ None │ +└──────────┴───────────────┘ diff --git a/src/test/resources/PrettyObject_simple_dict.yaml b/src/test/resources/PrettyObject_simple_dict.yaml new file mode 100644 index 0000000..7ba9333 --- /dev/null +++ b/src/test/resources/PrettyObject_simple_dict.yaml @@ -0,0 +1,12 @@ +abc: "def" +ghi: false +jkl: +- "mno" +- "pqr" +- "stu" +vwx: +- 1 +- 2 +- 4 +2: 3 +yxa: null