From d02cd563ed9cf0655a618a34d0834179c452f20e Mon Sep 17 00:00:00 2001 From: Rick Porter Date: Thu, 5 Nov 2026 06:14:27 -0500 Subject: [PATCH] Add pets-cli example CLI program --- .gitignore | 1 + README.md | 6 + examples/pets-cli/Makefile | 55 +++ examples/pets-cli/README.md | 45 +++ examples/pets-cli/checkstyle.xml | 209 ++++++++++++ examples/pets-cli/pet.yaml | 143 ++++++++ examples/pets-cli/pom.xml | 122 +++++++ .../prettytable/example/pets/PetsCli.java | 316 ++++++++++++++++++ .../example/pets/PetstoreClient.java | 147 ++++++++ .../example/pets/PetstoreException.java | 22 ++ .../prettytable/example/pets/PetsCliTest.java | 286 ++++++++++++++++ .../example/pets/PetstoreStub.java | 135 ++++++++ 12 files changed, 1487 insertions(+) create mode 100644 examples/pets-cli/Makefile create mode 100644 examples/pets-cli/README.md create mode 100644 examples/pets-cli/checkstyle.xml create mode 100644 examples/pets-cli/pet.yaml create mode 100644 examples/pets-cli/pom.xml create mode 100644 examples/pets-cli/src/main/java/rickwporter/prettytable/example/pets/PetsCli.java create mode 100644 examples/pets-cli/src/main/java/rickwporter/prettytable/example/pets/PetstoreClient.java create mode 100644 examples/pets-cli/src/main/java/rickwporter/prettytable/example/pets/PetstoreException.java create mode 100644 examples/pets-cli/src/test/java/rickwporter/prettytable/example/pets/PetsCliTest.java create mode 100644 examples/pets-cli/src/test/java/rickwporter/prettytable/example/pets/PetstoreStub.java 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 pets = new ArrayList(); + Set seen = new HashSet(); + String path = this.firstPath(); + while (path != null && seen.add(path)) { + Object body = http.get(path); + if (!(body instanceof List)) { + return pets.isEmpty() ? body : pets; + } + List page = (List) body; + pets.addAll(page); + String next = http.nextLink(); + boolean shortPage = this.limit != null && page.size() < this.limit; + if (next == null || page.isEmpty() || shortPage) { + break; + } + path = next; + } + return pets; + } + + private String firstPath() { + if (this.limit == null) { + return "/pets"; + } + return "/pets?limit=" + this.limit; + } + } + + @Command( + name = "add", + mixinStandardHelpOptions = true, + version = "pets 1.0", + description = "Create a pet." + ) + public static final class AddPet extends PetCommand { + @Option(names = "--id", required = true, description = "Pet id") + private long id; + + @Option(names = "--name", required = true, description = "Pet name") + private String name; + + @Option(names = "--owner", required = true, description = "Pet owner") + private String owner; + + @Option(names = "--tag", description = "Pet tag") + private String tag; + + @Override + public Integer call() { + if (this.name == null || this.name.isBlank()) { + return this.usage("Name is required."); + } + if (this.owner == null || this.owner.isBlank()) { + return this.usage("Owner is required."); + } + Map pet = petBody(this.id, this.name.trim(), this.owner.trim(), this.tag); + return this.execute(() -> this.show(this.client().post("/pets", pet))); + } + + private static Map petBody(long id, String name, String owner, String tag) { + Map pet = new LinkedHashMap(); + pet.put("id", id); + pet.put("name", name); + if (tag != null && !tag.isBlank()) { + pet.put("tag", tag.trim()); + } + pet.put("owner", owner); + return pet; + } + } + + @Command( + name = "show", + mixinStandardHelpOptions = true, + version = "pets 1.0", + description = "Info for a specific pet." + ) + public static final class ShowPet extends PetCommand { + @Parameters(index = "0", paramLabel = "PET_ID", description = "The id of the pet to retrieve") + private String petId; + + @Override + public Integer call() { + return this.execute(() -> this.show(this.client().get("/pets/" + pathId(this.petId)))); + } + } + + @Command( + name = "delete", + mixinStandardHelpOptions = true, + version = "pets 1.0", + description = "Delete a pet." + ) + public static final class DeletePet extends PetCommand { + @Parameters(index = "0", paramLabel = "PET_ID", description = "The id of the pet to retrieve") + private String petId; + + @Override + public Integer call() { + return this.execute(() -> this.show(this.client().delete("/pets/" + pathId(this.petId)))); + } + } + + private static String pathId(String petId) { + return URLEncoder.encode(petId, StandardCharsets.UTF_8).replace("+", "%20"); + } + + private static void write(PrintWriter writer, String text) { + writer.print(text); + if (!text.endsWith("\n")) { + writer.println(); + } else { + writer.flush(); + } + } +} diff --git a/examples/pets-cli/src/main/java/rickwporter/prettytable/example/pets/PetstoreClient.java b/examples/pets-cli/src/main/java/rickwporter/prettytable/example/pets/PetstoreClient.java new file mode 100644 index 0000000..800f6d4 --- /dev/null +++ b/examples/pets-cli/src/main/java/rickwporter/prettytable/example/pets/PetstoreClient.java @@ -0,0 +1,147 @@ +package rickwporter.prettytable.example.pets; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Locale; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Calls the Swagger Petstore described by pet.yaml. + * The documented server is http://petstore.swagger.io/v1. + */ +public final class PetstoreClient { + private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(10); + private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(60); + private static final int HTTP_ERROR = 400; + private static final String NEXT_HEADER = "x-next"; + + private final URI base; + private final String apiKey; + private final HttpClient http; + private final ObjectMapper json; + private String nextLink; + + public PetstoreClient(String serverUrl, String key) { + this.base = parseBase(serverUrl); + this.apiKey = blankToNull(key); + this.http = HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT) + .followRedirects(HttpClient.Redirect.NORMAL) + .build(); + this.json = new ObjectMapper(); + this.json.configure(DeserializationFeature.USE_LONG_FOR_INTS, true); + } + + public Object get(String path) throws IOException, PetstoreException { + return this.exchange("GET", path, null); + } + + public Object post(String path, Object body) throws IOException, PetstoreException { + return this.exchange("POST", path, body); + } + + public Object delete(String path) throws IOException, PetstoreException { + return this.exchange("DELETE", path, null); + } + + /** Link from the latest response {@code x-next} header, or null when the header is absent. */ + public String nextLink() { + return this.nextLink; + } + + private Object exchange(String method, String path, Object body) throws IOException, PetstoreException { + HttpRequest.Builder builder = HttpRequest.newBuilder() + .uri(this.endpoint(path)) + .timeout(REQUEST_TIMEOUT) + .header("Accept", "application/json") + .header("User-Agent", "pets-cli"); + if (this.apiKey != null) { + builder.header("Authorization", "Bearer " + this.apiKey); + } + if (body == null) { + builder.method(method, HttpRequest.BodyPublishers.noBody()); + } else { + builder.header("Content-Type", "application/json"); + builder.method(method, HttpRequest.BodyPublishers.ofByteArray(this.json.writeValueAsBytes(body))); + } + HttpResponse response; + try { + response = this.http.send(builder.build(), HttpResponse.BodyHandlers.ofByteArray()); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IOException("Request interrupted", ex); + } + this.nextLink = response.headers().firstValue(NEXT_HEADER) + .filter(value -> !value.isBlank()) + .orElse(null); + Object parsed = this.parse(response.body()); + if (response.statusCode() >= HTTP_ERROR) { + throw new PetstoreException(response.statusCode(), parsed); + } + return parsed; + } + + private URI endpoint(String path) { + if (path.startsWith("http://") || path.startsWith("https://")) { + return URI.create(path); + } + String suffix = path.startsWith("/") ? path : "/" + path; + // URI.resolve("/pets") would drop a path prefix on the base URL, so append the path. + return URI.create(this.base.toString() + suffix); + } + + private Object parse(byte[] body) throws IOException { + if (body == null || body.length == 0 || leadingSpace(body) == body.length) { + return null; + } + try { + return this.json.readValue(body, Object.class); + } catch (JsonProcessingException ex) { + return new String(body, StandardCharsets.UTF_8).trim(); + } + } + + private static int leadingSpace(byte[] body) { + int index = 0; + while (index < body.length && body[index] <= ' ') { + index++; + } + return index; + } + + private static URI parseBase(String serverUrl) { + if (serverUrl == null || serverUrl.trim().isEmpty()) { + throw new IllegalArgumentException("Server URL is required."); + } + String trimmed = serverUrl.trim(); + while (trimmed.endsWith("/")) { + trimmed = trimmed.substring(0, trimmed.length() - 1); + } + URI parsed; + try { + parsed = URI.create(trimmed); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("Invalid server URL: " + serverUrl, ex); + } + String scheme = parsed.getScheme() == null ? "" : parsed.getScheme().toLowerCase(Locale.ROOT); + if (!"http".equals(scheme) && !"https".equals(scheme)) { + throw new IllegalArgumentException("Server URL must be http or https: " + serverUrl); + } + return parsed; + } + + private static String blankToNull(String value) { + if (value == null || value.isBlank()) { + return null; + } + return value; + } +} diff --git a/examples/pets-cli/src/main/java/rickwporter/prettytable/example/pets/PetstoreException.java b/examples/pets-cli/src/main/java/rickwporter/prettytable/example/pets/PetstoreException.java new file mode 100644 index 0000000..6585930 --- /dev/null +++ b/examples/pets-cli/src/main/java/rickwporter/prettytable/example/pets/PetstoreException.java @@ -0,0 +1,22 @@ +package rickwporter.prettytable.example.pets; + +public final class PetstoreException extends Exception { + private static final long serialVersionUID = 1L; + + private final int status; + private final Object body; + + PetstoreException(int statusCode, Object responseBody) { + super("Petstore returned HTTP " + statusCode); + this.status = statusCode; + this.body = responseBody; + } + + public int getStatus() { + return this.status; + } + + public Object getBody() { + return this.body; + } +} diff --git a/examples/pets-cli/src/test/java/rickwporter/prettytable/example/pets/PetsCliTest.java b/examples/pets-cli/src/test/java/rickwporter/prettytable/example/pets/PetsCliTest.java new file mode 100644 index 0000000..71d18d8 --- /dev/null +++ b/examples/pets-cli/src/test/java/rickwporter/prettytable/example/pets/PetsCliTest.java @@ -0,0 +1,286 @@ +package rickwporter.prettytable.example.pets; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import picocli.CommandLine; + +public class PetsCliTest { + private PetstoreStub stub; + + @BeforeEach + public void setUp() throws Exception { + this.stub = PetstoreStub.start(); + } + + @AfterEach + public void tearDown() { + if (this.stub != null) { + this.stub.close(); + } + } + + @Test + public void testHelp() { + Result result = this.runRaw("--help"); + Assertions.assertEquals(0, result.exit, result.dump()); + Assertions.assertTrue(result.out.contains("list"), result.dump()); + Assertions.assertTrue(result.out.contains("show"), result.dump()); + Assertions.assertTrue(result.out.contains("add"), result.dump()); + Assertions.assertTrue(result.out.contains("delete"), result.dump()); + Assertions.assertFalse(result.out.contains("inventory"), result.dump()); + } + + @Test + public void testMissingCommand() { + Result result = this.runRaw(); + Assertions.assertEquals(CommandLine.ExitCode.USAGE, result.exit, result.dump()); + Assertions.assertTrue(result.err.contains("Usage:"), result.dump()); + } + + @Test + public void testListSendsLimitAndFollowsNext() { + Result all = this.run("--format", "text", "list"); + Assertions.assertEquals(0, all.exit, all.dump()); + Assertions.assertTrue(all.out.contains("Fido"), all.dump()); + Assertions.assertTrue(all.out.contains("Whiskers"), all.dump()); + Assertions.assertTrue(all.out.contains("Found 2 items"), all.dump()); + Assertions.assertNull(this.stub.lastQuery()); + Assertions.assertEquals("/pets", this.stub.lastPath()); + Assertions.assertEquals(1, this.stub.queries().size()); + + Result limited = this.run("--format", "text", "list", "--limit", "1"); + Assertions.assertEquals(0, limited.exit, limited.dump()); + Assertions.assertTrue(limited.out.contains("Fido"), limited.dump()); + Assertions.assertTrue(limited.out.contains("Whiskers"), limited.dump()); + Assertions.assertEquals(List.of("limit=1", "page=2"), this.stub.queries().subList(1, 3)); + } + + @Test + public void testFormats() { + Result listed = this.run("list", "--format", "json"); + Assertions.assertEquals(0, listed.exit, listed.dump()); + Assertions.assertTrue(listed.out.contains("\"Fido\""), listed.dump()); + Assertions.assertEquals("GET", this.stub.lastMethod()); + Assertions.assertEquals("/pets", this.stub.lastPath()); + + Result rich = this.run("--format", "rich", "list"); + Assertions.assertEquals(0, rich.exit, rich.dump()); + Assertions.assertTrue(rich.out.contains("┏"), rich.dump()); + + Result csv = this.run("--format", "CSV", "list"); + Assertions.assertEquals(0, csv.exit, csv.dump()); + Assertions.assertTrue(csv.out.contains("Fido"), csv.dump()); + } + + @Test + public void testShowAndApiKey() { + Result pet = this.run("--format", "text", "--api-key", "special-key", "show", "1"); + Assertions.assertEquals(0, pet.exit, pet.dump()); + Assertions.assertEquals("special-key", this.stub.lastApiKey()); + Assertions.assertTrue(pet.out.contains("Fido"), pet.dump()); + Assertions.assertTrue(pet.out.contains("trained"), pet.dump()); + Assertions.assertTrue(pet.out.contains("Rick"), pet.dump()); + Assertions.assertTrue(pet.out.contains("Property"), pet.dump()); + Assertions.assertEquals("/pets/1", this.stub.lastPath()); + } + + @Test + public void testAddDeleteAndErrors() throws Exception { + Result added = this.run( + "add", + "--name", "Fido", + "--id", "7", + "--owner", "Rick", + "--tag", "trained"); + Assertions.assertEquals(0, added.exit, added.dump()); + Assertions.assertTrue(added.out.contains("Empty response."), added.dump()); + Map posted = new ObjectMapper().readValue( + this.stub.lastBody(), new TypeReference>() { }); + Assertions.assertEquals("Fido", posted.get("name")); + Assertions.assertEquals("Rick", posted.get("owner")); + Assertions.assertEquals("trained", posted.get("tag")); + Assertions.assertEquals(7, ((Number) posted.get("id")).intValue()); + Assertions.assertFalse(posted.containsKey("status"), posted.toString()); + Assertions.assertEquals("/pets", this.stub.lastPath()); + + Result deleted = this.run("delete", "1"); + Assertions.assertEquals(0, deleted.exit, deleted.dump()); + Assertions.assertTrue(deleted.out.contains("Empty response."), deleted.dump()); + Assertions.assertEquals("DELETE", this.stub.lastMethod()); + Assertions.assertEquals("/pets/1", this.stub.lastPath()); + + Result missing = this.run("show", "404"); + Assertions.assertEquals(CommandLine.ExitCode.SOFTWARE, missing.exit, missing.dump()); + Assertions.assertTrue(missing.err.contains("HTTP 404"), missing.dump()); + Assertions.assertTrue(missing.err.contains("Pet not found"), missing.dump()); + + Result text = this.run("show", "5"); + Assertions.assertEquals(CommandLine.ExitCode.SOFTWARE, text.exit, text.dump()); + Assertions.assertTrue(text.err.contains("HTTP 400"), text.dump()); + Assertions.assertTrue(text.err.contains("nope"), text.dump()); + } + + @Test + public void testUsageErrors() { + Result limit = this.run("list", "--limit", "0"); + Assertions.assertEquals(CommandLine.ExitCode.USAGE, limit.exit, limit.dump()); + Assertions.assertNull(this.stub.lastPath()); + + Result tooMany = this.run("list", "--limit", "101"); + Assertions.assertEquals(CommandLine.ExitCode.USAGE, tooMany.exit, tooMany.dump()); + Assertions.assertTrue(tooMany.err.contains("100"), tooMany.dump()); + + Result format = this.run("--format", "nope", "list"); + Assertions.assertEquals(CommandLine.ExitCode.USAGE, format.exit, format.dump()); + + Result name = this.run("add"); + Assertions.assertEquals(CommandLine.ExitCode.USAGE, name.exit, name.dump()); + + Result server = this.runRaw("--server", "ftp://example.com", "list"); + Assertions.assertEquals(CommandLine.ExitCode.USAGE, server.exit, server.dump()); + Assertions.assertTrue(server.err.contains("http or https"), server.dump()); + + Result unknown = this.runRaw("nope"); + Assertions.assertEquals(CommandLine.ExitCode.USAGE, unknown.exit, unknown.dump()); + } + + @Test + public void testEnvironmentVariables() throws Exception { + Map env = new HashMap(); + env.put("API_HOST", this.stub.url()); + env.put("API_KEY", "special-key"); + env.put("OUTPUT_FORMAT", "json"); + Result listed = this.runProcess(env, "list"); + Assertions.assertEquals(0, listed.exit, listed.dump()); + Assertions.assertTrue(listed.out.contains("\"Fido\""), listed.dump()); + Assertions.assertTrue(listed.out.contains("\"Whiskers\""), listed.dump()); + Assertions.assertEquals("special-key", this.stub.lastApiKey()); + Assertions.assertEquals("/pets", this.stub.lastPath()); + + env.remove("API_KEY"); + env.put("OUTPUT_FORMAT", "text"); + Result pet = this.runProcess(env, "show", "1"); + Assertions.assertEquals(0, pet.exit, pet.dump()); + Assertions.assertTrue(pet.out.contains("Fido"), pet.dump()); + Assertions.assertNull(this.stub.lastApiKey()); + + env.put("OUTPUT_FORMAT", "nope"); + Result bad = this.runProcess(env, "list"); + Assertions.assertEquals(CommandLine.ExitCode.USAGE, bad.exit, bad.dump()); + } + + @Test + public void testFlagsOverrideEnvironment() throws Exception { + Map env = new HashMap(); + env.put("API_HOST", "http://127.0.0.1:1"); + env.put("API_KEY", "from-env"); + env.put("OUTPUT_FORMAT", "json"); + Result result = this.runProcess( + env, + "--server", this.stub.url(), + "--api-key", "special-key", + "--format", "text", "list"); + Assertions.assertEquals(0, result.exit, result.dump()); + Assertions.assertTrue(result.out.contains("Found 2 items"), result.dump()); + Assertions.assertTrue(result.out.contains("Fido"), result.dump()); + Assertions.assertFalse(result.out.contains("\"Fido\""), result.dump()); + Assertions.assertEquals("special-key", this.stub.lastApiKey()); + } + + private Result run(String... args) { + List full = new ArrayList(); + full.add("--server"); + full.add(this.stub.url()); + Collections.addAll(full, args); + return this.runRaw(full.toArray(new String[0])); + } + + private Result runProcess(Map env, String... args) throws Exception { + Path dir = Path.of("target"); + Files.createDirectories(dir); + Path outFile = Files.createTempFile(dir, "pets-out-", ".txt"); + Path errFile = Files.createTempFile(dir, "pets-err-", ".txt"); + List command = new ArrayList(); + command.add(ProcessHandle.current().info().command().orElse("java")); + command.add("-cp"); + command.add(System.getProperty("java.class.path")); + command.add(PetsCli.class.getName()); + Collections.addAll(command, args); + ProcessBuilder builder = new ProcessBuilder(command); + Map processEnv = builder.environment(); + processEnv.remove("API_HOST"); + processEnv.remove("API_KEY"); + processEnv.remove("OUTPUT_FORMAT"); + processEnv.putAll(env); + builder.redirectOutput(outFile.toFile()); + builder.redirectError(errFile.toFile()); + Process process = builder.start(); + try { + boolean finished = process.waitFor(30, TimeUnit.SECONDS); + if (!finished) { + process.destroyForcibly(); + } + String stdout = Files.readString(outFile); + String stderr = Files.readString(errFile); + if (!finished) { + return new Result(124, stdout, stderr + "\n(timed out)"); + } + return new Result(process.exitValue(), stdout, stderr); + } finally { + Files.deleteIfExists(outFile); + Files.deleteIfExists(errFile); + } + } + + private Result runRaw(String... args) { + ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); + ByteArrayOutputStream errBytes = new ByteArrayOutputStream(); + PrintWriter out = new PrintWriter(new OutputStreamWriter(outBytes, StandardCharsets.UTF_8), true); + PrintWriter err = new PrintWriter(new OutputStreamWriter(errBytes, StandardCharsets.UTF_8), true); + CommandLine cmd = PetsCli.commandLine(); + cmd.setOut(out); + cmd.setErr(err); + int exit = cmd.execute(args); + out.flush(); + err.flush(); + return new Result( + exit, + outBytes.toString(StandardCharsets.UTF_8), + errBytes.toString(StandardCharsets.UTF_8)); + } + + private static final class Result { + private final int exit; + private final String out; + private final String err; + + private Result(int exitCode, String stdout, String stderr) { + this.exit = exitCode; + this.out = stdout; + this.err = stderr; + } + + private String dump() { + return "exit " + this.exit + "\nstdout:\n" + this.out + "\nstderr:\n" + this.err; + } + } +} diff --git a/examples/pets-cli/src/test/java/rickwporter/prettytable/example/pets/PetstoreStub.java b/examples/pets-cli/src/test/java/rickwporter/prettytable/example/pets/PetstoreStub.java new file mode 100644 index 0000000..12abace --- /dev/null +++ b/examples/pets-cli/src/test/java/rickwporter/prettytable/example/pets/PetstoreStub.java @@ -0,0 +1,135 @@ +package rickwporter.prettytable.example.pets; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; + +final class PetstoreStub { + static final String FIDO = "{\"id\":1,\"name\":\"Fido\",\"tag\":\"trained\",\"owner\":\"Rick\"}"; + static final String WHISKERS = "{\"id\":2,\"name\":\"Whiskers\",\"tag\":\"fluffy\",\"owner\":\"Sam\"}"; + private static final String PETS = "[" + FIDO + "," + WHISKERS + "]"; + + private final HttpServer server; + private volatile String lastMethod; + private volatile String lastPath; + private volatile String lastQuery; + private volatile String lastApiKey; + private volatile String lastBody = ""; + private final List queries = new ArrayList(); + + private PetstoreStub(HttpServer httpServer) { + this.server = httpServer; + } + + static PetstoreStub start() throws IOException { + HttpServer httpServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + PetstoreStub stub = new PetstoreStub(httpServer); + httpServer.createContext("/", stub::handle); + httpServer.start(); + return stub; + } + + void close() { + this.server.stop(0); + } + + String url() { + return "http://127.0.0.1:" + this.server.getAddress().getPort(); + } + + String lastMethod() { + return this.lastMethod; + } + + String lastPath() { + return this.lastPath; + } + + String lastQuery() { + return this.lastQuery; + } + + List queries() { + return this.queries; + } + + String lastApiKey() { + if (this.lastApiKey == null) { + return null; + } + return this.lastApiKey.replaceFirst("Bearer ", ""); + } + + String lastBody() { + return this.lastBody; + } + + private void handle(HttpExchange exchange) throws IOException { + byte[] request; + try (InputStream in = exchange.getRequestBody()) { + request = in.readAllBytes(); + } + this.lastMethod = exchange.getRequestMethod(); + this.lastPath = exchange.getRequestURI().getPath(); + this.lastQuery = exchange.getRequestURI().getRawQuery(); + this.queries.add(this.lastQuery); + this.lastApiKey = exchange.getRequestHeaders().getFirst("Authorization"); + this.lastBody = new String(request, StandardCharsets.UTF_8); + + String method = exchange.getRequestMethod(); + String path = exchange.getRequestURI().getPath(); + String query = exchange.getRequestURI().getRawQuery(); + if ("GET".equals(method) && "/pets".equals(path)) { + if (query != null && query.contains("page=2")) { + respond(exchange, 200, "[" + WHISKERS + "]", null); + return; + } + if (query != null && query.contains("limit=1")) { + respond(exchange, 200, "[" + FIDO + "]", "/pets?page=2"); + return; + } + respond(exchange, 200, PETS, null); + return; + } + if ("GET".equals(method) && "/pets/1".equals(path)) { + respond(exchange, 200, FIDO, null); + return; + } + if ("GET".equals(method) && "/pets/5".equals(path)) { + respond(exchange, 400, "nope", null); + return; + } + if ("GET".equals(method) && "/pets/404".equals(path)) { + respond(exchange, 404, "{\"code\":404,\"message\":\"Pet not found\"}", null); + return; + } + if ("POST".equals(method) && "/pets".equals(path)) { + respond(exchange, 201, "", null); + return; + } + if ("DELETE".equals(method) && "/pets/1".equals(path)) { + respond(exchange, 204, "", null); + return; + } + respond(exchange, 404, "{\"message\":\"no such route\"}", null); + } + + private static void respond(HttpExchange exchange, int status, String body, String next) throws IOException { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8"); + if (next != null) { + exchange.getResponseHeaders().set("x-next", next); + } + exchange.sendResponseHeaders(status, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + } +}