diff --git a/.gitignore b/.gitignore
index 2dfff2f..57dce79 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,6 +3,7 @@
# Build Artifacts
/target
+examples/**/target/
# Compiled class file
*.class
diff --git a/README.md b/README.md
index 0ed9a2f..0b46ef9 100644
--- a/README.md
+++ b/README.md
@@ -331,6 +331,8 @@ The sorting looks like this:
A map becomes a Property / Value table. Nested maps become nested tables, and a list of plain values is joined into one cell. The `BuilderConfig` provides configurability for how `null`, `True`, and `False` values show up.
+The [pets-cli example](examples/pets-cli) code has a more complete example.
+
A list of strings, numbers, or booleans becomes one Items column with a caption such as `Found 6 items`. A list of maps uses the first matching key field (`name`, then `id`) as the row name. One other field becomes the second column. Further fields are nested under Properties. Long keys, values, and URLs are cut off with `...`.
```Java
@@ -392,6 +394,10 @@ import rickwporter.prettytable.BuilderConfig;
| `setUrlPrefixes` | `http://`, `https://`, `ftp://` |
| `setColumns` | `null` |
+## 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.
+
## Development
Your input is welcomed.
diff --git a/examples/pets-cli/Makefile b/examples/pets-cli/Makefile
new file mode 100644
index 0000000..178016d
--- /dev/null
+++ b/examples/pets-cli/Makefile
@@ -0,0 +1,55 @@
+.PHONY = build
+.PHONY += clean
+.PHONY += example
+.PHONY += depend-check
+.PHONY += depend-tree
+.PHONY += lint
+.PHONY += test
+
+MVN_ARGS ?= -ntp
+MVN_CMD ?= mvn
+
+#################################################
+# Targets
+#################################################
+default: help
+
+all: lint depend-check test build ## Perform lint, dependency checking, coverage, and build
+
+help: ## This message
+ @echo "===================="
+ @echo " Available Commands"
+ @echo "===================="
+ @awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m\033[0m\n"} /^[$$()% a-zA-Z_-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST)
+
+###########
+##@ Build
+build: ## Create the JAR file
+ $(MVN_CMD) $(MVN_ARGS) -Dmaven.test.skip=true package
+
+clean: ## Cleans up build artifacts
+ $(MVN_CMD) $(MVN_ARGS) clean
+
+###########
+##@ Dependencies
+depend-check: ## Checks to make sure all dependencies are used (or declared unused)
+ $(MVN_CMD) $(MVN_ARGS) dependency:analyze-only
+
+depend-tree: ## Generates dependency reports
+ $(MVN_CMD) $(MVN_ARGS) dependency:tree
+
+###########
+##@ Formatting
+lint: ## Check formatting
+ $(MVN_CMD) $(MVN_ARGS) checkstyle:check
+
+###########
+##@ Test
+test: ## Run unittests
+ $(MVN_CMD) $(MVN_ARGS) test
+
+###########
+##@ Example
+example: ## Build and test the pets CLI example
+ $(MVN_CMD) $(MVN_ARGS) -DskipTests package install:install
+ $(MVN_CMD) $(MVN_ARGS) -f examples/pets-cli verify
diff --git a/examples/pets-cli/README.md b/examples/pets-cli/README.md
new file mode 100644
index 0000000..70af142
--- /dev/null
+++ b/examples/pets-cli/README.md
@@ -0,0 +1,45 @@
+# pets
+
+A [picocli](https://picocli.info/) command line client for the Swagger Petstore in [`pet.yaml`](pet.yaml). Responses are printed with `TableBuilder`.
+
+The default server is `http://petstore.swagger.io/v1`. A flag on the command line wins over the environment variable.
+
+Requires Java 11 or newer. Install the prettytable jar into the local Maven repository first (the example depends on `io.github.rickwporter:prettytable:1.0.0`).
+
+```bash
+mvn -q package
+java -jar target/pets.jar list --limit 5
+```
+
+`make test` runs the example tests. The tests talk to an in-process stub, not the public server.
+
+## Commands
+
+The commands follow `pet.yaml`: `list` is `GET /pets`, `add` is `POST /pets`, `show` is `GET /pets/{petId}`, and `delete` is `DELETE /pets/{petId}`.
+
+Global options can go before the command or after it:
+
+| Option | Environment variable | Meaning |
+| --- | --- | --- |
+| `-s`, `--server` | `API_HOST` | Petstore base URL. `http://petstore.swagger.io/v1` is used when both are omitted. |
+| `-k`, `--api-key` | `API_KEY` | Bearer token. Omitted when both are empty. |
+| `-f`, `--format` | `OUTPUT_FORMAT` | `text`, `rich`, `csv`, `html`, or `json`. `rich` when both are omitted. |
+| `-h`, `--help` | | Help for the current command |
+
+```bash
+# First page holds at most 5 pets. Further pages come from the x-next header.
+java -jar target/pets.jar list --limit 5
+
+# One pet, as a Property / Value table.
+java -jar target/pets.jar show 1
+
+# Create a pet. id, name, and owner are required. tag is optional.
+# The spec responds with an empty 201 body.
+java -jar target/pets.jar add --id 7 --name Fido --owner Rick --tag trained
+
+java -jar target/pets.jar delete 1
+```
+
+`list --limit` is sent to the server and must be from 1 to 100. When the response includes an `x-next` header, `list` follows that link and prints the combined pages. `show` and `add` print the pet fields `id`, `name`, `tag`, and `owner`. `add` and `delete` print `Empty response.` when the server returns no body.
+
+`mvn exec:java -Dexec.args="list --limit 5"` runs the same main class without the shaded jar.
diff --git a/examples/pets-cli/checkstyle.xml b/examples/pets-cli/checkstyle.xml
new file mode 100644
index 0000000..2f7edde
--- /dev/null
+++ b/examples/pets-cli/checkstyle.xml
@@ -0,0 +1,209 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/examples/pets-cli/pet.yaml b/examples/pets-cli/pet.yaml
new file mode 100644
index 0000000..917b7be
--- /dev/null
+++ b/examples/pets-cli/pet.yaml
@@ -0,0 +1,143 @@
+openapi: "3.0.0"
+info:
+ version: 1.0.0
+ title: Swagger Petstore
+ license:
+ name: MIT
+servers:
+ - url: http://petstore.swagger.io/v1
+tags:
+- name: pets
+ description: Normal pets operations
+- name: admin
+ description: Operations only performed by admin user
+paths:
+ /pets:
+ get:
+ summary: List all pets
+ operationId: listPets
+ tags:
+ - pets
+ parameters:
+ - name: limit
+ in: query
+ description: How many items to return at one time (max 100)
+ required: false
+ schema:
+ type: integer
+ maximum: 100
+ format: int32
+ responses:
+ '200':
+ description: A paged array of pets
+ headers:
+ x-next:
+ description: A link to the next page of responses
+ schema:
+ type: string
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/Pets"
+ default:
+ description: unexpected error
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/Error"
+ post:
+ summary: Create a pet
+ operationId: createPets
+ tags:
+ - pets
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Pet'
+ required: true
+ responses:
+ '201':
+ description: Null response
+ default:
+ description: unexpected error
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/Error"
+ /pets/{petId}:
+ parameters:
+ - name: petId
+ in: path
+ required: true
+ description: The id of the pet to retrieve
+ schema:
+ type: string
+ get:
+ summary: Info for a specific pet
+ operationId: showPetById
+ tags:
+ - pets
+ responses:
+ '200':
+ description: Expected response to a valid request
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/Pet"
+ default:
+ description: unexpected error
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/Error"
+ delete:
+ summary: Delete a pet
+ operationId: deletePetById
+ tags:
+ - admin
+ responses:
+ '204':
+ description: Expected empty response for successful delete
+ default:
+ description: unexpected error
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/Error"
+
+components:
+ schemas:
+ Pet:
+ type: object
+ required:
+ - id
+ - name
+ - owner
+ properties:
+ id:
+ type: integer
+ format: int64
+ name:
+ type: string
+ tag:
+ type: string
+ owner:
+ type: string
+ nullable: true
+ Pets:
+ type: array
+ maxItems: 100
+ items:
+ $ref: "#/components/schemas/Pet"
+ Error:
+ type: object
+ required:
+ - code
+ - message
+ properties:
+ code:
+ type: integer
+ format: int32
+ message:
+ type: string
diff --git a/examples/pets-cli/pom.xml b/examples/pets-cli/pom.xml
new file mode 100644
index 0000000..86f5f10
--- /dev/null
+++ b/examples/pets-cli/pom.xml
@@ -0,0 +1,122 @@
+
+ 4.0.0
+ rickwporter.prettytable
+ pets-cli
+ 0.1.0
+ pets-cli
+ CLI for the OpenAPI Petstore, rendered with prettytable.
+
+
+ 11
+ UTF-8
+ 4.7.6
+ 2.18.2
+ 5.14.1
+ 1.0.0
+
+
+ 3.6.0
+ 8.30
+
+
+
+
+
+ io.github.rickwporter
+ prettytable
+ ${version.prettytable}
+
+
+ info.picocli
+ picocli
+ ${version.picocli}
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ ${version.jackson}
+
+
+ org.junit.jupiter
+ junit-jupiter
+ ${version.junit}
+ test
+
+
+
+
+ pets
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.13.0
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 3.5.2
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ 3.5.0
+
+ rickwporter.prettytable.example.pets.PetsCli
+
+
+
+ org.apache.maven.plugins
+ maven-shade-plugin
+ 3.6.0
+
+
+ package
+
+ shade
+
+
+ false
+
+
+ rickwporter.prettytable.example.pets.PetsCli
+
+
+
+
+ *:*
+
+ META-INF/*.SF
+ META-INF/*.DSA
+ META-INF/*.RSA
+ module-info.class
+
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-checkstyle-plugin
+ ${version.plugin.checkstyle}
+
+
+ com.puppycrawl.tools
+ checkstyle
+ ${version.checkstyle}
+
+
+
+ checkstyle.xml
+ true
+ true
+ false
+
+
+
+
+
diff --git a/examples/pets-cli/src/main/java/rickwporter/prettytable/example/pets/PetsCli.java b/examples/pets-cli/src/main/java/rickwporter/prettytable/example/pets/PetsCli.java
new file mode 100644
index 0000000..a8d9b8b
--- /dev/null
+++ b/examples/pets-cli/src/main/java/rickwporter/prettytable/example/pets/PetsCli.java
@@ -0,0 +1,316 @@
+package rickwporter.prettytable.example.pets;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Callable;
+
+import picocli.CommandLine;
+import picocli.CommandLine.Command;
+import picocli.CommandLine.Model.CommandSpec;
+import picocli.CommandLine.Option;
+import picocli.CommandLine.Parameters;
+import picocli.CommandLine.ParentCommand;
+import picocli.CommandLine.ScopeType;
+import picocli.CommandLine.Spec;
+
+import rickwporter.prettytable.PrettyTable;
+import rickwporter.prettytable.PrettyTable.OutputFormat;
+import rickwporter.prettytable.TableBuilder;
+
+@Command(
+ name = "pets",
+ mixinStandardHelpOptions = true,
+ version = "pets 1.0",
+ description = "Manage pets and print the response with prettytable.",
+ subcommands = {
+ PetsCli.ListPets.class,
+ PetsCli.AddPet.class,
+ PetsCli.ShowPet.class,
+ PetsCli.DeletePet.class
+ },
+ footer = {
+ "Examples:",
+ " pets list --limit 5",
+ " pets show 1",
+ " pets add --id 7 --name Fido --owner Rick --tag trained",
+ " pets delete 1"
+ }
+)
+public final class PetsCli implements Callable {
+ static final String DEFAULT_SERVER = "http://petstore.swagger.io/v1";
+ private static final String SERVER_DEFAULT = "${env:API_HOST:-" + DEFAULT_SERVER + "}";
+ private static final String API_KEY_DEFAULT = "${env:API_KEY:-}";
+ private static final String FORMAT_DEFAULT = "${env:OUTPUT_FORMAT:-RICH}";
+ private static final int HELP_WIDTH = 120;
+ private static final int MAX_LIMIT = 100;
+
+ @Spec
+ private CommandSpec spec;
+
+ @Option(
+ names = {"-s", "--server"},
+ defaultValue = SERVER_DEFAULT,
+ scope = ScopeType.INHERIT,
+ description = "Petstore base URL. Uses API_HOST when omitted (default: ${DEFAULT-VALUE})"
+ )
+ private String server;
+
+ @Option(
+ names = {"-k", "--api-key"},
+ defaultValue = API_KEY_DEFAULT,
+ scope = ScopeType.INHERIT,
+ description = "Bearer token from API_KEY. Omitted when both are empty."
+ )
+ private String apiKey;
+
+ @Option(
+ names = {"-f", "--format"},
+ defaultValue = FORMAT_DEFAULT,
+ scope = ScopeType.INHERIT,
+ description = "Format: ${COMPLETION-CANDIDATES}. OUTPUT_FORMAT is the default (default: ${DEFAULT-VALUE})"
+ )
+ private OutputFormat format = OutputFormat.RICH;
+
+ public static void main(String[] args) {
+ int exit = commandLine().execute(args);
+ System.exit(exit);
+ }
+
+ public static CommandLine commandLine() {
+ CommandLine cmd = new CommandLine(new PetsCli());
+ cmd.setCaseInsensitiveEnumValuesAllowed(true);
+ cmd.setUsageHelpWidth(HELP_WIDTH);
+ for (CommandLine sub : cmd.getSubcommands().values()) {
+ sub.setCaseInsensitiveEnumValuesAllowed(true);
+ sub.setUsageHelpWidth(HELP_WIDTH);
+ }
+ return cmd;
+ }
+
+ @Override
+ public Integer call() {
+ this.spec.commandLine().usage(this.spec.commandLine().getErr());
+ return CommandLine.ExitCode.USAGE;
+ }
+
+ private PetstoreClient client() {
+ return new PetstoreClient(this.server, this.apiKey);
+ }
+
+ private abstract static class PetCommand implements Callable {
+ @ParentCommand
+ private PetsCli parent;
+
+ @Spec
+ private CommandSpec spec;
+
+ protected PetstoreClient client() {
+ return this.parent.client();
+ }
+
+ protected int execute(Callable action) {
+ try {
+ return action.call();
+ } catch (PetstoreException ex) {
+ return this.fail(ex);
+ } catch (IllegalArgumentException ex) {
+ return this.usage(ex.getMessage());
+ } catch (IOException ex) {
+ this.spec.commandLine().getErr().println("Request failed: " + ex.getMessage());
+ return CommandLine.ExitCode.SOFTWARE;
+ } catch (Exception ex) {
+ String message = ex.getMessage() == null ? ex.toString() : ex.getMessage();
+ this.spec.commandLine().getErr().println(message);
+ return CommandLine.ExitCode.SOFTWARE;
+ }
+ }
+
+ protected int usage(String message) {
+ this.spec.commandLine().getErr().println(message);
+ return CommandLine.ExitCode.USAGE;
+ }
+
+ private String render(Object body) {
+ if (body == null) {
+ return "";
+ }
+ if (body instanceof String || body instanceof Number || body instanceof Boolean) {
+ return String.valueOf(body);
+ }
+ PrettyTable table = new TableBuilder().build(body);
+ if (table == null) {
+ return "";
+ }
+ OutputFormat format = this.parent.format;
+ return table.formattedString(format == null ? OutputFormat.RICH : format);
+ }
+
+ protected int show(Object body) {
+ String rendered = this.render(body);
+ PrintWriter out = this.spec.commandLine().getOut();
+ if (rendered.isEmpty()) {
+ out.println("Empty response.");
+ return CommandLine.ExitCode.OK;
+ }
+ write(out, rendered);
+ return CommandLine.ExitCode.OK;
+ }
+
+ private int fail(PetstoreException ex) {
+ PrintWriter err = this.spec.commandLine().getErr();
+ err.println(ex.getMessage());
+ String rendered = this.render(ex.getBody());
+ if (!rendered.isEmpty()) {
+ write(err, rendered);
+ }
+ return CommandLine.ExitCode.SOFTWARE;
+ }
+ }
+
+ @Command(
+ name = "list",
+ mixinStandardHelpOptions = true,
+ version = "pets 1.0",
+ description = "List all pets. The server pages with limit and the x-next header."
+ )
+ public static final class ListPets extends PetCommand {
+ @Option(
+ names = "--limit",
+ description = "How many items to return at one time (max 100)"
+ )
+ private Integer limit;
+
+ @Override
+ public Integer call() {
+ if (this.limit != null && (this.limit < 1 || this.limit > MAX_LIMIT)) {
+ return this.usage("Limit must be from 1 to 100.");
+ }
+ return this.execute(() -> this.show(this.pages()));
+ }
+
+ private Object pages() throws IOException, PetstoreException {
+ PetstoreClient http = this.client();
+ List