diff --git a/.claude/skills/update-cloudhub-client/SKILL.md b/.claude/skills/update-cloudhub-client/SKILL.md new file mode 100644 index 0000000..9c61908 --- /dev/null +++ b/.claude/skills/update-cloudhub-client/SKILL.md @@ -0,0 +1,115 @@ +--- +name: update-cloudhub-client +description: > + Re-sync this Java client (cloudhub-java-client) with the CloudHub .NET API: capture the + latest OpenAPI spec from CloudHub, regenerate the client, re-apply the protected + customizations, build, summarize what changed, and bump the version. Use whenever the + client must mirror new/changed CloudHub endpoints or models, after CloudHub is updated, + or when asked to "update / regenerate / sync the cloudhub java client". +--- + +# Update the Cloudhub Java client + +This skill drives a mostly-deterministic pipeline and supplies the judgment the pipeline +can't. The mechanical work lives in `scripts/Update-JavaClient.ps1`, `openapi-generator.gradle`, +and `.openapi-generator-ignore`. Your job is to run it, read the spec diff, make the few +decisions a generator can't, and report clearly. + +## How the pieces fit (read first) + +- The client mirrors CloudHub's **OpenAPI spec** — it has no binary dependency on CloudHub. +- `openapi/cloudhub.json` is the committed **source of truth**. `git diff` on it = "what changed upstream". +- Code generation regenerates everything under `src/main/java/**`, `src/test/java/**`, `docs/**` + **except** files in `.openapi-generator-ignore` (the hand-written `CloudhubClient.java`, + `CloudhubUtils.java`, `build.gradle`, `README.md`, `CHANGELOG.md`, gradle wrapper, this skill). +- `hideGenerationTimestamp=true` keeps generator output stable, so a re-run with no upstream + change produces an **empty diff**. + +## Prerequisites + +- **.NET SDK** compatible with CloudHub's target framework (currently `net10.0`), and access to + restore CloudHub's NuGet dependencies (private Lacuna feed or a warm package cache). +- **JDK 8+** on `PATH` (or `JAVA_HOME` set) — Gradle and the generator need it. +- The **CloudHub repo** checked out, by default as a sibling folder `../cloudhub`. + +## Procedure + +### 1. Capture the new spec +Run capture-only first so you can inspect the diff before regenerating: +``` +pwsh scripts/Update-JavaClient.ps1 -SpecOnly +``` +This builds CloudHub, then writes `openapi/cloudhub.json` via the Swashbuckle CLI tool +(`dotnet swagger tofile ... v1`). If the build/capture fails, see **Troubleshooting**. + +### 2. Review what changed upstream +``` +git diff -- openapi/cloudhub.json +``` +Read the diff and write a short human summary grouped as: +- **Added** paths / schemas / properties +- **Removed** paths / schemas / properties ← breaking +- **Changed** types, `required`, enum members, `format` ← often breaking + +### 3. Classify the change → decide the version bump +Use [semver](https://semver.org) against the current `version` in `build.gradle`: + +| Change | Bump | +|---|---| +| Only additive (new endpoints/models/optional fields) | **minor** | +| Removed/renamed endpoint, field, or enum member; a property became `required`; a type or wire `format` changed; an enum's underlying type changed (e.g. integer→string) | **major** | +| Doc-only / cosmetic | **patch** | + +State the recommended new version and the reason. CloudHub's own version is a useful signal +but the client's Maven version is independent — bump it on its own merits. + +### 4. Handle judgment items the generator can't (FLAG, don't guess) +Scan the spec diff for these and resolve each explicitly: + +- **New INTEGER-valued enum** (`{"enum": [1,2,...], "type": "integer"}`): the generator would emit + `NUMBER_1`, `NUMBER_2`, …. Add a mapping to `openapi/overrides.json` under `enumVarnames` + (schema name → ordered constant names). String enums self-name — no action. +- **New endpoint returning `string/format: byte` or a stream**: the existing client provides + helpers in `cloudhub/CloudhubUtils.java` (`convertCertificateToString`, + `convertToSignHashToByteArray64`). Consider whether the new endpoint warrants a similar + convenience helper; if unsure, **flag it for a human** rather than inventing one. +- **Removed endpoints/fields**: confirm intentional, call it out as breaking in the summary. +- **New auth scheme**: the generated `ApiClient` wires schemes from the spec automatically, but + `CloudhubClient`'s convenience constructor only knows `X-Api-Key`. Update `CloudhubClient.java` + if a new scheme must be first-class. + +### 5. Regenerate + build +``` +pwsh scripts/Update-JavaClient.ps1 -SkipCloudHubBuild +``` +(`-SkipCloudHubBuild` reuses the assemblies from step 1.) This runs `openApiGenerate`, the +idempotent JavaDoc safety patch, then `clean build`. The build must be green. + +### 6. Finalize +- Bump `version` in `build.gradle` to the value from step 3 (the generator reads it for `artifactVersion`). +- Prepend an entry to `CHANGELOG.md`: new version, date, and the step-2 summary. +- Re-run `git status` / `git diff` and sanity-check that **only** intended files changed and that + the protected files (`CloudhubClient.java`, `CloudhubUtils.java`) are untouched. + +### 7. Report +Tell the user: the new version, the upstream-change summary, any flagged judgment items and how +you resolved them, and the build result. Do **not** commit/push unless asked. + +## Verifying the result +- `./gradlew clean build` is green. +- Idempotence: a second `-SkipCloudHubBuild` run with no upstream change leaves an empty `git diff`. +- Protected customizations intact: `CloudhubClient extends ApiClient` with the `(baseURL, apiKey)` + ctor + 2-minute timeouts; `CloudhubUtils` helpers present. + +## Troubleshooting +- **CloudHub build fails on restore**: the private Lacuna NuGet feed isn't configured. Add it + (`dotnet nuget add source ...`) or build on a machine with a warm package cache. If you only + have a pre-exported `swagger.json`, copy it to `openapi/cloudhub.json` and skip to step 2. +- **`dotnet swagger tofile` fails**: confirm the Swagger doc name is still `v1` + (`Site/Startup.cs` → `SwaggerDoc("v1", ...)`); pass the matching name as the last arg. +- **Generation overwrote a hand-written file**: it isn't listed in `.openapi-generator-ignore` — + add it and regenerate. +- **JavaDoc build error about ``**: the safety patch in the script handles it; if + it recurs, add a `templates/api_doc.mustache` override (the gradle config auto-uses `templates/`). +- **Spurious diffs on every run**: ensure `hideGenerationTimestamp=true` is still set in + `openapi-generator.gradle`. diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json new file mode 100644 index 0000000..38cd3a5 --- /dev/null +++ b/.config/dotnet-tools.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "swashbuckle.aspnetcore.cli": { + "version": "10.1.7", + "commands": [ + "swagger" + ], + "rollForward": false + } + } +} \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8b2399d --- /dev/null +++ b/.gitattributes @@ -0,0 +1,13 @@ +# Normalize line endings so code generation produces content-only diffs whether it runs +# locally on Windows or in Linux CI. Generated sources use LF; without this, CI (LF) vs a +# Windows-committed baseline (CRLF) shows every line as changed in the PR. +* text=auto eol=lf + +# Windows batch scripts keep CRLF +*.bat text eol=crlf + +# Binary assets (never touch line endings) +*.jar binary +*.gpg binary +*.p12 binary +*.pfx binary diff --git a/.github/workflows/sync-from-cloudhub.yml b/.github/workflows/sync-from-cloudhub.yml new file mode 100644 index 0000000..f9ea519 --- /dev/null +++ b/.github/workflows/sync-from-cloudhub.yml @@ -0,0 +1,90 @@ +name: Sync from CloudHub (regenerate client) + +# Regenerates this client from CloudHub's current OpenAPI spec and opens a PR. +# Triggers: +# - repository_dispatch : fired by the cloudhub repo's "Trigger Java client sync" workflow +# - schedule : weekly poll (reads CloudHub's CHANGELOG as the change signal) +# - workflow_dispatch : manual +# +# ALL secrets below are PLACEHOLDERS — fill them in later. + +on: + repository_dispatch: + types: [regenerate-client] + schedule: + - cron: '0 6 * * 1' + workflow_dispatch: {} + +permissions: + contents: write + pull-requests: write + +jobs: + regenerate: + # A hosted VM. If building CloudHub needs Windows/licensed components or a private + # network, switch to a self-hosted runner: runs-on: [self-hosted, windows] + runs-on: ubuntu-latest + + steps: + - name: Checkout java client + uses: actions/checkout@v4 + + - name: Checkout CloudHub (.NET server) to build + capture the spec + uses: actions/checkout@v4 + with: + repository: LacunaSoftware/cloudhub + path: cloudhub + token: ${{ secrets.CLOUDHUB_REPO_TOKEN }} # PLACEHOLDER: read access to the private cloudhub repo + + - name: Read CloudHub CHANGELOG (the trigger signal / target version) + run: | + echo "----- CloudHub CHANGELOG (top) -----" + head -n 40 cloudhub/CHANGELOG.md || echo "(no CHANGELOG.md in cloudhub)" + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + - name: Configure private Lacuna NuGet feed + run: | + dotnet nuget add source "${{ secrets.LACUNA_NUGET_FEED_URL }}" \ + --name lacuna \ + --username "${{ secrets.LACUNA_NUGET_USER }}" \ + --password "${{ secrets.LACUNA_NUGET_TOKEN }}" \ + --store-password-in-clear-text + # PLACEHOLDERS: creds for restoring Lacuna.Pki / BrazilTrustServices packages + + - name: Build CloudHub + capture OpenAPI spec (no tests) + run: | + dotnet build cloudhub/Site/Lacuna.Cloudhub.Site.csproj -c Release --nologo + dotnet tool restore + DLL="$(find cloudhub/Site/bin/Release -name Lacuna.Cloudhub.Site.dll | head -n1)" + dotnet swagger tofile --output openapi/cloudhub.json "$DLL" v1 + + - name: Setup JDK + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + - name: Code generation only (no build/tests) + run: ./gradlew normalizeOpenApiSpec openApiGenerate --console=plain + + - name: Claude Code — finalize (version + changelog) and open PR + uses: anthropics/claude-code-action@v1 + with: + # ┌─ PLACEHOLDER: choose ONE Claude auth method ───────────────────────────────┐ + # │ (a) Teams/Enterprise seat via OAuth token (claude setup-token): │ + claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} + # │ (b) or a Console service-account API key: │ + # anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} │ + # └────────────────────────────────────────────────────────────────────────────┘ + prompt: > + Follow the /update-cloudhub-client skill. The CloudHub spec has already been captured + to openapi/cloudhub.json and the client regenerated (./gradlew openApiGenerate ran). + Do NOT run app tests. Review the generated diff against CloudHub's changelog at + ./cloudhub/CHANGELOG.md, bump the version in build.gradle accordingly, update this + repo's CHANGELOG.md, then open a pull request summarizing the API changes. If there is + no effective change, do not open a PR. + claude_args: "--model opus" diff --git a/.gitignore b/.gitignore index c98b048..a2a8ed4 100644 --- a/.gitignore +++ b/.gitignore @@ -3,32 +3,33 @@ # Mobile Tools for Java (J2ME) .mtj.tmp/ -# Package Files # +# Package files *.jar *.war *.ear - -# exclude jar for gradle wrapper !gradle/wrapper/*.jar -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +# JVM crash logs hs_err_pid* -# build files +# Build output **/target target .gradle build -.github/workflows/maven.yml -git_push.sh + +# Local / machine-specific / secrets gradle.properties -.openapi-generator/* + +# OpenAPI Generator byproducts we don't use (also suppressed in .openapi-generator-ignore +# so they are never generated; ignored here as a safety net). +.openapi-generator/ pom.xml -.openapi-generator/* -api/openapi.yaml build.sbt .travis.yml +git_push.sh +api/openapi.yaml src/main/AndroidManifest.xml -.openapi-generator-ignore +.github/workflows/maven.yml *.gpg .vscode/settings.json diff --git a/.openapi-generator-ignore b/.openapi-generator-ignore new file mode 100644 index 0000000..1920781 --- /dev/null +++ b/.openapi-generator-ignore @@ -0,0 +1,59 @@ +# OpenAPI Generator ignore file (committed; honored via `ignoreFileOverride` in openapi-generator.gradle). +# +# Files matched here are NEVER overwritten by `openApiGenerate`. Everything else under +# src/main/java/**, src/test/java/**, and docs/** IS regenerated on every run. +# Pattern syntax is .gitignore-style, rooted at the repository root (the generator outputDir). + +############################ +# Hand-written source code # +############################ +# Convenience entry point: extends the generated ApiClient with a (baseURL, apiKey) +# constructor and default 2-minute timeouts. See openapi-generator.gradle / README. +src/main/java/cloudhub/client/CloudhubClient.java +# Lacuna-specific helpers, moved out of the (regenerated) SessionsApi so they survive. +src/main/java/cloudhub/CloudhubUtils.java + +########################### +# Build & publish config # +########################### +build.gradle +settings.gradle +gradle.properties +gradlew +gradlew.bat +gradle/** +openapi-generator.gradle + +########################### +# Pipeline inputs/tooling # +########################### +.openapi-generator-ignore +openapi/** +templates/** +scripts/** +.config/** +.github/** +.claude/** + +################## +# Docs & project # +################## +README.md +CHANGELOG.md +LICENSE + +########################################## +# Generator byproducts we don't use # +# (this is a Gradle project - not Maven/ # +# SBT/Travis/Android; spec lives in # +# openapi/cloudhub.json) # +########################################## +pom.xml +build.sbt +.travis.yml +git_push.sh +api/** +src/main/AndroidManifest.xml + +# Never overwrite the hand-maintained VCS ignore file (the generator emits its own .gitignore) +.gitignore diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..0b8252d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,47 @@ +# Changelog + +All notable changes to the Cloudhub Java client are documented here. +This project adheres to [Semantic Versioning](https://semver.org). + +## [2.0.0] - 2026-06-30 + +### Fixed +- **Client sends the `X-Api-Key` header.** CloudHub's spec declares the `ApiKey` security *scheme* + but no *requirement* (its `AddSecurityRequirement` is commented out), so the generated operations + had empty `authNames` and every authenticated call failed with **HTTP 401**. The + `normalizeOpenApiSpec` step injects a global security requirement + (`openapi/overrides.json` → `globalSecurity: [{ ApiKey: [] }]`) so all operations attach the key. + +### Added — automated CloudHub sync pipeline +- `openapi/cloudhub.json` — OpenAPI spec captured from CloudHub, committed as the source of truth. +- `openapi-generator.gradle` — pinned OpenAPI Generator (7.14.0) config and a `normalizeOpenApiSpec` + task (the declarative spec-fix hook, driven by `openapi/overrides.json`). +- `.openapi-generator-ignore` — protects hand-maintained files from regeneration (now committed). +- `scripts/Update-JavaClient.ps1` — one command: capture spec → regenerate → build. +- `.config/dotnet-tools.json` — pins the Swashbuckle CLI used for headless spec capture. +- `.claude/skills/update-cloudhub-client` — skill that orchestrates the pipeline, summarizes the + upstream diff, recommends the version bump, and flags judgment calls. +- `cloudhub.CloudhubUtils` — new home for the `convertCertificateToString` / + `convertToSignHashToByteArray64` helpers (previously inside the generated `SessionsApi`). + +### Changed +- `cloudhub.client.CloudhubClient` is now a thin subclass of the generated `cloudhub.client.ApiClient` + (keeping the `(baseURL, apiKey)` constructor and 2-minute timeouts) instead of a renamed copy of the + generated invoker. Existing `new CloudhubClient(endpoint, apiKey)` usage is unchanged. (`setBasePath` + now returns `ApiClient` rather than `CloudhubClient`, affecting only fluent chaining.) +- `build.gradle`: signing is now required only when publishing to the **remote** Maven repository, and + the OSSRH credentials resolve null-safely. This lets regeneration, `build`, and `publishToMavenLocal` + run without a GPG key or credentials (CI / local testing); the real `publish` to Sonatype is unchanged. + +### Migration note (source compatibility) +- The two helpers moved from `cloudhub.SessionsApi` to `cloudhub.CloudhubUtils`. Update any callers: + `SessionsApi.convertCertificateToString(...)` → `CloudhubUtils.convertCertificateToString(...)`. + +### Updated to the CloudHub 2.0.0 API surface +Regenerated from the current CloudHub spec. Changes since client 1.0.5: +- **Added** endpoints: `GET /api/sessions/services/{name}/availability`, `GET /api/sessions/custom-state`. +- **Added** model `GetServiceAvailabilityResponse`; added `CertificateModel.serviceName`. +- **Changed** `SessionCreateRequest`: `lifetimeInMinutes` → `lifetimeInSeconds` (int32); added + `identifierType`; `redirectUri` is now required. +- **Changed (breaking)** `TrustServiceSessionTypes` is now a **string** enum (was integer) — the wire + format changed upstream. This alone implies a **major** version bump. diff --git a/README.md b/README.md index 30c18ab..b3035fe 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,29 @@ # cloudhub-java-client Cloudhub API client library for Java -- API version: 1.0.5 - - Build date: 2025-03-24T09:46:17.287214-03:00[America/Sao_Paulo] +- API version: 2.0.0 -*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) with modifications* +*Generated from the CloudHub OpenAPI spec by the [OpenAPI Generator](https://openapi-generator.tech). Hand-written customizations are kept in separate, protected files — see "Keeping this client up to date".* + + +## Keeping this client up to date + +This client mirrors the [CloudHub](https://cloudhub.lacunasoftware.com/) REST API and is +**regenerated from its OpenAPI spec**. The sync is automated: + +```shell +# capture the latest spec from CloudHub, regenerate, then build +pwsh scripts/Update-JavaClient.ps1 +``` + +- `openapi/cloudhub.json` is the committed source of truth — `git diff` on it shows what changed upstream. +- Hand-written code (`cloudhub.client.CloudhubClient`, `cloudhub.CloudhubUtils`, `build.gradle`, this + README) is protected by `.openapi-generator-ignore` and is never overwritten by generation. +- For a guided update (upstream-change summary, version bump, and the few judgment calls a generator + can't make), use the **`update-cloudhub-client`** skill. See `CHANGELOG.md` for history. + +Running the generator needs a **JDK 11+** (the produced library still targets Java 8) plus the **.NET +SDK** to build CloudHub. Generator config lives in `openapi-generator.gradle`. ## Requirements @@ -37,7 +56,7 @@ Add this dependency to your project's POM: com.lacunasoftware.cloudhub cloudhub-client - 1.0.5 + 2.0.0 compile ``` @@ -53,7 +72,7 @@ Add this dependency to your project's build file: } dependencies { - implementation "com.lacunasoftware.cloudhub:cloudhub-client:1.0.5" + implementation "com.lacunasoftware.cloudhub:cloudhub-client:2.0.0" } ``` @@ -67,7 +86,7 @@ mvn clean package Then manually install the following JARs: -* `target/cloudhub-client-1.0.5.jar` +* `target/cloudhub-client-2.0.0.jar` * `target/lib/*.jar` ## Getting Started diff --git a/build.gradle b/build.gradle index fda7f07..2f810f6 100644 --- a/build.gradle +++ b/build.gradle @@ -5,7 +5,7 @@ apply plugin: 'maven-publish' apply plugin: 'signing' group = 'com.lacunasoftware.cloudhub' -version = '1.0.5' +version = '2.0.0' sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 @@ -23,9 +23,14 @@ buildscript { classpath 'com.android.tools.build:gradle:2.3.+' classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' classpath 'com.diffplug.spotless:spotless-plugin-gradle:6.11.0' + classpath 'org.openapitools:openapi-generator-gradle-plugin:7.14.0' } } +// Code generation (OpenAPI Generator). Task + config live in openapi-generator.gradle. +apply plugin: 'org.openapi.generator' +apply from: "$projectDir/openapi-generator.gradle" + repositories { mavenCentral() @@ -74,8 +79,11 @@ publishing { maven { url "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/" credentials { - username ossrhUsername - password ossrhPassword + // Resolve null-safely so configuration (and regeneration/build) works without + // credentials present. Supply -PossrhUsername/-PossrhPassword (or gradle.properties) + // when actually publishing. + username = project.findProperty('ossrhUsername') ?: '' + password = project.findProperty('ossrhPassword') ?: '' } } } @@ -128,6 +136,10 @@ test { signing { + // Require signing only when publishing to the REMOTE Maven repository (Sonatype). This lets + // `build` and `publishToMavenLocal` run without a configured GPG key (CI / local testing), + // while real releases (`publish`) still sign as before. + required { gradle.taskGraph.allTasks.any { it.name.endsWith('PublicationToMavenRepository') } } sign publishing.publications.mavenJava sign configurations.archives } \ No newline at end of file diff --git a/docs/CertificateModel.md b/docs/CertificateModel.md index 9573f9c..253d6fd 100644 --- a/docs/CertificateModel.md +++ b/docs/CertificateModel.md @@ -9,6 +9,7 @@ |------------ | ------------- | ------------- | -------------| |**content** | **byte[]** | | [optional] | |**alias** | **String** | | [optional] | +|**serviceName** | **String** | | [optional] | diff --git a/docs/GetServiceAvailabilityResponse.md b/docs/GetServiceAvailabilityResponse.md new file mode 100644 index 0000000..4000b59 --- /dev/null +++ b/docs/GetServiceAvailabilityResponse.md @@ -0,0 +1,14 @@ + + +# GetServiceAvailabilityResponse + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**discoveryAvailable** | **Boolean** | | [optional] | +|**certificateFound** | **Boolean** | | [optional] | + + + diff --git a/docs/ServiceSessionCreateRequest.md b/docs/ServiceSessionCreateRequest.md index ff6b917..03c767c 100644 --- a/docs/ServiceSessionCreateRequest.md +++ b/docs/ServiceSessionCreateRequest.md @@ -7,10 +7,12 @@ | Name | Type | Description | Notes | |------------ | ------------- | ------------- | -------------| -|**identifier** | **String** | | | +|**identifier** | **String** | | [optional] | |**type** | **TrustServiceSessionTypes** | | [optional] | |**redirectUri** | **String** | | | |**lifetimeInSeconds** | **Integer** | | [optional] | +|**customState** | **String** | | [optional] | +|**discover** | **Boolean** | | [optional] | diff --git a/docs/SessionCreateRequest.md b/docs/SessionCreateRequest.md index a4b0c94..05d78b0 100644 --- a/docs/SessionCreateRequest.md +++ b/docs/SessionCreateRequest.md @@ -8,10 +8,12 @@ | Name | Type | Description | Notes | |------------ | ------------- | ------------- | -------------| |**identifierType** | **IdentifierTypes** | | [optional] | -|**identifier** | **String** | | | +|**identifier** | **String** | | [optional] | |**type** | **TrustServiceSessionTypes** | | [optional] | |**redirectUri** | **String** | | | |**lifetimeInSeconds** | **Integer** | | [optional] | +|**customState** | **String** | | [optional] | +|**discover** | **Boolean** | | [optional] | diff --git a/docs/SessionsApi.md b/docs/SessionsApi.md index 3eaab51..efc5b5a 100644 --- a/docs/SessionsApi.md +++ b/docs/SessionsApi.md @@ -5,14 +5,16 @@ All URIs are relative to *http://localhost* | Method | HTTP request | Description | |------------- | ------------- | -------------| | [**apiSessionsCertificateGet**](SessionsApi.md#apiSessionsCertificateGet) | **GET** /api/sessions/certificate | | +| [**apiSessionsCustomStateGet**](SessionsApi.md#apiSessionsCustomStateGet) | **GET** /api/sessions/custom-state | | | [**apiSessionsPost**](SessionsApi.md#apiSessionsPost) | **POST** /api/sessions | | | [**apiSessionsServicesGet**](SessionsApi.md#apiSessionsServicesGet) | **GET** /api/sessions/services | | +| [**apiSessionsServicesNameAvailabilityGet**](SessionsApi.md#apiSessionsServicesNameAvailabilityGet) | **GET** /api/sessions/services/{name}/availability | | | [**apiSessionsServicesNamePost**](SessionsApi.md#apiSessionsServicesNamePost) | **POST** /api/sessions/services/{name} | | | [**apiSessionsSignHashPost**](SessionsApi.md#apiSessionsSignHashPost) | **POST** /api/sessions/sign-hash | | | [**apiV2SessionsCertificateGet**](SessionsApi.md#apiV2SessionsCertificateGet) | **GET** /api/v2/sessions/certificate | | - + # **apiSessionsCertificateGet** > byte[] apiSessionsCertificateGet(session) @@ -77,9 +79,76 @@ public class Example { ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | Success | - | +| **200** | OK | - | - + +# **apiSessionsCustomStateGet** +> String apiSessionsCustomStateGet(session) + + + +### Example +```java +// Import classes: +import cloudhub.client.ApiClient; +import cloudhub.client.ApiException; +import cloudhub.client.Configuration; +import cloudhub.client.auth.*; +import cloudhub.client.models.*; +import cloudhub.SessionsApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost"); + + // Configure API key authorization: ApiKey + ApiKeyAuth ApiKey = (ApiKeyAuth) defaultClient.getAuthentication("ApiKey"); + ApiKey.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //ApiKey.setApiKeyPrefix("Token"); + + SessionsApi apiInstance = new SessionsApi(defaultClient); + String session = "session_example"; // String | + try { + String result = apiInstance.apiSessionsCustomStateGet(session); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling SessionsApi#apiSessionsCustomStateGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **session** | **String**| | | + +### Return type + +**String** + +### Authorization + +[ApiKey](../README.md#ApiKey) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain, application/json, text/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | OK | - | + + # **apiSessionsPost** > SessionModel apiSessionsPost(sessionCreateRequest) @@ -144,9 +213,9 @@ public class Example { ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | Success | - | +| **200** | OK | - | - + # **apiSessionsServicesGet** > List<TrustServiceInfoModel> apiSessionsServicesGet(identifier, identifierType) @@ -213,9 +282,80 @@ public class Example { ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | Success | - | +| **200** | OK | - | + + +# **apiSessionsServicesNameAvailabilityGet** +> GetServiceAvailabilityResponse apiSessionsServicesNameAvailabilityGet(name, identifier, identifierType) + + + +### Example +```java +// Import classes: +import cloudhub.client.ApiClient; +import cloudhub.client.ApiException; +import cloudhub.client.Configuration; +import cloudhub.client.auth.*; +import cloudhub.client.models.*; +import cloudhub.SessionsApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost"); + + // Configure API key authorization: ApiKey + ApiKeyAuth ApiKey = (ApiKeyAuth) defaultClient.getAuthentication("ApiKey"); + ApiKey.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //ApiKey.setApiKeyPrefix("Token"); + + SessionsApi apiInstance = new SessionsApi(defaultClient); + String name = "name_example"; // String | + String identifier = "identifier_example"; // String | + IdentifierTypes identifierType = IdentifierTypes.fromValue("CPF"); // IdentifierTypes | + try { + GetServiceAvailabilityResponse result = apiInstance.apiSessionsServicesNameAvailabilityGet(name, identifier, identifierType); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling SessionsApi#apiSessionsServicesNameAvailabilityGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **name** | **String**| | | +| **identifier** | **String**| | [optional] | +| **identifierType** | [**IdentifierTypes**](.md)| | [optional] [enum: CPF, CNPJ] | + +### Return type + +[**GetServiceAvailabilityResponse**](GetServiceAvailabilityResponse.md) + +### Authorization + +[ApiKey](../README.md#ApiKey) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain, application/json, text/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | OK | - | - + # **apiSessionsServicesNamePost** > ServiceSessionCreateResponse apiSessionsServicesNamePost(name, serviceSessionCreateRequest) @@ -282,9 +422,9 @@ public class Example { ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | Success | - | +| **200** | OK | - | - + # **apiSessionsSignHashPost** > byte[] apiSessionsSignHashPost(signHashRequest) @@ -349,9 +489,9 @@ public class Example { ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | Success | - | +| **200** | OK | - | - + # **apiV2SessionsCertificateGet** > CertificateModel apiV2SessionsCertificateGet(session) @@ -416,5 +556,5 @@ public class Example { ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | Success | - | +| **200** | OK | - | diff --git a/docs/TrustServiceSessionTypes.md b/docs/TrustServiceSessionTypes.md index 3a08c5f..5c285f4 100644 --- a/docs/TrustServiceSessionTypes.md +++ b/docs/TrustServiceSessionTypes.md @@ -5,13 +5,13 @@ ## Enum -* `SINGLESIGNATURE` (value: `"SingleSignature"`) +* `SINGLE_SIGNATURE` (value: `"SingleSignature"`) -* `MULTISIGNATURE` (value: `"MultiSignature"`) +* `MULTI_SIGNATURE` (value: `"MultiSignature"`) -* `SIGNATURESESSION` (value: `"SignatureSession"`) +* `SIGNATURE_SESSION` (value: `"SignatureSession"`) -* `AUTHENTICATIONSESSION` (value: `"AuthenticationSession"`) +* `AUTHENTICATION_SESSION` (value: `"AuthenticationSession"`) diff --git a/openapi-generator.gradle b/openapi-generator.gradle new file mode 100644 index 0000000..573b76a --- /dev/null +++ b/openapi-generator.gradle @@ -0,0 +1,119 @@ +/* + * CloudHub Java client - code generation configuration. + * + * Applied from build.gradle. The OpenAPI Generator plugin is placed on the buildscript + * classpath in build.gradle; this file only defines the generation tasks and config. + * + * Usage: + * ./gradlew normalizeOpenApiSpec openApiGenerate # regenerate from openapi/cloudhub.json + * ./gradlew clean build # compile + verify + * + * Files listed in .openapi-generator-ignore are NEVER overwritten (hand-maintained). + */ + +import groovy.json.JsonSlurper +import groovy.json.JsonOutput + +def rawSpec = file("$projectDir/openapi/cloudhub.json") +def overridesFile = file("$projectDir/openapi/overrides.json") +def normalizedSpec = new File(layout.buildDirectory.get().asFile, 'openapi/cloudhub.normalized.json') + +/* + * Stage 1 - normalize the captured spec. + * + * The spec captured straight from CloudHub currently needs NO content changes: both enums + * are string-typed (they self-name) and binary fields use `format: byte` (handled natively). + * This task is the single declarative place to apply spec-level fixes the generator cannot + * infer - most importantly `x-enum-varnames` for any INTEGER-valued enum CloudHub may add. + * Overrides are declared in openapi/overrides.json. + */ +task normalizeOpenApiSpec { + description = 'Apply declarative overrides (openapi/overrides.json) to the captured spec.' + group = 'openapi' + inputs.file rawSpec + inputs.file overridesFile + outputs.file normalizedSpec + doLast { + def spec = new JsonSlurper().parse(rawSpec) + def ov = overridesFile.exists() ? new JsonSlurper().parse(overridesFile) : [:] + + if (ov.infoVersion) { + spec.info = spec.info ?: [:] + spec.info.version = ov.infoVersion + } + + // Inject a global security requirement. CloudHub declares the ApiKey scheme but no + // requirement, so without this the generator emits empty authNames and never sends the + // X-Api-Key header (every call -> HTTP 401). + if (ov.globalSecurity) { + spec.security = ov.globalSecurity + logger.lifecycle("applied global security requirement: ${ov.globalSecurity}") + } + + ov.enumVarnames?.each { schemaName, names -> + if (schemaName.startsWith('_')) return // skip example/comment keys + def schema = spec.components?.schemas?.get(schemaName) + if (schema?.enum) { + schema['x-enum-varnames'] = names + logger.lifecycle("applied x-enum-varnames to ${schemaName}") + } else { + logger.warn("overrides.json: enum schema '${schemaName}' not found in spec") + } + } + + normalizedSpec.parentFile.mkdirs() + normalizedSpec.text = JsonOutput.prettyPrint(JsonOutput.toJson(spec)) + logger.lifecycle("normalized spec -> ${normalizedSpec}") + } +} + +/* + * Stage 2 - generate the Java client in place. + * Package layout and options are pinned to reproduce the existing client exactly. + */ +def tplDir = file("$projectDir/templates") +def hasTemplates = tplDir.exists() && + ((tplDir.listFiles({ File d, String n -> n.endsWith('.mustache') } as FilenameFilter)?.length ?: 0) > 0) + +openApiGenerate { + generatorName.set('java') + library.set('okhttp-gson') + inputSpec.set(normalizedSpec.toString()) + outputDir.set(projectDir.toString()) + ignoreFileOverride.set(file("$projectDir/.openapi-generator-ignore").toString()) + if (hasTemplates) { + templateDir.set(tplDir.toString()) + } + + invokerPackage.set('cloudhub.client') + apiPackage.set('cloudhub') + modelPackage.set('cloudhub.client.model') + + // Artifact coordinates (groupId/id/version) are intentionally omitted: the generated + // build.gradle/pom are protected by .openapi-generator-ignore, so the real coordinates + // live only in the hand-maintained build.gradle. + + configOptions.set([ + hideGenerationTimestamp: 'true', // stable output -> diffs reflect real API changes + dateLibrary : 'java8', + enumPropertyNaming : 'MACRO_CASE', + sourceFolder : 'src/main/java', + useJakartaEe : 'false', // current code uses javax.* annotations + openApiNullable : 'true' + ]) + + // Generated tests are @Disabled stubs that the generator will NOT overwrite once they exist, + // so they go stale and break compilation on renames/API changes. Skip them; real tests can be + // added under src/test and generation will never touch them. + generateApiTests.set(false) + generateModelTests.set(false) + generateApiDocumentation.set(true) + generateModelDocumentation.set(true) +} + +tasks.named('openApiGenerate') { + dependsOn 'normalizeOpenApiSpec' + // We generate in place (outputDir = projectDir). Gradle would otherwise try to snapshot the + // entire repository as task output and fail to hash unreadable files (e.g. under .git). + doNotTrackState('Generates in place into the project tree; whole-repo output snapshotting is unnecessary.') +} diff --git a/openapi/cloudhub.json b/openapi/cloudhub.json new file mode 100644 index 0000000..3af92bf --- /dev/null +++ b/openapi/cloudhub.json @@ -0,0 +1,631 @@ +{ + "openapi": "3.0.4", + "info": { + "title": "Cloudhub API", + "version": "v1" + }, + "paths": { + "/api/sessions/services": { + "get": { + "tags": [ + "Sessions" + ], + "parameters": [ + { + "name": "identifier", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "identifierType", + "in": "query", + "schema": { + "$ref": "#/components/schemas/IdentifierTypes" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TrustServiceInfoModel" + } + } + }, + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TrustServiceInfoModel" + } + } + }, + "text/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TrustServiceInfoModel" + } + } + } + } + } + } + } + }, + "/api/sessions/services/{name}/availability": { + "get": { + "tags": [ + "Sessions" + ], + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "identifier", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "identifierType", + "in": "query", + "schema": { + "$ref": "#/components/schemas/IdentifierTypes" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/GetServiceAvailabilityResponse" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetServiceAvailabilityResponse" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/GetServiceAvailabilityResponse" + } + } + } + } + } + } + }, + "/api/sessions": { + "post": { + "tags": [ + "Sessions" + ], + "requestBody": { + "content": { + "application/json-patch+json": { + "schema": { + "$ref": "#/components/schemas/SessionCreateRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/SessionCreateRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/SessionCreateRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/SessionCreateRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/SessionModel" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/SessionModel" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/SessionModel" + } + } + } + } + } + } + }, + "/api/sessions/services/{name}": { + "post": { + "tags": [ + "Sessions" + ], + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json-patch+json": { + "schema": { + "$ref": "#/components/schemas/ServiceSessionCreateRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceSessionCreateRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ServiceSessionCreateRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ServiceSessionCreateRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ServiceSessionCreateResponse" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceSessionCreateResponse" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ServiceSessionCreateResponse" + } + } + } + } + } + } + }, + "/api/sessions/certificate": { + "get": { + "tags": [ + "Sessions" + ], + "parameters": [ + { + "name": "session", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "type": "string", + "format": "byte" + } + }, + "application/json": { + "schema": { + "type": "string", + "format": "byte" + } + }, + "text/json": { + "schema": { + "type": "string", + "format": "byte" + } + } + } + } + } + } + }, + "/api/v2/sessions/certificate": { + "get": { + "tags": [ + "Sessions" + ], + "parameters": [ + { + "name": "session", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/CertificateModel" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/CertificateModel" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/CertificateModel" + } + } + } + } + } + } + }, + "/api/sessions/sign-hash": { + "post": { + "tags": [ + "Sessions" + ], + "requestBody": { + "content": { + "application/json-patch+json": { + "schema": { + "$ref": "#/components/schemas/SignHashRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/SignHashRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/SignHashRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/SignHashRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "type": "string", + "format": "byte" + } + }, + "application/json": { + "schema": { + "type": "string", + "format": "byte" + } + }, + "text/json": { + "schema": { + "type": "string", + "format": "byte" + } + } + } + } + } + } + }, + "/api/sessions/custom-state": { + "get": { + "tags": [ + "Sessions" + ], + "parameters": [ + { + "name": "session", + "in": "query", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + }, + "application/json": { + "schema": { + "type": "string" + } + }, + "text/json": { + "schema": { + "type": "string" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "CertificateModel": { + "type": "object", + "properties": { + "content": { + "type": "string", + "format": "byte", + "nullable": true + }, + "alias": { + "type": "string", + "nullable": true + }, + "serviceName": { + "type": "string", + "nullable": true + } + }, + "additionalProperties": false + }, + "GetServiceAvailabilityResponse": { + "type": "object", + "properties": { + "discoveryAvailable": { + "type": "boolean" + }, + "certificateFound": { + "type": "boolean", + "nullable": true + } + }, + "additionalProperties": false + }, + "IdentifierTypes": { + "enum": [ + "CPF", + "CNPJ" + ], + "type": "string" + }, + "ServiceSessionCreateRequest": { + "required": [ + "redirectUri" + ], + "type": "object", + "properties": { + "identifier": { + "type": "string", + "nullable": true + }, + "type": { + "$ref": "#/components/schemas/TrustServiceSessionTypes" + }, + "redirectUri": { + "minLength": 1, + "type": "string" + }, + "lifetimeInSeconds": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "customState": { + "type": "string", + "nullable": true + }, + "discover": { + "type": "boolean", + "nullable": true + } + }, + "additionalProperties": false + }, + "ServiceSessionCreateResponse": { + "type": "object", + "properties": { + "serviceInfo": { + "$ref": "#/components/schemas/TrustServiceInfoModel" + }, + "authUrl": { + "type": "string", + "nullable": true + } + }, + "additionalProperties": false + }, + "SessionCreateRequest": { + "required": [ + "redirectUri" + ], + "type": "object", + "properties": { + "identifierType": { + "$ref": "#/components/schemas/IdentifierTypes" + }, + "identifier": { + "type": "string", + "nullable": true + }, + "type": { + "$ref": "#/components/schemas/TrustServiceSessionTypes" + }, + "redirectUri": { + "minLength": 1, + "type": "string" + }, + "lifetimeInSeconds": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "customState": { + "type": "string", + "nullable": true + }, + "discover": { + "type": "boolean", + "nullable": true + } + }, + "additionalProperties": false + }, + "SessionModel": { + "type": "object", + "properties": { + "services": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TrustServiceAuthParametersModel" + }, + "nullable": true + } + }, + "additionalProperties": false + }, + "SignHashRequest": { + "required": [ + "hash", + "session" + ], + "type": "object", + "properties": { + "session": { + "minLength": 1, + "type": "string" + }, + "hash": { + "type": "string", + "format": "byte" + }, + "digestAlgorithm": { + "type": "string", + "nullable": true + }, + "digestAlgorithmOid": { + "type": "string", + "nullable": true + }, + "certificateAlias": { + "type": "string", + "nullable": true + } + }, + "additionalProperties": false + }, + "TrustServiceAuthParametersModel": { + "type": "object", + "properties": { + "serviceInfo": { + "$ref": "#/components/schemas/TrustServiceInfoModel" + }, + "authUrl": { + "type": "string", + "nullable": true + } + }, + "additionalProperties": false + }, + "TrustServiceInfoModel": { + "type": "object", + "properties": { + "serviceName": { + "type": "string", + "nullable": true + }, + "provider": { + "type": "string", + "nullable": true + }, + "endpoint": { + "type": "string", + "nullable": true + }, + "badgeUrl": { + "type": "string", + "nullable": true + } + }, + "additionalProperties": false + }, + "TrustServiceSessionTypes": { + "enum": [ + "SingleSignature", + "MultiSignature", + "SignatureSession", + "AuthenticationSession" + ], + "type": "string" + } + }, + "securitySchemes": { + "ApiKey": { + "type": "apiKey", + "description": "Api Key authentication", + "name": "X-Api-Key", + "in": "header" + } + } + }, + "tags": [ + { + "name": "Sessions" + } + ] +} \ No newline at end of file diff --git a/openapi/overrides.json b/openapi/overrides.json new file mode 100644 index 0000000..c09191a --- /dev/null +++ b/openapi/overrides.json @@ -0,0 +1,8 @@ +{ + "_comment": "Declarative spec-level overrides applied by the `normalizeOpenApiSpec` Gradle task BEFORE code generation. CloudHub's Swagger defines the ApiKey security SCHEME but, with AddSecurityRequirement commented out, declares no security REQUIREMENT on its operations. Without that, OpenAPI Generator emits operations with empty authNames and the client never sends the X-Api-Key header (every call gets HTTP 401). `globalSecurity` injects the requirement so every operation attaches the key.", + "infoVersion": "v1", + "globalSecurity": [ { "ApiKey": [] } ], + "enumVarnames": { + "_example": "If CloudHub ever introduces an INTEGER-valued enum, map its schema name to ordered constant names here, e.g. \"SomeIntEnum\": [\"FIRST\", \"SECOND\"]. String enums self-name and need no entry. Keys starting with '_' are ignored." + } +} diff --git a/scripts/Update-JavaClient.ps1 b/scripts/Update-JavaClient.ps1 new file mode 100644 index 0000000..8f9ffcb --- /dev/null +++ b/scripts/Update-JavaClient.ps1 @@ -0,0 +1,134 @@ +<# +.SYNOPSIS + Re-syncs the Cloudhub Java client with the CloudHub API in one command. + +.DESCRIPTION + Pipeline stages: + 1. Build the CloudHub .NET Site (so its assemblies exist). + 2. Capture its OpenAPI spec headlessly -> openapi/cloudhub.json (Swashbuckle CLI). + 3. Regenerate the Java client (./gradlew openApiGenerate). + 4. Apply a conditional JavaDoc safety patch to generated sources. + 5. Compile + verify (./gradlew clean build). + + Files listed in .openapi-generator-ignore (CloudhubClient.java, CloudhubUtils.java, + build.gradle, README.md, ...) are never overwritten. + + After it runs, `git diff openapi/cloudhub.json` shows exactly what changed upstream. + +.PARAMETER CloudHubRepo + Path to the CloudHub .NET repo. Defaults to a sibling folder named "cloudhub". + +.PARAMETER Configuration + .NET build configuration (Debug/Release). Default: Debug. + +.PARAMETER SpecOnly + Capture the spec only; skip generation and build. + +.PARAMETER SkipCloudHubBuild + Reuse already-built CloudHub assemblies (skip stage 1). + +.PARAMETER SkipGradleBuild + Regenerate but skip the final `clean build` (stage 5). + +.EXAMPLE + pwsh scripts/Update-JavaClient.ps1 +.EXAMPLE + pwsh scripts/Update-JavaClient.ps1 -CloudHubRepo ..\cloudhub -Configuration Release +#> +[CmdletBinding()] +param( + [string] $CloudHubRepo, + [ValidateSet('Debug', 'Release')] [string] $Configuration = 'Debug', + [switch] $SpecOnly, + [switch] $SkipCloudHubBuild, + [switch] $SkipGradleBuild +) + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest + +function Write-Step($msg) { Write-Host "`n==> $msg" -ForegroundColor Cyan } +function Fail($msg) { Write-Error $msg; exit 1 } + +# --- Resolve paths ----------------------------------------------------------- +$RepoRoot = Split-Path -Parent $PSScriptRoot +Write-Step "Java client repo: $RepoRoot" + +if (-not $CloudHubRepo) { $CloudHubRepo = Join-Path (Split-Path -Parent $RepoRoot) 'cloudhub' } +$resolved = Resolve-Path -LiteralPath $CloudHubRepo -ErrorAction SilentlyContinue +$CloudHubRepo = if ($resolved) { $resolved.Path } else { $null } +if (-not $CloudHubRepo) { Fail "CloudHub repo not found. Pass -CloudHubRepo ." } +Write-Host "CloudHub repo: $CloudHubRepo" + +$SiteCsproj = Join-Path $CloudHubRepo 'Site\Lacuna.Cloudhub.Site.csproj' +if (-not (Test-Path $SiteCsproj)) { Fail "Site project not found at $SiteCsproj" } + +$SpecPath = Join-Path $RepoRoot 'openapi\cloudhub.json' + +# --- Stage 1: build CloudHub ------------------------------------------------- +if (-not $SkipCloudHubBuild) { + Write-Step "Building CloudHub Site ($Configuration)" + dotnet build $SiteCsproj -c $Configuration --nologo -v minimal + if ($LASTEXITCODE -ne 0) { Fail "CloudHub build failed (exit $LASTEXITCODE)." } +} else { + Write-Step "Skipping CloudHub build (-SkipCloudHubBuild)" +} + +# --- Stage 2: capture the spec ---------------------------------------------- +Write-Step "Locating built Site assembly" +$SiteDll = Get-ChildItem -Path (Join-Path $CloudHubRepo "Site\bin\$Configuration") -Recurse -Filter 'Lacuna.Cloudhub.Site.dll' -ErrorAction SilentlyContinue | + Sort-Object LastWriteTime -Descending | Select-Object -First 1 +if (-not $SiteDll) { Fail "Could not find Lacuna.Cloudhub.Site.dll under Site\bin\$Configuration. Build first (omit -SkipCloudHubBuild)." } +Write-Host "Assembly: $($SiteDll.FullName)" + +Write-Step "Restoring the Swashbuckle CLI tool" +Push-Location $RepoRoot +try { + dotnet tool restore + if ($LASTEXITCODE -ne 0) { Fail "dotnet tool restore failed." } + + Write-Step "Capturing OpenAPI spec -> openapi/cloudhub.json" + New-Item -ItemType Directory -Force -Path (Split-Path $SpecPath) | Out-Null + dotnet swagger tofile --output $SpecPath $SiteDll.FullName v1 + if ($LASTEXITCODE -ne 0) { Fail "Spec capture failed. (Doc name 'v1' must match the Swashbuckle SwaggerDoc id.)" } + Write-Host "Spec written: $((Get-Item $SpecPath).Length) bytes" +} +finally { Pop-Location } + +if ($SpecOnly) { Write-Step "Done (spec only). Review with: git -C `"$RepoRoot`" diff openapi/cloudhub.json"; exit 0 } + +# --- Java required from here on --------------------------------------------- +if (-not (Get-Command java -ErrorAction SilentlyContinue) -and -not $env:JAVA_HOME) { + Fail "No JDK found (java not on PATH, JAVA_HOME unset). Generation/build need a JDK 8+. Install one, or re-run with -SpecOnly and generate where Java is available." +} + +$Gradlew = Join-Path $RepoRoot 'gradlew.bat' + +# --- Stage 3: regenerate ----------------------------------------------------- +Write-Step "Regenerating the Java client (./gradlew openApiGenerate)" +& $Gradlew -p $RepoRoot normalizeOpenApiSpec openApiGenerate +if ($LASTEXITCODE -ne 0) { Fail "openApiGenerate failed (exit $LASTEXITCODE)." } + +# --- Stage 4: JavaDoc safety patch (idempotent; usually a no-op on 7.x) ------ +Write-Step "Applying JavaDoc HTML5 safety patch (if needed)" +$patched = 0 +Get-ChildItem -Path (Join-Path $RepoRoot 'src\main\java') -Recurse -Filter '*.java' | ForEach-Object { + $text = Get-Content -LiteralPath $_.FullName -Raw + $new = [regex]::Replace($text, '
', '
') + if ($new -ne $text) { Set-Content -LiteralPath $_.FullName -Value $new -NoNewline; $patched++ } +} +Write-Host "Files patched: $patched" + +# --- Stage 5: compile + verify ---------------------------------------------- +if (-not $SkipGradleBuild) { + Write-Step "Building + verifying (./gradlew clean build)" + & $Gradlew -p $RepoRoot clean build + if ($LASTEXITCODE -ne 0) { Fail "Gradle build failed (exit $LASTEXITCODE)." } +} else { + Write-Step "Skipping Gradle build (-SkipGradleBuild)" +} + +Write-Step "Done." +Write-Host "Review upstream API changes: git -C `"$RepoRoot`" diff openapi/cloudhub.json" +Write-Host "Review generated code changes: git -C `"$RepoRoot`" status" +Write-Host "Remember to bump `version` in build.gradle and add a CHANGELOG entry (the skill does this)." diff --git a/src/main/java/cloudhub/CloudhubUtils.java b/src/main/java/cloudhub/CloudhubUtils.java new file mode 100644 index 0000000..aa61e16 --- /dev/null +++ b/src/main/java/cloudhub/CloudhubUtils.java @@ -0,0 +1,38 @@ +package cloudhub; + +import java.util.Base64; + +/** + * Lacuna-specific helper utilities for working with the Cloudhub API. + * + *

This class is hand-maintained (listed in + * {@code .openapi-generator-ignore}) and is never overwritten by code generation. + * These helpers previously lived inside the generated {@code SessionsApi}; they were + * moved here so they survive regeneration. + */ +public final class CloudhubUtils { + + private CloudhubUtils() { + } + + /** + * Converts a given byte array certificate into a readable string for signature or validation purposes. + * + * @param certificate The certificate obtained from {@code apiSessionsCertificateGet} + * @return a String with the certificate in base 64 + */ + public static String convertCertificateToString(byte[] certificate) { + return new String(certificate).replace("\"", ""); + } + + /** + * Converts a given byte array toSignHash into a base64 encoded byte array for signature purposes. + * + * @param toSignHash the hash used to sign the document + * @return base64 encoded byte array + */ + public static byte[] convertToSignHashToByteArray64(byte[] toSignHash) { + // first we need to convert it to string and then decode as base64 + return Base64.getDecoder().decode(convertCertificateToString(toSignHash)); + } +} diff --git a/src/main/java/cloudhub/SessionsApi.java b/src/main/java/cloudhub/SessionsApi.java index 2c9c757..db5af7e 100644 --- a/src/main/java/cloudhub/SessionsApi.java +++ b/src/main/java/cloudhub/SessionsApi.java @@ -13,21 +13,22 @@ package cloudhub; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Base64; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.google.gson.reflect.TypeToken; - import cloudhub.client.ApiCallback; +import cloudhub.client.ApiClient; import cloudhub.client.ApiException; import cloudhub.client.ApiResponse; -import cloudhub.client.CloudhubClient; +import cloudhub.client.Configuration; import cloudhub.client.Pair; +import cloudhub.client.ProgressRequestBody; +import cloudhub.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + import cloudhub.client.model.CertificateModel; +import cloudhub.client.model.GetServiceAvailabilityResponse; import cloudhub.client.model.IdentifierTypes; import cloudhub.client.model.ServiceSessionCreateRequest; import cloudhub.client.model.ServiceSessionCreateResponse; @@ -36,22 +37,31 @@ import cloudhub.client.model.SignHashRequest; import cloudhub.client.model.TrustServiceInfoModel; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + public class SessionsApi { - private CloudhubClient localVarCloudhubClient; + private ApiClient localVarApiClient; private int localHostIndex; private String localCustomBaseUrl; - public SessionsApi(CloudhubClient CloudhubClient) { - this.localVarCloudhubClient = CloudhubClient; - this.localCustomBaseUrl = this.localVarCloudhubClient.getBasePath(); + public SessionsApi() { + this(Configuration.getDefaultApiClient()); } - public CloudhubClient getCloudhubClient() { - return localVarCloudhubClient; + public SessionsApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; } - public void setCloudhubClient(CloudhubClient CloudhubClient) { - this.localVarCloudhubClient = CloudhubClient; + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; } public int getHostIndex() { @@ -78,12 +88,12 @@ public void setCustomBaseUrl(String customBaseUrl) { * @throws ApiException If fail to serialize the request body object * @http.response.details

$1
- + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public okhttp3.Call apiSessionsCertificateGetCall(String session, final ApiCallback _callback) throws ApiException { + public okhttp3.Call apiSessionsCertificateGetCall(@javax.annotation.Nullable String session, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] { }; @@ -109,7 +119,7 @@ public okhttp3.Call apiSessionsCertificateGetCall(String session, final ApiCallb Map localVarFormParams = new HashMap(); if (session != null) { - localVarQueryParams.addAll(localVarCloudhubClient.parameterToPair("session", session)); + localVarQueryParams.addAll(localVarApiClient.parameterToPair("session", session)); } final String[] localVarAccepts = { @@ -117,24 +127,24 @@ public okhttp3.Call apiSessionsCertificateGetCall(String session, final ApiCallb "application/json", "text/json" }; - final String localVarAccept = localVarCloudhubClient.selectHeaderAccept(localVarAccepts); + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; - final String localVarContentType = localVarCloudhubClient.selectHeaderContentType(localVarContentTypes); + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] { "ApiKey" }; - return localVarCloudhubClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") - private okhttp3.Call apiSessionsCertificateGetValidateBeforeCall(String session, final ApiCallback _callback) throws ApiException { + private okhttp3.Call apiSessionsCertificateGetValidateBeforeCall(@javax.annotation.Nullable String session, final ApiCallback _callback) throws ApiException { return apiSessionsCertificateGetCall(session, _callback); } @@ -147,12 +157,12 @@ private okhttp3.Call apiSessionsCertificateGetValidateBeforeCall(String session, * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public byte[] apiSessionsCertificateGet(String session) throws ApiException { + public byte[] apiSessionsCertificateGet(@javax.annotation.Nullable String session) throws ApiException { ApiResponse localVarResp = apiSessionsCertificateGetWithHttpInfo(session); return localVarResp.getData(); } @@ -165,15 +175,15 @@ public byte[] apiSessionsCertificateGet(String session) throws ApiException { * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public ApiResponse apiSessionsCertificateGetWithHttpInfo(String session) throws ApiException { + public ApiResponse apiSessionsCertificateGetWithHttpInfo(@javax.annotation.Nullable String session) throws ApiException { okhttp3.Call localVarCall = apiSessionsCertificateGetValidateBeforeCall(session, null); Type localVarReturnType = new TypeToken(){}.getType(); - return localVarCloudhubClient.execute(localVarCall, localVarReturnType); + return localVarApiClient.execute(localVarCall, localVarReturnType); } /** @@ -185,16 +195,148 @@ public ApiResponse apiSessionsCertificateGetWithHttpInfo(String session) * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public okhttp3.Call apiSessionsCertificateGetAsync(String session, final ApiCallback _callback) throws ApiException { + public okhttp3.Call apiSessionsCertificateGetAsync(@javax.annotation.Nullable String session, final ApiCallback _callback) throws ApiException { okhttp3.Call localVarCall = apiSessionsCertificateGetValidateBeforeCall(session, _callback); Type localVarReturnType = new TypeToken(){}.getType(); - localVarCloudhubClient.executeAsync(localVarCall, localVarReturnType, _callback); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for apiSessionsCustomStateGet + * @param session (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
Response Details
Status Code Description Response Headers
200 OK -
+ */ + public okhttp3.Call apiSessionsCustomStateGetCall(@javax.annotation.Nonnull String session, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/api/sessions/custom-state"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (session != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("session", session)); + } + + final String[] localVarAccepts = { + "text/plain", + "application/json", + "text/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "ApiKey" }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call apiSessionsCustomStateGetValidateBeforeCall(@javax.annotation.Nonnull String session, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'session' is set + if (session == null) { + throw new ApiException("Missing the required parameter 'session' when calling apiSessionsCustomStateGet(Async)"); + } + + return apiSessionsCustomStateGetCall(session, _callback); + + } + + /** + * + * + * @param session (required) + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Response Details
Status Code Description Response Headers
200 OK -
+ */ + public String apiSessionsCustomStateGet(@javax.annotation.Nonnull String session) throws ApiException { + ApiResponse localVarResp = apiSessionsCustomStateGetWithHttpInfo(session); + return localVarResp.getData(); + } + + /** + * + * + * @param session (required) + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Response Details
Status Code Description Response Headers
200 OK -
+ */ + public ApiResponse apiSessionsCustomStateGetWithHttpInfo(@javax.annotation.Nonnull String session) throws ApiException { + okhttp3.Call localVarCall = apiSessionsCustomStateGetValidateBeforeCall(session, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * + * @param session (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
Response Details
Status Code Description Response Headers
200 OK -
+ */ + public okhttp3.Call apiSessionsCustomStateGetAsync(@javax.annotation.Nonnull String session, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = apiSessionsCustomStateGetValidateBeforeCall(session, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** @@ -205,12 +347,12 @@ public okhttp3.Call apiSessionsCertificateGetAsync(String session, final ApiCall * @throws ApiException If fail to serialize the request body object * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public okhttp3.Call apiSessionsPostCall(SessionCreateRequest sessionCreateRequest, final ApiCallback _callback) throws ApiException { + public okhttp3.Call apiSessionsPostCall(@javax.annotation.Nullable SessionCreateRequest sessionCreateRequest, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] { }; @@ -240,7 +382,7 @@ public okhttp3.Call apiSessionsPostCall(SessionCreateRequest sessionCreateReques "application/json", "text/json" }; - final String localVarAccept = localVarCloudhubClient.selectHeaderAccept(localVarAccepts); + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } @@ -251,17 +393,17 @@ public okhttp3.Call apiSessionsPostCall(SessionCreateRequest sessionCreateReques "text/json", "application/*+json" }; - final String localVarContentType = localVarCloudhubClient.selectHeaderContentType(localVarContentTypes); + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] { "ApiKey" }; - return localVarCloudhubClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") - private okhttp3.Call apiSessionsPostValidateBeforeCall(SessionCreateRequest sessionCreateRequest, final ApiCallback _callback) throws ApiException { + private okhttp3.Call apiSessionsPostValidateBeforeCall(@javax.annotation.Nullable SessionCreateRequest sessionCreateRequest, final ApiCallback _callback) throws ApiException { return apiSessionsPostCall(sessionCreateRequest, _callback); } @@ -274,12 +416,12 @@ private okhttp3.Call apiSessionsPostValidateBeforeCall(SessionCreateRequest sess * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public SessionModel apiSessionsPost(SessionCreateRequest sessionCreateRequest) throws ApiException { + public SessionModel apiSessionsPost(@javax.annotation.Nullable SessionCreateRequest sessionCreateRequest) throws ApiException { ApiResponse localVarResp = apiSessionsPostWithHttpInfo(sessionCreateRequest); return localVarResp.getData(); } @@ -292,15 +434,15 @@ public SessionModel apiSessionsPost(SessionCreateRequest sessionCreateRequest) t * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public ApiResponse apiSessionsPostWithHttpInfo(SessionCreateRequest sessionCreateRequest) throws ApiException { + public ApiResponse apiSessionsPostWithHttpInfo(@javax.annotation.Nullable SessionCreateRequest sessionCreateRequest) throws ApiException { okhttp3.Call localVarCall = apiSessionsPostValidateBeforeCall(sessionCreateRequest, null); Type localVarReturnType = new TypeToken(){}.getType(); - return localVarCloudhubClient.execute(localVarCall, localVarReturnType); + return localVarApiClient.execute(localVarCall, localVarReturnType); } /** @@ -312,16 +454,16 @@ public ApiResponse apiSessionsPostWithHttpInfo(SessionCreateReques * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public okhttp3.Call apiSessionsPostAsync(SessionCreateRequest sessionCreateRequest, final ApiCallback _callback) throws ApiException { + public okhttp3.Call apiSessionsPostAsync(@javax.annotation.Nullable SessionCreateRequest sessionCreateRequest, final ApiCallback _callback) throws ApiException { okhttp3.Call localVarCall = apiSessionsPostValidateBeforeCall(sessionCreateRequest, _callback); Type localVarReturnType = new TypeToken(){}.getType(); - localVarCloudhubClient.executeAsync(localVarCall, localVarReturnType, _callback); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** @@ -333,12 +475,12 @@ public okhttp3.Call apiSessionsPostAsync(SessionCreateRequest sessionCreateReque * @throws ApiException If fail to serialize the request body object * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public okhttp3.Call apiSessionsServicesGetCall(String identifier, IdentifierTypes identifierType, final ApiCallback _callback) throws ApiException { + public okhttp3.Call apiSessionsServicesGetCall(@javax.annotation.Nullable String identifier, @javax.annotation.Nullable IdentifierTypes identifierType, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] { }; @@ -364,11 +506,11 @@ public okhttp3.Call apiSessionsServicesGetCall(String identifier, IdentifierType Map localVarFormParams = new HashMap(); if (identifier != null) { - localVarQueryParams.addAll(localVarCloudhubClient.parameterToPair("identifier", identifier)); + localVarQueryParams.addAll(localVarApiClient.parameterToPair("identifier", identifier)); } if (identifierType != null) { - localVarQueryParams.addAll(localVarCloudhubClient.parameterToPair("identifierType", identifierType)); + localVarQueryParams.addAll(localVarApiClient.parameterToPair("identifierType", identifierType)); } final String[] localVarAccepts = { @@ -376,24 +518,24 @@ public okhttp3.Call apiSessionsServicesGetCall(String identifier, IdentifierType "application/json", "text/json" }; - final String localVarAccept = localVarCloudhubClient.selectHeaderAccept(localVarAccepts); + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; - final String localVarContentType = localVarCloudhubClient.selectHeaderContentType(localVarContentTypes); + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] { "ApiKey" }; - return localVarCloudhubClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") - private okhttp3.Call apiSessionsServicesGetValidateBeforeCall(String identifier, IdentifierTypes identifierType, final ApiCallback _callback) throws ApiException { + private okhttp3.Call apiSessionsServicesGetValidateBeforeCall(@javax.annotation.Nullable String identifier, @javax.annotation.Nullable IdentifierTypes identifierType, final ApiCallback _callback) throws ApiException { return apiSessionsServicesGetCall(identifier, identifierType, _callback); } @@ -407,12 +549,12 @@ private okhttp3.Call apiSessionsServicesGetValidateBeforeCall(String identifier, * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public List apiSessionsServicesGet(String identifier, IdentifierTypes identifierType) throws ApiException { + public List apiSessionsServicesGet(@javax.annotation.Nullable String identifier, @javax.annotation.Nullable IdentifierTypes identifierType) throws ApiException { ApiResponse> localVarResp = apiSessionsServicesGetWithHttpInfo(identifier, identifierType); return localVarResp.getData(); } @@ -426,15 +568,15 @@ public List apiSessionsServicesGet(String identifier, Ide * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public ApiResponse> apiSessionsServicesGetWithHttpInfo(String identifier, IdentifierTypes identifierType) throws ApiException { + public ApiResponse> apiSessionsServicesGetWithHttpInfo(@javax.annotation.Nullable String identifier, @javax.annotation.Nullable IdentifierTypes identifierType) throws ApiException { okhttp3.Call localVarCall = apiSessionsServicesGetValidateBeforeCall(identifier, identifierType, null); Type localVarReturnType = new TypeToken>(){}.getType(); - return localVarCloudhubClient.execute(localVarCall, localVarReturnType); + return localVarApiClient.execute(localVarCall, localVarReturnType); } /** @@ -447,16 +589,161 @@ public ApiResponse> apiSessionsServicesGetWithHttpIn * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public okhttp3.Call apiSessionsServicesGetAsync(String identifier, IdentifierTypes identifierType, final ApiCallback> _callback) throws ApiException { + public okhttp3.Call apiSessionsServicesGetAsync(@javax.annotation.Nullable String identifier, @javax.annotation.Nullable IdentifierTypes identifierType, final ApiCallback> _callback) throws ApiException { okhttp3.Call localVarCall = apiSessionsServicesGetValidateBeforeCall(identifier, identifierType, _callback); Type localVarReturnType = new TypeToken>(){}.getType(); - localVarCloudhubClient.executeAsync(localVarCall, localVarReturnType, _callback); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for apiSessionsServicesNameAvailabilityGet + * @param name (required) + * @param identifier (optional) + * @param identifierType (optional) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
Response Details
Status Code Description Response Headers
200 OK -
+ */ + public okhttp3.Call apiSessionsServicesNameAvailabilityGetCall(@javax.annotation.Nonnull String name, @javax.annotation.Nullable String identifier, @javax.annotation.Nullable IdentifierTypes identifierType, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/api/sessions/services/{name}/availability" + .replace("{" + "name" + "}", localVarApiClient.escapeString(name.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (identifier != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("identifier", identifier)); + } + + if (identifierType != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("identifierType", identifierType)); + } + + final String[] localVarAccepts = { + "text/plain", + "application/json", + "text/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "ApiKey" }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call apiSessionsServicesNameAvailabilityGetValidateBeforeCall(@javax.annotation.Nonnull String name, @javax.annotation.Nullable String identifier, @javax.annotation.Nullable IdentifierTypes identifierType, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'name' is set + if (name == null) { + throw new ApiException("Missing the required parameter 'name' when calling apiSessionsServicesNameAvailabilityGet(Async)"); + } + + return apiSessionsServicesNameAvailabilityGetCall(name, identifier, identifierType, _callback); + + } + + /** + * + * + * @param name (required) + * @param identifier (optional) + * @param identifierType (optional) + * @return GetServiceAvailabilityResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Response Details
Status Code Description Response Headers
200 OK -
+ */ + public GetServiceAvailabilityResponse apiSessionsServicesNameAvailabilityGet(@javax.annotation.Nonnull String name, @javax.annotation.Nullable String identifier, @javax.annotation.Nullable IdentifierTypes identifierType) throws ApiException { + ApiResponse localVarResp = apiSessionsServicesNameAvailabilityGetWithHttpInfo(name, identifier, identifierType); + return localVarResp.getData(); + } + + /** + * + * + * @param name (required) + * @param identifier (optional) + * @param identifierType (optional) + * @return ApiResponse<GetServiceAvailabilityResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Response Details
Status Code Description Response Headers
200 OK -
+ */ + public ApiResponse apiSessionsServicesNameAvailabilityGetWithHttpInfo(@javax.annotation.Nonnull String name, @javax.annotation.Nullable String identifier, @javax.annotation.Nullable IdentifierTypes identifierType) throws ApiException { + okhttp3.Call localVarCall = apiSessionsServicesNameAvailabilityGetValidateBeforeCall(name, identifier, identifierType, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * + * @param name (required) + * @param identifier (optional) + * @param identifierType (optional) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
Response Details
Status Code Description Response Headers
200 OK -
+ */ + public okhttp3.Call apiSessionsServicesNameAvailabilityGetAsync(@javax.annotation.Nonnull String name, @javax.annotation.Nullable String identifier, @javax.annotation.Nullable IdentifierTypes identifierType, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = apiSessionsServicesNameAvailabilityGetValidateBeforeCall(name, identifier, identifierType, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** @@ -468,12 +755,12 @@ public okhttp3.Call apiSessionsServicesGetAsync(String identifier, IdentifierTyp * @throws ApiException If fail to serialize the request body object * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public okhttp3.Call apiSessionsServicesNamePostCall(String name, ServiceSessionCreateRequest serviceSessionCreateRequest, final ApiCallback _callback) throws ApiException { + public okhttp3.Call apiSessionsServicesNamePostCall(@javax.annotation.Nonnull String name, @javax.annotation.Nullable ServiceSessionCreateRequest serviceSessionCreateRequest, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] { }; @@ -491,7 +778,7 @@ public okhttp3.Call apiSessionsServicesNamePostCall(String name, ServiceSessionC // create path and map variables String localVarPath = "/api/sessions/services/{name}" - .replace("{" + "name" + "}", localVarCloudhubClient.escapeString(name.toString())); + .replace("{" + "name" + "}", localVarApiClient.escapeString(name.toString())); List localVarQueryParams = new ArrayList(); List localVarCollectionQueryParams = new ArrayList(); @@ -504,7 +791,7 @@ public okhttp3.Call apiSessionsServicesNamePostCall(String name, ServiceSessionC "application/json", "text/json" }; - final String localVarAccept = localVarCloudhubClient.selectHeaderAccept(localVarAccepts); + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } @@ -515,17 +802,17 @@ public okhttp3.Call apiSessionsServicesNamePostCall(String name, ServiceSessionC "text/json", "application/*+json" }; - final String localVarContentType = localVarCloudhubClient.selectHeaderContentType(localVarContentTypes); + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] { "ApiKey" }; - return localVarCloudhubClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") - private okhttp3.Call apiSessionsServicesNamePostValidateBeforeCall(String name, ServiceSessionCreateRequest serviceSessionCreateRequest, final ApiCallback _callback) throws ApiException { + private okhttp3.Call apiSessionsServicesNamePostValidateBeforeCall(@javax.annotation.Nonnull String name, @javax.annotation.Nullable ServiceSessionCreateRequest serviceSessionCreateRequest, final ApiCallback _callback) throws ApiException { // verify the required parameter 'name' is set if (name == null) { throw new ApiException("Missing the required parameter 'name' when calling apiSessionsServicesNamePost(Async)"); @@ -544,12 +831,12 @@ private okhttp3.Call apiSessionsServicesNamePostValidateBeforeCall(String name, * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public ServiceSessionCreateResponse apiSessionsServicesNamePost(String name, ServiceSessionCreateRequest serviceSessionCreateRequest) throws ApiException { + public ServiceSessionCreateResponse apiSessionsServicesNamePost(@javax.annotation.Nonnull String name, @javax.annotation.Nullable ServiceSessionCreateRequest serviceSessionCreateRequest) throws ApiException { ApiResponse localVarResp = apiSessionsServicesNamePostWithHttpInfo(name, serviceSessionCreateRequest); return localVarResp.getData(); } @@ -563,15 +850,15 @@ public ServiceSessionCreateResponse apiSessionsServicesNamePost(String name, Ser * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public ApiResponse apiSessionsServicesNamePostWithHttpInfo(String name, ServiceSessionCreateRequest serviceSessionCreateRequest) throws ApiException { + public ApiResponse apiSessionsServicesNamePostWithHttpInfo(@javax.annotation.Nonnull String name, @javax.annotation.Nullable ServiceSessionCreateRequest serviceSessionCreateRequest) throws ApiException { okhttp3.Call localVarCall = apiSessionsServicesNamePostValidateBeforeCall(name, serviceSessionCreateRequest, null); Type localVarReturnType = new TypeToken(){}.getType(); - return localVarCloudhubClient.execute(localVarCall, localVarReturnType); + return localVarApiClient.execute(localVarCall, localVarReturnType); } /** @@ -584,16 +871,16 @@ public ApiResponse apiSessionsServicesNamePostWith * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public okhttp3.Call apiSessionsServicesNamePostAsync(String name, ServiceSessionCreateRequest serviceSessionCreateRequest, final ApiCallback _callback) throws ApiException { + public okhttp3.Call apiSessionsServicesNamePostAsync(@javax.annotation.Nonnull String name, @javax.annotation.Nullable ServiceSessionCreateRequest serviceSessionCreateRequest, final ApiCallback _callback) throws ApiException { okhttp3.Call localVarCall = apiSessionsServicesNamePostValidateBeforeCall(name, serviceSessionCreateRequest, _callback); Type localVarReturnType = new TypeToken(){}.getType(); - localVarCloudhubClient.executeAsync(localVarCall, localVarReturnType, _callback); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** @@ -604,12 +891,12 @@ public okhttp3.Call apiSessionsServicesNamePostAsync(String name, ServiceSession * @throws ApiException If fail to serialize the request body object * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public okhttp3.Call apiSessionsSignHashPostCall(SignHashRequest signHashRequest, final ApiCallback _callback) throws ApiException { + public okhttp3.Call apiSessionsSignHashPostCall(@javax.annotation.Nullable SignHashRequest signHashRequest, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] { }; @@ -639,7 +926,7 @@ public okhttp3.Call apiSessionsSignHashPostCall(SignHashRequest signHashRequest, "application/json", "text/json" }; - final String localVarAccept = localVarCloudhubClient.selectHeaderAccept(localVarAccepts); + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } @@ -650,17 +937,17 @@ public okhttp3.Call apiSessionsSignHashPostCall(SignHashRequest signHashRequest, "text/json", "application/*+json" }; - final String localVarContentType = localVarCloudhubClient.selectHeaderContentType(localVarContentTypes); + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] { "ApiKey" }; - return localVarCloudhubClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") - private okhttp3.Call apiSessionsSignHashPostValidateBeforeCall(SignHashRequest signHashRequest, final ApiCallback _callback) throws ApiException { + private okhttp3.Call apiSessionsSignHashPostValidateBeforeCall(@javax.annotation.Nullable SignHashRequest signHashRequest, final ApiCallback _callback) throws ApiException { return apiSessionsSignHashPostCall(signHashRequest, _callback); } @@ -673,12 +960,12 @@ private okhttp3.Call apiSessionsSignHashPostValidateBeforeCall(SignHashRequest s * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public byte[] apiSessionsSignHashPost(SignHashRequest signHashRequest) throws ApiException { + public byte[] apiSessionsSignHashPost(@javax.annotation.Nullable SignHashRequest signHashRequest) throws ApiException { ApiResponse localVarResp = apiSessionsSignHashPostWithHttpInfo(signHashRequest); return localVarResp.getData(); } @@ -691,15 +978,15 @@ public byte[] apiSessionsSignHashPost(SignHashRequest signHashRequest) throws Ap * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public ApiResponse apiSessionsSignHashPostWithHttpInfo(SignHashRequest signHashRequest) throws ApiException { + public ApiResponse apiSessionsSignHashPostWithHttpInfo(@javax.annotation.Nullable SignHashRequest signHashRequest) throws ApiException { okhttp3.Call localVarCall = apiSessionsSignHashPostValidateBeforeCall(signHashRequest, null); Type localVarReturnType = new TypeToken(){}.getType(); - return localVarCloudhubClient.execute(localVarCall, localVarReturnType); + return localVarApiClient.execute(localVarCall, localVarReturnType); } /** @@ -711,16 +998,16 @@ public ApiResponse apiSessionsSignHashPostWithHttpInfo(SignHashRequest s * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public okhttp3.Call apiSessionsSignHashPostAsync(SignHashRequest signHashRequest, final ApiCallback _callback) throws ApiException { + public okhttp3.Call apiSessionsSignHashPostAsync(@javax.annotation.Nullable SignHashRequest signHashRequest, final ApiCallback _callback) throws ApiException { okhttp3.Call localVarCall = apiSessionsSignHashPostValidateBeforeCall(signHashRequest, _callback); Type localVarReturnType = new TypeToken(){}.getType(); - localVarCloudhubClient.executeAsync(localVarCall, localVarReturnType, _callback); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** @@ -731,12 +1018,12 @@ public okhttp3.Call apiSessionsSignHashPostAsync(SignHashRequest signHashRequest * @throws ApiException If fail to serialize the request body object * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public okhttp3.Call apiV2SessionsCertificateGetCall(String session, final ApiCallback _callback) throws ApiException { + public okhttp3.Call apiV2SessionsCertificateGetCall(@javax.annotation.Nullable String session, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] { }; @@ -762,7 +1049,7 @@ public okhttp3.Call apiV2SessionsCertificateGetCall(String session, final ApiCal Map localVarFormParams = new HashMap(); if (session != null) { - localVarQueryParams.addAll(localVarCloudhubClient.parameterToPair("session", session)); + localVarQueryParams.addAll(localVarApiClient.parameterToPair("session", session)); } final String[] localVarAccepts = { @@ -770,24 +1057,24 @@ public okhttp3.Call apiV2SessionsCertificateGetCall(String session, final ApiCal "application/json", "text/json" }; - final String localVarAccept = localVarCloudhubClient.selectHeaderAccept(localVarAccepts); + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; - final String localVarContentType = localVarCloudhubClient.selectHeaderContentType(localVarContentTypes); + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] { "ApiKey" }; - return localVarCloudhubClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") - private okhttp3.Call apiV2SessionsCertificateGetValidateBeforeCall(String session, final ApiCallback _callback) throws ApiException { + private okhttp3.Call apiV2SessionsCertificateGetValidateBeforeCall(@javax.annotation.Nullable String session, final ApiCallback _callback) throws ApiException { return apiV2SessionsCertificateGetCall(session, _callback); } @@ -800,12 +1087,12 @@ private okhttp3.Call apiV2SessionsCertificateGetValidateBeforeCall(String sessio * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public CertificateModel apiV2SessionsCertificateGet(String session) throws ApiException { + public CertificateModel apiV2SessionsCertificateGet(@javax.annotation.Nullable String session) throws ApiException { ApiResponse localVarResp = apiV2SessionsCertificateGetWithHttpInfo(session); return localVarResp.getData(); } @@ -818,15 +1105,15 @@ public CertificateModel apiV2SessionsCertificateGet(String session) throws ApiEx * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public ApiResponse apiV2SessionsCertificateGetWithHttpInfo(String session) throws ApiException { + public ApiResponse apiV2SessionsCertificateGetWithHttpInfo(@javax.annotation.Nullable String session) throws ApiException { okhttp3.Call localVarCall = apiV2SessionsCertificateGetValidateBeforeCall(session, null); Type localVarReturnType = new TypeToken(){}.getType(); - return localVarCloudhubClient.execute(localVarCall, localVarReturnType); + return localVarApiClient.execute(localVarCall, localVarReturnType); } /** @@ -838,35 +1125,16 @@ public ApiResponse apiV2SessionsCertificateGetWithHttpInfo(Str * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details - + - +
Response DetailsResponse Details
Status Code Description Response Headers
200 Success -
200 OK -
*/ - public okhttp3.Call apiV2SessionsCertificateGetAsync(String session, final ApiCallback _callback) throws ApiException { + public okhttp3.Call apiV2SessionsCertificateGetAsync(@javax.annotation.Nullable String session, final ApiCallback _callback) throws ApiException { okhttp3.Call localVarCall = apiV2SessionsCertificateGetValidateBeforeCall(session, _callback); Type localVarReturnType = new TypeToken(){}.getType(); - localVarCloudhubClient.executeAsync(localVarCall, localVarReturnType, _callback); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } - - /** - * Converts a given byte array certificate into a readable string for signature or validation purposes - * @param certificate The certificate obtained from apiCertificateGet - * @return a String with the certificate in base 64 - */ - public static String convertCertificateToString(byte[] certificate) { - return new String(certificate).replace("\"", ""); - } - - /** - * Converts a given byte array toSignHash into a base64 encoded byte array for signature purposes - * @param toSignHash the hash used to sign the document - * @return base64 encoded byte array - */ - public static byte[] convertToSignHashToByteArray64(byte[] toSignHash){ - // first we need to convert it to string and then decode as base64 - return Base64.getDecoder().decode(convertCertificateToString(toSignHash)); - } } diff --git a/src/main/java/cloudhub/client/ApiClient.java b/src/main/java/cloudhub/client/ApiClient.java new file mode 100644 index 0000000..d95d1b5 --- /dev/null +++ b/src/main/java/cloudhub/client/ApiClient.java @@ -0,0 +1,1588 @@ +/* + * Cloudhub API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: v1 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package cloudhub.client; + +import okhttp3.*; +import okhttp3.internal.http.HttpMethod; +import okhttp3.internal.tls.OkHostnameVerifier; +import okhttp3.logging.HttpLoggingInterceptor; +import okhttp3.logging.HttpLoggingInterceptor.Level; +import okio.Buffer; +import okio.BufferedSink; +import okio.Okio; + +import javax.net.ssl.*; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Type; +import java.net.URI; +import java.net.URLConnection; +import java.net.URLEncoder; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.text.DateFormat; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import cloudhub.client.auth.Authentication; +import cloudhub.client.auth.HttpBasicAuth; +import cloudhub.client.auth.HttpBearerAuth; +import cloudhub.client.auth.ApiKeyAuth; + +/** + *

ApiClient class.

+ */ +public class ApiClient { + + protected String basePath = "http://localhost"; + protected List servers = new ArrayList(Arrays.asList( + new ServerConfiguration( + "", + "No description provided", + new HashMap() + ) + )); + protected Integer serverIndex = 0; + protected Map serverVariables = null; + protected boolean debugging = false; + protected Map defaultHeaderMap = new HashMap(); + protected Map defaultCookieMap = new HashMap(); + protected String tempFolderPath = null; + + protected Map authentications; + + protected DateFormat dateFormat; + protected DateFormat datetimeFormat; + protected boolean lenientDatetimeFormat; + protected int dateLength; + + protected InputStream sslCaCert; + protected boolean verifyingSsl; + protected KeyManager[] keyManagers; + + protected OkHttpClient httpClient; + protected JSON json; + + protected HttpLoggingInterceptor loggingInterceptor; + + /** + * Basic constructor for ApiClient + */ + public ApiClient() { + init(); + initHttpClient(); + + // Setup authentications (key: authentication name, value: authentication). + authentications.put("ApiKey", new ApiKeyAuth("header", "X-Api-Key")); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Basic constructor with custom OkHttpClient + * + * @param client a {@link okhttp3.OkHttpClient} object + */ + public ApiClient(OkHttpClient client) { + init(); + + httpClient = client; + + // Setup authentications (key: authentication name, value: authentication). + authentications.put("ApiKey", new ApiKeyAuth("header", "X-Api-Key")); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + protected void initHttpClient() { + initHttpClient(Collections.emptyList()); + } + + protected void initHttpClient(List interceptors) { + OkHttpClient.Builder builder = new OkHttpClient.Builder(); + builder.addNetworkInterceptor(getProgressInterceptor()); + for (Interceptor interceptor: interceptors) { + builder.addInterceptor(interceptor); + } + + httpClient = builder.build(); + } + + protected void init() { + verifyingSsl = true; + + json = new JSON(); + + // Set default User-Agent. + setUserAgent("OpenAPI-Generator/v1/java"); + + authentications = new HashMap(); + } + + /** + * Get base path + * + * @return Base path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set base path + * + * @param basePath Base path of the URL (e.g http://localhost + * @return An instance of OkHttpClient + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + this.serverIndex = null; + return this; + } + + public List getServers() { + return servers; + } + + public ApiClient setServers(List servers) { + this.servers = servers; + return this; + } + + public Integer getServerIndex() { + return serverIndex; + } + + public ApiClient setServerIndex(Integer serverIndex) { + this.serverIndex = serverIndex; + return this; + } + + public Map getServerVariables() { + return serverVariables; + } + + public ApiClient setServerVariables(Map serverVariables) { + this.serverVariables = serverVariables; + return this; + } + + /** + * Get HTTP client + * + * @return An instance of OkHttpClient + */ + public OkHttpClient getHttpClient() { + return httpClient; + } + + /** + * Set HTTP client, which must never be null. + * + * @param newHttpClient An instance of OkHttpClient + * @return Api Client + * @throws java.lang.NullPointerException when newHttpClient is null + */ + public ApiClient setHttpClient(OkHttpClient newHttpClient) { + this.httpClient = Objects.requireNonNull(newHttpClient, "HttpClient must not be null!"); + return this; + } + + /** + * Get JSON + * + * @return JSON object + */ + public JSON getJSON() { + return json; + } + + /** + * Set JSON + * + * @param json JSON object + * @return Api client + */ + public ApiClient setJSON(JSON json) { + this.json = json; + return this; + } + + /** + * True if isVerifyingSsl flag is on + * + * @return True if isVerifySsl flag is on + */ + public boolean isVerifyingSsl() { + return verifyingSsl; + } + + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + * + * @param verifyingSsl True to verify TLS/SSL connection + * @return ApiClient + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; + } + + /** + * Get SSL CA cert. + * + * @return Input stream to the SSL CA cert + */ + public InputStream getSslCaCert() { + return sslCaCert; + } + + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + * + * @param sslCaCert input stream for SSL CA cert + * @return ApiClient + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; + } + + /** + *

Getter for the field keyManagers.

+ * + * @return an array of {@link javax.net.ssl.KeyManager} objects + */ + public KeyManager[] getKeyManagers() { + return keyManagers; + } + + /** + * Configure client keys to use for authorization in an SSL session. + * Use null to reset to default. + * + * @param managers The KeyManagers to use + * @return ApiClient + */ + public ApiClient setKeyManagers(KeyManager[] managers) { + this.keyManagers = managers; + applySslSettings(); + return this; + } + + /** + *

Getter for the field dateFormat.

+ * + * @return a {@link java.text.DateFormat} object + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + *

Setter for the field dateFormat.

+ * + * @param dateFormat a {@link java.text.DateFormat} object + * @return a {@link cloudhub.client.ApiClient} object + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + JSON.setDateFormat(dateFormat); + return this; + } + + /** + *

Set SqlDateFormat.

+ * + * @param dateFormat a {@link java.text.DateFormat} object + * @return a {@link cloudhub.client.ApiClient} object + */ + public ApiClient setSqlDateFormat(DateFormat dateFormat) { + JSON.setSqlDateFormat(dateFormat); + return this; + } + + /** + *

Set OffsetDateTimeFormat.

+ * + * @param dateFormat a {@link java.time.format.DateTimeFormatter} object + * @return a {@link cloudhub.client.ApiClient} object + */ + public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { + JSON.setOffsetDateTimeFormat(dateFormat); + return this; + } + + /** + *

Set LocalDateFormat.

+ * + * @param dateFormat a {@link java.time.format.DateTimeFormatter} object + * @return a {@link cloudhub.client.ApiClient} object + */ + public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { + JSON.setLocalDateFormat(dateFormat); + return this; + } + + /** + *

Set LenientOnJson.

+ * + * @param lenientOnJson a boolean + * @return a {@link cloudhub.client.ApiClient} object + */ + public ApiClient setLenientOnJson(boolean lenientOnJson) { + JSON.setLenientOnJson(lenientOnJson); + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication objects + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + public void setAccessToken(String accessToken) { + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Helper method to set credentials for AWSV4 Signature + * + * @param accessKey Access Key + * @param secretKey Secret Key + * @param region Region + * @param service Service to access to + */ + public void setAWS4Configuration(String accessKey, String secretKey, String region, String service) { + throw new RuntimeException("No AWS4 authentication configured!"); + } + + /** + * Helper method to set credentials for AWSV4 Signature + * + * @param accessKey Access Key + * @param secretKey Secret Key + * @param sessionToken Session Token + * @param region Region + * @param service Service to access to + */ + public void setAWS4Configuration(String accessKey, String secretKey, String sessionToken, String region, String service) { + throw new RuntimeException("No AWS4 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent HTTP request's user agent + * @return ApiClient + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return ApiClient + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * Add a default cookie. + * + * @param key The cookie's key + * @param value The cookie's value + * @return ApiClient + */ + public ApiClient addDefaultCookie(String key, String value) { + defaultCookieMap.put(key, value); + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * + * @return True if debugging is enabled, false otherwise. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return ApiClient + */ + public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient = httpClient.newBuilder().addInterceptor(loggingInterceptor).build(); + } else { + final OkHttpClient.Builder builder = httpClient.newBuilder(); + builder.interceptors().remove(loggingInterceptor); + httpClient = builder.build(); + loggingInterceptor = null; + } + } + this.debugging = debugging; + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default temporary folder. + * + * @see createTempFile + * @return Temporary folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set the temporary folder path (for downloading files) + * + * @param tempFolderPath Temporary folder path + * @return ApiClient + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getConnectTimeout() { + return httpClient.connectTimeoutMillis(); + } + + /** + * Sets the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param connectionTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + httpClient = httpClient.newBuilder().connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + /** + * Get read timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getReadTimeout() { + return httpClient.readTimeoutMillis(); + } + + /** + * Sets the read timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param readTimeout read timeout in milliseconds + * @return Api client + */ + public ApiClient setReadTimeout(int readTimeout) { + httpClient = httpClient.newBuilder().readTimeout(readTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + /** + * Get write timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getWriteTimeout() { + return httpClient.writeTimeoutMillis(); + } + + /** + * Sets the write timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param writeTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setWriteTimeout(int writeTimeout) { + httpClient = httpClient.newBuilder().writeTimeout(writeTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + + /** + * Format the given parameter object into string. + * + * @param param Parameter + * @return String representation of the parameter + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date || param instanceof OffsetDateTime || param instanceof LocalDate) { + //Serialize to json string and remove the " enclosing characters + String jsonStr = JSON.serialize(param); + return jsonStr.substring(1, jsonStr.length() - 1); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection) param) { + if (b.length() > 0) { + b.append(","); + } + b.append(o); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Formats the specified query parameter to a list containing a single {@code Pair} object. + * + * Note that {@code value} must not be a collection. + * + * @param name The name of the parameter. + * @param value The value of the parameter. + * @return A list containing a single {@code Pair} object. + */ + public List parameterToPair(String name, Object value) { + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null || value instanceof Collection) { + return params; + } + + params.add(new Pair(name, parameterToString(value))); + return params; + } + + /** + * Formats the specified collection query parameters to a list of {@code Pair} objects. + * + * Note that the values of each of the returned Pair objects are percent-encoded. + * + * @param collectionFormat The collection format of the parameter. + * @param name The name of the parameter. + * @param value The value of the parameter. + * @return A list of {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Collection value) { + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null || value.isEmpty()) { + return params; + } + + // create the params based on the collection format + if ("multi".equals(collectionFormat)) { + for (Object item : value) { + params.add(new Pair(name, escapeString(parameterToString(item)))); + } + return params; + } + + // collectionFormat is assumed to be "csv" by default + String delimiter = ","; + + // escape all delimiters except commas, which are URI reserved + // characters + if ("ssv".equals(collectionFormat)) { + delimiter = escapeString(" "); + } else if ("tsv".equals(collectionFormat)) { + delimiter = escapeString("\t"); + } else if ("pipes".equals(collectionFormat)) { + delimiter = escapeString("|"); + } + + StringBuilder sb = new StringBuilder(); + for (Object item : value) { + sb.append(delimiter); + sb.append(escapeString(parameterToString(item))); + } + + params.add(new Pair(name, sb.substring(delimiter.length()))); + + return params; + } + + /** + * Formats the specified free-form query parameters to a list of {@code Pair} objects. + * + * @param value The free-form query parameters. + * @return A list of {@code Pair} objects. + */ + public List freeFormParameterToPairs(Object value) { + List params = new ArrayList<>(); + + // preconditions + if (value == null || !(value instanceof Map )) { + return params; + } + + @SuppressWarnings("unchecked") + final Map valuesMap = (Map) value; + + for (Map.Entry entry : valuesMap.entrySet()) { + params.add(new Pair(entry.getKey(), parameterToString(entry.getValue()))); + } + + return params; + } + + + /** + * Formats the specified collection path parameter to a string value. + * + * @param collectionFormat The collection format of the parameter. + * @param value The value of the parameter. + * @return String representation of the parameter + */ + public String collectionPathParameterToString(String collectionFormat, Collection value) { + // create the value based on the collection format + if ("multi".equals(collectionFormat)) { + // not valid for path params + return parameterToString(value); + } + + // collectionFormat is assumed to be "csv" by default + String delimiter = ","; + + if ("ssv".equals(collectionFormat)) { + delimiter = " "; + } else if ("tsv".equals(collectionFormat)) { + delimiter = "\t"; + } else if ("pipes".equals(collectionFormat)) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : value) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + return sb.substring(delimiter.length()); + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param filename The filename to be sanitized + * @return The sanitized filename + */ + public String sanitizeFilename(String filename) { + return filename.replaceFirst("^.*[/\\\\]", ""); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * "* / *" is also default to JSON + * @param mime MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public boolean isJsonMime(String mime) { + String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; + return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * returns null. If it matches "any", JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return null; + } + + if (contentTypes[0].equals("*/*")) { + return "application/json"; + } + + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * + * @param str String to be escaped + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. + * + * @param Type + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + * @throws cloudhub.client.ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. + */ + @SuppressWarnings("unchecked") + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. + return (T) downloadFileFromResponse(response); + } + + ResponseBody respBody = response.body(); + if (respBody == null) { + return null; + } + + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; + } + try { + if (isJsonMime(contentType)) { + return JSON.deserialize(respBody.byteStream(), returnType); + } else if (returnType.equals(String.class)) { + String respBodyString = respBody.string(); + if (respBodyString.isEmpty()) { + return null; + } + // Expecting string, return the raw response body. + return (T) respBodyString; + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported for type: " + returnType, + response.code(), + response.headers().toMultimap(), + response.body().string()); + } + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized request body + * @throws cloudhub.client.ApiException If fail to serialize the given object + */ + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create((byte[]) obj, MediaType.parse(contentType)); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create((File) obj, MediaType.parse(contentType)); + } else if ("text/plain".equals(contentType) && obj instanceof String) { + return RequestBody.create((String) obj, MediaType.parse(contentType)); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = JSON.serialize(obj); + } else { + content = null; + } + return RequestBody.create(content, MediaType.parse(contentType)); + } else if (obj instanceof String) { + return RequestBody.create((String) obj, MediaType.parse(contentType)); + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * Download file from the given response. + * + * @param response An instance of the Response object + * @throws cloudhub.client.ApiException If fail to read file content from response and write to disk + * @return Downloaded file + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Prepare file for download + * + * @param response An instance of the Response object + * @return Prepared file for the download + * @throws java.io.IOException If fail to prepare file for download + */ + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) { + filename = sanitizeFilename(matcher.group(1)); + } + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // Files.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return Files.createTempFile(prefix, suffix).toFile(); + else + return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile(); + } + + /** + * {@link #execute(Call, Type)} + * + * @param Type + * @param call An instance of the Call object + * @return ApiResponse<T> + * @throws cloudhub.client.ApiException If fail to execute the call + */ + public ApiResponse execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @param call Call + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws cloudhub.client.ApiException If fail to execute the call + */ + public ApiResponse execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * {@link #executeAsync(Call, Type, ApiCallback)} + * + * @param Type + * @param call An instance of the Call object + * @param callback ApiCallback<T> + */ + public void executeAsync(Call call, ApiCallback callback) { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @param Type + * @param call The callback to be executed when the API call finishes + * @param returnType Return type + * @param callback ApiCallback + * @see #execute(Call, Type) + */ + @SuppressWarnings("unchecked") + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Call call, IOException e) { + callback.onFailure(new ApiException(e), 0, null); + } + + @Override + public void onResponse(Call call, Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e, response.code(), response.headers().toMultimap()); + return; + } catch (Exception e) { + callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap()); + return; + } + callback.onSuccess(result, response.code(), response.headers().toMultimap()); + } + }); + } + + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @param Type + * @param response Response + * @param returnType Return type + * @return Type + * @throws cloudhub.client.ApiException If the response has an unsuccessful status code or + * fail to deserialize the response body + */ + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + if (response.body() != null) { + try { + response.body().close(); + } catch (Exception e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param baseUrl The base URL + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param callback Callback for upload/download progress + * @return The HTTP call + * @throws cloudhub.client.ApiException If fail to serialize the request body object + */ + public Call buildCall(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); + + return httpClient.newCall(request); + } + + /** + * Build an HTTP request with the given options. + * + * @param baseUrl The base URL + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param callback Callback for upload/download progress + * @return The HTTP request + * @throws cloudhub.client.ApiException If fail to serialize the request body object + */ + public Request buildRequest(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); + + // prepare HTTP request body + RequestBody reqBody; + String contentType = headerParams.get("Content-Type"); + String contentTypePure = contentType; + if (contentTypePure != null && contentTypePure.contains(";")) { + contentTypePure = contentType.substring(0, contentType.indexOf(";")); + } + if (!HttpMethod.permitsRequestBody(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentTypePure)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentTypePure)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create("", contentType == null ? null : MediaType.parse(contentType)); + } + } else { + reqBody = serialize(body, contentType); + } + + List updatedQueryParams = new ArrayList<>(queryParams); + + // update parameters with authentication settings + updateParamsForAuth(authNames, updatedQueryParams, headerParams, cookieParams, requestBodyToString(reqBody), method, URI.create(url)); + + final Request.Builder reqBuilder = new Request.Builder().url(buildUrl(baseUrl, path, updatedQueryParams, collectionQueryParams)); + processHeaderParams(headerParams, reqBuilder); + processCookieParams(cookieParams, reqBuilder); + + // Associate callback with request (if not null) so interceptor can + // access it when creating ProgressResponseBody + reqBuilder.tag(callback); + + Request request = null; + + if (callback != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, callback); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + + return request; + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param baseUrl The base URL + * @param path The sub path + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @return The full URL + */ + public String buildUrl(String baseUrl, String path, List queryParams, List collectionQueryParams) { + final StringBuilder url = new StringBuilder(); + if (baseUrl != null) { + url.append(baseUrl).append(path); + } else { + String baseURL; + if (serverIndex != null) { + if (serverIndex < 0 || serverIndex >= servers.size()) { + throw new ArrayIndexOutOfBoundsException(String.format( + "Invalid index %d when selecting the host settings. Must be less than %d", serverIndex, servers.size() + )); + } + baseURL = servers.get(serverIndex).URL(serverVariables); + } else { + baseURL = basePath; + } + url.append(baseURL).append(path); + } + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) { + String prefix = url.toString().contains("?") ? "&" : "?"; + for (Pair param : collectionQueryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + // collection query parameter value already escaped as part of parameterToPairs + url.append(escapeString(param.getName())).append("=").append(value); + } + } + } + + return url.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + * + * @param headerParams Header parameters in the form of Map + * @param reqBuilder Request.Builder + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Set cookie parameters to the request builder, including default cookies. + * + * @param cookieParams Cookie parameters in the form of Map + * @param reqBuilder Request.Builder + */ + public void processCookieParams(Map cookieParams, Request.Builder reqBuilder) { + for (Entry param : cookieParams.entrySet()) { + reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); + } + for (Entry param : defaultCookieMap.entrySet()) { + if (!cookieParams.containsKey(param.getKey())) { + reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + * @param cookieParams Map of cookie parameters + * @param payload HTTP request body + * @param method HTTP method + * @param uri URI + * @throws cloudhub.client.ApiException If fails to update the parameters + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams, + Map cookieParams, String payload, String method, URI uri) throws ApiException { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) { + throw new RuntimeException("Authentication undefined: " + authName); + } + auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + okhttp3.FormBody.Builder formBuilder = new okhttp3.FormBody.Builder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBody.Builder mpBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + addPartToMultiPartBuilder(mpBuilder, param.getKey(), file); + } else if (param.getValue() instanceof List) { + List list = (List) param.getValue(); + for (Object item: list) { + if (item instanceof File) { + addPartToMultiPartBuilder(mpBuilder, param.getKey(), (File) item); + } else { + addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); + } + } + } else { + addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } + + /** + * Add a Content-Disposition Header for the given key and file to the MultipartBody Builder. + * + * @param mpBuilder MultipartBody.Builder + * @param key The key of the Header element + * @param file The file to add to the Header + */ + protected void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, File file) { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(file, mediaType)); + } + + /** + * Add a Content-Disposition Header for the given key and complex object to the MultipartBody Builder. + * + * @param mpBuilder MultipartBody.Builder + * @param key The key of the Header element + * @param obj The complex object to add to the Header + */ + protected void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, Object obj) { + RequestBody requestBody; + if (obj instanceof String) { + requestBody = RequestBody.create((String) obj, MediaType.parse("text/plain")); + } else { + String content; + if (obj != null) { + content = JSON.serialize(obj); + } else { + content = null; + } + requestBody = RequestBody.create(content, MediaType.parse("application/json")); + } + + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""); + mpBuilder.addPart(partHeaders, requestBody); + } + + /** + * Get network interceptor to add it to the httpClient to track download progress for + * async requests. + */ + protected Interceptor getProgressInterceptor() { + return new Interceptor() { + @Override + public Response intercept(Interceptor.Chain chain) throws IOException { + final Request request = chain.request(); + final Response originalResponse = chain.proceed(request); + if (request.tag() instanceof ApiCallback) { + final ApiCallback callback = (ApiCallback) request.tag(); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), callback)) + .build(); + } + return originalResponse; + } + }; + } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + protected void applySslSettings() { + try { + TrustManager[] trustManagers; + HostnameVerifier hostnameVerifier; + if (!verifyingSsl) { + trustManagers = new TrustManager[]{ + new X509TrustManager() { + @Override + public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new java.security.cert.X509Certificate[]{}; + } + } + }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + } else { + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + + if (sslCaCert == null) { + trustManagerFactory.init((KeyStore) null); + } else { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + (index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + trustManagerFactory.init(caKeyStore); + } + trustManagers = trustManagerFactory.getTrustManagers(); + hostnameVerifier = OkHostnameVerifier.INSTANCE; + } + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient = httpClient.newBuilder() + .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]) + .hostnameVerifier(hostnameVerifier) + .build(); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + protected KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } + } + + /** + * Convert the HTTP request body to a string. + * + * @param requestBody The HTTP request object + * @return The string representation of the HTTP request body + * @throws cloudhub.client.ApiException If fail to serialize the request body object into a string + */ + protected String requestBodyToString(RequestBody requestBody) throws ApiException { + if (requestBody != null) { + try { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + return buffer.readUtf8(); + } catch (final IOException e) { + throw new ApiException(e); + } + } + + // empty http request body + return ""; + } +} diff --git a/src/main/java/cloudhub/client/ApiException.java b/src/main/java/cloudhub/client/ApiException.java index 98d04c3..d8c19a5 100644 --- a/src/main/java/cloudhub/client/ApiException.java +++ b/src/main/java/cloudhub/client/ApiException.java @@ -16,18 +16,19 @@ import java.util.Map; import java.util.List; -import javax.ws.rs.core.GenericType; /** *

ApiException class.

*/ @SuppressWarnings("serial") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-03-24T09:46:17.287214-03:00[America/Sao_Paulo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public class ApiException extends Exception { + private static final long serialVersionUID = 1L; + private int code = 0; private Map> responseHeaders = null; private String responseBody = null; - + /** *

Constructor for ApiException.

*/ diff --git a/src/main/java/cloudhub/client/CloudhubClient.java b/src/main/java/cloudhub/client/CloudhubClient.java index b89fc7b..d7d8d83 100644 --- a/src/main/java/cloudhub/client/CloudhubClient.java +++ b/src/main/java/cloudhub/client/CloudhubClient.java @@ -1,1572 +1,68 @@ -/* - * Cloudhub API - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: v1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - package cloudhub.client; -import okhttp3.*; -import okhttp3.internal.http.HttpMethod; -import okhttp3.internal.tls.OkHostnameVerifier; -import okhttp3.logging.HttpLoggingInterceptor; -import okhttp3.logging.HttpLoggingInterceptor.Level; -import okio.Buffer; -import okio.BufferedSink; -import okio.Okio; - -import javax.net.ssl.*; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; -import java.net.URI; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.text.DateFormat; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.*; -import java.util.Map.Entry; import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import cloudhub.client.auth.Authentication; -import cloudhub.client.auth.HttpBasicAuth; -import cloudhub.client.auth.HttpBearerAuth; -import cloudhub.client.auth.ApiKeyAuth; +import okhttp3.OkHttpClient; /** - *

CloudhubClient class.

+ * Convenience entry point for the Cloudhub API client. + * + *

This class is hand-maintained (listed in + * {@code .openapi-generator-ignore}) and is never overwritten by code generation. + * It extends the generated {@link ApiClient} to add: + *

    + *
  • a {@code (baseURL, apiKey)} constructor for one-line setup, and
  • + *
  • default 2-minute connect/read/write timeouts, since signing operations + * performed by the remote trust services can be slow.
  • + *
+ * + *

A {@code CloudhubClient} can be passed anywhere an {@link ApiClient} is expected: + *

{@code
+ * CloudhubClient client = new CloudhubClient("https://cloudhub.example.com", apiKey);
+ * SessionsApi api = new SessionsApi(client);
+ * }
*/ -public class CloudhubClient { - - private String basePath = ""; - protected List servers = new ArrayList(Arrays.asList( - new ServerConfiguration( - "", - "No description provided", - new HashMap() - ) - )); - protected Integer serverIndex = 0; - protected Map serverVariables = null; - private boolean debugging = false; - private Map defaultHeaderMap = new HashMap(); - private Map defaultCookieMap = new HashMap(); - private String tempFolderPath = null; - - private Map authentications; - - private DateFormat dateFormat; - private DateFormat datetimeFormat; - private boolean lenientDatetimeFormat; - private int dateLength; +public class CloudhubClient extends ApiClient { - private InputStream sslCaCert; - private boolean verifyingSsl; - private KeyManager[] keyManagers; - - private OkHttpClient httpClient; - private JSON json; - - private HttpLoggingInterceptor loggingInterceptor; + private static final long DEFAULT_TIMEOUT_MINUTES = 2; /** - * Basic constructor for CloudhubClient + * Creates a client with default timeouts. Set the base path and API key + * (via {@link #setBasePath(String)} / {@link #setApiKey(String)}) before use. */ public CloudhubClient() { - init(); - initHttpClient(); - - // Setup authentications (key: authentication name, value: authentication). - authentications.put("ApiKey", new ApiKeyAuth("header", "X-Api-Key")); - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); + super(); + applyDefaultTimeouts(); } /** - * Modified constructor for CloudhubClient - * @param baseURL The basePath used in all HTTP requests - * @param apiKey The apiKey used for authentication in the header + * Creates a ready-to-use client with default timeouts. + * + * @param baseURL the API base URL used in all HTTP requests + * @param apiKey the value sent in the {@code X-Api-Key} authentication header */ public CloudhubClient(String baseURL, String apiKey) { - init(); - initHttpClient(); - - // Setup authentications (key: authentication name, value: authentication). - authentications.put("ApiKey", new ApiKeyAuth("header", "X-Api-Key")); - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - - // Set the base URL - this.setBasePath(baseURL); - // Set the API Key - this.setApiKey(apiKey); + super(); + applyDefaultTimeouts(); + setBasePath(baseURL); + setApiKey(apiKey); } /** - * Basic constructor with custom OkHttpClient + * Creates a client backed by a caller-supplied OkHttp client. The supplied + * client's timeouts are left untouched. * - * @param client a {@link okhttp3.OkHttpClient} object + * @param client a configured {@link okhttp3.OkHttpClient} */ public CloudhubClient(OkHttpClient client) { - init(); - - httpClient = client; - - // Setup authentications (key: authentication name, value: authentication). - authentications.put("ApiKey", new ApiKeyAuth("header", "X-Api-Key")); - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - private void initHttpClient() { - initHttpClient(Collections.emptyList()); - } - - private void initHttpClient(List interceptors) { - OkHttpClient.Builder builder = new OkHttpClient.Builder(); - builder.connectTimeout(2, TimeUnit.MINUTES) // connect timeout - .writeTimeout(2, TimeUnit.MINUTES) // write timeout - .readTimeout(2, TimeUnit.MINUTES); // read timeout - - builder.addNetworkInterceptor(getProgressInterceptor()); - for (Interceptor interceptor: interceptors) { - builder.addInterceptor(interceptor); - } - - httpClient = builder.build(); - } - - private void init() { - verifyingSsl = true; - - json = new JSON(); - - // Set default User-Agent. - setUserAgent("OpenAPI-Generator/v1/java"); - - authentications = new HashMap(); - } - - /** - * Get base path - * - * @return Base path - */ - public String getBasePath() { - return basePath; - } - - /** - * Set base path - * - * @param basePath Base path of the URL (e.g http://localhost - * @return An instance of OkHttpClient - */ - public CloudhubClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } - - public List getServers() { - return servers; - } - - public CloudhubClient setServers(List servers) { - this.servers = servers; - return this; - } - - public Integer getServerIndex() { - return serverIndex; - } - - public CloudhubClient setServerIndex(Integer serverIndex) { - this.serverIndex = serverIndex; - return this; - } - - public Map getServerVariables() { - return serverVariables; - } - - public CloudhubClient setServerVariables(Map serverVariables) { - this.serverVariables = serverVariables; - return this; - } - - /** - * Get HTTP client - * - * @return An instance of OkHttpClient - */ - public OkHttpClient getHttpClient() { - return httpClient; - } - - /** - * Set HTTP client, which must never be null. - * - * @param newHttpClient An instance of OkHttpClient - * @return Api Client - * @throws java.lang.NullPointerException when newHttpClient is null - */ - public CloudhubClient setHttpClient(OkHttpClient newHttpClient) { - this.httpClient = Objects.requireNonNull(newHttpClient, "HttpClient must not be null!"); - return this; - } - - /** - * Get JSON - * - * @return JSON object - */ - public JSON getJSON() { - return json; - } - - /** - * Set JSON - * - * @param json JSON object - * @return Api client - */ - public CloudhubClient setJSON(JSON json) { - this.json = json; - return this; - } - - /** - * True if isVerifyingSsl flag is on - * - * @return True if isVerifySsl flag is on - */ - public boolean isVerifyingSsl() { - return verifyingSsl; - } - - /** - * Configure whether to verify certificate and hostname when making https requests. - * Default to true. - * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. - * - * @param verifyingSsl True to verify TLS/SSL connection - * @return CloudhubClient - */ - public CloudhubClient setVerifyingSsl(boolean verifyingSsl) { - this.verifyingSsl = verifyingSsl; - applySslSettings(); - return this; - } - - /** - * Get SSL CA cert. - * - * @return Input stream to the SSL CA cert - */ - public InputStream getSslCaCert() { - return sslCaCert; - } - - /** - * Configure the CA certificate to be trusted when making https requests. - * Use null to reset to default. - * - * @param sslCaCert input stream for SSL CA cert - * @return CloudhubClient - */ - public CloudhubClient setSslCaCert(InputStream sslCaCert) { - this.sslCaCert = sslCaCert; - applySslSettings(); - return this; - } - - /** - *

Getter for the field keyManagers.

- * - * @return an array of {@link javax.net.ssl.KeyManager} objects - */ - public KeyManager[] getKeyManagers() { - return keyManagers; - } - - /** - * Configure client keys to use for authorization in an SSL session. - * Use null to reset to default. - * - * @param managers The KeyManagers to use - * @return CloudhubClient - */ - public CloudhubClient setKeyManagers(KeyManager[] managers) { - this.keyManagers = managers; - applySslSettings(); - return this; - } - - /** - *

Getter for the field dateFormat.

- * - * @return a {@link java.text.DateFormat} object - */ - public DateFormat getDateFormat() { - return dateFormat; - } - - /** - *

Setter for the field dateFormat.

- * - * @param dateFormat a {@link java.text.DateFormat} object - * @return a {@link cloudhub.client.CloudhubClient} object - */ - public CloudhubClient setDateFormat(DateFormat dateFormat) { - JSON.setDateFormat(dateFormat); - return this; - } - - /** - *

Set SqlDateFormat.

- * - * @param dateFormat a {@link java.text.DateFormat} object - * @return a {@link cloudhub.client.CloudhubClient} object - */ - public CloudhubClient setSqlDateFormat(DateFormat dateFormat) { - JSON.setSqlDateFormat(dateFormat); - return this; - } - - /** - *

Set OffsetDateTimeFormat.

- * - * @param dateFormat a {@link java.time.format.DateTimeFormatter} object - * @return a {@link cloudhub.client.CloudhubClient} object - */ - public CloudhubClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { - JSON.setOffsetDateTimeFormat(dateFormat); - return this; - } - - /** - *

Set LocalDateFormat.

- * - * @param dateFormat a {@link java.time.format.DateTimeFormatter} object - * @return a {@link cloudhub.client.CloudhubClient} object - */ - public CloudhubClient setLocalDateFormat(DateTimeFormatter dateFormat) { - JSON.setLocalDateFormat(dateFormat); - return this; - } - - /** - *

Set LenientOnJson.

- * - * @param lenientOnJson a boolean - * @return a {@link cloudhub.client.CloudhubClient} object - */ - public CloudhubClient setLenientOnJson(boolean lenientOnJson) { - JSON.setLenientOnJson(lenientOnJson); - return this; - } - - /** - * Get authentications (key: authentication name, value: authentication). - * - * @return Map of authentication objects - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - - /** - * Helper method to set username for the first HTTP basic authentication. - * - * @param username Username - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - * - * @param password Password - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - * - * @param apiKey API key - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - * - * @param apiKeyPrefix API key prefix - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - * - * @param accessToken Access token - */ - public void setAccessToken(String accessToken) { - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Helper method to set credentials for AWSV4 Signature - * - * @param accessKey Access Key - * @param secretKey Secret Key - * @param region Region - * @param service Service to access to - */ - public void setAWS4Configuration(String accessKey, String secretKey, String region, String service) { - throw new RuntimeException("No AWS4 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - * - * @param userAgent HTTP request's user agent - * @return CloudhubClient - */ - public CloudhubClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - * @return CloudhubClient - */ - public CloudhubClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * Add a default cookie. - * - * @param key The cookie's key - * @param value The cookie's value - * @return CloudhubClient - */ - public CloudhubClient addDefaultCookie(String key, String value) { - defaultCookieMap.put(key, value); - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - * - * @return True if debugging is enabled, false otherwise. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - * @return CloudhubClient - */ - public CloudhubClient setDebugging(boolean debugging) { - if (debugging != this.debugging) { - if (debugging) { - loggingInterceptor = new HttpLoggingInterceptor(); - loggingInterceptor.setLevel(Level.BODY); - httpClient = httpClient.newBuilder().addInterceptor(loggingInterceptor).build(); - } else { - final OkHttpClient.Builder builder = httpClient.newBuilder(); - builder.interceptors().remove(loggingInterceptor); - httpClient = builder.build(); - loggingInterceptor = null; - } - } - this.debugging = debugging; - return this; - } - - /** - * The path of temporary folder used to store downloaded files from endpoints - * with file response. The default value is null, i.e. using - * the system's default temporary folder. - * - * @see createTempFile - * @return Temporary folder path - */ - public String getTempFolderPath() { - return tempFolderPath; - } - - /** - * Set the temporary folder path (for downloading files) - * - * @param tempFolderPath Temporary folder path - * @return CloudhubClient - */ - public CloudhubClient setTempFolderPath(String tempFolderPath) { - this.tempFolderPath = tempFolderPath; - return this; - } - - /** - * Get connection timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getConnectTimeout() { - return httpClient.connectTimeoutMillis(); - } - - /** - * Sets the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param connectionTimeout connection timeout in milliseconds - * @return Api client - */ - public CloudhubClient setConnectTimeout(int connectionTimeout) { - httpClient = httpClient.newBuilder().connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - /** - * Get read timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getReadTimeout() { - return httpClient.readTimeoutMillis(); - } - - /** - * Sets the read timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param readTimeout read timeout in milliseconds - * @return Api client - */ - public CloudhubClient setReadTimeout(int readTimeout) { - httpClient = httpClient.newBuilder().readTimeout(readTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - /** - * Get write timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getWriteTimeout() { - return httpClient.writeTimeoutMillis(); - } - - /** - * Sets the write timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param writeTimeout connection timeout in milliseconds - * @return Api client - */ - public CloudhubClient setWriteTimeout(int writeTimeout) { - httpClient = httpClient.newBuilder().writeTimeout(writeTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - - /** - * Format the given parameter object into string. - * - * @param param Parameter - * @return String representation of the parameter - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date || param instanceof OffsetDateTime || param instanceof LocalDate) { - //Serialize to json string and remove the " enclosing characters - String jsonStr = JSON.serialize(param); - return jsonStr.substring(1, jsonStr.length() - 1); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for (Object o : (Collection) param) { - if (b.length() > 0) { - b.append(","); - } - b.append(o); - } - return b.toString(); - } else { - return String.valueOf(param); - } - } - - /** - * Formats the specified query parameter to a list containing a single {@code Pair} object. - * - * Note that {@code value} must not be a collection. - * - * @param name The name of the parameter. - * @param value The value of the parameter. - * @return A list containing a single {@code Pair} object. - */ - public List parameterToPair(String name, Object value) { - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null || value instanceof Collection) { - return params; - } - - params.add(new Pair(name, parameterToString(value))); - return params; - } - - /** - * Formats the specified collection query parameters to a list of {@code Pair} objects. - * - * Note that the values of each of the returned Pair objects are percent-encoded. - * - * @param collectionFormat The collection format of the parameter. - * @param name The name of the parameter. - * @param value The value of the parameter. - * @return A list of {@code Pair} objects. - */ - public List parameterToPairs(String collectionFormat, String name, Collection value) { - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null || value.isEmpty()) { - return params; - } - - // create the params based on the collection format - if ("multi".equals(collectionFormat)) { - for (Object item : value) { - params.add(new Pair(name, escapeString(parameterToString(item)))); - } - return params; - } - - // collectionFormat is assumed to be "csv" by default - String delimiter = ","; - - // escape all delimiters except commas, which are URI reserved - // characters - if ("ssv".equals(collectionFormat)) { - delimiter = escapeString(" "); - } else if ("tsv".equals(collectionFormat)) { - delimiter = escapeString("\t"); - } else if ("pipes".equals(collectionFormat)) { - delimiter = escapeString("|"); - } - - StringBuilder sb = new StringBuilder(); - for (Object item : value) { - sb.append(delimiter); - sb.append(escapeString(parameterToString(item))); - } - - params.add(new Pair(name, sb.substring(delimiter.length()))); - - return params; - } - - /** - * Formats the specified collection path parameter to a string value. - * - * @param collectionFormat The collection format of the parameter. - * @param value The value of the parameter. - * @return String representation of the parameter - */ - public String collectionPathParameterToString(String collectionFormat, Collection value) { - // create the value based on the collection format - if ("multi".equals(collectionFormat)) { - // not valid for path params - return parameterToString(value); - } - - // collectionFormat is assumed to be "csv" by default - String delimiter = ","; - - if ("ssv".equals(collectionFormat)) { - delimiter = " "; - } else if ("tsv".equals(collectionFormat)) { - delimiter = "\t"; - } else if ("pipes".equals(collectionFormat)) { - delimiter = "|"; - } - - StringBuilder sb = new StringBuilder() ; - for (Object item : value) { - sb.append(delimiter); - sb.append(parameterToString(item)); - } - - return sb.substring(delimiter.length()); - } - - /** - * Sanitize filename by removing path. - * e.g. ../../sun.gif becomes sun.gif - * - * @param filename The filename to be sanitized - * @return The sanitized filename - */ - public String sanitizeFilename(String filename) { - return filename.replaceAll(".*[/\\\\]", ""); - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - * application/vnd.company+json - * "* / *" is also default to JSON - * @param mime MIME (Multipurpose Internet Mail Extensions) - * @return True if the given MIME is JSON, false otherwise. - */ - public boolean isJsonMime(String mime) { - String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; - return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * returns null. If it matches "any", JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return null; - } - - if (contentTypes[0].equals("*/*")) { - return "application/json"; - } - - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - - return contentTypes[0]; + super(client); } - /** - * Escape the given string to be used as URL query value. - * - * @param str String to be escaped - * @return Escaped string - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Deserialize response body to Java object, according to the return type and - * the Content-Type response header. - * - * @param Type - * @param response HTTP response - * @param returnType The type of the Java object - * @return The deserialized Java object - * @throws cloudhub.client.ApiException If fail to deserialize response body, i.e. cannot read response body - * or the Content-Type of the response is not supported. - */ - @SuppressWarnings("unchecked") - public T deserialize(Response response, Type returnType) throws ApiException { - if (response == null || returnType == null) { - return null; - } - - if ("byte[]".equals(returnType.toString())) { - // Handle binary response (byte array). - try { - return (T) response.body().bytes(); - } catch (IOException e) { - throw new ApiException(e); - } - } else if (returnType.equals(File.class)) { - // Handle file downloading. - return (T) downloadFileFromResponse(response); - } - - String respBody; - try { - if (response.body() != null) - respBody = response.body().string(); - else - respBody = null; - } catch (IOException e) { - throw new ApiException(e); - } - - if (respBody == null || "".equals(respBody)) { - return null; - } - - String contentType = response.headers().get("Content-Type"); - if (contentType == null) { - // ensuring a default content type - contentType = "application/json"; - } - if (isJsonMime(contentType)) { - return JSON.deserialize(respBody, returnType); - } else if (returnType.equals(String.class)) { - // Expecting string, return the raw response body. - return (T) respBody; - } else { - throw new ApiException( - "Content type \"" + contentType + "\" is not supported for type: " + returnType, - response.code(), - response.headers().toMultimap(), - respBody); - } - } - - /** - * Serialize the given Java object into request body according to the object's - * class and the request Content-Type. - * - * @param obj The Java object - * @param contentType The request Content-Type - * @return The serialized request body - * @throws cloudhub.client.ApiException If fail to serialize the given object - */ - public RequestBody serialize(Object obj, String contentType) throws ApiException { - if (obj instanceof byte[]) { - // Binary (byte array) body parameter support. - return RequestBody.create((byte[]) obj, MediaType.parse(contentType)); - } else if (obj instanceof File) { - // File body parameter support. - return RequestBody.create((File) obj, MediaType.parse(contentType)); - } else if ("text/plain".equals(contentType) && obj instanceof String) { - return RequestBody.create((String) obj, MediaType.parse(contentType)); - } else if (isJsonMime(contentType)) { - String content; - if (obj != null) { - content = JSON.serialize(obj); - } else { - content = null; - } - return RequestBody.create(content, MediaType.parse(contentType)); - } else if (obj instanceof String) { - return RequestBody.create((String) obj, MediaType.parse(contentType)); - } else { - throw new ApiException("Content type \"" + contentType + "\" is not supported"); - } - } - - /** - * Download file from the given response. - * - * @param response An instance of the Response object - * @throws cloudhub.client.ApiException If fail to read file content from response and write to disk - * @return Downloaded file - */ - public File downloadFileFromResponse(Response response) throws ApiException { - try { - File file = prepareDownloadFile(response); - BufferedSink sink = Okio.buffer(Okio.sink(file)); - sink.writeAll(response.body().source()); - sink.close(); - return file; - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * Prepare file for download - * - * @param response An instance of the Response object - * @return Prepared file for the download - * @throws java.io.IOException If fail to prepare file for download - */ - public File prepareDownloadFile(Response response) throws IOException { - String filename = null; - String contentDisposition = response.header("Content-Disposition"); - if (contentDisposition != null && !"".equals(contentDisposition)) { - // Get filename from the Content-Disposition header. - Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); - Matcher matcher = pattern.matcher(contentDisposition); - if (matcher.find()) { - filename = sanitizeFilename(matcher.group(1)); - } - } - - String prefix = null; - String suffix = null; - if (filename == null) { - prefix = "download-"; - suffix = ""; - } else { - int pos = filename.lastIndexOf("."); - if (pos == -1) { - prefix = filename + "-"; - } else { - prefix = filename.substring(0, pos) + "-"; - suffix = filename.substring(pos); - } - // Files.createTempFile requires the prefix to be at least three characters long - if (prefix.length() < 3) - prefix = "download-"; - } - - if (tempFolderPath == null) - return Files.createTempFile(prefix, suffix).toFile(); - else - return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile(); - } - - /** - * {@link #execute(Call, Type)} - * - * @param Type - * @param call An instance of the Call object - * @return ApiResponse<T> - * @throws cloudhub.client.ApiException If fail to execute the call - */ - public ApiResponse execute(Call call) throws ApiException { - return execute(call, null); - } - - /** - * Execute HTTP call and deserialize the HTTP response body into the given return type. - * - * @param returnType The return type used to deserialize HTTP response body - * @param The return type corresponding to (same with) returnType - * @param call Call - * @return ApiResponse object containing response status, headers and - * data, which is a Java object deserialized from response body and would be null - * when returnType is null. - * @throws cloudhub.client.ApiException If fail to execute the call - */ - public ApiResponse execute(Call call, Type returnType) throws ApiException { - try { - Response response = call.execute(); - T data = handleResponse(response, returnType); - return new ApiResponse(response.code(), response.headers().toMultimap(), data); - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * {@link #executeAsync(Call, Type, ApiCallback)} - * - * @param Type - * @param call An instance of the Call object - * @param callback ApiCallback<T> - */ - public void executeAsync(Call call, ApiCallback callback) { - executeAsync(call, null, callback); - } - - /** - * Execute HTTP call asynchronously. - * - * @param Type - * @param call The callback to be executed when the API call finishes - * @param returnType Return type - * @param callback ApiCallback - * @see #execute(Call, Type) - */ - @SuppressWarnings("unchecked") - public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { - call.enqueue(new Callback() { - @Override - public void onFailure(Call call, IOException e) { - callback.onFailure(new ApiException(e), 0, null); - } - - @Override - public void onResponse(Call call, Response response) throws IOException { - T result; - try { - result = (T) handleResponse(response, returnType); - } catch (ApiException e) { - callback.onFailure(e, response.code(), response.headers().toMultimap()); - return; - } catch (Exception e) { - callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap()); - return; - } - callback.onSuccess(result, response.code(), response.headers().toMultimap()); - } - }); - } - - /** - * Handle the given response, return the deserialized object when the response is successful. - * - * @param Type - * @param response Response - * @param returnType Return type - * @return Type - * @throws cloudhub.client.ApiException If the response has an unsuccessful status code or - * fail to deserialize the response body - */ - public T handleResponse(Response response, Type returnType) throws ApiException { - if (response.isSuccessful()) { - if (returnType == null || response.code() == 204) { - // returning null if the returnType is not defined, - // or the status code is 204 (No Content) - if (response.body() != null) { - try { - response.body().close(); - } catch (Exception e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - return null; - } else { - return deserialize(response, returnType); - } - } else { - String respBody = null; - if (response.body() != null) { - try { - respBody = response.body().string(); - } catch (IOException e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); - } - } - - /** - * Build HTTP call with the given options. - * - * @param baseUrl The base URL - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param cookieParams The cookie parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param callback Callback for upload/download progress - * @return The HTTP call - * @throws cloudhub.client.ApiException If fail to serialize the request body object - */ - public Call buildCall(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); - - return httpClient.newCall(request); - } - - /** - * Build an HTTP request with the given options. - * - * @param baseUrl The base URL - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param cookieParams The cookie parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param callback Callback for upload/download progress - * @return The HTTP request - * @throws cloudhub.client.ApiException If fail to serialize the request body object - */ - public Request buildRequest(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - // aggregate queryParams (non-collection) and collectionQueryParams into allQueryParams - List allQueryParams = new ArrayList(queryParams); - allQueryParams.addAll(collectionQueryParams); - - final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); - - // prepare HTTP request body - RequestBody reqBody; - String contentType = headerParams.get("Content-Type"); - - if (!HttpMethod.permitsRequestBody(method)) { - reqBody = null; - } else if ("application/x-www-form-urlencoded".equals(contentType)) { - reqBody = buildRequestBodyFormEncoding(formParams); - } else if ("multipart/form-data".equals(contentType)) { - reqBody = buildRequestBodyMultipart(formParams); - } else if (body == null) { - if ("DELETE".equals(method)) { - // allow calling DELETE without sending a request body - reqBody = null; - } else { - // use an empty request body (for POST, PUT and PATCH) - reqBody = RequestBody.create("", contentType == null ? null : MediaType.parse(contentType)); - } - } else { - reqBody = serialize(body, contentType); - } - - // update parameters with authentication settings - updateParamsForAuth(authNames, allQueryParams, headerParams, cookieParams, requestBodyToString(reqBody), method, URI.create(url)); - - final Request.Builder reqBuilder = new Request.Builder().url(url); - processHeaderParams(headerParams, reqBuilder); - processCookieParams(cookieParams, reqBuilder); - - // Associate callback with request (if not null) so interceptor can - // access it when creating ProgressResponseBody - reqBuilder.tag(callback); - - Request request = null; - - if (callback != null && reqBody != null) { - ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, callback); - request = reqBuilder.method(method, progressRequestBody).build(); - } else { - request = reqBuilder.method(method, reqBody).build(); - } - - return request; - } - - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param baseUrl The base URL - * @param path The sub path - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @return The full URL - */ - public String buildUrl(String baseUrl, String path, List queryParams, List collectionQueryParams) { - final StringBuilder url = new StringBuilder(); - if (baseUrl != null) { - url.append(baseUrl).append(path); - } else { - String baseURL; - if (serverIndex != null) { - if (serverIndex < 0 || serverIndex >= servers.size()) { - throw new ArrayIndexOutOfBoundsException(String.format( - "Invalid index %d when selecting the host settings. Must be less than %d", serverIndex, servers.size() - )); - } - baseURL = servers.get(serverIndex).URL(serverVariables); - } else { - baseURL = basePath; - } - url.append(baseURL).append(path); - } - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); - } - } - } - - if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) { - String prefix = url.toString().contains("?") ? "&" : "?"; - for (Pair param : collectionQueryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - // collection query parameter value already escaped as part of parameterToPairs - url.append(escapeString(param.getName())).append("=").append(value); - } - } - } - - return url.toString(); - } - - /** - * Set header parameters to the request builder, including default headers. - * - * @param headerParams Header parameters in the form of Map - * @param reqBuilder Request.Builder - */ - public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { - for (Entry param : headerParams.entrySet()) { - reqBuilder.header(param.getKey(), parameterToString(param.getValue())); - } - for (Entry header : defaultHeaderMap.entrySet()) { - if (!headerParams.containsKey(header.getKey())) { - reqBuilder.header(header.getKey(), parameterToString(header.getValue())); - } - } - } - - /** - * Set cookie parameters to the request builder, including default cookies. - * - * @param cookieParams Cookie parameters in the form of Map - * @param reqBuilder Request.Builder - */ - public void processCookieParams(Map cookieParams, Request.Builder reqBuilder) { - for (Entry param : cookieParams.entrySet()) { - reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); - } - for (Entry param : defaultCookieMap.entrySet()) { - if (!cookieParams.containsKey(param.getKey())) { - reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); - } - } - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - * @param cookieParams Map of cookie parameters - * @param payload HTTP request body - * @param method HTTP method - * @param uri URI - * @throws cloudhub.client.ApiException If fails to update the parameters - */ - public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams, - Map cookieParams, String payload, String method, URI uri) throws ApiException { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) { - throw new RuntimeException("Authentication undefined: " + authName); - } - auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri); - } - } - - /** - * Build a form-encoding request body with the given form parameters. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyFormEncoding(Map formParams) { - okhttp3.FormBody.Builder formBuilder = new okhttp3.FormBody.Builder(); - for (Entry param : formParams.entrySet()) { - formBuilder.add(param.getKey(), parameterToString(param.getValue())); - } - return formBuilder.build(); - } - - /** - * Build a multipart (file uploading) request body with the given form parameters, - * which could contain text fields and file fields. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyMultipart(Map formParams) { - MultipartBody.Builder mpBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); - for (Entry param : formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - addPartToMultiPartBuilder(mpBuilder, param.getKey(), file); - } else if (param.getValue() instanceof List) { - List list = (List) param.getValue(); - for (Object item: list) { - if (item instanceof File) { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), (File) item); - } else { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); - } - } - } else { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); - } - } - return mpBuilder.build(); - } - - /** - * Guess Content-Type header from the given file (defaults to "application/octet-stream"). - * - * @param file The given file - * @return The guessed Content-Type - */ - public String guessContentTypeFromFile(File file) { - String contentType = URLConnection.guessContentTypeFromName(file.getName()); - if (contentType == null) { - return "application/octet-stream"; - } else { - return contentType; - } - } - - /** - * Add a Content-Disposition Header for the given key and file to the MultipartBody Builder. - * - * @param mpBuilder MultipartBody.Builder - * @param key The key of the Header element - * @param file The file to add to the Header - */ - private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, File file) { - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\""); - MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); - mpBuilder.addPart(partHeaders, RequestBody.create(file, mediaType)); - } - - /** - * Add a Content-Disposition Header for the given key and complex object to the MultipartBody Builder. - * - * @param mpBuilder MultipartBody.Builder - * @param key The key of the Header element - * @param obj The complex object to add to the Header - */ - private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, Object obj) { - RequestBody requestBody; - if (obj instanceof String) { - requestBody = RequestBody.create((String) obj, MediaType.parse("text/plain")); - } else { - String content; - if (obj != null) { - content = JSON.serialize(obj); - } else { - content = null; - } - requestBody = RequestBody.create(content, MediaType.parse("application/json")); - } - - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""); - mpBuilder.addPart(partHeaders, requestBody); - } - - /** - * Get network interceptor to add it to the httpClient to track download progress for - * async requests. - */ - private Interceptor getProgressInterceptor() { - return new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - final Request request = chain.request(); - final Response originalResponse = chain.proceed(request); - if (request.tag() instanceof ApiCallback) { - final ApiCallback callback = (ApiCallback) request.tag(); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), callback)) - .build(); - } - return originalResponse; - } - }; - } - - /** - * Apply SSL related settings to httpClient according to the current values of - * verifyingSsl and sslCaCert. - */ - private void applySslSettings() { - try { - TrustManager[] trustManagers; - HostnameVerifier hostnameVerifier; - if (!verifyingSsl) { - trustManagers = new TrustManager[]{ - new X509TrustManager() { - @Override - public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new java.security.cert.X509Certificate[]{}; - } - } - }; - hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - } else { - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - - if (sslCaCert == null) { - trustManagerFactory.init((KeyStore) null); - } else { - char[] password = null; // Any password will work. - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - Collection certificates = certificateFactory.generateCertificates(sslCaCert); - if (certificates.isEmpty()) { - throw new IllegalArgumentException("expected non-empty set of trusted certificates"); - } - KeyStore caKeyStore = newEmptyKeyStore(password); - int index = 0; - for (Certificate certificate : certificates) { - String certificateAlias = "ca" + (index++); - caKeyStore.setCertificateEntry(certificateAlias, certificate); - } - trustManagerFactory.init(caKeyStore); - } - trustManagers = trustManagerFactory.getTrustManagers(); - hostnameVerifier = OkHostnameVerifier.INSTANCE; - } - - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, new SecureRandom()); - httpClient = httpClient.newBuilder() - .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]) - .hostnameVerifier(hostnameVerifier) - .build(); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } - - private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { - try { - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, password); - return keyStore; - } catch (IOException e) { - throw new AssertionError(e); - } - } - - /** - * Convert the HTTP request body to a string. - * - * @param requestBody The HTTP request object - * @return The string representation of the HTTP request body - * @throws cloudhub.client.ApiException If fail to serialize the request body object into a string - */ - private String requestBodyToString(RequestBody requestBody) throws ApiException { - if (requestBody != null) { - try { - final Buffer buffer = new Buffer(); - requestBody.writeTo(buffer); - return buffer.readUtf8(); - } catch (final IOException e) { - throw new ApiException(e); - } - } - - // empty http request body - return ""; + private void applyDefaultTimeouts() { + setHttpClient(getHttpClient().newBuilder() + .connectTimeout(DEFAULT_TIMEOUT_MINUTES, TimeUnit.MINUTES) + .readTimeout(DEFAULT_TIMEOUT_MINUTES, TimeUnit.MINUTES) + .writeTimeout(DEFAULT_TIMEOUT_MINUTES, TimeUnit.MINUTES) + .build()); } } diff --git a/src/main/java/cloudhub/client/Configuration.java b/src/main/java/cloudhub/client/Configuration.java index bf2e5dd..910a040 100644 --- a/src/main/java/cloudhub/client/Configuration.java +++ b/src/main/java/cloudhub/client/Configuration.java @@ -13,27 +13,51 @@ package cloudhub.client; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-03-24T09:46:17.287214-03:00[America/Sao_Paulo]") +import java.util.Objects; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public class Configuration { - private static CloudhubClient defaultCloudhubClient = new CloudhubClient(); - - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - * - * @return CloudhubClient API client - */ - public static CloudhubClient getDefaultCloudhubClient() { - return defaultCloudhubClient; - } + public static final String VERSION = "v1"; + + private static final AtomicReference defaultApiClient = new AtomicReference<>(); + private static volatile Supplier apiClientFactory = ApiClient::new; - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - * - * @param CloudhubClient API client - */ - public static void setDefaultCloudhubClient(CloudhubClient CloudhubClient) { - defaultCloudhubClient = CloudhubClient; + /** + * Get the default API client, which would be used when creating API instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + ApiClient client = defaultApiClient.get(); + if (client == null) { + client = defaultApiClient.updateAndGet(val -> { + if (val != null) { // changed by another thread + return val; + } + return apiClientFactory.get(); + }); } -} + return client; + } + + /** + * Set the default API client, which would be used when creating API instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient.set(apiClient); + } + + /** + * set the callback used to create new ApiClient objects + */ + public static void setApiClientFactory(Supplier factory) { + apiClientFactory = Objects.requireNonNull(factory); + } + + private Configuration() { + } +} \ No newline at end of file diff --git a/src/main/java/cloudhub/client/JSON.java b/src/main/java/cloudhub/client/JSON.java index 4c65379..e525a8a 100644 --- a/src/main/java/cloudhub/client/JSON.java +++ b/src/main/java/cloudhub/client/JSON.java @@ -27,8 +27,11 @@ import okio.ByteString; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.io.StringReader; import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.ParseException; import java.text.ParsePosition; @@ -86,7 +89,7 @@ private static Class getClassByDiscriminator(Map classByDiscriminatorValue, Stri return clazz; } - { + static { GsonBuilder gsonBuilder = createGson(); gsonBuilder.registerTypeAdapter(Date.class, dateTypeAdapter); gsonBuilder.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter); @@ -94,6 +97,7 @@ private static Class getClassByDiscriminator(Map classByDiscriminatorValue, Stri gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter); gsonBuilder.registerTypeAdapterFactory(new cloudhub.client.model.CertificateModel.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new cloudhub.client.model.GetServiceAvailabilityResponse.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new cloudhub.client.model.ServiceSessionCreateRequest.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new cloudhub.client.model.ServiceSessionCreateResponse.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new cloudhub.client.model.SessionCreateRequest.CustomTypeAdapterFactory()); @@ -166,6 +170,28 @@ public static T deserialize(String body, Type returnType) { } } + /** + * Deserialize the given JSON InputStream to a Java object. + * + * @param Type + * @param inputStream The JSON InputStream + * @param returnType The type to deserialize into + * @return The deserialized Java object + */ + @SuppressWarnings("unchecked") + public static T deserialize(InputStream inputStream, Type returnType) throws IOException { + try (InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) { + if (isLenientOnJson) { + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + JsonReader jsonReader = new JsonReader(reader); + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(reader, returnType); + } + } + } + /** * Gson TypeAdapter for Byte Array type */ diff --git a/src/main/java/cloudhub/client/Pair.java b/src/main/java/cloudhub/client/Pair.java index 0454ed4..7e072dd 100644 --- a/src/main/java/cloudhub/client/Pair.java +++ b/src/main/java/cloudhub/client/Pair.java @@ -13,7 +13,7 @@ package cloudhub.client; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-03-24T09:46:17.287214-03:00[America/Sao_Paulo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public class Pair { private String name = ""; private String value = ""; diff --git a/src/main/java/cloudhub/client/ServerConfiguration.java b/src/main/java/cloudhub/client/ServerConfiguration.java index 8d7f278..3eb0e0b 100644 --- a/src/main/java/cloudhub/client/ServerConfiguration.java +++ b/src/main/java/cloudhub/client/ServerConfiguration.java @@ -1,3 +1,16 @@ +/* + * Cloudhub API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: v1 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + package cloudhub.client; import java.util.Map; @@ -5,6 +18,7 @@ /** * Representing a Server configuration. */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public class ServerConfiguration { public String URL; public String description; diff --git a/src/main/java/cloudhub/client/ServerVariable.java b/src/main/java/cloudhub/client/ServerVariable.java index c7ca5aa..247b872 100644 --- a/src/main/java/cloudhub/client/ServerVariable.java +++ b/src/main/java/cloudhub/client/ServerVariable.java @@ -1,3 +1,16 @@ +/* + * Cloudhub API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: v1 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + package cloudhub.client; import java.util.HashSet; @@ -5,6 +18,7 @@ /** * Representing a Server Variable for server URL template substitution. */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public class ServerVariable { public String description; public String defaultValue; diff --git a/src/main/java/cloudhub/client/StringUtil.java b/src/main/java/cloudhub/client/StringUtil.java index 4c88b7b..fe596d8 100644 --- a/src/main/java/cloudhub/client/StringUtil.java +++ b/src/main/java/cloudhub/client/StringUtil.java @@ -16,7 +16,7 @@ import java.util.Collection; import java.util.Iterator; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-03-24T09:46:17.287214-03:00[America/Sao_Paulo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/src/main/java/cloudhub/client/auth/ApiKeyAuth.java b/src/main/java/cloudhub/client/auth/ApiKeyAuth.java index 7d16c51..c6c5c53 100644 --- a/src/main/java/cloudhub/client/auth/ApiKeyAuth.java +++ b/src/main/java/cloudhub/client/auth/ApiKeyAuth.java @@ -20,7 +20,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-03-24T09:46:17.287214-03:00[America/Sao_Paulo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/src/main/java/cloudhub/client/auth/Authentication.java b/src/main/java/cloudhub/client/auth/Authentication.java index 14fa9b5..2781b82 100644 --- a/src/main/java/cloudhub/client/auth/Authentication.java +++ b/src/main/java/cloudhub/client/auth/Authentication.java @@ -20,6 +20,7 @@ import java.util.Map; import java.util.List; +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public interface Authentication { /** * Apply authentication settings to header and query params. diff --git a/src/main/java/cloudhub/client/auth/HttpBasicAuth.java b/src/main/java/cloudhub/client/auth/HttpBasicAuth.java index 8832752..653ad89 100644 --- a/src/main/java/cloudhub/client/auth/HttpBasicAuth.java +++ b/src/main/java/cloudhub/client/auth/HttpBasicAuth.java @@ -22,8 +22,6 @@ import java.util.Map; import java.util.List; -import java.io.UnsupportedEncodingException; - public class HttpBasicAuth implements Authentication { private String username; private String password; diff --git a/src/main/java/cloudhub/client/auth/HttpBearerAuth.java b/src/main/java/cloudhub/client/auth/HttpBearerAuth.java index c039d5f..186c649 100644 --- a/src/main/java/cloudhub/client/auth/HttpBearerAuth.java +++ b/src/main/java/cloudhub/client/auth/HttpBearerAuth.java @@ -17,13 +17,15 @@ import cloudhub.client.Pair; import java.net.URI; -import java.util.Map; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-03-24T09:46:17.287214-03:00[America/Sao_Paulo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public class HttpBearerAuth implements Authentication { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -35,7 +37,7 @@ public HttpBearerAuth(String scheme) { * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** @@ -44,12 +46,22 @@ public String getBearerToken() { * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); if (bearerToken == null) { return; } diff --git a/src/main/java/cloudhub/client/model/AbstractOpenApiSchema.java b/src/main/java/cloudhub/client/model/AbstractOpenApiSchema.java index 8ed9da4..1c1cdec 100644 --- a/src/main/java/cloudhub/client/model/AbstractOpenApiSchema.java +++ b/src/main/java/cloudhub/client/model/AbstractOpenApiSchema.java @@ -17,14 +17,11 @@ import java.util.Objects; import java.lang.reflect.Type; import java.util.Map; -import javax.ws.rs.core.GenericType; - -//import com.fasterxml.jackson.annotation.JsonValue; /** * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-03-24T09:46:17.287214-03:00[America/Sao_Paulo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public abstract class AbstractOpenApiSchema { // store the actual instance of the schema/object @@ -46,7 +43,7 @@ public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { * * @return an instance of the actual schema/object */ - public abstract Map getSchemas(); + public abstract Map> getSchemas(); /** * Get the actual instance diff --git a/src/main/java/cloudhub/client/model/CertificateModel.java b/src/main/java/cloudhub/client/model/CertificateModel.java index f784b06..3b22592 100644 --- a/src/main/java/cloudhub/client/model/CertificateModel.java +++ b/src/main/java/cloudhub/client/model/CertificateModel.java @@ -14,13 +14,13 @@ package cloudhub.client.model; import java.util.Objects; -import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; +import java.util.Arrays; import org.openapitools.jackson.nullable.JsonNullable; import com.google.gson.Gson; @@ -33,13 +33,15 @@ import com.google.gson.JsonParseException; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; -import java.lang.reflect.Type; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Set; import cloudhub.client.JSON; @@ -47,63 +49,83 @@ /** * CertificateModel */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-03-24T09:46:17.287214-03:00[America/Sao_Paulo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public class CertificateModel { public static final String SERIALIZED_NAME_CONTENT = "content"; @SerializedName(SERIALIZED_NAME_CONTENT) + @javax.annotation.Nullable private byte[] content; public static final String SERIALIZED_NAME_ALIAS = "alias"; @SerializedName(SERIALIZED_NAME_ALIAS) + @javax.annotation.Nullable private String alias; + public static final String SERIALIZED_NAME_SERVICE_NAME = "serviceName"; + @SerializedName(SERIALIZED_NAME_SERVICE_NAME) + @javax.annotation.Nullable + private String serviceName; + public CertificateModel() { } - public CertificateModel content(byte[] content) { - + public CertificateModel content(@javax.annotation.Nullable byte[] content) { this.content = content; return this; } - /** + /** * Get content * @return content - **/ + */ @javax.annotation.Nullable - public byte[] getContent() { return content; } - - public void setContent(byte[] content) { + public void setContent(@javax.annotation.Nullable byte[] content) { this.content = content; } - public CertificateModel alias(String alias) { - + public CertificateModel alias(@javax.annotation.Nullable String alias) { this.alias = alias; return this; } - /** + /** * Get alias * @return alias - **/ + */ @javax.annotation.Nullable - public String getAlias() { return alias; } - - public void setAlias(String alias) { + public void setAlias(@javax.annotation.Nullable String alias) { this.alias = alias; } + public CertificateModel serviceName(@javax.annotation.Nullable String serviceName) { + this.serviceName = serviceName; + return this; + } + + /** + * Get serviceName + * @return serviceName + */ + @javax.annotation.Nullable + public String getServiceName() { + return serviceName; + } + + public void setServiceName(@javax.annotation.Nullable String serviceName) { + this.serviceName = serviceName; + } + + @Override public boolean equals(Object o) { @@ -115,7 +137,8 @@ public boolean equals(Object o) { } CertificateModel certificateModel = (CertificateModel) o; return Arrays.equals(this.content, certificateModel.content) && - Objects.equals(this.alias, certificateModel.alias); + Objects.equals(this.alias, certificateModel.alias) && + Objects.equals(this.serviceName, certificateModel.serviceName); } private static boolean equalsNullable(JsonNullable a, JsonNullable b) { @@ -124,7 +147,7 @@ private static boolean equalsNullable(JsonNullable a, JsonNullable b) @Override public int hashCode() { - return Objects.hash(Arrays.hashCode(content), alias); + return Objects.hash(Arrays.hashCode(content), alias, serviceName); } private static int hashCodeNullable(JsonNullable a) { @@ -140,6 +163,7 @@ public String toString() { sb.append("class CertificateModel {\n"); sb.append(" content: ").append(toIndentedString(content)).append("\n"); sb.append(" alias: ").append(toIndentedString(alias)).append("\n"); + sb.append(" serviceName: ").append(toIndentedString(serviceName)).append("\n"); sb.append("}"); return sb.toString(); } @@ -161,37 +185,39 @@ private String toIndentedString(Object o) { static { // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("content"); - openapiFields.add("alias"); + openapiFields = new HashSet(Arrays.asList("content", "alias", "serviceName")); // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Object and throws an exception if issues found - * - * @param jsonObj JSON Object - * @throws IOException if the JSON Object is invalid with respect to CertificateModel - */ - public static void validateJsonObject(JsonObject jsonObj) throws IOException { - if (jsonObj == null) { - if (!CertificateModel.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + openapiRequiredFields = new HashSet(0); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to CertificateModel + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!CertificateModel.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null throw new IllegalArgumentException(String.format("The required field(s) %s in CertificateModel is not found in the empty JSON string", CertificateModel.openapiRequiredFields.toString())); } } - Set> entries = jsonObj.entrySet(); + Set> entries = jsonElement.getAsJsonObject().entrySet(); // check to see if the JSON string contains additional fields - for (Entry entry : entries) { + for (Map.Entry entry : entries) { if (!CertificateModel.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `CertificateModel` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `CertificateModel` properties. JSON: %s", entry.getKey(), jsonElement.toString())); } } + JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("alias") != null && !jsonObj.get("alias").isJsonNull()) && !jsonObj.get("alias").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `alias` to be a primitive type in the JSON string but got `%s`", jsonObj.get("alias").toString())); } + if ((jsonObj.get("serviceName") != null && !jsonObj.get("serviceName").isJsonNull()) && !jsonObj.get("serviceName").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `serviceName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("serviceName").toString())); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { @@ -214,31 +240,31 @@ public void write(JsonWriter out, CertificateModel value) throws IOException { @Override public CertificateModel read(JsonReader in) throws IOException { - JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); - validateJsonObject(jsonObj); - return thisAdapter.fromJsonTree(jsonObj); + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); } }.nullSafe(); } } - /** - * Create an instance of CertificateModel given an JSON string - * - * @param jsonString JSON string - * @return An instance of CertificateModel - * @throws IOException if the JSON string is invalid with respect to CertificateModel - */ + /** + * Create an instance of CertificateModel given an JSON string + * + * @param jsonString JSON string + * @return An instance of CertificateModel + * @throws IOException if the JSON string is invalid with respect to CertificateModel + */ public static CertificateModel fromJson(String jsonString) throws IOException { return JSON.getGson().fromJson(jsonString, CertificateModel.class); } - /** - * Convert an instance of CertificateModel to an JSON string - * - * @return JSON string - */ + /** + * Convert an instance of CertificateModel to an JSON string + * + * @return JSON string + */ public String toJson() { return JSON.getGson().toJson(this); } diff --git a/src/main/java/cloudhub/client/model/GetServiceAvailabilityResponse.java b/src/main/java/cloudhub/client/model/GetServiceAvailabilityResponse.java new file mode 100644 index 0000000..35fb6c7 --- /dev/null +++ b/src/main/java/cloudhub/client/model/GetServiceAvailabilityResponse.java @@ -0,0 +1,240 @@ +/* + * Cloudhub API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: v1 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package cloudhub.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; +import org.openapitools.jackson.nullable.JsonNullable; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import cloudhub.client.JSON; + +/** + * GetServiceAvailabilityResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") +public class GetServiceAvailabilityResponse { + public static final String SERIALIZED_NAME_DISCOVERY_AVAILABLE = "discoveryAvailable"; + @SerializedName(SERIALIZED_NAME_DISCOVERY_AVAILABLE) + @javax.annotation.Nullable + private Boolean discoveryAvailable; + + public static final String SERIALIZED_NAME_CERTIFICATE_FOUND = "certificateFound"; + @SerializedName(SERIALIZED_NAME_CERTIFICATE_FOUND) + @javax.annotation.Nullable + private Boolean certificateFound; + + public GetServiceAvailabilityResponse() { + } + + public GetServiceAvailabilityResponse discoveryAvailable(@javax.annotation.Nullable Boolean discoveryAvailable) { + this.discoveryAvailable = discoveryAvailable; + return this; + } + + /** + * Get discoveryAvailable + * @return discoveryAvailable + */ + @javax.annotation.Nullable + public Boolean getDiscoveryAvailable() { + return discoveryAvailable; + } + + public void setDiscoveryAvailable(@javax.annotation.Nullable Boolean discoveryAvailable) { + this.discoveryAvailable = discoveryAvailable; + } + + + public GetServiceAvailabilityResponse certificateFound(@javax.annotation.Nullable Boolean certificateFound) { + this.certificateFound = certificateFound; + return this; + } + + /** + * Get certificateFound + * @return certificateFound + */ + @javax.annotation.Nullable + public Boolean getCertificateFound() { + return certificateFound; + } + + public void setCertificateFound(@javax.annotation.Nullable Boolean certificateFound) { + this.certificateFound = certificateFound; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + GetServiceAvailabilityResponse getServiceAvailabilityResponse = (GetServiceAvailabilityResponse) o; + return Objects.equals(this.discoveryAvailable, getServiceAvailabilityResponse.discoveryAvailable) && + Objects.equals(this.certificateFound, getServiceAvailabilityResponse.certificateFound); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(discoveryAvailable, certificateFound); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class GetServiceAvailabilityResponse {\n"); + sb.append(" discoveryAvailable: ").append(toIndentedString(discoveryAvailable)).append("\n"); + sb.append(" certificateFound: ").append(toIndentedString(certificateFound)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(Arrays.asList("discoveryAvailable", "certificateFound")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(0); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to GetServiceAvailabilityResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!GetServiceAvailabilityResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in GetServiceAvailabilityResponse is not found in the empty JSON string", GetServiceAvailabilityResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!GetServiceAvailabilityResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `GetServiceAvailabilityResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!GetServiceAvailabilityResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'GetServiceAvailabilityResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(GetServiceAvailabilityResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, GetServiceAvailabilityResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public GetServiceAvailabilityResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of GetServiceAvailabilityResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of GetServiceAvailabilityResponse + * @throws IOException if the JSON string is invalid with respect to GetServiceAvailabilityResponse + */ + public static GetServiceAvailabilityResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, GetServiceAvailabilityResponse.class); + } + + /** + * Convert an instance of GetServiceAvailabilityResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/src/main/java/cloudhub/client/model/IdentifierTypes.java b/src/main/java/cloudhub/client/model/IdentifierTypes.java index 7d452a7..96ee6d9 100644 --- a/src/main/java/cloudhub/client/model/IdentifierTypes.java +++ b/src/main/java/cloudhub/client/model/IdentifierTypes.java @@ -14,11 +14,11 @@ package cloudhub.client.model; import java.util.Objects; -import java.util.Arrays; import com.google.gson.annotations.SerializedName; import java.io.IOException; import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; @@ -69,5 +69,10 @@ public IdentifierTypes read(final JsonReader jsonReader) throws IOException { return IdentifierTypes.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + IdentifierTypes.fromValue(value); + } } diff --git a/src/main/java/cloudhub/client/model/ServiceSessionCreateRequest.java b/src/main/java/cloudhub/client/model/ServiceSessionCreateRequest.java index f2270a5..394d794 100644 --- a/src/main/java/cloudhub/client/model/ServiceSessionCreateRequest.java +++ b/src/main/java/cloudhub/client/model/ServiceSessionCreateRequest.java @@ -14,7 +14,6 @@ package cloudhub.client.model; import java.util.Objects; -import java.util.Arrays; import cloudhub.client.model.TrustServiceSessionTypes; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; @@ -22,6 +21,7 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; +import java.util.Arrays; import org.openapitools.jackson.nullable.JsonNullable; import com.google.gson.Gson; @@ -34,13 +34,15 @@ import com.google.gson.JsonParseException; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; -import java.lang.reflect.Type; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Set; import cloudhub.client.JSON; @@ -48,115 +50,155 @@ /** * ServiceSessionCreateRequest */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-03-24T09:46:17.287214-03:00[America/Sao_Paulo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public class ServiceSessionCreateRequest { public static final String SERIALIZED_NAME_IDENTIFIER = "identifier"; @SerializedName(SERIALIZED_NAME_IDENTIFIER) + @javax.annotation.Nullable private String identifier; public static final String SERIALIZED_NAME_TYPE = "type"; @SerializedName(SERIALIZED_NAME_TYPE) + @javax.annotation.Nullable private TrustServiceSessionTypes type; public static final String SERIALIZED_NAME_REDIRECT_URI = "redirectUri"; @SerializedName(SERIALIZED_NAME_REDIRECT_URI) + @javax.annotation.Nonnull private String redirectUri; public static final String SERIALIZED_NAME_LIFETIME_IN_SECONDS = "lifetimeInSeconds"; @SerializedName(SERIALIZED_NAME_LIFETIME_IN_SECONDS) + @javax.annotation.Nullable private Integer lifetimeInSeconds; + public static final String SERIALIZED_NAME_CUSTOM_STATE = "customState"; + @SerializedName(SERIALIZED_NAME_CUSTOM_STATE) + @javax.annotation.Nullable + private String customState; + + public static final String SERIALIZED_NAME_DISCOVER = "discover"; + @SerializedName(SERIALIZED_NAME_DISCOVER) + @javax.annotation.Nullable + private Boolean discover; + public ServiceSessionCreateRequest() { } - public ServiceSessionCreateRequest identifier(String identifier) { - + public ServiceSessionCreateRequest identifier(@javax.annotation.Nullable String identifier) { this.identifier = identifier; return this; } - /** + /** * Get identifier * @return identifier - **/ - @javax.annotation.Nonnull - + */ + @javax.annotation.Nullable public String getIdentifier() { return identifier; } - - public void setIdentifier(String identifier) { + public void setIdentifier(@javax.annotation.Nullable String identifier) { this.identifier = identifier; } - public ServiceSessionCreateRequest type(TrustServiceSessionTypes type) { - + public ServiceSessionCreateRequest type(@javax.annotation.Nullable TrustServiceSessionTypes type) { this.type = type; return this; } - /** + /** * Get type * @return type - **/ + */ @javax.annotation.Nullable - public TrustServiceSessionTypes getType() { return type; } - - public void setType(TrustServiceSessionTypes type) { + public void setType(@javax.annotation.Nullable TrustServiceSessionTypes type) { this.type = type; } - public ServiceSessionCreateRequest redirectUri(String redirectUri) { - + public ServiceSessionCreateRequest redirectUri(@javax.annotation.Nonnull String redirectUri) { this.redirectUri = redirectUri; return this; } - /** + /** * Get redirectUri * @return redirectUri - **/ + */ @javax.annotation.Nonnull - public String getRedirectUri() { return redirectUri; } - - public void setRedirectUri(String redirectUri) { + public void setRedirectUri(@javax.annotation.Nonnull String redirectUri) { this.redirectUri = redirectUri; } - public ServiceSessionCreateRequest lifetimeInSeconds(Integer lifetimeInSeconds) { - + public ServiceSessionCreateRequest lifetimeInSeconds(@javax.annotation.Nullable Integer lifetimeInSeconds) { this.lifetimeInSeconds = lifetimeInSeconds; return this; } - /** + /** * Get lifetimeInSeconds * @return lifetimeInSeconds - **/ + */ @javax.annotation.Nullable - public Integer getLifetimeInSeconds() { return lifetimeInSeconds; } - - public void setLifetimeInSeconds(Integer lifetimeInSeconds) { + public void setLifetimeInSeconds(@javax.annotation.Nullable Integer lifetimeInSeconds) { this.lifetimeInSeconds = lifetimeInSeconds; } + public ServiceSessionCreateRequest customState(@javax.annotation.Nullable String customState) { + this.customState = customState; + return this; + } + + /** + * Get customState + * @return customState + */ + @javax.annotation.Nullable + public String getCustomState() { + return customState; + } + + public void setCustomState(@javax.annotation.Nullable String customState) { + this.customState = customState; + } + + + public ServiceSessionCreateRequest discover(@javax.annotation.Nullable Boolean discover) { + this.discover = discover; + return this; + } + + /** + * Get discover + * @return discover + */ + @javax.annotation.Nullable + public Boolean getDiscover() { + return discover; + } + + public void setDiscover(@javax.annotation.Nullable Boolean discover) { + this.discover = discover; + } + + @Override public boolean equals(Object o) { @@ -170,7 +212,9 @@ public boolean equals(Object o) { return Objects.equals(this.identifier, serviceSessionCreateRequest.identifier) && Objects.equals(this.type, serviceSessionCreateRequest.type) && Objects.equals(this.redirectUri, serviceSessionCreateRequest.redirectUri) && - Objects.equals(this.lifetimeInSeconds, serviceSessionCreateRequest.lifetimeInSeconds); + Objects.equals(this.lifetimeInSeconds, serviceSessionCreateRequest.lifetimeInSeconds) && + Objects.equals(this.customState, serviceSessionCreateRequest.customState) && + Objects.equals(this.discover, serviceSessionCreateRequest.discover); } private static boolean equalsNullable(JsonNullable a, JsonNullable b) { @@ -179,7 +223,7 @@ private static boolean equalsNullable(JsonNullable a, JsonNullable b) @Override public int hashCode() { - return Objects.hash(identifier, type, redirectUri, lifetimeInSeconds); + return Objects.hash(identifier, type, redirectUri, lifetimeInSeconds, customState, discover); } private static int hashCodeNullable(JsonNullable a) { @@ -197,6 +241,8 @@ public String toString() { sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" redirectUri: ").append(toIndentedString(redirectUri)).append("\n"); sb.append(" lifetimeInSeconds: ").append(toIndentedString(lifetimeInSeconds)).append("\n"); + sb.append(" customState: ").append(toIndentedString(customState)).append("\n"); + sb.append(" discover: ").append(toIndentedString(discover)).append("\n"); sb.append("}"); return sb.toString(); } @@ -218,51 +264,53 @@ private String toIndentedString(Object o) { static { // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("identifier"); - openapiFields.add("type"); - openapiFields.add("redirectUri"); - openapiFields.add("lifetimeInSeconds"); + openapiFields = new HashSet(Arrays.asList("identifier", "type", "redirectUri", "lifetimeInSeconds", "customState", "discover")); // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("identifier"); - openapiRequiredFields.add("redirectUri"); + openapiRequiredFields = new HashSet(Arrays.asList("redirectUri")); } - /** - * Validates the JSON Object and throws an exception if issues found - * - * @param jsonObj JSON Object - * @throws IOException if the JSON Object is invalid with respect to ServiceSessionCreateRequest - */ - public static void validateJsonObject(JsonObject jsonObj) throws IOException { - if (jsonObj == null) { - if (!ServiceSessionCreateRequest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to ServiceSessionCreateRequest + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ServiceSessionCreateRequest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null throw new IllegalArgumentException(String.format("The required field(s) %s in ServiceSessionCreateRequest is not found in the empty JSON string", ServiceSessionCreateRequest.openapiRequiredFields.toString())); } } - Set> entries = jsonObj.entrySet(); + Set> entries = jsonElement.getAsJsonObject().entrySet(); // check to see if the JSON string contains additional fields - for (Entry entry : entries) { + for (Map.Entry entry : entries) { if (!ServiceSessionCreateRequest.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ServiceSessionCreateRequest` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ServiceSessionCreateRequest` properties. JSON: %s", entry.getKey(), jsonElement.toString())); } } // check to make sure all required properties/fields are present in the JSON string for (String requiredField : ServiceSessionCreateRequest.openapiRequiredFields) { - if (jsonObj.get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); } } - if (!jsonObj.get("identifier").isJsonPrimitive()) { + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("identifier") != null && !jsonObj.get("identifier").isJsonNull()) && !jsonObj.get("identifier").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `identifier` to be a primitive type in the JSON string but got `%s`", jsonObj.get("identifier").toString())); } + // validate the optional field `type` + if (jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) { + TrustServiceSessionTypes.validateJsonElement(jsonObj.get("type")); + } if (!jsonObj.get("redirectUri").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `redirectUri` to be a primitive type in the JSON string but got `%s`", jsonObj.get("redirectUri").toString())); } + if ((jsonObj.get("customState") != null && !jsonObj.get("customState").isJsonNull()) && !jsonObj.get("customState").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `customState` to be a primitive type in the JSON string but got `%s`", jsonObj.get("customState").toString())); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { @@ -285,31 +333,31 @@ public void write(JsonWriter out, ServiceSessionCreateRequest value) throws IOEx @Override public ServiceSessionCreateRequest read(JsonReader in) throws IOException { - JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); - validateJsonObject(jsonObj); - return thisAdapter.fromJsonTree(jsonObj); + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); } }.nullSafe(); } } - /** - * Create an instance of ServiceSessionCreateRequest given an JSON string - * - * @param jsonString JSON string - * @return An instance of ServiceSessionCreateRequest - * @throws IOException if the JSON string is invalid with respect to ServiceSessionCreateRequest - */ + /** + * Create an instance of ServiceSessionCreateRequest given an JSON string + * + * @param jsonString JSON string + * @return An instance of ServiceSessionCreateRequest + * @throws IOException if the JSON string is invalid with respect to ServiceSessionCreateRequest + */ public static ServiceSessionCreateRequest fromJson(String jsonString) throws IOException { return JSON.getGson().fromJson(jsonString, ServiceSessionCreateRequest.class); } - /** - * Convert an instance of ServiceSessionCreateRequest to an JSON string - * - * @return JSON string - */ + /** + * Convert an instance of ServiceSessionCreateRequest to an JSON string + * + * @return JSON string + */ public String toJson() { return JSON.getGson().toJson(this); } diff --git a/src/main/java/cloudhub/client/model/ServiceSessionCreateResponse.java b/src/main/java/cloudhub/client/model/ServiceSessionCreateResponse.java index efc1183..26e5a1a 100644 --- a/src/main/java/cloudhub/client/model/ServiceSessionCreateResponse.java +++ b/src/main/java/cloudhub/client/model/ServiceSessionCreateResponse.java @@ -14,7 +14,6 @@ package cloudhub.client.model; import java.util.Objects; -import java.util.Arrays; import cloudhub.client.model.TrustServiceInfoModel; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; @@ -22,6 +21,7 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; +import java.util.Arrays; import org.openapitools.jackson.nullable.JsonNullable; import com.google.gson.Gson; @@ -34,13 +34,15 @@ import com.google.gson.JsonParseException; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; -import java.lang.reflect.Type; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Set; import cloudhub.client.JSON; @@ -48,59 +50,55 @@ /** * ServiceSessionCreateResponse */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-03-24T09:46:17.287214-03:00[America/Sao_Paulo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public class ServiceSessionCreateResponse { public static final String SERIALIZED_NAME_SERVICE_INFO = "serviceInfo"; @SerializedName(SERIALIZED_NAME_SERVICE_INFO) + @javax.annotation.Nullable private TrustServiceInfoModel serviceInfo; public static final String SERIALIZED_NAME_AUTH_URL = "authUrl"; @SerializedName(SERIALIZED_NAME_AUTH_URL) + @javax.annotation.Nullable private String authUrl; public ServiceSessionCreateResponse() { } - public ServiceSessionCreateResponse serviceInfo(TrustServiceInfoModel serviceInfo) { - + public ServiceSessionCreateResponse serviceInfo(@javax.annotation.Nullable TrustServiceInfoModel serviceInfo) { this.serviceInfo = serviceInfo; return this; } - /** + /** * Get serviceInfo * @return serviceInfo - **/ + */ @javax.annotation.Nullable - public TrustServiceInfoModel getServiceInfo() { return serviceInfo; } - - public void setServiceInfo(TrustServiceInfoModel serviceInfo) { + public void setServiceInfo(@javax.annotation.Nullable TrustServiceInfoModel serviceInfo) { this.serviceInfo = serviceInfo; } - public ServiceSessionCreateResponse authUrl(String authUrl) { - + public ServiceSessionCreateResponse authUrl(@javax.annotation.Nullable String authUrl) { this.authUrl = authUrl; return this; } - /** + /** * Get authUrl * @return authUrl - **/ + */ @javax.annotation.Nullable - public String getAuthUrl() { return authUrl; } - - public void setAuthUrl(String authUrl) { + public void setAuthUrl(@javax.annotation.Nullable String authUrl) { this.authUrl = authUrl; } @@ -162,37 +160,36 @@ private String toIndentedString(Object o) { static { // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("serviceInfo"); - openapiFields.add("authUrl"); + openapiFields = new HashSet(Arrays.asList("serviceInfo", "authUrl")); // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Object and throws an exception if issues found - * - * @param jsonObj JSON Object - * @throws IOException if the JSON Object is invalid with respect to ServiceSessionCreateResponse - */ - public static void validateJsonObject(JsonObject jsonObj) throws IOException { - if (jsonObj == null) { - if (!ServiceSessionCreateResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + openapiRequiredFields = new HashSet(0); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to ServiceSessionCreateResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ServiceSessionCreateResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null throw new IllegalArgumentException(String.format("The required field(s) %s in ServiceSessionCreateResponse is not found in the empty JSON string", ServiceSessionCreateResponse.openapiRequiredFields.toString())); } } - Set> entries = jsonObj.entrySet(); + Set> entries = jsonElement.getAsJsonObject().entrySet(); // check to see if the JSON string contains additional fields - for (Entry entry : entries) { + for (Map.Entry entry : entries) { if (!ServiceSessionCreateResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ServiceSessionCreateResponse` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ServiceSessionCreateResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); } } + JsonObject jsonObj = jsonElement.getAsJsonObject(); // validate the optional field `serviceInfo` if (jsonObj.get("serviceInfo") != null && !jsonObj.get("serviceInfo").isJsonNull()) { - TrustServiceInfoModel.validateJsonObject(jsonObj.getAsJsonObject("serviceInfo")); + TrustServiceInfoModel.validateJsonElement(jsonObj.get("serviceInfo")); } if ((jsonObj.get("authUrl") != null && !jsonObj.get("authUrl").isJsonNull()) && !jsonObj.get("authUrl").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `authUrl` to be a primitive type in the JSON string but got `%s`", jsonObj.get("authUrl").toString())); @@ -219,31 +216,31 @@ public void write(JsonWriter out, ServiceSessionCreateResponse value) throws IOE @Override public ServiceSessionCreateResponse read(JsonReader in) throws IOException { - JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); - validateJsonObject(jsonObj); - return thisAdapter.fromJsonTree(jsonObj); + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); } }.nullSafe(); } } - /** - * Create an instance of ServiceSessionCreateResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of ServiceSessionCreateResponse - * @throws IOException if the JSON string is invalid with respect to ServiceSessionCreateResponse - */ + /** + * Create an instance of ServiceSessionCreateResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of ServiceSessionCreateResponse + * @throws IOException if the JSON string is invalid with respect to ServiceSessionCreateResponse + */ public static ServiceSessionCreateResponse fromJson(String jsonString) throws IOException { return JSON.getGson().fromJson(jsonString, ServiceSessionCreateResponse.class); } - /** - * Convert an instance of ServiceSessionCreateResponse to an JSON string - * - * @return JSON string - */ + /** + * Convert an instance of ServiceSessionCreateResponse to an JSON string + * + * @return JSON string + */ public String toJson() { return JSON.getGson().toJson(this); } diff --git a/src/main/java/cloudhub/client/model/SessionCreateRequest.java b/src/main/java/cloudhub/client/model/SessionCreateRequest.java index 4fde76a..5d5500e 100644 --- a/src/main/java/cloudhub/client/model/SessionCreateRequest.java +++ b/src/main/java/cloudhub/client/model/SessionCreateRequest.java @@ -14,7 +14,6 @@ package cloudhub.client.model; import java.util.Objects; -import java.util.Arrays; import cloudhub.client.model.IdentifierTypes; import cloudhub.client.model.TrustServiceSessionTypes; import com.google.gson.TypeAdapter; @@ -23,6 +22,7 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; +import java.util.Arrays; import org.openapitools.jackson.nullable.JsonNullable; import com.google.gson.Gson; @@ -35,13 +35,15 @@ import com.google.gson.JsonParseException; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; -import java.lang.reflect.Type; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Set; import cloudhub.client.JSON; @@ -49,141 +51,179 @@ /** * SessionCreateRequest */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-03-24T09:46:17.287214-03:00[America/Sao_Paulo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public class SessionCreateRequest { public static final String SERIALIZED_NAME_IDENTIFIER_TYPE = "identifierType"; @SerializedName(SERIALIZED_NAME_IDENTIFIER_TYPE) + @javax.annotation.Nullable private IdentifierTypes identifierType; public static final String SERIALIZED_NAME_IDENTIFIER = "identifier"; @SerializedName(SERIALIZED_NAME_IDENTIFIER) + @javax.annotation.Nullable private String identifier; public static final String SERIALIZED_NAME_TYPE = "type"; @SerializedName(SERIALIZED_NAME_TYPE) + @javax.annotation.Nullable private TrustServiceSessionTypes type; public static final String SERIALIZED_NAME_REDIRECT_URI = "redirectUri"; @SerializedName(SERIALIZED_NAME_REDIRECT_URI) + @javax.annotation.Nonnull private String redirectUri; public static final String SERIALIZED_NAME_LIFETIME_IN_SECONDS = "lifetimeInSeconds"; @SerializedName(SERIALIZED_NAME_LIFETIME_IN_SECONDS) + @javax.annotation.Nullable private Integer lifetimeInSeconds; + public static final String SERIALIZED_NAME_CUSTOM_STATE = "customState"; + @SerializedName(SERIALIZED_NAME_CUSTOM_STATE) + @javax.annotation.Nullable + private String customState; + + public static final String SERIALIZED_NAME_DISCOVER = "discover"; + @SerializedName(SERIALIZED_NAME_DISCOVER) + @javax.annotation.Nullable + private Boolean discover; + public SessionCreateRequest() { } - public SessionCreateRequest identifierType(IdentifierTypes identifierType) { - + public SessionCreateRequest identifierType(@javax.annotation.Nullable IdentifierTypes identifierType) { this.identifierType = identifierType; return this; } - /** + /** * Get identifierType * @return identifierType - **/ + */ @javax.annotation.Nullable - public IdentifierTypes getIdentifierType() { return identifierType; } - - public void setIdentifierType(IdentifierTypes identifierType) { + public void setIdentifierType(@javax.annotation.Nullable IdentifierTypes identifierType) { this.identifierType = identifierType; } - public SessionCreateRequest identifier(String identifier) { - + public SessionCreateRequest identifier(@javax.annotation.Nullable String identifier) { this.identifier = identifier; return this; } - /** + /** * Get identifier * @return identifier - **/ - @javax.annotation.Nonnull - + */ + @javax.annotation.Nullable public String getIdentifier() { return identifier; } - - public void setIdentifier(String identifier) { + public void setIdentifier(@javax.annotation.Nullable String identifier) { this.identifier = identifier; } - public SessionCreateRequest type(TrustServiceSessionTypes type) { - + public SessionCreateRequest type(@javax.annotation.Nullable TrustServiceSessionTypes type) { this.type = type; return this; } - /** + /** * Get type * @return type - **/ + */ @javax.annotation.Nullable - public TrustServiceSessionTypes getType() { return type; } - - public void setType(TrustServiceSessionTypes type) { + public void setType(@javax.annotation.Nullable TrustServiceSessionTypes type) { this.type = type; } - public SessionCreateRequest redirectUri(String redirectUri) { - + public SessionCreateRequest redirectUri(@javax.annotation.Nonnull String redirectUri) { this.redirectUri = redirectUri; return this; } - /** + /** * Get redirectUri * @return redirectUri - **/ + */ @javax.annotation.Nonnull - public String getRedirectUri() { return redirectUri; } - - public void setRedirectUri(String redirectUri) { + public void setRedirectUri(@javax.annotation.Nonnull String redirectUri) { this.redirectUri = redirectUri; } - public SessionCreateRequest lifetimeInSeconds(Integer lifetimeInSeconds) { - + public SessionCreateRequest lifetimeInSeconds(@javax.annotation.Nullable Integer lifetimeInSeconds) { this.lifetimeInSeconds = lifetimeInSeconds; return this; } - /** + /** * Get lifetimeInSeconds * @return lifetimeInSeconds - **/ + */ @javax.annotation.Nullable - public Integer getLifetimeInSeconds() { return lifetimeInSeconds; } - - public void setLifetimeInSeconds(Integer lifetimeInSeconds) { + public void setLifetimeInSeconds(@javax.annotation.Nullable Integer lifetimeInSeconds) { this.lifetimeInSeconds = lifetimeInSeconds; } + public SessionCreateRequest customState(@javax.annotation.Nullable String customState) { + this.customState = customState; + return this; + } + + /** + * Get customState + * @return customState + */ + @javax.annotation.Nullable + public String getCustomState() { + return customState; + } + + public void setCustomState(@javax.annotation.Nullable String customState) { + this.customState = customState; + } + + + public SessionCreateRequest discover(@javax.annotation.Nullable Boolean discover) { + this.discover = discover; + return this; + } + + /** + * Get discover + * @return discover + */ + @javax.annotation.Nullable + public Boolean getDiscover() { + return discover; + } + + public void setDiscover(@javax.annotation.Nullable Boolean discover) { + this.discover = discover; + } + + @Override public boolean equals(Object o) { @@ -198,7 +238,9 @@ public boolean equals(Object o) { Objects.equals(this.identifier, sessionCreateRequest.identifier) && Objects.equals(this.type, sessionCreateRequest.type) && Objects.equals(this.redirectUri, sessionCreateRequest.redirectUri) && - Objects.equals(this.lifetimeInSeconds, sessionCreateRequest.lifetimeInSeconds); + Objects.equals(this.lifetimeInSeconds, sessionCreateRequest.lifetimeInSeconds) && + Objects.equals(this.customState, sessionCreateRequest.customState) && + Objects.equals(this.discover, sessionCreateRequest.discover); } private static boolean equalsNullable(JsonNullable a, JsonNullable b) { @@ -207,7 +249,7 @@ private static boolean equalsNullable(JsonNullable a, JsonNullable b) @Override public int hashCode() { - return Objects.hash(identifierType, identifier, type, redirectUri, lifetimeInSeconds); + return Objects.hash(identifierType, identifier, type, redirectUri, lifetimeInSeconds, customState, discover); } private static int hashCodeNullable(JsonNullable a) { @@ -226,6 +268,8 @@ public String toString() { sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" redirectUri: ").append(toIndentedString(redirectUri)).append("\n"); sb.append(" lifetimeInSeconds: ").append(toIndentedString(lifetimeInSeconds)).append("\n"); + sb.append(" customState: ").append(toIndentedString(customState)).append("\n"); + sb.append(" discover: ").append(toIndentedString(discover)).append("\n"); sb.append("}"); return sb.toString(); } @@ -247,52 +291,57 @@ private String toIndentedString(Object o) { static { // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("identifierType"); - openapiFields.add("identifier"); - openapiFields.add("type"); - openapiFields.add("redirectUri"); - openapiFields.add("lifetimeInSeconds"); + openapiFields = new HashSet(Arrays.asList("identifierType", "identifier", "type", "redirectUri", "lifetimeInSeconds", "customState", "discover")); // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("identifier"); - openapiRequiredFields.add("redirectUri"); - } - - /** - * Validates the JSON Object and throws an exception if issues found - * - * @param jsonObj JSON Object - * @throws IOException if the JSON Object is invalid with respect to SessionCreateRequest - */ - public static void validateJsonObject(JsonObject jsonObj) throws IOException { - if (jsonObj == null) { - if (!SessionCreateRequest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + openapiRequiredFields = new HashSet(Arrays.asList("redirectUri")); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to SessionCreateRequest + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!SessionCreateRequest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null throw new IllegalArgumentException(String.format("The required field(s) %s in SessionCreateRequest is not found in the empty JSON string", SessionCreateRequest.openapiRequiredFields.toString())); } } - Set> entries = jsonObj.entrySet(); + Set> entries = jsonElement.getAsJsonObject().entrySet(); // check to see if the JSON string contains additional fields - for (Entry entry : entries) { + for (Map.Entry entry : entries) { if (!SessionCreateRequest.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SessionCreateRequest` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SessionCreateRequest` properties. JSON: %s", entry.getKey(), jsonElement.toString())); } } // check to make sure all required properties/fields are present in the JSON string for (String requiredField : SessionCreateRequest.openapiRequiredFields) { - if (jsonObj.get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); } } - if (!jsonObj.get("identifier").isJsonPrimitive()) { + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `identifierType` + if (jsonObj.get("identifierType") != null && !jsonObj.get("identifierType").isJsonNull()) { + IdentifierTypes.validateJsonElement(jsonObj.get("identifierType")); + } + if ((jsonObj.get("identifier") != null && !jsonObj.get("identifier").isJsonNull()) && !jsonObj.get("identifier").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `identifier` to be a primitive type in the JSON string but got `%s`", jsonObj.get("identifier").toString())); } + // validate the optional field `type` + if (jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) { + TrustServiceSessionTypes.validateJsonElement(jsonObj.get("type")); + } if (!jsonObj.get("redirectUri").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `redirectUri` to be a primitive type in the JSON string but got `%s`", jsonObj.get("redirectUri").toString())); } + if ((jsonObj.get("customState") != null && !jsonObj.get("customState").isJsonNull()) && !jsonObj.get("customState").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `customState` to be a primitive type in the JSON string but got `%s`", jsonObj.get("customState").toString())); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { @@ -315,31 +364,31 @@ public void write(JsonWriter out, SessionCreateRequest value) throws IOException @Override public SessionCreateRequest read(JsonReader in) throws IOException { - JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); - validateJsonObject(jsonObj); - return thisAdapter.fromJsonTree(jsonObj); + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); } }.nullSafe(); } } - /** - * Create an instance of SessionCreateRequest given an JSON string - * - * @param jsonString JSON string - * @return An instance of SessionCreateRequest - * @throws IOException if the JSON string is invalid with respect to SessionCreateRequest - */ + /** + * Create an instance of SessionCreateRequest given an JSON string + * + * @param jsonString JSON string + * @return An instance of SessionCreateRequest + * @throws IOException if the JSON string is invalid with respect to SessionCreateRequest + */ public static SessionCreateRequest fromJson(String jsonString) throws IOException { return JSON.getGson().fromJson(jsonString, SessionCreateRequest.class); } - /** - * Convert an instance of SessionCreateRequest to an JSON string - * - * @return JSON string - */ + /** + * Convert an instance of SessionCreateRequest to an JSON string + * + * @return JSON string + */ public String toJson() { return JSON.getGson().toJson(this); } diff --git a/src/main/java/cloudhub/client/model/SessionModel.java b/src/main/java/cloudhub/client/model/SessionModel.java index a76009c..3ee82ec 100644 --- a/src/main/java/cloudhub/client/model/SessionModel.java +++ b/src/main/java/cloudhub/client/model/SessionModel.java @@ -14,7 +14,6 @@ package cloudhub.client.model; import java.util.Objects; -import java.util.Arrays; import cloudhub.client.model.TrustServiceAuthParametersModel; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; @@ -23,6 +22,7 @@ import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import org.openapitools.jackson.nullable.JsonNullable; @@ -36,13 +36,15 @@ import com.google.gson.JsonParseException; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; -import java.lang.reflect.Type; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Set; import cloudhub.client.JSON; @@ -50,41 +52,39 @@ /** * SessionModel */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-03-24T09:46:17.287214-03:00[America/Sao_Paulo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public class SessionModel { public static final String SERIALIZED_NAME_SERVICES = "services"; @SerializedName(SERIALIZED_NAME_SERVICES) - private List services = null; + @javax.annotation.Nullable + private List services; public SessionModel() { } - public SessionModel services(List services) { - + public SessionModel services(@javax.annotation.Nullable List services) { this.services = services; return this; } public SessionModel addServicesItem(TrustServiceAuthParametersModel servicesItem) { if (this.services == null) { - this.services = null; + this.services = new ArrayList<>(); } this.services.add(servicesItem); return this; } - /** + /** * Get services * @return services - **/ + */ @javax.annotation.Nullable - public List getServices() { return services; } - - public void setServices(List services) { + public void setServices(@javax.annotation.Nullable List services) { this.services = services; } @@ -144,33 +144,33 @@ private String toIndentedString(Object o) { static { // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("services"); + openapiFields = new HashSet(Arrays.asList("services")); // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Object and throws an exception if issues found - * - * @param jsonObj JSON Object - * @throws IOException if the JSON Object is invalid with respect to SessionModel - */ - public static void validateJsonObject(JsonObject jsonObj) throws IOException { - if (jsonObj == null) { - if (!SessionModel.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + openapiRequiredFields = new HashSet(0); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to SessionModel + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!SessionModel.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null throw new IllegalArgumentException(String.format("The required field(s) %s in SessionModel is not found in the empty JSON string", SessionModel.openapiRequiredFields.toString())); } } - Set> entries = jsonObj.entrySet(); + Set> entries = jsonElement.getAsJsonObject().entrySet(); // check to see if the JSON string contains additional fields - for (Entry entry : entries) { + for (Map.Entry entry : entries) { if (!SessionModel.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SessionModel` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SessionModel` properties. JSON: %s", entry.getKey(), jsonElement.toString())); } } + JsonObject jsonObj = jsonElement.getAsJsonObject(); if (jsonObj.get("services") != null && !jsonObj.get("services").isJsonNull()) { JsonArray jsonArrayservices = jsonObj.getAsJsonArray("services"); if (jsonArrayservices != null) { @@ -181,7 +181,7 @@ public static void validateJsonObject(JsonObject jsonObj) throws IOException { // validate the optional field `services` (array) for (int i = 0; i < jsonArrayservices.size(); i++) { - TrustServiceAuthParametersModel.validateJsonObject(jsonArrayservices.get(i).getAsJsonObject()); + TrustServiceAuthParametersModel.validateJsonElement(jsonArrayservices.get(i)); }; } } @@ -207,31 +207,31 @@ public void write(JsonWriter out, SessionModel value) throws IOException { @Override public SessionModel read(JsonReader in) throws IOException { - JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); - validateJsonObject(jsonObj); - return thisAdapter.fromJsonTree(jsonObj); + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); } }.nullSafe(); } } - /** - * Create an instance of SessionModel given an JSON string - * - * @param jsonString JSON string - * @return An instance of SessionModel - * @throws IOException if the JSON string is invalid with respect to SessionModel - */ + /** + * Create an instance of SessionModel given an JSON string + * + * @param jsonString JSON string + * @return An instance of SessionModel + * @throws IOException if the JSON string is invalid with respect to SessionModel + */ public static SessionModel fromJson(String jsonString) throws IOException { return JSON.getGson().fromJson(jsonString, SessionModel.class); } - /** - * Convert an instance of SessionModel to an JSON string - * - * @return JSON string - */ + /** + * Convert an instance of SessionModel to an JSON string + * + * @return JSON string + */ public String toJson() { return JSON.getGson().toJson(this); } diff --git a/src/main/java/cloudhub/client/model/SignHashRequest.java b/src/main/java/cloudhub/client/model/SignHashRequest.java index 05af151..1455b3d 100644 --- a/src/main/java/cloudhub/client/model/SignHashRequest.java +++ b/src/main/java/cloudhub/client/model/SignHashRequest.java @@ -14,13 +14,13 @@ package cloudhub.client.model; import java.util.Objects; -import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; +import java.util.Arrays; import org.openapitools.jackson.nullable.JsonNullable; import com.google.gson.Gson; @@ -33,13 +33,15 @@ import com.google.gson.JsonParseException; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; -import java.lang.reflect.Type; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Set; import cloudhub.client.JSON; @@ -47,137 +49,127 @@ /** * SignHashRequest */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-03-24T09:46:17.287214-03:00[America/Sao_Paulo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public class SignHashRequest { public static final String SERIALIZED_NAME_SESSION = "session"; @SerializedName(SERIALIZED_NAME_SESSION) + @javax.annotation.Nonnull private String session; public static final String SERIALIZED_NAME_HASH = "hash"; @SerializedName(SERIALIZED_NAME_HASH) + @javax.annotation.Nonnull private byte[] hash; public static final String SERIALIZED_NAME_DIGEST_ALGORITHM = "digestAlgorithm"; @SerializedName(SERIALIZED_NAME_DIGEST_ALGORITHM) + @javax.annotation.Nullable private String digestAlgorithm; public static final String SERIALIZED_NAME_DIGEST_ALGORITHM_OID = "digestAlgorithmOid"; @SerializedName(SERIALIZED_NAME_DIGEST_ALGORITHM_OID) + @javax.annotation.Nullable private String digestAlgorithmOid; public static final String SERIALIZED_NAME_CERTIFICATE_ALIAS = "certificateAlias"; @SerializedName(SERIALIZED_NAME_CERTIFICATE_ALIAS) + @javax.annotation.Nullable private String certificateAlias; public SignHashRequest() { } - public SignHashRequest session(String session) { - + public SignHashRequest session(@javax.annotation.Nonnull String session) { this.session = session; return this; } - /** + /** * Get session * @return session - **/ + */ @javax.annotation.Nonnull - public String getSession() { return session; } - - public void setSession(String session) { + public void setSession(@javax.annotation.Nonnull String session) { this.session = session; } - public SignHashRequest hash(byte[] hash) { - + public SignHashRequest hash(@javax.annotation.Nonnull byte[] hash) { this.hash = hash; return this; } - /** + /** * Get hash * @return hash - **/ + */ @javax.annotation.Nonnull - public byte[] getHash() { return hash; } - - public void setHash(byte[] hash) { + public void setHash(@javax.annotation.Nonnull byte[] hash) { this.hash = hash; } - public SignHashRequest digestAlgorithm(String digestAlgorithm) { - + public SignHashRequest digestAlgorithm(@javax.annotation.Nullable String digestAlgorithm) { this.digestAlgorithm = digestAlgorithm; return this; } - /** + /** * Get digestAlgorithm * @return digestAlgorithm - **/ + */ @javax.annotation.Nullable - public String getDigestAlgorithm() { return digestAlgorithm; } - - public void setDigestAlgorithm(String digestAlgorithm) { + public void setDigestAlgorithm(@javax.annotation.Nullable String digestAlgorithm) { this.digestAlgorithm = digestAlgorithm; } - public SignHashRequest digestAlgorithmOid(String digestAlgorithmOid) { - + public SignHashRequest digestAlgorithmOid(@javax.annotation.Nullable String digestAlgorithmOid) { this.digestAlgorithmOid = digestAlgorithmOid; return this; } - /** + /** * Get digestAlgorithmOid * @return digestAlgorithmOid - **/ + */ @javax.annotation.Nullable - public String getDigestAlgorithmOid() { return digestAlgorithmOid; } - - public void setDigestAlgorithmOid(String digestAlgorithmOid) { + public void setDigestAlgorithmOid(@javax.annotation.Nullable String digestAlgorithmOid) { this.digestAlgorithmOid = digestAlgorithmOid; } - public SignHashRequest certificateAlias(String certificateAlias) { - + public SignHashRequest certificateAlias(@javax.annotation.Nullable String certificateAlias) { this.certificateAlias = certificateAlias; return this; } - /** + /** * Get certificateAlias * @return certificateAlias - **/ + */ @javax.annotation.Nullable - public String getCertificateAlias() { return certificateAlias; } - - public void setCertificateAlias(String certificateAlias) { + public void setCertificateAlias(@javax.annotation.Nullable String certificateAlias) { this.certificateAlias = certificateAlias; } @@ -245,46 +237,40 @@ private String toIndentedString(Object o) { static { // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("session"); - openapiFields.add("hash"); - openapiFields.add("digestAlgorithm"); - openapiFields.add("digestAlgorithmOid"); - openapiFields.add("certificateAlias"); + openapiFields = new HashSet(Arrays.asList("session", "hash", "digestAlgorithm", "digestAlgorithmOid", "certificateAlias")); // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("session"); - openapiRequiredFields.add("hash"); + openapiRequiredFields = new HashSet(Arrays.asList("session", "hash")); } - /** - * Validates the JSON Object and throws an exception if issues found - * - * @param jsonObj JSON Object - * @throws IOException if the JSON Object is invalid with respect to SignHashRequest - */ - public static void validateJsonObject(JsonObject jsonObj) throws IOException { - if (jsonObj == null) { - if (!SignHashRequest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to SignHashRequest + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!SignHashRequest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null throw new IllegalArgumentException(String.format("The required field(s) %s in SignHashRequest is not found in the empty JSON string", SignHashRequest.openapiRequiredFields.toString())); } } - Set> entries = jsonObj.entrySet(); + Set> entries = jsonElement.getAsJsonObject().entrySet(); // check to see if the JSON string contains additional fields - for (Entry entry : entries) { + for (Map.Entry entry : entries) { if (!SignHashRequest.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SignHashRequest` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SignHashRequest` properties. JSON: %s", entry.getKey(), jsonElement.toString())); } } // check to make sure all required properties/fields are present in the JSON string for (String requiredField : SignHashRequest.openapiRequiredFields) { - if (jsonObj.get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); } } + JsonObject jsonObj = jsonElement.getAsJsonObject(); if (!jsonObj.get("session").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `session` to be a primitive type in the JSON string but got `%s`", jsonObj.get("session").toString())); } @@ -319,31 +305,31 @@ public void write(JsonWriter out, SignHashRequest value) throws IOException { @Override public SignHashRequest read(JsonReader in) throws IOException { - JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); - validateJsonObject(jsonObj); - return thisAdapter.fromJsonTree(jsonObj); + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); } }.nullSafe(); } } - /** - * Create an instance of SignHashRequest given an JSON string - * - * @param jsonString JSON string - * @return An instance of SignHashRequest - * @throws IOException if the JSON string is invalid with respect to SignHashRequest - */ + /** + * Create an instance of SignHashRequest given an JSON string + * + * @param jsonString JSON string + * @return An instance of SignHashRequest + * @throws IOException if the JSON string is invalid with respect to SignHashRequest + */ public static SignHashRequest fromJson(String jsonString) throws IOException { return JSON.getGson().fromJson(jsonString, SignHashRequest.class); } - /** - * Convert an instance of SignHashRequest to an JSON string - * - * @return JSON string - */ + /** + * Convert an instance of SignHashRequest to an JSON string + * + * @return JSON string + */ public String toJson() { return JSON.getGson().toJson(this); } diff --git a/src/main/java/cloudhub/client/model/TrustServiceAuthParametersModel.java b/src/main/java/cloudhub/client/model/TrustServiceAuthParametersModel.java index a8dc453..def8cc9 100644 --- a/src/main/java/cloudhub/client/model/TrustServiceAuthParametersModel.java +++ b/src/main/java/cloudhub/client/model/TrustServiceAuthParametersModel.java @@ -14,7 +14,6 @@ package cloudhub.client.model; import java.util.Objects; -import java.util.Arrays; import cloudhub.client.model.TrustServiceInfoModel; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; @@ -22,6 +21,7 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; +import java.util.Arrays; import org.openapitools.jackson.nullable.JsonNullable; import com.google.gson.Gson; @@ -34,13 +34,15 @@ import com.google.gson.JsonParseException; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; -import java.lang.reflect.Type; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Set; import cloudhub.client.JSON; @@ -48,59 +50,55 @@ /** * TrustServiceAuthParametersModel */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-03-24T09:46:17.287214-03:00[America/Sao_Paulo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public class TrustServiceAuthParametersModel { public static final String SERIALIZED_NAME_SERVICE_INFO = "serviceInfo"; @SerializedName(SERIALIZED_NAME_SERVICE_INFO) + @javax.annotation.Nullable private TrustServiceInfoModel serviceInfo; public static final String SERIALIZED_NAME_AUTH_URL = "authUrl"; @SerializedName(SERIALIZED_NAME_AUTH_URL) + @javax.annotation.Nullable private String authUrl; public TrustServiceAuthParametersModel() { } - public TrustServiceAuthParametersModel serviceInfo(TrustServiceInfoModel serviceInfo) { - + public TrustServiceAuthParametersModel serviceInfo(@javax.annotation.Nullable TrustServiceInfoModel serviceInfo) { this.serviceInfo = serviceInfo; return this; } - /** + /** * Get serviceInfo * @return serviceInfo - **/ + */ @javax.annotation.Nullable - public TrustServiceInfoModel getServiceInfo() { return serviceInfo; } - - public void setServiceInfo(TrustServiceInfoModel serviceInfo) { + public void setServiceInfo(@javax.annotation.Nullable TrustServiceInfoModel serviceInfo) { this.serviceInfo = serviceInfo; } - public TrustServiceAuthParametersModel authUrl(String authUrl) { - + public TrustServiceAuthParametersModel authUrl(@javax.annotation.Nullable String authUrl) { this.authUrl = authUrl; return this; } - /** + /** * Get authUrl * @return authUrl - **/ + */ @javax.annotation.Nullable - public String getAuthUrl() { return authUrl; } - - public void setAuthUrl(String authUrl) { + public void setAuthUrl(@javax.annotation.Nullable String authUrl) { this.authUrl = authUrl; } @@ -162,37 +160,36 @@ private String toIndentedString(Object o) { static { // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("serviceInfo"); - openapiFields.add("authUrl"); + openapiFields = new HashSet(Arrays.asList("serviceInfo", "authUrl")); // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Object and throws an exception if issues found - * - * @param jsonObj JSON Object - * @throws IOException if the JSON Object is invalid with respect to TrustServiceAuthParametersModel - */ - public static void validateJsonObject(JsonObject jsonObj) throws IOException { - if (jsonObj == null) { - if (!TrustServiceAuthParametersModel.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + openapiRequiredFields = new HashSet(0); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to TrustServiceAuthParametersModel + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!TrustServiceAuthParametersModel.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null throw new IllegalArgumentException(String.format("The required field(s) %s in TrustServiceAuthParametersModel is not found in the empty JSON string", TrustServiceAuthParametersModel.openapiRequiredFields.toString())); } } - Set> entries = jsonObj.entrySet(); + Set> entries = jsonElement.getAsJsonObject().entrySet(); // check to see if the JSON string contains additional fields - for (Entry entry : entries) { + for (Map.Entry entry : entries) { if (!TrustServiceAuthParametersModel.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `TrustServiceAuthParametersModel` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `TrustServiceAuthParametersModel` properties. JSON: %s", entry.getKey(), jsonElement.toString())); } } + JsonObject jsonObj = jsonElement.getAsJsonObject(); // validate the optional field `serviceInfo` if (jsonObj.get("serviceInfo") != null && !jsonObj.get("serviceInfo").isJsonNull()) { - TrustServiceInfoModel.validateJsonObject(jsonObj.getAsJsonObject("serviceInfo")); + TrustServiceInfoModel.validateJsonElement(jsonObj.get("serviceInfo")); } if ((jsonObj.get("authUrl") != null && !jsonObj.get("authUrl").isJsonNull()) && !jsonObj.get("authUrl").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `authUrl` to be a primitive type in the JSON string but got `%s`", jsonObj.get("authUrl").toString())); @@ -219,31 +216,31 @@ public void write(JsonWriter out, TrustServiceAuthParametersModel value) throws @Override public TrustServiceAuthParametersModel read(JsonReader in) throws IOException { - JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); - validateJsonObject(jsonObj); - return thisAdapter.fromJsonTree(jsonObj); + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); } }.nullSafe(); } } - /** - * Create an instance of TrustServiceAuthParametersModel given an JSON string - * - * @param jsonString JSON string - * @return An instance of TrustServiceAuthParametersModel - * @throws IOException if the JSON string is invalid with respect to TrustServiceAuthParametersModel - */ + /** + * Create an instance of TrustServiceAuthParametersModel given an JSON string + * + * @param jsonString JSON string + * @return An instance of TrustServiceAuthParametersModel + * @throws IOException if the JSON string is invalid with respect to TrustServiceAuthParametersModel + */ public static TrustServiceAuthParametersModel fromJson(String jsonString) throws IOException { return JSON.getGson().fromJson(jsonString, TrustServiceAuthParametersModel.class); } - /** - * Convert an instance of TrustServiceAuthParametersModel to an JSON string - * - * @return JSON string - */ + /** + * Convert an instance of TrustServiceAuthParametersModel to an JSON string + * + * @return JSON string + */ public String toJson() { return JSON.getGson().toJson(this); } diff --git a/src/main/java/cloudhub/client/model/TrustServiceInfoModel.java b/src/main/java/cloudhub/client/model/TrustServiceInfoModel.java index 7713840..3416753 100644 --- a/src/main/java/cloudhub/client/model/TrustServiceInfoModel.java +++ b/src/main/java/cloudhub/client/model/TrustServiceInfoModel.java @@ -14,13 +14,13 @@ package cloudhub.client.model; import java.util.Objects; -import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; +import java.util.Arrays; import org.openapitools.jackson.nullable.JsonNullable; import com.google.gson.Gson; @@ -33,13 +33,15 @@ import com.google.gson.JsonParseException; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; -import java.lang.reflect.Type; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Set; import cloudhub.client.JSON; @@ -47,111 +49,103 @@ /** * TrustServiceInfoModel */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-03-24T09:46:17.287214-03:00[America/Sao_Paulo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0") public class TrustServiceInfoModel { public static final String SERIALIZED_NAME_SERVICE_NAME = "serviceName"; @SerializedName(SERIALIZED_NAME_SERVICE_NAME) + @javax.annotation.Nullable private String serviceName; public static final String SERIALIZED_NAME_PROVIDER = "provider"; @SerializedName(SERIALIZED_NAME_PROVIDER) + @javax.annotation.Nullable private String provider; public static final String SERIALIZED_NAME_ENDPOINT = "endpoint"; @SerializedName(SERIALIZED_NAME_ENDPOINT) + @javax.annotation.Nullable private String endpoint; public static final String SERIALIZED_NAME_BADGE_URL = "badgeUrl"; @SerializedName(SERIALIZED_NAME_BADGE_URL) + @javax.annotation.Nullable private String badgeUrl; public TrustServiceInfoModel() { } - public TrustServiceInfoModel serviceName(String serviceName) { - + public TrustServiceInfoModel serviceName(@javax.annotation.Nullable String serviceName) { this.serviceName = serviceName; return this; } - /** + /** * Get serviceName * @return serviceName - **/ + */ @javax.annotation.Nullable - public String getServiceName() { return serviceName; } - - public void setServiceName(String serviceName) { + public void setServiceName(@javax.annotation.Nullable String serviceName) { this.serviceName = serviceName; } - public TrustServiceInfoModel provider(String provider) { - + public TrustServiceInfoModel provider(@javax.annotation.Nullable String provider) { this.provider = provider; return this; } - /** + /** * Get provider * @return provider - **/ + */ @javax.annotation.Nullable - public String getProvider() { return provider; } - - public void setProvider(String provider) { + public void setProvider(@javax.annotation.Nullable String provider) { this.provider = provider; } - public TrustServiceInfoModel endpoint(String endpoint) { - + public TrustServiceInfoModel endpoint(@javax.annotation.Nullable String endpoint) { this.endpoint = endpoint; return this; } - /** + /** * Get endpoint * @return endpoint - **/ + */ @javax.annotation.Nullable - public String getEndpoint() { return endpoint; } - - public void setEndpoint(String endpoint) { + public void setEndpoint(@javax.annotation.Nullable String endpoint) { this.endpoint = endpoint; } - public TrustServiceInfoModel badgeUrl(String badgeUrl) { - + public TrustServiceInfoModel badgeUrl(@javax.annotation.Nullable String badgeUrl) { this.badgeUrl = badgeUrl; return this; } - /** + /** * Get badgeUrl * @return badgeUrl - **/ + */ @javax.annotation.Nullable - public String getBadgeUrl() { return badgeUrl; } - - public void setBadgeUrl(String badgeUrl) { + public void setBadgeUrl(@javax.annotation.Nullable String badgeUrl) { this.badgeUrl = badgeUrl; } @@ -217,36 +211,33 @@ private String toIndentedString(Object o) { static { // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("serviceName"); - openapiFields.add("provider"); - openapiFields.add("endpoint"); - openapiFields.add("badgeUrl"); + openapiFields = new HashSet(Arrays.asList("serviceName", "provider", "endpoint", "badgeUrl")); // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); + openapiRequiredFields = new HashSet(0); } - /** - * Validates the JSON Object and throws an exception if issues found - * - * @param jsonObj JSON Object - * @throws IOException if the JSON Object is invalid with respect to TrustServiceInfoModel - */ - public static void validateJsonObject(JsonObject jsonObj) throws IOException { - if (jsonObj == null) { - if (!TrustServiceInfoModel.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to TrustServiceInfoModel + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!TrustServiceInfoModel.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null throw new IllegalArgumentException(String.format("The required field(s) %s in TrustServiceInfoModel is not found in the empty JSON string", TrustServiceInfoModel.openapiRequiredFields.toString())); } } - Set> entries = jsonObj.entrySet(); + Set> entries = jsonElement.getAsJsonObject().entrySet(); // check to see if the JSON string contains additional fields - for (Entry entry : entries) { + for (Map.Entry entry : entries) { if (!TrustServiceInfoModel.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `TrustServiceInfoModel` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `TrustServiceInfoModel` properties. JSON: %s", entry.getKey(), jsonElement.toString())); } } + JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("serviceName") != null && !jsonObj.get("serviceName").isJsonNull()) && !jsonObj.get("serviceName").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `serviceName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("serviceName").toString())); } @@ -281,31 +272,31 @@ public void write(JsonWriter out, TrustServiceInfoModel value) throws IOExceptio @Override public TrustServiceInfoModel read(JsonReader in) throws IOException { - JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); - validateJsonObject(jsonObj); - return thisAdapter.fromJsonTree(jsonObj); + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); } }.nullSafe(); } } - /** - * Create an instance of TrustServiceInfoModel given an JSON string - * - * @param jsonString JSON string - * @return An instance of TrustServiceInfoModel - * @throws IOException if the JSON string is invalid with respect to TrustServiceInfoModel - */ + /** + * Create an instance of TrustServiceInfoModel given an JSON string + * + * @param jsonString JSON string + * @return An instance of TrustServiceInfoModel + * @throws IOException if the JSON string is invalid with respect to TrustServiceInfoModel + */ public static TrustServiceInfoModel fromJson(String jsonString) throws IOException { return JSON.getGson().fromJson(jsonString, TrustServiceInfoModel.class); } - /** - * Convert an instance of TrustServiceInfoModel to an JSON string - * - * @return JSON string - */ + /** + * Convert an instance of TrustServiceInfoModel to an JSON string + * + * @return JSON string + */ public String toJson() { return JSON.getGson().toJson(this); } diff --git a/src/main/java/cloudhub/client/model/TrustServiceSessionTypes.java b/src/main/java/cloudhub/client/model/TrustServiceSessionTypes.java index 0bf630d..8429a70 100644 --- a/src/main/java/cloudhub/client/model/TrustServiceSessionTypes.java +++ b/src/main/java/cloudhub/client/model/TrustServiceSessionTypes.java @@ -14,11 +14,11 @@ package cloudhub.client.model; import java.util.Objects; -import java.util.Arrays; import com.google.gson.annotations.SerializedName; import java.io.IOException; import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; @@ -29,21 +29,21 @@ @JsonAdapter(TrustServiceSessionTypes.Adapter.class) public enum TrustServiceSessionTypes { - SINGLE_SIGNATURE(1), + SINGLE_SIGNATURE("SingleSignature"), - MULTI_SIGNATURE(2), + MULTI_SIGNATURE("MultiSignature"), - SIGNATURE_SESSION(3), + SIGNATURE_SESSION("SignatureSession"), - AUTHENTICATION_SESSION(4); + AUTHENTICATION_SESSION("AuthenticationSession"); - private Integer value; + private String value; - TrustServiceSessionTypes(Integer value) { + TrustServiceSessionTypes(String value) { this.value = value; } - public Integer getValue() { + public String getValue() { return value; } @@ -52,7 +52,7 @@ public String toString() { return String.valueOf(value); } - public static TrustServiceSessionTypes fromValue(Integer value) { + public static TrustServiceSessionTypes fromValue(String value) { for (TrustServiceSessionTypes b : TrustServiceSessionTypes.values()) { if (b.value.equals(value)) { return b; @@ -69,9 +69,14 @@ public void write(final JsonWriter jsonWriter, final TrustServiceSessionTypes en @Override public TrustServiceSessionTypes read(final JsonReader jsonReader) throws IOException { - Integer value = jsonReader.nextInt(); + String value = jsonReader.nextString(); return TrustServiceSessionTypes.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + TrustServiceSessionTypes.fromValue(value); + } } diff --git a/src/test/java/cloudhub/CloudhubUtilsTest.java b/src/test/java/cloudhub/CloudhubUtilsTest.java new file mode 100644 index 0000000..a9ae2f7 --- /dev/null +++ b/src/test/java/cloudhub/CloudhubUtilsTest.java @@ -0,0 +1,32 @@ +package cloudhub; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.charset.StandardCharsets; + +import org.junit.jupiter.api.Test; + +/** + * Focused unit tests for the hand-maintained {@link CloudhubUtils} helpers that were + * refactored out of the generated {@code SessionsApi}. These run with no network and no + * certificate, so they are the fast way to validate this feature in isolation. + */ +class CloudhubUtilsTest { + + @Test + void convertCertificateToString_stripsSurroundingQuotes() { + // CloudHub returns the value as a JSON-quoted string; the helper removes the quotes. + byte[] quoted = "\"aGVsbG8=\"".getBytes(StandardCharsets.UTF_8); + assertEquals("aGVsbG8=", CloudhubUtils.convertCertificateToString(quoted)); + } + + @Test + void convertToSignHashToByteArray64_decodesQuotedBase64() { + // The to-sign hash arrives as a JSON-quoted base64 string; the helper strips the quotes + // and base64-decodes it. "aGVsbG8=" is base64 for the bytes of "hello". + byte[] quotedBase64 = "\"aGVsbG8=\"".getBytes(StandardCharsets.UTF_8); + byte[] expected = "hello".getBytes(StandardCharsets.UTF_8); + assertArrayEquals(expected, CloudhubUtils.convertToSignHashToByteArray64(quotedBase64)); + } +} diff --git a/src/test/java/cloudhub/SessionsApiTest.java b/src/test/java/cloudhub/SessionsApiTest.java deleted file mode 100644 index 6c2c217..0000000 --- a/src/test/java/cloudhub/SessionsApiTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Cloudhub API - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: v1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package cloudhub; - -import cloudhub.client.ApiException; -import cloudhub.client.Configuration; -import cloudhub.client.model.SessionCreateRequest; -import cloudhub.client.model.SessionModel; -import cloudhub.client.model.SignHashRequest; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * API tests for SessionsApi - */ -@Disabled -public class SessionsApiTest { - - private final SessionsApi api = new SessionsApi(Configuration.getDefaultCloudhubClient()); - - /** - * @throws ApiException if the Api call fails - */ - @Test - public void apiSessionsCertificateGetTest() throws ApiException { - String session = null; - byte[] response = api.apiSessionsCertificateGet(session); - // TODO: test validations - } - - /** - * @throws ApiException if the Api call fails - */ - @Test - public void apiSessionsPostTest() throws ApiException { - SessionCreateRequest sessionCreateRequest = null; - SessionModel response = api.apiSessionsPost(sessionCreateRequest); - // TODO: test validations - } - - /** - * @throws ApiException if the Api call fails - */ - @Test - public void apiSessionsSignHashPostTest() throws ApiException { - SignHashRequest signHashRequest = null; - byte[] response = api.apiSessionsSignHashPost(signHashRequest); - // TODO: test validations - } - -} diff --git a/src/test/java/cloudhub/client/model/CertificateModelTest.java b/src/test/java/cloudhub/client/model/CertificateModelTest.java deleted file mode 100644 index 2e567ee..0000000 --- a/src/test/java/cloudhub/client/model/CertificateModelTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Cloudhub API - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: v1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package cloudhub.client.model; - -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import org.openapitools.jackson.nullable.JsonNullable; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - - -/** - * Model tests for CertificateModel - */ -public class CertificateModelTest { - private final CertificateModel model = new CertificateModel(); - - /** - * Model tests for CertificateModel - */ - @Test - public void testCertificateModel() { - // TODO: test CertificateModel - } - - /** - * Test the property 'content' - */ - @Test - public void contentTest() { - // TODO: test content - } - - /** - * Test the property 'alias' - */ - @Test - public void aliasTest() { - // TODO: test alias - } - -} diff --git a/src/test/java/cloudhub/client/model/IdentifierTypesTest.java b/src/test/java/cloudhub/client/model/IdentifierTypesTest.java deleted file mode 100644 index fc9df45..0000000 --- a/src/test/java/cloudhub/client/model/IdentifierTypesTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Cloudhub API - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: v1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package cloudhub.client.model; - -import com.google.gson.annotations.SerializedName; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - - -/** - * Model tests for IdentifierTypes - */ -public class IdentifierTypesTest { - /** - * Model tests for IdentifierTypes - */ - @Test - public void testIdentifierTypes() { - // TODO: test IdentifierTypes - } - -} diff --git a/src/test/java/cloudhub/client/model/ServiceSessionCreateRequestTest.java b/src/test/java/cloudhub/client/model/ServiceSessionCreateRequestTest.java deleted file mode 100644 index 3fbd92e..0000000 --- a/src/test/java/cloudhub/client/model/ServiceSessionCreateRequestTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Cloudhub API - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: v1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package cloudhub.client.model; - -import cloudhub.client.model.TrustServiceSessionTypes; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import org.openapitools.jackson.nullable.JsonNullable; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - - -/** - * Model tests for ServiceSessionCreateRequest - */ -public class ServiceSessionCreateRequestTest { - private final ServiceSessionCreateRequest model = new ServiceSessionCreateRequest(); - - /** - * Model tests for ServiceSessionCreateRequest - */ - @Test - public void testServiceSessionCreateRequest() { - // TODO: test ServiceSessionCreateRequest - } - - /** - * Test the property 'identifier' - */ - @Test - public void identifierTest() { - // TODO: test identifier - } - - /** - * Test the property 'type' - */ - @Test - public void typeTest() { - // TODO: test type - } - - /** - * Test the property 'redirectUri' - */ - @Test - public void redirectUriTest() { - // TODO: test redirectUri - } - - /** - * Test the property 'lifetimeInSeconds' - */ - @Test - public void lifetimeInSecondsTest() { - // TODO: test lifetimeInSeconds - } - -} diff --git a/src/test/java/cloudhub/client/model/ServiceSessionCreateResponseTest.java b/src/test/java/cloudhub/client/model/ServiceSessionCreateResponseTest.java deleted file mode 100644 index c50dc4e..0000000 --- a/src/test/java/cloudhub/client/model/ServiceSessionCreateResponseTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Cloudhub API - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: v1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package cloudhub.client.model; - -import cloudhub.client.model.TrustServiceInfoModel; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import org.openapitools.jackson.nullable.JsonNullable; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - - -/** - * Model tests for ServiceSessionCreateResponse - */ -public class ServiceSessionCreateResponseTest { - private final ServiceSessionCreateResponse model = new ServiceSessionCreateResponse(); - - /** - * Model tests for ServiceSessionCreateResponse - */ - @Test - public void testServiceSessionCreateResponse() { - // TODO: test ServiceSessionCreateResponse - } - - /** - * Test the property 'serviceInfo' - */ - @Test - public void serviceInfoTest() { - // TODO: test serviceInfo - } - - /** - * Test the property 'authUrl' - */ - @Test - public void authUrlTest() { - // TODO: test authUrl - } - -} diff --git a/src/test/java/cloudhub/client/model/SessionCreateRequestTest.java b/src/test/java/cloudhub/client/model/SessionCreateRequestTest.java deleted file mode 100644 index dc51eee..0000000 --- a/src/test/java/cloudhub/client/model/SessionCreateRequestTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Cloudhub API - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: v1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package cloudhub.client.model; - -import cloudhub.client.model.TrustServiceSessionTypes; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - - -/** - * Model tests for SessionCreateRequest - */ -public class SessionCreateRequestTest { - private final SessionCreateRequest model = new SessionCreateRequest(); - - /** - * Model tests for SessionCreateRequest - */ - @Test - public void testSessionCreateRequest() { - // TODO: test SessionCreateRequest - } - - /** - * Test the property 'identifier' - */ - @Test - public void identifierTest() { - // TODO: test identifier - } - - /** - * Test the property 'type' - */ - @Test - public void typeTest() { - // TODO: test type - } - - /** - * Test the property 'redirectUri' - */ - @Test - public void redirectUriTest() { - // TODO: test redirectUri - } - -} diff --git a/src/test/java/cloudhub/client/model/SessionModelTest.java b/src/test/java/cloudhub/client/model/SessionModelTest.java deleted file mode 100644 index fc95684..0000000 --- a/src/test/java/cloudhub/client/model/SessionModelTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Cloudhub API - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: v1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package cloudhub.client.model; - -import cloudhub.client.model.TrustServiceAuthParametersModel; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import org.openapitools.jackson.nullable.JsonNullable; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - - -/** - * Model tests for SessionModel - */ -public class SessionModelTest { - private final SessionModel model = new SessionModel(); - - /** - * Model tests for SessionModel - */ - @Test - public void testSessionModel() { - // TODO: test SessionModel - } - - /** - * Test the property 'services' - */ - @Test - public void servicesTest() { - // TODO: test services - } - -} diff --git a/src/test/java/cloudhub/client/model/SignHashRequestTest.java b/src/test/java/cloudhub/client/model/SignHashRequestTest.java deleted file mode 100644 index 1affa2f..0000000 --- a/src/test/java/cloudhub/client/model/SignHashRequestTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Cloudhub API - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: v1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package cloudhub.client.model; - -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import org.openapitools.jackson.nullable.JsonNullable; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - - -/** - * Model tests for SignHashRequest - */ -public class SignHashRequestTest { - private final SignHashRequest model = new SignHashRequest(); - - /** - * Model tests for SignHashRequest - */ - @Test - public void testSignHashRequest() { - // TODO: test SignHashRequest - } - - /** - * Test the property 'session' - */ - @Test - public void sessionTest() { - // TODO: test session - } - - /** - * Test the property 'hash' - */ - @Test - public void hashTest() { - // TODO: test hash - } - - /** - * Test the property 'digestAlgorithm' - */ - @Test - public void digestAlgorithmTest() { - // TODO: test digestAlgorithm - } - - /** - * Test the property 'digestAlgorithmOid' - */ - @Test - public void digestAlgorithmOidTest() { - // TODO: test digestAlgorithmOid - } - - /** - * Test the property 'certificateAlias' - */ - @Test - public void certificateAliasTest() { - // TODO: test certificateAlias - } - -} diff --git a/src/test/java/cloudhub/client/model/TrustServiceAuthParametersModelTest.java b/src/test/java/cloudhub/client/model/TrustServiceAuthParametersModelTest.java deleted file mode 100644 index 062f9d0..0000000 --- a/src/test/java/cloudhub/client/model/TrustServiceAuthParametersModelTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Cloudhub API - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: v1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package cloudhub.client.model; - -import cloudhub.client.model.TrustServiceInfoModel; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import org.openapitools.jackson.nullable.JsonNullable; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - - -/** - * Model tests for TrustServiceAuthParametersModel - */ -public class TrustServiceAuthParametersModelTest { - private final TrustServiceAuthParametersModel model = new TrustServiceAuthParametersModel(); - - /** - * Model tests for TrustServiceAuthParametersModel - */ - @Test - public void testTrustServiceAuthParametersModel() { - // TODO: test TrustServiceAuthParametersModel - } - - /** - * Test the property 'serviceInfo' - */ - @Test - public void serviceInfoTest() { - // TODO: test serviceInfo - } - - /** - * Test the property 'authUrl' - */ - @Test - public void authUrlTest() { - // TODO: test authUrl - } - -} diff --git a/src/test/java/cloudhub/client/model/TrustServiceInfoModelTest.java b/src/test/java/cloudhub/client/model/TrustServiceInfoModelTest.java deleted file mode 100644 index a8df8f4..0000000 --- a/src/test/java/cloudhub/client/model/TrustServiceInfoModelTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Cloudhub API - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: v1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package cloudhub.client.model; - -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import org.openapitools.jackson.nullable.JsonNullable; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - - -/** - * Model tests for TrustServiceInfoModel - */ -public class TrustServiceInfoModelTest { - private final TrustServiceInfoModel model = new TrustServiceInfoModel(); - - /** - * Model tests for TrustServiceInfoModel - */ - @Test - public void testTrustServiceInfoModel() { - // TODO: test TrustServiceInfoModel - } - - /** - * Test the property 'serviceName' - */ - @Test - public void serviceNameTest() { - // TODO: test serviceName - } - - /** - * Test the property 'provider' - */ - @Test - public void providerTest() { - // TODO: test provider - } - - /** - * Test the property 'endpoint' - */ - @Test - public void endpointTest() { - // TODO: test endpoint - } - - /** - * Test the property 'badgeUrl' - */ - @Test - public void badgeUrlTest() { - // TODO: test badgeUrl - } - -} diff --git a/src/test/java/cloudhub/client/model/TrustServiceSessionTypesTest.java b/src/test/java/cloudhub/client/model/TrustServiceSessionTypesTest.java deleted file mode 100644 index 71a7c43..0000000 --- a/src/test/java/cloudhub/client/model/TrustServiceSessionTypesTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Cloudhub API - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: v1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package cloudhub.client.model; - -import com.google.gson.annotations.SerializedName; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - - -/** - * Model tests for TrustServiceSessionTypes - */ -public class TrustServiceSessionTypesTest { - /** - * Model tests for TrustServiceSessionTypes - */ - @Test - public void testTrustServiceSessionTypes() { - // TODO: test TrustServiceSessionTypes - } - -}